Romin Irani

About Romin Irani

Principal Architect
04
Oct

Welcome to Part IV of this series. We covered the basics of HTML5 Geolocation support in Part I of this series. In that article, we looked at how an HTML5 based web application can make use of Geolocation support built in the browser.

To recap, I will recreate the Javascript code for you below:


<script type="text/javascript">

function findCurrentLocation(){
	var geoService = navigator.geolocation;
	if (geoService){
		geoService.getCurrentPosition(showCurrentLocation,errorHandler);
	} else {
		alert("Your Browser does not support Geolocation.");
	}
}

function showCurrentLocation(position){
	document.getElementById("mylocation").innerHTML = "Current Latitude : " + position.coords.latitude + " , Longitude : " + position.coords.longitude;
}

function errorHandler(error){
	  alert("Error while retrieving current position. Error code: " + error.code + ",Message: " + error.message);
}
</script>

In the above code, we used the getCurrentPosition method on the navigator.geolocation object to get the current location co-ordinates. The main point to note about this method is that it is just a onetime call to get the location co-ordinates. The application is then in control to provide location relevant data. So while this might suffice for certain kinds of applications, it may not be enough for an application that needs the location regularly at a certain interval. For e.g. if you wish to write an application that would provide different location based data, if the user co-ordinates are changing i.e. if the user is moving.

To do that, you need to substitute the getCurrentPosition call with watchPosition. This method functions in a similar manner to getCurrentPosition, just that your application will get notified when the users position changes. In addition to getting notified i.e. the success function getting called when the location has changed, the watchPosition method also returns a unique ID. This ID is used together with a paired method called clearWatch. So whenever you wish to stop tracking the users location (which you should by the way, since these operations are draining), you can use the ID and pass it as a parameter to the navigator.geolocation.clearWatch method. This will stop the tracking of the user’s location.

Let us take a look at our modified code then continuously gets notified when the location of the user changes. We are simply changing the code that we covered here in Part I of the series.

Do note that I have decided to use the Modernizr Javascript library for detecting HTML5 support that we covered in Part II of the series.

The geotest.html file is shown below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML GeoLocation Test</title>
<script src="js/modernizr-1.5.min.js"></script>
<script type="text/javascript">
var watchPositionID=0;

function startLocationTracking(){
	alert("startLocationTracking");
	if (Modernizr.geolocation) {
		alert("Your Browser supports GeoLocation");
		watchPositionID = navigator.geolocation.watchPosition(showCurrentLocation,errorHandler,{enableHighAccuracy: true});
	} else {
		alert("Your Browser does not support GeoLocation.");
	}
}

function showCurrentLocation(position){
	document.getElementById("mylocation").innerHTML = "Current Latitude : " + position.coords.latitude + " , Longitude : " + position.coords.longitude;
}

function errorHandler(error){
	  alert("Error while retrieving current position. Error code: " + error.code + ",Message: " + error.message);
}

function stopLocationTracking(){
	if (watchPositionID > 0) {
		navigator.geolocation.clearWatch(watchPositionID);
		alert("Stopped Tracking Location");
	}
}

</script>
</head>
<body>
<div id="main">
	<div id="mylocation"></div>
	<input type="button" value="Start" onclick="startLocationTracking()"/>
	<input type="button" value="Stop" onclick="stopLocationTracking()"/>
</div>
</body>
</html>

Let us go through the code in brief:

  • Our HTML page is simple. It has two buttons, one to start location tracking and the other to stop location tracking.
  • The Start button, invokes the startLocationTracking method. This method determines first if Geolocation support is present. If yes, it will invoke the watchPosition() method on the navigator.geolocation object. The first parameter to the watchPosition() method is the success function that gets invoked if the location is determined. That success function i.e. showCurrentLocation simply displays the location in terms of latitude and longitude.
  • The watchPosition method returns an ID that we are saving in the global variable named watchPositionID.
  • The Stop button, invokes the stopLocationTracking method. This method simply uses the watchPositionID and passes that as a parameter to the navigator.geolocation.clearWatch(…) method. This will stop the invocation of the success function i.e. showCurrentLocation if the users location changes.

Conclusion

We have seen in this article how we can use the navigator.geolocation object to keep tracking a user’s location as it changes. In an earlier part of the series on HTML5 Geolocation, we had covered getting the location on demand or only once. As per the requirements of your application, you can use any of these two mechanisms. Do keep in mind, that determining the location of the device is quite a drain on the battery, especially on mobile devices. So if you are using the watchPosition method to keep a track as the location changes, be sensitive to the battery consumption too.

Please participate

We look forward to your feedback on this article and the others in the series. Let us know which feature you would like to see covered. Additionally, do share your experiences with HTML5.

28
Sep

Hope you have been enjoying the series on HTML5 so far, where we covered HTML5 GeoLocation and the Javascript library Modernizr. In this part of the series, we shall cover the new HTML Form elements that have been introduced in HTML5.

A Form is one of the most basic and essential features of any web site. The form elements available in HTML so far include the textbox, checkbox, radio, button, drop-down list, password and file picker. While these have sufficed so far, there is a clear need for newer form elements. The question is not just of newer form elements, but the ability to inject behavior into existing form elements so that usability and validity, which is a cornerstone of any good UI, is given highest consideration.

We shall break up HTML5 Form features into 2 parts in this series. This part will be more focused on the different types of input elements that are introduced in HTML5. In the next part, we shall look at how additional attributes introduced in HTML5 bring in significant improvements to both usability and also to the development code.

New Input Types

HTML5 brings to the table several new input types, a total of 13. The philosophy behind these new input types is to address the common types of data fields that users typically have to fill up in a web form. Apart from plain text, there is data to be filled up like email address, web site URLs, Phone Numbers, Date/Time, Numeric data, Colors, etc.

HTML5 introduces these data types via the <input type=”_NEW_TYPE_HERE_”/> format.

What if my browser does not support these new HTML5 form elements?

No problem. One of the key design decisions in HTML5 is backward compatibility. What this means is that if the new input types are not supported, then by default it falls back to <input type=”text”…./>, so it will be rendered as a plain text box, which the user can then fill data in.

One may ask, what is the advantage of these new input types and how are the browsers supposed to implement them? By supporting the new input types, two things happen:

a) You get automatic validity of the fields as per the format. This means that the form is not going to get submitted if the value entered is not as per the default validation of that type

b) The browser inspects the input type and if it finds that it is of a specific type, then it does something quite clear to aid the input of that data. For e.g. On the Smart Phones, which do not have a physical keyboard but instead a virtual keyboard, the keyboard that will be shown up will only contain keys that will aid the user in filling out the data.

Let us look at the new HTML5 input types that are present.

Email Address

This input type allows for entry of email addresses. The format is shown below:

<input type="email"/>

This input type is useful for entering email ids like test@test.com

Web URLs

<input type="url"/>

This input type is useful for entering web urls like http://www.xoriant.com

Tel

This input type is useful for entering telephone numbers

<input type="tel"/>

The email, url and tel input types are meant to instruct to the browser that the input would be valid only if it contains characters that validate the input type. Additionally, Smart Phone browsers like Apple iPhone do a very neat trick when they encounter input types like URL, Email and Telephone. Since they have a virtual keyboard, they will only show those keys that aid in entering the value quickly. So if you are trying to type the Telephone, it will only show the numbers and some characters, the other keys are hidden from you.

Shown below is a screenshot of the Android Web browser accessing a form which contains an input element of type tel. Notice that in the virtual keyboard, it only shows keys that aid in faster and less error prone data entry.

Android Web browser accessing a form Date Time

HTML5 provides for 6 types of DateTime inputs, which cater to a variety of date time entries, as your application may require. They are date, time, datetime, local-datetime, month, year. The syntax is shown below:

<input type="datetime"/>
  <input type="date"/>
  <input type="time"/>
  <input type="month"/>
  <input type="week"/>
  <input type="local-datetime"/>

Shown below is the datetime input type rendered in the Opera Browser:

Datetime input type rendered in the Opera Browser

Datetime input type rendered in Opera Browser

Spin Box

A frequent requirement in forms is to fill out numeric values. An input type number has been added. This will render the input as a spinbox if the browser supports it. It will even honor the min, max values that you specify. The step attribute is used to indicate the increment/decrement if the user clicks the up/ down spin button. The value attribute specifies an initial value for the control.


<input type="number"
       min="1"
       max="5"
       step="1"
       value="3">

Slider

Spin boxes are not the only way to enter numeric input. You can also allow a user to use a slider to specify a value. The syntax is shown below:

<input type="range"
       min="1"
       max="5"
       step="1"
       value="3">

If the browser supports the number and range types, it will render as shown below:

Browser supports the number & range types

Browser supports the number & range types

Search

This input is specified by giving the type=”search” as shown below.

<form>
  <input name="search_terms" type="search">
  <input type="submit" value="Go">
</form>

It will be rendered as shown below:

As you type, a cross icon will appear at the end of the input box and you can clear the search term by clicking on it.

autofocus, placeholder and novalidation

There are 3 attributes that we can apply to HTML5 forms that aid in data entry.

  • autofocus: This attribute when applied to any form element, will result in the field receiving focus. For e.g. consider the form shown below:

<form>
	<label for=”firstname”>First Name</label>
	<input type=”text” id=”firstname” name=”firstname” autofocus>
              <label for=”lastname”>Last Name</label>
	<input type=”text” id=”lastname” name=”lastname”>
	<input type=”submit” label=”Go”>
</form>

We have added the attribute autofocus to the firstname input field. When the form loads, you will find that the focus is already set on that field, thereby making it easier for the user to start filling the form.

  • placeholder: This attribute when applied to any form element, will display helper text to aid the user to fill up the value. When you give focus to the element, the placeholder value will go away and let the user enter the value. If no value is entered and you move away to another field, then the placeholder value will be shown again. Consider the same example as above but with placeholder values for both firstname and lastname fields.

<form>
	<label for=”firstname”>First Name</label>
	<input type=”text” id=”firstname” name=”firstname” placeholder=”Enter First Name here” autofocus>
              <label for=”lastname”>Last Name</label>
	<input type=”text” id=”lastname” name=”lastname” placeholder=”Enter Last Name here” >
	<input type=”submit” label=”Go”>
</form>

When we visit this page, we see the following form:

Placeholder rendered

You will notice that we had put placeholders for both the fields, but since the firstname field also had the autofocus, the placeholder text is not shown. Instead it has the focus so that the user can start entering the text. The lastname field has the placeholder text as shown. As you tab in and out the First Name field without entering any data, you will find the placeholder text returning back there.

Do note that not all browsers support placeholder text. The above support was from Google Chrome browser.
  • novalidation: By default, when you submit a form, all the fields in the form will be validated. This means that the browser that fully supports the HTML5 input types, will validate all the fields as per the input types and if they are not valid, the form is not submitted. Browser support varies over here so be careful. By default, all the forms are validated before submission. However, you can opt for the form to not be validated, by adding the novalidation tag to the <form> tag as shown below:
<form …. novalidation>

Conclusion

The new HTML5 input types and several attributes introduced in the specification are a clear step to address data input via forms, which forms a cornerstone of any public web application. Do note that there are many more features like pattern, etc which we have not discussed in this blog post, but the reader is encouraged to go and refer to documentation on the standard. While testing out any of these features, it is important to first determine if your browser supports them. In our tests, we have found the Opera browser to be one of the first to implement the different input types, however latest versions of Chrome and Firefox Beta are not far behind. We believe that the browsers will catch up soon and implement most of them.

Please participate

We look forward to your feedback on this article and the others in the series. Let us know which feature you would like to see covered. Additionally, do share your experiences with HTML5.

26
Sep

In the first part of our series, we saw how to use the Geolocation feature of HTML5. While this part will not focus on any specific feature of HTML5, it will bring to the table an interesting way in which you can determine if your browser supports a particular HTML5 feature or not.

To understand that a little bit, let us go back to the code in the first part in which we determine if the browser has Geolocation support or not. Take a look at the code snippet below that is reproduced from the first part:


function findCurrentLocation(){
	var geoService = navigator.geolocation;
	if (geoService){
		geoService.getCurrentPosition(showCurrentLocation,errorHandler);
	} else {
		alert("Your Browser does not support Geolocation.");
	}
}

The above Javascript function findCurrentLocation() is interested in determining first if there is Geolocation support or not. If you notice, it queries the standard navigator object first. If your browser support Geolocation, then it will have an object geolocation. We then put in an if statement that does something if support is there and if there is no support then it falls back to another path of execution.

While this approach is fair enough, you will soon end up with similar pieces of code to determine if a certain HTML5 feature exists or not. In certain situations you may also do browser sniffing (User Agent detection) to include a certain piece of code if support exists or not. This soon becomes unwieldy and clutters up your code too. You need a cleaner mechanism of detecting support for HTML5 features (since we still in the transition phase where all browsers support most features).

Enter Modernizr. To quote from their web site, Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies.

And how does it do that? Modernizr creates a global JavaScript object (called Modernizr) which contains properties for each feature. If your browser supports it, it will evaluate to true, else it will be false.

Modernizr is useful for all aspects of HTML5. It not only helps you detect if your browser supports new HTML5 markup elements, CSS3 features but also the Javascript APIs (Geolocation, Storage, Web Workers, etc). Keep in mind that it does not enable any of the features, it is simply there to help you detect it.

You can refer to its complete documentation for all the features that it can help detect for HTML5. I provide a brief summary below for certain HTML5 features and we will see how to modify our function above to incorporate Modernizr.

HTML5 Feature Modernizr Object
Geolocation Modernizr.geolocation
Local Storage Modernizr.localstorage
Session Storage Modernizr.sessionstorage
if (Modernizr.<feature>) {
//Yes! Your browser supports the feature, so take advantage of it
}
else {
//No! Your browser does not support the feature, so fall back on some other mechanism. Degrade gracefully.
}

Using Modernizr in your code
We shall modify our existing Geolocation code shown at the start of the article and which we covered previously in the series and employ Modernizr.

Follow these steps to include Modernizr:

  1. Download modernizr-1.5.min.js from the main web site
  2. Include the script in your code. This will initialize Modernizr when the page loads. In fact, it creates the global Modernizr JavaScript object with all the feature objects created, so that you can start using it in your code.
  3. Finally, use the template pattern in your code as shown above.

I will recreate the geotest.html example that we covered in Part 1: Geolocation article.

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8">
<title>HTML Geolocation Test</title>
<script src="js/modernizr-1.5.min.js"></script>
<script type="text/javascript">

if (Modernizr.geolocation) {
  navigator.geolocation.getCurrentPosition(showCurrentLocation,errorHandler);
}
else {
  alert("Your Browser does not support GeoLocation.");
}
… REST OF THE CODE
</script>
</head>

<body>
<div id="main">
	<div id="mylocation"></div>
	<input type="button" value="Get Location" onclick="findCurrentLocation()"/>
</div>

If you look at the above code, we have simply included the script file i.e. js/modernizr-1.5.min.js and then checked if the Geolocation feature is supported. The rest of the code remains straightforward.

While this is a simple example, the utility of Modernizr becomes visible when you deal with many other features of HTML5. Let it do all the hard work of determining a particular feature of HTML5 in your browser.

Please participate

We look forward to your feedback on this article and the others in the series. Let us know which feature you would like to see covered. Additionally, do share your experiences with HTML5.

23
Sep
14

Welcome to the series on HTML5 development brought to you by the team at Xoriant.

HTML5 has been in the news of late and it promises to help deliver the next set of web applications with features that closely resemble some top of the line desktop applications.

This series will focus on demonstrating a feature of HTML5 with emphasis on a short working example. The idea is to introduce to you what your applications could gain by using HTML5 today. We will focus less on controversial stuff like Flash v/s HTML5 and instead focus on the features. As a developer, you are the best judge of using the technology in your applications today by looking at all factors. We will focus particular on bringing these experiences to mobile web applications, where the Webkit based browsers on most Smart phones today are more than capable of supporting several HTML5 features.

All you need is a text editor (or your favorite IDE), a Web Server (maybe) and a HTML5 compliant browser (more on that later).

Ready, Set … Lets Go!

Which Browser?

First, a word about the browser support for HTML5. To summarize in brief, HTML5 support has been announced in most browsers and all of them support core features, though several features present in the specification are still not implemented. With the announcement of IE9 Beta, HTML5 support has got a fillip in the IE world too, though Google Chrome presents your best bet at this point in time to try out some of the features.

Enter “The HTML5 Test”

A quick tip to figure out how well your browser supports HTML5 specification is to navigate to http://www.html5test.com. This will display a score about how well your browser supports HTML5. You should not worry too much about the score, rather there are 2 things that are particular important here and can actually act as a guide to your learning HTML5 and they are:

  • Check out all the features that are there in HTML5. Just a look at the number of features should get you excited about HTML5. Pick each of them up, refer to the web and learn about them. We will also be covering most of them in our series.
  • Once you have learnt about a particular feature and wish to see it work, check if your browser is supporting that feature of HTML5. If Yes – you are good to go. If not – you will need to wait.

A quick look at http://www.html5test.com in my browser (I am running Google Chrome 6.0.472.63 beta) shows that it does quite well.

html5test.com in Google Chrome browser

html5test.com in Google Chrome browser

Some assumptions

We will assume that our readers are familiar with developing basic web applications with HTML, JavaScript and a little bit of CSS. That will help you best to appreciate the new capabilities that HTML5 is bringing forth to the table.

What about Mobile Browsers?

The thing that excites us the most today is the fact that most Smart phones shipping today are equipped with the fantastic WebKit browser, which has great support for several HTML5 features. So if you have a Smart Phone, be it Android or the iPhone, you are all set. The other Smart Phone manufacturers including RIM and Nokia have also announced support for WebKit, so moving forward your application will be well placed to be functional on newer devices coming from them.

Where do we go from here?

Well, the question to ask should be “Where am I?” before we can go anywhere. And with that, we can look at the Geolocation APIs that are provided in HTML5. Geolocation is all about telling us where we are. In short, we will know the Latitude and Longitude, though it gives much more information than that like Altitude, Accuracy, etc.

To make sure that your browser supports Geolocation, point it to http://html5test.com and navigate below the Geolocation section, where you should see a score of 10 as shown below.

Browser supports Geolocation

In case there is no Geolocation support, which means the screen below:

Browser does not support Geolocation

Then I strongly suggest that you get either the latest version of Google Chrome or Firefox to see the example work. If not, you can still follow the article.

The code (geotest.html)

We will write a minimal piece of HTML code that is functional in nature and will access the Geolocation support in the browser and show the current Latitude and Longitude. First, take a look at the geotest.html file below:


<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8">
<title>HTML Geolocation Test</title>
<script type="text/javascript">

function findCurrentLocation(){
	var geoService = navigator.geolocation;
	if (geoService){
		geoService.getCurrentPosition(showCurrentLocation,errorHandler);
	} else {
		alert("Your Browser does not support Geolocation.");
	}
}

function showCurrentLocation(position){
	document.getElementById("mylocation").innerHTML = "Current Latitude : " + position.coords.latitude + " , Longitude : " + position.coords.longitude;
}

function errorHandler(error){
	  alert("Error while retrieving current position. Error code: " + error.code + ",Message: " + error.message);
}
</script>
</head>

<body>
<div id="main">
	<div id="mylocation"></div>
	<input type="button" value="Get Location" onclick="findCurrentLocation()"/>
</div>
</body>
</html>

Let us analyze the code which is rather straightforward:

1) Our body has a div element named mylocation, that we shall populate once we have the Latitude and Longitude.

2) We have a button, which when clicked calls the findCurrentLocation() method

3) The findCurrentLocation() method is where all the magic happens. The standard navigator object now has an object named geolocation. So, if your browser supports the geolocation object the navigator object will contain it. That is the first test we do. If there is no object then we display a standard alert informing the user that his/her browser does not support Geolocation.

4) If you do have support for the geolocation object, then all you need to do is invoke the getCurrentPosition method on it. The getCurrentPosition method takes 3 parameters:

  1. A success callback function
  2. An error callback function
  3. An optional parameters where you can provide some additional options to get the Current Position

5)  The success callback function in our case is the showCurrentPosition method. This method will get passed one parameter, an object of type Position. This object has two parameters, a property called timestamp and a property called coords that is an instance of type Coordinates. The coords object has several properties related to the current location like latitude, longtitude, altitude and several more. For our example, we are interested only in latitude and longitude.

6) The error callback function in our case is the errorHandler method. This method will get passed one parameter, an object of type PositionError. This object has two properties: code and message. The code is either 1 (PERMISSION_DENIED), 2(POSITION_UNAVAILABLE) or 3(TIMEOUT). The message is dependent on the device / machine browser.

7) We can leave out the 3rd optional parameter for now, since it is not fully supported on all browsers.

8)  So once the success callback function i.e. showCurrentPosition is invoked, we simply retrieve the latitude and longitude and populate the div with the results.

Our Geolocation Example in Action

We serve the geotest.html file via a local web server as shown below. Please note that I am using a latest version of Google Chrome browser.

Geolocation Example

Geolocation Example

When we click the Get Location button, we see that the browser prompts a warning message as shown below. This is important since it is recommended that all applications that deal with the location of the user should always allow the user to opt-in for sharing the location. It is good practice and strongly recommended, since it is a privacy issue and more users in the future will demand it.

Geolocation Example

Geolocation Example

If we click on Allow, you will find that it takes a little while (at times) to get the location and the current latitude and longitude are printed below.

Geolocation Example

Geolocation Example

Do note that since you allowed the browser to share the location, it has remembered that you have opted-in. On subsequent calls or even across browser restarts, this is remembered by the browser and you are no longer prompted by the browser for permission to determine your location. You can clear this preference, by clicking on the Icon shown below and then clicking on Clear these settings for future visits.
Geolocation Example

What happens, if we refuse permission to the browser to determine our location? Let us see what happens by running our example again. We navigate to the home page i.e. geotest.html and once again the browser prompts us, asking for our permission, as shown below:

Geolocation Example

This time we refuse it by clicking on Deny. This will results in the error callback function getting invoked i.e. errorHandler and we extract out the PositionError.code i.e. value of 1 (PERMISSION_DENIED) and PositionError.message that is device specific. In the case of Google Chrome, it rightly populates it to “User denied Geolocation” as shown below.

Do not assume that this message will be populated correctly. The same error message on Firefox browser gave the following alert message, as shown below:

So remember to provide a user friendly message that is populated by your application rather than depending on the device to do that.

What if the Browser does not support Geolocation?

If the browser does not support Geolocation, we have handled the scenario such that it displays an alert to the user in our test code. For e.g. I accessed our sample page via Internet Explorer 9 Beta and found that it displayed the appropriate message as shown below:

Remember HTML5Test that we covered earlier in the article. If we access http://www.html5test.com in Internet Explorer 9 Beta, we get the correct results for Geolocation feature as shown below.

So remember to save yourself enough heartburn and use html5test.com as a quick way to ascertain if a particular feature is supported or not.

What can we do with our location?

Location is the starting point of an entirely new class of applications/services that called themselves “Location Based Services”. Once you know the Location of the user, several value added features can be built on top of it. Location of a user is such a hot topic nowadays that everyone from Google, Yahoo, Twitter and Facebook added location of the user activity to their applications. Examples of how you can use a location are:

· Weather Reports for a particular location as the user is passing through it

· Traffic incidents as they happen

· Retail offers from merchants in the vicinity of the location that the user is currently in

· A Friend Locator application that informs the user of his/her friends if they are within close proximity of each other.

Most of these LBS application also make use of Google Maps to provide an intuitive user interface.

Conclusion

We saw how easy it was to get access to Location using the Geolocation APIs in HTML5. Geolocation data when combined with Maps and Other services can help create powerful applications.

Please participate

How important is Location to your application? How did you incorporate it into your application? What do you think of HTML5 Geolocation APIs? Would it make things simpler/better? Please discuss in the comments below. We look forward to your active participation.

16
Sep

A commonly used class in any application, whether it is a desktop application or a mobile application is an application level class. An application level class also called a controller is a single instance available across the application and visible to all modules within an application. This application controller can be used to maintain global state across an application, contain common methods, etc.

Android provides support in every application to create an application wide class. The base class for this is the android.app.Application class. The official documentation of the Application class is given below:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml’s <application> tag, which will cause that class to be instantiated for you when the process for your application/package is created.

Let us look at how to incorporate an Application class in our Android applications.

Step 1: Provide an implementation of the Application class

You need to extend the android.app.Application class and override the OnCreate method. This method is invoked by the Android runtime once when your application is started. So this is a good point to do application initialization and set some global settings like shared preferences, etc.

Shown below is a template for your own Application class:

public class ApplicationController extends Application {

	//Application wide instance variables
      //Preferable to expose them via getter/setter methods
@Override
	public void onCreate() {
		super.onCreate();
		//Do Application initialization over here
        }
        //Appplication wide methods
}

Step 2: Code your Application class

You can then introduce public methods in your Application class above. These public methods can then be called from anywhere in the Android application. We shall how to invoke them in Step 4.

Step 3: Specify our Application class in the Android manifest.xml file

Specify your application class in the Android manifest.xml file. Each Android manifest has the <application> tag and you need to provide the application class as an attribute of this element as shown below:

<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".android.controller.ApplicationController">

Step 4: Utilize the Application class from other places in your application

To access the Application class instance in any activity, you can use the code as shown below:


ApplicationController AC = (ApplicationController)getApplicationContext();

The main method is getApplicationContext(). This gives an instance to the Application class if defined in the application. You need to simply type cast it to your provided Application implementation class. Once you have this instance, you can invoke any public methods that you would have defined in the class. Additionally, if you provide getter/setter methods for application wide state variables, you can invoke them too.

Having an Application wide controller in your application is a commonly used design with significant benefits. Instead of rolling out your own custom implementation, Android provides a simple mechanism to introduce it in your applications, letting you focus on your Application wide logic while it takes care of its lifecycle methods. Start using the Application class to bring in structure to your applications today.

28
Jul

Cloud Computing seems to be the talk of the town. It is very difficult to separate hype from reality. Overnight, people have been asking questions from our software products i.e. is it ready for the cloud? Cloud computing is a different model and not all products can be a good fit for the cloud. This article will assume that you have a current product and have done enough homework to move it to the cloud. The article will list down key high level areas that you need to consider while moving to the cloud. These are based on our experiences with executing projects over the last one year in the cloud computing space.

Self Hosting or Outsource

Given the options that are out there vis-à-vis cloud architectures, there is a tendency to think that one should do all the hosting initially and then move to a cloud (public) once the application gains more acceptance, etc. While this might seem plausible in the beginning, there is no point trying to replicate complicated and massively scalable architectures that cloud vendors have already built out. So it is important to do your homework first in terms of the cloud vendors that are out there, evaluate them, discuss your requirements and go with one of them. Depending on your choice of technology, you might have to go with a vendor who provides that platform.

PaaS or IaaS

This article intentionally keeps aside SaaS (Software as a Service) since that can be done for your product in the cloud, but before that you need to get to the cloud. You can either take the IaaS (Infrastructure as a Service) or the PaaS (Platform as a Service) route. The IaaS vendors such as Amazon provide you computing resources: Virtual Machines, databases and processing in a pay as you use model. This is most flexible if all you want is a virtually available application for everyone to access. You will have to most likely build an image of your application and use a service such as Amazon to host it for you. The IaaS vendor will take care of all aspects like scalability and availability.

The other route to go is PaaS (Platform as a Service). These are specific to a technology platform and PaaS providers provide you a complete technology stack to develop and a scalable network where they will host the application for you. Key players in this area are Google App Engine (Java, Python), Heroku (Ruby on Rails), Azure (Microsoft .NET) and Force.com (a PaaS platform from Sales Force). Do keep in mind that each of them have different billing plans (typically pay as you use) and not all of your application can be ported as is to a specific PaaS. You will in all probability have to rewrite some parts of your application to fit the PaaS Technology and runtime stack that you go with. For e.g. Google App Engine provides core services like Caching, Task Scheduling, Networking, etc that might not be compatible with the way your current code is written. If moving to a PaaS, you need to evaluate each of your core system and infrastructural services/layers with respect to the Technology Stack that the PaaS provider gives you.

Databases

Most applications are still dependent on a relational database (SQL). The current opinion is that relational databases are not that suited to horizontal scaling at a large level. The movement towards noSQL databases has found widespread acceptance and it is something worthwhile to investigate into. Several PaaS vendors simply do not support SQL databases at this point in time (Google App Engine) and instead provide support for NoSQL databases. Several NoSQL databases like Google Big Table, MongoDB, Voldemort, etc are gaining acceptance. The database layer is therefore something that you need to pay close attention to as you move to the cloud since it would impact the architecture/design of that layer.

Abstraction

A cloud in its purest sense stands for abstraction. You are more interested in the interfaces and service contracts rather that the details about the implementation. The same philosophy applies to your product architecture and functionality as it moves to the cloud. You need to abstract significant portions of your application and service enable them to be accessible using open technologies like HTTP, XML and JSON.

Versioning in the Cloud

Your product will go through several iterations or versions. Each new version will come with its new set of features. There is a good chance that the versions would be incompatible with each other and yet they need to be running and supported till end of life. The impact of this on your architecture will be the need to build in versioning in all aspects of your product. All Interfaces to the outside world vis-à-vis integration points will need to incorporate versioning.

Session/Cache Management

Scalable cloud architectures rely on multiple instances of your application running across clusters that could be geographically distant. The cloud provider takes care of all this for you. The architectural impact of this will require that you take a good look at how you manage sessions in your product. An overreliance on sessions and expecting that the request will be forwarded to the same server that serviced the original request could result in problems. You will also need to employ Cache architectures in your product to allow for scaling.

Management

Moving to the cloud requires that you provide new features in your product vis-à-vis managing the product. You will also need tools to help building, deploying and monitoring your product in the cloud. Some of these are:

  • Keeping a track of resource usage that your application consumes
  • Tools to provision a new instance or multiple instances of your application in case of increased load
  • Mechanism to send out Alerts in case of System downtime
  • New tools for building/deploying to the cloud
  • A comprehensive dashboard that allows to do all the above along with access logs.

Economics

There are enough technical reasons why one should move to the cloud. Given the choices that are out there, you would be able to look at the pros and cons. A final point is about the economics part of the process too. At the end of the day, it should make economic sense to moving the product to the cloud. Business models that incorporate the cloud are being demanded. It would also help to determine how much it is going to cost to move to the cloud in terms of servers, resources, etc. Different payment plans are available and most cloud vendors provide a free quota along with plans that charge you only if you use resources. A quick check would be to analyze your current traffic, taking into consideration peak days and numbers and determine the approximate cost of moving to a cloud.

Conclusion

The above are high level architectural factors to take into consideration while moving to the cloud. Each of them can be broken down into fine grained points but these high level items should form the basis of a good discussion/strategy before moving to the cloud.

01
Jul

In this blog, we will look at various factors to be considered while  designing Public APIs

The web has moved from its image of hosting web applications to that of a platform. A platform is primarily, a set of building blocks that you can combine in innovative ways to build your own application. One of the key factors that have driven the web towards the “platform” avatar has been the emergence of a large number of Public APIs based on Open Standards. A Public API in simple terms is exposing key pieces of your application for the consumption of other applications.

A Public API is an important piece of any web application today. Over the last 5 years, public APIs have proliferated and everyone from the big companies to the newest startup bets big on a public API. According to the premier API tracking site, The Programmable Web (http://www.programmableweb.com), there are currently 2033 APIs available for applications today [dated 21st June 2010]

What can we do with the Public APIs? Here are some of them:

  1. You can integrate a best of class functionality that is already being exposed by the Public API. For e.g. if you need to integrate Maps, simply integrate the Google Maps API. You do not need to reinvent the wheel.
  2. You can provide a complete different user experience (interface) to an existing service.
  3. You can utilize the Public API in a larger mashup that you are creating.
  4. You can create applications running on devices that the current provider of the Public API does not address. For e.g. you could write mobile applications running on the iPhone, Android, etc – which the Public API provider does not even provide.

Now that we have discussed some of the points about what one can do with a Public API, here are some points about potential benefits that a public API brings to your existing application.

A Public API gives access to your platform to a huge number of programmers/applications.

  1. Using open standards, they are able to build out applications using your API in ways that even the creators of the API could not have envisioned. And since the public APIs are usually built on Open Standards, they are integrated into a wide range of applications that run on hardware ranging from desktops to mobiles.
  2. In the current market scenario, programmers do not want to build something that is already exposed by the publicly available API and if the API is backed by a scalable and high available environment, they will adopt it.

This article now builds on the premise that you are convinced that a public API will help your already available service. The article now discusses important points that you must consider before you embark on coding out the public API. Each of these points focuses on a theme rather than the implementation details and they are listed in no particular order of importance.

  • REST v/s Web Services (SOAP)

These are the two predominant models of invoking your API: REST and Web Service. REST is being preferred by most applications today, primarily because of its simplicity and implicit mapping to operations like GET, PUT, POST, etc. It is fair enough to say at this point that you should expose your services via the REST way, even if you have a Web Services (SOAP) mechanism of exposing your services.

  • Response Data Format (XML, JSON)

Every API call results in data being returned to the calling application. The data could be a result contains data records or in case of update APIs, simply a response text indicating “success” or “failure”. Two formats are predominant here: XML and JSON format. Your API should be flexible that it will allow the caller to specify which format they would like the data response to be sent back. Several APIs of late have been adopting only JSON as the supported data format. The best option over here at this point in time should be to support both if possible.

  • Service Contract Description

A Service Contract of your API is extremely important. It clearly defines what features your public API provides. This includes:

  1. The different Services and their names
  2. How they are accessible
  3. Authentication mechanisms
  4. Method signature for each method in a Service
  5. Description of each parameter in a method

It is important that you take small steps in the initial release of your API. Do not expose all functionality at once. A preferred approach might be to expose a read-only API that first gives users access to your data and then introduce write-methods that allow users to save their information. Introduce newer methods/functionalities in later versions but release a fairly compact Service Contract in your initial versions. It will help you identify the chinks early enough and help to refactor the existing Service Contact and introduce newer ones.

  • API Authentication

One need not stress enough about how important it is to make your public API secure. You only want authenticated users to access your public API. There are various strategies and authentication/authorization standards emerging for you to begin with. The most common approach is to issue a API Key for any application that wants to use your public API. This API Key is provided on signing up and is to be provided with every request to your API by the calling application. You can then authenticate the key and also determine if the call is within acceptable Rate Limits (this is covered in a point later) that you have set per API Key.

An authentication standard OAuth is gaining widespread acceptance as a preferred way to allow users to first validate themselves with the Service Providers and then pass a token to the calling application that they have been validated. This removes the need for the calling application to store your users’ username/password with them. A large number of popular public APIs like Twitter have adopted this standard and you should have it on your radar.

  • Service Versioning

As your service evolves, the public API could also change to match the new features. You need to make sure that you do not break existing clients who have already binded to your existing public API. Enter versioning! Think about versioning your public API right from the first release. If you are using a REST like mechanism that inserting a version number like 1 or v1 might be a good start. With each version, specify clearly what is different, what the additional features are, etc.

  • Rate Limits

All public APIs should be free to exercise to increase their adoption in the initial phase. Unless you strongly feel that you need to have a paid public API right from Day 1, you should definitely make the public API free to use. However, it is important for it to make business sense at the end of the day. After all, computing resources do cost. An approach typically used by almost all companies is to build in Rate Limits (or Quota Limits) into their public API. Some examples include:

  1. 10,000 calls per day
  2. 1000 calls per hour
  3. 1 GB Free total disk space (This is required in scenarios where you also persist the objects in your cloud as part of the public API)

The rate limits are typically reset at regular intervals like an hour, daily, etc. In certain cases, where you also provide storage space, the disk space quota is fixed at an upper limit and is not typically reset.

No matter what your functionality is, defining the rate limits is important because you will need to build checks in your public API infrastructure.

At the same time, there is a clear possibility that if your application and consequently your public API, is huge successful, then there will be applications which will easily go past your rate limits. That is a good problem to solve. In those scenarios (and you should expect them), you need to think about any of two approaches:

  1. Selectively increase the rate limits for a particular application. You will first need to discuss the requirements with the original creators of the application.
  2. Provide a paid option, where the application buys the increased limit either in tiers that you have set up or on a pay-as-you-go service. The pay-as-you-go service is generally preferred because you may not get the high spikes every single day.
  • Documentation
    It is important to support your public API with strong documentation. Pay attention to every aspect of the documentation. At the minimum, you must document the following clearly:

    1. End Points for different Architectural Styles (REST,WS) along with versioning.
    2. Define all services, methods (actions) and their parameters
    3. Provide sample request / response data formats for each method(action) in your service
    4. Document the error scenarios clearly along with Server side status codes

The best way to get started in documentation is to look at the documentation of existing public APIs. Pick one that suits you and stick to it. Several public APIs even have a RSS Feed about their API documentation to inform about any changes.

  • Helper Libraries

It is important to envelop your REST/Web Service calls into easy to use helper libraries. Helper Libraries target a number of client programming languages/platforms like Java, Python, Ruby, Javascript, .NET, etc. A Helper library gives a quick starting point to get someone exercising your public API within minutes or hours. A Helper library should address the following (recommended):

  1. Envelope the security calls (Authorization)
  2. Envelope the REST/WS calls and Data Format (XML, JSON) parsing.
  3. Optionally, return the results in Classes defined in the target high level language. For e.g. Java classes, etc.
  • Dedicated Public API Web page/site

It is strongly recommended to have a companion web site for your Public API. This companion website can serve as a one stop destination for all documentation related to your public API. It can also provide information like:

  1. Signing up for the API and getting issued an API Key
  2. Showcase applications / case studies of how people have used  your public API
  3. List official Helper libraries and contributed Helper libraries that make it easier to use your API.
  4. An API forum where users discuss your API and which your API support engineers can regularly monitor
  5. RSS Feeds that allow people to subscribe to API updates. Providing a “Sign up” for email updates to notify users is also recommended.

I hope this article gives a broad framework about the high level factors that you can consider your Public API release to support. Designing and Development can then commence much more smoothly. There are many other small details to consider, so please share your additional points in the comments for the benefit of all.

References

  1. ProgrammableWeb (http://www.programmableweb.com)
  2. Open APIs: State of the Market, May 2010. John Musser (http://www.slideshare.net/jmusser/pw-glue-conmay2010)
  3. OAuth Protocol Site : http://oauth.net/