Archive for July, 2010
30
Jul

Animation is the illusion of movement created by a rapid display of a sequence of images. Scientifically, this occurs due to the persistence of vision experienced by the eye. The most common and everyday example of animation is a video program.

3D animation came into existence with advancements in computing software and technology. 3D animation creates graphics using a 3D representation of 2D geometric data stored in a computer.

Examples of 3D graphics or animation would be cartoon films and 3D models used in engineering and architecture.

How Does Animation Work

The basic principle of animation is the same for all media – displaying a rapid sequence of images which are slightly different than each other creating the illusion of movement before the eye.

However, this is how regular, 2D animation is created (or rather, was created until a few years ago). Nowadays, for both creating 2D as well as 3D animation, computer software from several vendors such as Adobe, Xara, Strata and Corel are available.

The Thaumatrope was one of the earliest devices designed to understand the persistence of vision (Source: http://www.aranpa.com)

Thaumatrope

Thaumatrope

The various steps involved in generating 3D animation are described next.

Concepts and Storyboarding

Storyboarding is the process of creating a visual representation of the actual screenplay of the animation’s story. It basically consists of a series of illustrations or images presented in a sequence for pre-visualizing an animation. It is usually an intricate and tedious process as it is supposed to visually convey the actual story of the animation.

Modeling

3D modeling is usually done using specialized computer software and involves developing a mathematical model of any surface of a three dimensional object. This is actually done using 2D images of the object using a process called 3D rendering. Models may be created automatically or manually; the latter is usually done by an artist and is similar to sculpting. An example of a computerized 3D model of a human head is shown next. (Source: http://pabs.us/graphictutorials/wp-content)

3D model of a human head

3D model of a human head

Layout

To render objects on the media being used, they must first be placed within a scene, a process known as layout. In this process, the physical and spatial interrelations between the objects contained in a scene are first decided. Next, several techniques such as motion capturing and keyframing are used to capture their movement and deformation over time.

Just as in modeling, layout may also involve physical movement of the objects in the scene, similar to sculpting. An example of the use of layout is shown below in a promotional poster for the film ‘Shrek’.

Layout

Layout

Positioning the Cameras and Lighting

For the scene to provide a realistic feel to the viewer, the lights and cameras must be positioned correctly. This ensures that minor details, such as shadows, also appear authentic in the final results. As an example, the following image shows the results of correctly positioning the cameras and lights in the making of a promotional poster for the Ford Focus car. (Source: http://www.leblogauto.com/images/focus_cc2.jpg)

Positioning the Cameras and Lighting

Positioning the Cameras and Lighting

Rendering

This is usually the last step in creating the illusion of motion between the objects in the scene. This step also involves complex interaction of different light sources of varying intensities and positioned at different places to get the desired effects in the scene.

This step is most commonly performed using 3D computer software. A technique known as 3D projection, which allows a 3D image or object to be viewed in 2 dimensions is also used in the process of rendering.

Visual Effects (VFX)

Visual effects are the combination of various processes in which live action footage is combined with computer generated static imagery. It is used to create realistic looking environments which may be costly or dangerous to create artificially and then capture on film.

Visual effects are most commonly part of a film’s post-production, and have now become accessible to amateur filmmakers with affordable animation software.

An example of visual effects is the use of Computer Generated Imagery or CGI, which consists of developing scenes, first shot with real actors and then processed using computer software to render a computerized 3D equivalent of that scene, as shown in the image below from the movie ‘Avatar’ (Source: http://images2.fanpop.com)

Computer Generated Imagery

Computer Generated Imagery

In summary, we have seen in this blog that 3D animation involves several steps, starting from the concept right up to post-production with each of these steps involving technical as well as creative expertise in equal measures. Thankfully, advances in technology have made this field simpler and more productive for the professionals, and within reach for the amateurs.

Amit Sheth
Amit Sheth– Sr. Technical Writer

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.

Romin Irani
Romin Irani– Principal Architect

22
Jul

Almost everyone today must have seen science-fiction and action movies with hi-tech special effects. These effects are a culmination of not only the developments in computer science and technology in the last two decades, but also the accompanying developments in computer animation and graphics technologies.

In this blog we take a tour of the world of computer graphics and special effects and see the types of effects that are in use today as well as some behind-the-scenes action that goes into making these scenes appear as real as they do on the screens.

What are special effects?

Special effects are a combination of detailed art and high-level technology. It consists of understanding how human begins perceive the world through sound and visual sensory parts of their body and their brain.

Persistence of Vision: When a related sequence of still images is passed at a particular speed (minimum 15 frames/sec.) in front of human eye, the human brain perceives it as a single image with motion, i.e., it perceives the second, third images as a continuation of the first image. This is because a human’s nerve impulses are slow as compared to speed of light.

Principle of Motion Pictures: Persistence of vision of the human eye is the principle behind motion pictures in which camera, lights, audio, computer generated objects (CG) and other visual media are employed to exploit this phenomenon.

What is motion: Motion of an object is the continuous displacement of the object in space with reference to another object. This phenomenon forms the basis for compositing technology.

Types of special effects:

Computer Effects:

Some of the popular computer generated special effects are:

  • A complete blue or green screen
  • Computer animations or cartoon films
  • Compositing
  • Morphing/Warping

Humanized Effects:

These are some of the effects generated by a computer and used in films:

  • Use of Latex
  • Creating the illusion of rain, snow, wind and fire
  • Showing realistic on-screen blood bags/bullet hits
  • Explosions
Computer Effects:

These are effects generated with the help of computer technologies. Some of these effects are as follows:

Showing a complete blue/green screen: In this technique, a blue/green background screen is used in a scene. This scene is then made to overlap on another and the blue/green colored background removed with the help of compositing software’s. This technique needs a special kind of compositing, where the mask is calculated from the foreground image.

Below is an excellent example of action photo compositing, sometimes referred to as transitional photography (source: http://www.photosfan.com).

Photo compositing

Photo compositing

Computer Animation: For generating computer animations, real footage is first shot and is then converted to animation using compositing software. A good example of this technique would be Gollum, a computer generated character in the movie ‘The Lords of the Rings’.

Cartoons Frames: For displaying real characters with cartoons, cartoon character is used with real footages. The best example of this technique is the movie ‘SpaceJam’ (shown below, source: http://animatedviews.com/)

Cartoon Frames

Cartoon Frames

Using Physical Models for Animation: In this technique, a physical model (mechanical robot) is used to depict the character on screen. Good examples of this technique would be the films ‘Jurassic Park’, ‘Godzilla’ etc

Morphing: This is a special-effects technique that creates a smooth, controlled transformation of one image, character or movie into another.

Morphing

Morphing

The figure above shows the morphing of a person’s face to that of a tiger (source: http://www.blorge.com)

Warping: Warping is also the same as morphing, except that it uses only one image or movie. An example of warping created using Adobe Photoshop is shown below.

Humanized Effects:

These are effects which are generated manually. They are generated as follows:

Using latex: Latex is a material used in commercial make-ups. It can add scars on faces, extra eyes on ‘monster’ heads, and can also make young people look old and vice versa. A good example of this would be the movies ‘The Nutty Professor’ (as below), ‘Lord of the Rings’ etc.

Rain: Computer generated rain makes it difficult to give the realistic look and feel of real rain since it does not wet the actors’ clothes. Hence, film makers arrange for artificially created rain-like effects.

Snow: Snow machines are available which help in creating snow for the shots.

Wind: Production staff uses large fans and high speed blowers to create good wind effects.

Fire: For creating massive fires, experts are called, who create huge fire shots with fire machines, and which can easily be turned on for massive fire scenes, as well as off just be pressing a button.

Blood bags/bullet hits: The blood bursting out from a person in the movies is achieved by a small, battery-triggered explosive charge, causing a blood-filled bag to burst out. A small, 9V battery is used to burst a squib (fireworks consisting of a tube filled with powder that burns with a fizzing noise), which has to place under the character’s costume.

Explosions: At times when computer generated explosions are not effective, and for realistic looks, a pyrotechnic machine is used to achieve the explosive effects.

Technology used to create special effects (Software):

The following are some of the software used to create special effects:

  • Autodesk Combustion
  • Autodesk Inferno
  • Autodesk Flame
  • Autodesk Flint
  • Adobe After Effects
  • Digital Fusion
  • Elastic Reality
  • Boris FX
  • Hollywod FX

In summary, we have seen in this blog post that advancements in special effects have revolutionized entertainment and have made movies seem life-like. This may just be the beginning of special effects in movies; the best is yet to come.

20
Jul

The concept of retrieving location information using GPS device and Location API is already discussed in one of the earlier post (http://www.xoriant.com/blog/mobile-application-development/location-based-programming.html ). In this article we are going to learn to use of Blackberry’s Location API and work with geocoding and reverse geocoding. Though, Geocoding and reverse Geocoding information could be used in multiple applications, a majority of applications will need to integrate the location information and display that on a Map.

To start with, let me introduce some terms:

Geocoding: is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). With geographic coordinates, the features can be mapped and entered into Geographic Information Systems, or the coordinates can be embedded into media such as digital photographs via geotagging.

Reverse Geocoding: is the process of back (reverse) coding of a point location (latitude, longitude) to a readable address or place name. This permits the identification of nearby street addresses, places, and/or real subdivisions such as neighborhoods, county, state, or country. Combined with geocoding and routing services, reverse geocoding is a critical component of mobile location-based services to convert a coordinate obtained by GPS to a readable street address which is easier to understand by the end user.

Before we see the code part, let us look at the BlackBerry API (Locator) that facilitates the application to gain access to geospatial coordinates for an address and vice-versa i.e.  retrieve a street address for given coordinates in case of reverse geocoding.

Locator is a Geocoding service in BlackBerry that allows you to obtain location address for an address. This service has static method “geocode”, “reverseGeocode” and as it should be obvious by now, geocode require address and returns coordinates, reverseGeocode require coordinates and returns the address information.

There are few things to keep in mind while Locator is used in the application

  1. LBS Map API is a pre-requisite for Locator API to work. Application may throw exception if the LS MAP API is not installed.
  2. Call to geocode is synchronous in nature. And at any given time there should be one call made using the Locator class. Application may throw exception if more than one call is made.
  3. Call to geocode and reverseGeocode should be made outside the event dispatch thread. Requests to these methods that are made on the event dispatch thread are denied and result in an exception.

Let us look how to use the Locator API to retrieve geospatial coordinates for an address using geocode.

  • Packages required
import net.rim.device.api.lbs.*;
import javax.microedition.location.*;
  • Create a class and constructor
public class myGeocode
{
public myGeocode()
{

}
}
  • Create a private Thread variable
private Thread geocoder;
  • In constructor, create instance of the Thread class. As mentioned earlier, geocode cannot be performed on the application’s primary thread.
geocoder = new Thread(thread);
geocoder.setPriority(Thread.MIN_PRIORITY);
geocoder.start();
  • In the class, create a Thread that invokdes a public run() method.
Runnable thread = new Runnable() {

public void run() {

AddressInfo addrInfo = new AddressInfo();

addrInfo.setField(AddressInfo.STREET, "Whitewood Dr");

addrInfo.setField(AddressInfo.CITY, "San Jose");

addrInfo.setField(AddressInfo.STATE, "California");

addrInfo.setField(AddressInfo.POSTAL_CODE, "95110");

addrInfo.setField(AddressInfo.COUNTRY, "US");

Coordinates startCoords = new Coordinates(37.386087,-121.889244, Float.NaN);

try {

Landmark[] results = Locator.geocode(addrInfo, startCoords);

}

catch ( LocatorException lex ) {

//thrown when The BlackBerry device is not sufficiently connected to send or receive over any transport.

}

catch (MapServiceException mex) {

// if the LBS Map API is not installed on a BlackBerry device or if an application makes more than one request at a time.

}

catch (IllegalThreadStateException itex) {

// if a request is made on the event dispatch thread

}

catch(IllegalStateException isex) {

// if there is no valid radio/wi-fi connection to send the request to

}

}

};
  • The new two classes used above AddressInfo and Landmark, they allow application to pass formatted address object. However, overloaded geocode also accept “String” (e.g. Whitewood Dr, San Jose, Santa Clara, California 95110). This should also work and return the array of Landmark, the first array element contains the most relevant Landmark to the locator request. May be null if geocode request is cancelled or the request fails.
  • startCoords are for hint to the geocode for starting the search specified in the request. This could also be null.
  • Using the same class structure, let us see how to get the address info using coordinates.
Runnable thread = new Runnable() {

public void run() {

AddressInfo addrInfo = null;

int latitude = (int)(45.423488 * 100000);

int longitude = (int)(-80.32480 * 100000);

try {

Landmark[] results = Locator.reverseGeocode

(latitude, longitude, Locator.ADDRESS );

if ( results != null && results.length > 0 )

addrInfo = results[0].getAddressInfo();

} catch ( LocatorException lex ) {

//do something

}

}

};
  • Pass one of the following parameters to Locator.reverseGeocode():
    • Locator.ADDRESS: requests the nearest address or nearest street to the specified latitude/longitude
    • Locator.CITY: returns a value that is focused on the city level Development Guide Retrieve an address by using reverse geocoding 44
    • Locator.COUNTRY: returns a value that is focused on the country level
    • Locator.PROVINCE_STATE: returns a value that is focused on the province or state level

Now, we’ve seen how to use the Locator API to get geospatial and address information. When we talk about coordinates, the next thing that comes to mind is how the same code can be extended to show the location on a map.

Well, BlackBerry also has a Map API that allows us to extend the above example and use the information as is i.e. to plot the address point on a map.

  • Package required
import net.rim.blackberry.api.invoke.*;
import net.rim.blackberry.api.maps.*;
  • Maps is an inbuilt application in BlackBerry. This eliminates the user from writing core Map logic like displaying images, , calling Google Maps API and rendering the image in the application. All we have to do is invoke the external application (external to your application).
  • Create class and constructor
public class showMap {
public showMap ()
{
}
}
  • In constructor create an instance of MapView
MapView mapView = new MapView();
mapView.setLatitude(4328915);
mapView.setLongitude(-8032480);
mapView.setZoom(10);
  • In the constructor, create an instance of the MapsArguments class using the MapView object as an argument. Invoke Invoke.invokeApplication() to open BlackBerry Maps and pass in the MapsArguments object.
MapsArguments mapsArgs = new MapsArguments(mapView);
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs);

Or you can also use the Lankmark object return by Locator.geocode

MapsArguments mapsArgs = new MapsArguments(results);
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs)

Location Based applications that incorporate maps are everywhere. The BlackBerry platform allows you to incorporate both location information and merge that into maps as we have seen in the blog post. It is important to note that the BlackBerry platform provide additional ways of showing a map using different inputs. You can also embed the map  within the application. What I have covered here are the basics and hope that this article highlights the important nuances that could be useful for developers to try things quickly and then extend the same by building more complex applications.

Pawan Sachdeva
Pawan Sachdeva– Technical Architect

15
Jul

This blog post introduces one of the important mechanism of Async Task for Android with sample code.

Android implements single thread model and whenever an Android application is launched, a thread is created. Now assume you have long running operations like a network call on a button click in your application. On button click a request would be made to the server and response will be awaited. Now due to the single thread model of Android, till the time response is awaited your UI screen hangs or in other words, it is non-responsive.

We can overcome this by creating a new Thread and implement the run method to perform the time consuming operation, so that the UI remains responsive.

As shown below a new Thread is created in onClick method

public void onClick(View v) {
    Thread t = new Thread(){
    public void run(){
	// Long running operation
	  }
   };
   t.start();
}

But since Android follows single thread model and Android UI toolkit is not thread safe, so if there is a need to make some change to the UI based on the result of the operation performed, then this approach may lead some issues.

There are various approaches via which control can be given back to UI thread (Main thread running the application). Handler approach is one among the various approaches.

Handler

Let us look at the code snippet below to understand Handler approach.

public void onClick(View v) {
   Thread t = new Thread(){
	public void run(){
   	   // Long time comsuming operation
	 	Message myMessage=new Message();
		Bundle resBundle = new Bundle();
		resBundle.putString("status", "SUCCESS");
		myMessage.obj=resBundle;
		handler.sendMessage(myMessage);
	}
  };
  t.start();
}

As seen we have modified the original run method and added code to create Message object, which is then passed as parameter to sendMessage method of Handler. Now let us look at the Handler. Note that the code below is present in the main activity code.

private Handler handler = new Handler() {
@Override
	public void handleMessage(Message msg) {
		// Code to process the response and update UI.
	}
};

After the execution of long running operation, the result is set in Message and passed to sendMessage of handler. Handle will extract the response from Message and will process and accordingly update the UI. Since Handler is part of main activity, UI thread will be responsible for updating the UI.

Handler approach works fine, but with increasing number of long operations, Thread needs to be created,  run method needs to be implemented and Handler needs to be created. This can be a bit cumbersome. The Android framework has identified this pattern and has nicely enveloped it into what is called an Android Async Task. Let us look at how it can help simplify things.

Async Task

Android Async Task takes cares of thread management and is the recommended mechanism for performing long running operations.

Let us look at a sample class LongOperation, which extends the AsyncTask below:

private class LongOperation extends AsyncTask<String, Void, String> {

	@Override
	protected String doInBackground(String... params) {
		// perform long running operation operation
		return null;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		// execution of result of Long time consuming operation
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
	// Things to be done before execution of long running operation. For example showing ProgessDialog
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	 */
	@Override
	protected void onProgressUpdate(Void... values) {
      // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
	 }
}

Modify the onClick method as shown below:

public void onClick(View v) {
new LongOperation().execute("");
}

As seen class LongOperation extends AsyncTask and implements 4 methods:

  1. doInBackground: Code performing long running operation goes in this method.  When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
  2. onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  3. onPreExecute: This method is called before doInBackground method is called.
  4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.

Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.

Points to remember:

  1. Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.
  2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.
  3. Task can be executed only once.

Hope this blog helped you understand Android async task and why it is important in Android application development.

Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.

14
Jul

Gone are the days when a simple browser was more than enough for our daily browsing tasks. As the Web has evolved, our demands from a Web browser have also increased. To leverage the maximum out of a browser, plug-ins or add-ons were designed. Let us understand these add-ons & the important points to consider while designing its test plan

Understanding add-ons

Add-ons, also known as plugins, extensions, helper objects, or toolbars, are a set of software components that adds specific capabilities to a larger software application. In case of a Web browser, an add-on can add significant value to your browsing experience by providing various features to extend the functionality of the browser. Examples of such features would be the ability to play streaming audio/video, scanning files or folders for viruses and viewing new file types.

The added toolbars may also provide helpful and useful functionality such as blocking pop-ups, managing bookmarks and passwords, performing searches across multiple search engines, automatically filling out online forms, playing multimedia and animations etc.

This blog is intended to present an overview of the important items to be considered while preparing a test plan for such browser toolbars.

The following screenshot shows three popular toolbars – Yahoo!, ZoneAlarm and Softonic – integrated in the IE browser.

toolbar - plugin

Strategy to design a test plan for the add-ons

Since a toolbar would have a large, global user base with a variety of system configurations, we need to strictly keep the end-user in context while preparing the test plan for the add-ons.

In this blog, we will walk through the most important testing phases which are a mandatory part of the master test plan for any browser add-on.

1. Installation Testing

The installation testing phase starts from testing the very first window shown to the user in the installation process. The entire installation process should be quick and informative and to achieve this, specific test cases need to be added to the installation testing phase to cover the following aspects of the installation process:

  1. User interface and installation steps: Should be kept short and informative.
  2. Cancellation of installation from any step in the process: Installation should abort in a stable manner with proper cleanups.
  3. Verification of installation: Making sure the required files are deployed correctly and the application footprints are added to the required places in the browser, start-up etc.
  4. Performing a proper cleanup in case of an aborted installation.

The installation process has to be tested thoroughly on different machines with different system configurations. Properly designed add-ons are generally supported by common operating systems such as Windows and Linux, and browsers such as IE and Mozilla Firefox.

By default, the add-ons are usually installed in pre-defined directories. Testing these installation directories for the add-on files also comes under the purview of installation testing. For example, the following is the installation directory for toolbar applications when using IE:


C:\Program Files\Toolbar_Application

Similarly, Firefox add-ons are usually installed in the following directory on Windows:

C:\Documents and Settings\<UserName>\Application
Data\Mozilla\Firefox\Profiles\fpt8dilh.default\
extensions\<Toolbar_Application_id>

Toolbar add-ons use the registry and/or configuration files to save local settings. These add-ons may also use browser cookies and cache files. Hence, it may be necessary to clear the cache and delete the cookies before testing begins.

2. Compatibility Testing

The toolbar’s user base may be very wide with a variety of OSes, browsers, configurations, display resolutions, and Internet connection speeds and hence, all these factors can impact the behavior of the add-on and introduce compatibility problems. Hence, compatibility testing is a major area of importance.

For compatibility testing, one can either set up a physical test lab with various machines, or use virtualization software (such as VMware) to perform the test.

The following items need to be considered when planning for compatibility testing:

  • Platform Testing: Testing across various operating systems and browsers. Platform testing for IE and Firefox browsers should include the following:
    • Compatibility testing across operating system versions (such as Windows XP, Vista, Windows 7 etc).
    • Compatibility with major browsers (such as IE and Firefox).
    • Testing under different screen resolutions.

Users should have the same visual experience irrespective of the browsers they are using. Also, in terms of functionality, the application must behave and respond in the same way across different browsers, OSes and screen resolutions.

  • Testing with important operating system settings:
    • UAC (User Access Control): UAC is a security feature available with OSes starting with Windows Vista, such as Windows 7 and Windows Server 2008. UAC limits a standard user’s privileges to application software until an administrator authorizes an elevation. The add-on should be tested with various types of system users to make sure it works fine for all users of different groups that it is installed/available for.
    • DEP (Data Execution Prevention): DEP helps protect the system from viruses and other security threats. The end user may have this setting ON or OFF, due to which, the add-on may behave differently or may crash and hence, testing with DEP ON and OFF is required to be added to the test plan.
    • Protected Mode: This is a security measure added to IE 7 and later browsers to control how objects interact with each other to make surfing the Web safer.
  • Theme testing: The appearance of the toolbar has to be tested across various themes supported by the operating system. Windows XP and Vista have two main themes – Basic and Classic, whereas Windows 7 includes multiple themes.

  • Testing with already installed popular add-ons/toolbars: It is likely that the end user would already have several add-ons installed on his/her browser. Some of them may be of the same domain/type and offer similar features and may conflict with your add-on. Hence, it is advisable to add this test case in your test plan.
  • Testing with Firefox profiles: If your add-on supports Mozilla Firefox, then testing with Firefox’s profiles is needed. In Firefox, one can create more than one profile and the add-on can be installed in all or any specific profile.

3. Performance Testing: In performance testing, some technical parameters of the add-on are tested against defined benchmarks. A few of these parameters are listed below:

  • Browser load time.
  • Web page load time.
  • Add-on response time.
  • Web-services (if used).
  • Memory usage.
  • Resource uses (GDI count).

4. Functional Testing: Functional testing of any software or application includes testing carried out to satisfy the business requirements given in the application’s specification document. In this case, the functional testing is very specific to the toolbar and needs to be planned according to its requirement documents.

Plan for compatibility with updated OS and browser versions

All major browsers and their supported operating systems provide regular updates and hence, it is necessary to see if your add-on works correctly with the updated versions.

For this, it is required to set up a process to track the upcoming alpha/beta/RC versions of browsers and operating systems that your toolbar supports. To keep the add-on up-to-date with upcoming versions of browsers/OSes, it is required to start the testing cycle with their early alpha/beta releases to identify issues at early stages. This will make sure that the add-on is ready to support new versions of the browser/OS at the time of release.

This is what we cover in this post, check this space for more updates.

Manisha P
Manisha P– Member of Xoriant QA Center of Excellence

12
Jul

This blog will focus on the best practices to be followed for Internationalization & Localization testing of web based applications.

Introduction

Internationalization testing is the process of testing software which is supposed to work uniformly across multiple regions and cultures. There are two of the major aspects of international software – world readiness (globalization) and localization. World readiness refers to the process of designing, coding and testing the product such that it can be easily localized for different regions. Localization involves translating and customizing the product for different regions.

Ensuring world readiness is different from testing localized versions of the product, and it is broader than just testing the functionality. It also includes realizing the implications of globalization, and verifying that those implicit requirements are met throughout all the design and development steps.

Internationalization testing

The goal of Internationalization testing is to detect potential problems in software globalization. It makes sure that the code can handle all international support without breaking functionality that would cause either data loss or display problems. Globalization testing checks proper functionality of the product with any of the locale settings using every type of international input possible. There are two basic testing requirements which ensure that the product works well in all regions for which it was developed:

  • Testing to check if the product is locale aware (globalization).
  • Testing the localized versions of the product.

The following diagram depicts the breakdown of the product with respect to internationalization and localization testing:

Internationalization testing

Best Practices in Internationalization Testing

  • Feature based Testing

The product may be marketed with some features applicable and others not applicable to specific cultures. While testing, it is important to ensure that these features are turned on or off as required while switching locales.

  • Testing for Localized content

Localized content includes both text and graphic artifacts on the user interface. Textual content to be localized includes the static text on controls such as menus, buttons, etc. and user specific messages. Language experts are required for testing the localized content in each language that the product supports.

  • Testing for culture awareness

User locale settings define items such as number, date and currency formatting. Input locales should be handled and the user be allowed to input data in that language.

In many cases, data would need to be converted from one encoding format to another. Correct handling and understanding of encoding formats is required in such cases. If coded incorrectly, in addition to operational errors, it can also result in loss of data. For example, converting from a multi-byte character set to a single or double-byte character set can result in data loss if not handled properly. User locales do not impact conversion of data from one encoding format to another.

  • Testing rendering

Internationalization testing should check whether an internationalized product properly displays all supported scripts in accordance with the linguistic characteristics associated with them. The characteristics include bi-directionality, character reordering, contextual shaping, combining characters and special rules in terms of word breaking, line breaking and text justification.

  • Testing user interface

Internationalization testing should cover whether the user interface, on which the fonts are rendered, supports the different fonts and character widths as well as the varying spacing requirements introduced by translation. For example, it is a well known fact that German text occupies more space to convey the same information when compared to English. Thus, the user interface should be adaptable to accommodate user messages in both languages.

Following are the recommended guidelines for user interface testing:

  1. Check if textbox labels appear on top of the textboxes in order to handle text with larger widths. If it is still required to have the label beside a textbox, enough room should be left for the text to grow.
  2. Check if dialog boxes expand while localizing. Additional space (ideally, 30%) should be left between the end of messages and the edge of dialog boxes for further expansion.
  3. Check the text embedded in images and icons. Having text in images will make localization difficult and require the efforts of a user interface designer/tester.
  4. Buttons and labels should have a larger width to accommodate for longer text in non-English languages.
  5. Images embedded within resource files of forms should be moved out as separate image files.
  6. Mirroring: Mirroring is the process of localizing the user interface to handle right to left (RTL) languages such as Arabic, Hebrew, Farsi, etc. To give a perfect RTL look and feel to an application’s UI, both the text and the UI elements need to be laid out from right to left once they are translated into RTL languages. A complete discussion on Mirroring is not within the scope of this paper.
  7. Graphical images: Graphics can be difficult and expensive to translate. Hence it is preferable to have graphics which are universally acceptable.
  8. Following are some of the key user interface elements that need to be localized:
    1. Menus
    2. Messages
    3. Dialog boxes
    4. Images
    5. Toolbars
    6. Status bar
  • Storage testing

Internationalization testing should also cover data storage and retrieval in multilingual applications, which warrants careful attention. The key sources of storage include files and databases.

  • Testing File Transactions

While reading from a file which contains Unicode characters, it is important to specify the encoding. If the encoding is not explicitly specified, a default encoding may be used (UTF-8 in case of .NET framework) resulting in misinterpretation of data. For example, if a text file stored in UTF-16 is read without specifying the encoding, .NET will interpret the UTF-16 characters as UTF-8 resulting in unintelligible input. Please note that ASCII and UTF-8 are interoperable if the file contains only English characters having code point less than 128

  • Database Testing

Testing should cover the support of Unicode characters in databases; special data types are used which are defined for this purpose. For example, SQL Server defines nchar, nvarchar and ntext data types to allow you to store Unicode text. (The n prefix for these data types comes from the SQL-92 standard for National (Unicode) data types). Use of nchar, nvarchar and ntext in SQL Server 2000 is the same as char, varchar, and text, respectively, except that:

  • Unicode supports a wider range of characters.
  • More disk space is needed to store Unicode characters.
  • The maximum size of nchar and nvarchar columns is 4000 characters and not 8000 characters as for char and varchar.

Unicode constants are specified with a leading N (for example, N<a Unicode string>). The following example shows how to insert Unicode values (Russian) into an nvarchar column.

Internationalization

Once you have defined a Unicode compatible column in the database, inserting and retrieving multilingual data is the same as working with regular (ASCII) data. In database migration, care should be taken while mapping the source and target data columns. If the source data type is nchar, and the target data type is char, data could be lost upon migration.

In summary, there are several aspects to be kept in mind while designing software for a global audience. These aspects cover not only coding and testing, but also the interface and layout of the software as well as factors such as the file formats and data encoding to be used.

Dada Mote
Dada Mote– Member of Xoriant QA Center of Excellence

09
Jul

Almost everyone today is aware of internet based companies such as Yahoo!, MSN and Google. These are sites concurrently handling several million visitors from across the globe every hour. Have you ever wondered about what goes into designing such high volume websites? This blog discusses the factors that need to be kept in mind while designing such portals.

There are several aspects to architecting high traffic web portals, which are expected to serve high concurrency with high availability and without degrading the performance. Apart from the architecture, other SDLC phases such as design, development and deployment also need special considerations. Since architecting the system is the very first step towards building the portal, this post will highlight some of the important architectural considerations.

To withstand the heavy traffic, the system should primarily be scalable, be highly available and should be able to intelligently delegate/distribute the traffic to improve the overall performance. Each of these aspects is discussed in turn below.

Scalability

Scalability is about concurrency and expandability. In the current context, it is related more to servers which are serving the application. Higher the capacity of the server, more the traffic it can serve. There are two types of scaling with their own pros and cons and it is a judgmental decision to choose which one (or even both, in combination) to go for depending on the expected traffic.

Vertical Scaling vs. Horizontal Scaling

Vertical Scaling: Also known as scaling up. This means adding more hardware resources in terms of number of processors, memory etc. to the existing server to cope up with increasing traffic. The ease of implementation of this method also comes with some disadvantages, such as:

  • Continuous upgrading of server is expensive.
  • There is always a limit for a given server to upgrade to.
  • If the server crashes, the application is not available.

Horizontal Scaling: Also known as scaling out. In this approach, instead of adding hardware resources to the existing server, extra server machines (maybe with comparatively lower capacity) are added to the pool. All the servers serve the same application. This is a cheaper approach since individual servers need not have very high end configuration. Additionally, even if one server crashes, the others in the cluster will still continue to serve the application. The only drawback is that it requires more administrative efforts in terms of configuring and monitoring the cluster.

High Availability

Backup Server

In this configuration, two servers are deployed for the same application. The primary server serves the application and the second server acts as a backup for the primary. If the primary server goes down for some reason, the backup server takes care of the user requests. There are two configurations possible with this:

Active-Standby: where the standby server is passive while the primary server is active. In case the primary server goes down, the current user sessions are not maintained when the backup server takes over.

Active-Active: In this case, the user sessions are maintained and are continued to be served by the backup server when the primary goes down.

Clustering

For very high traffic, the clustered approach (Horizontal Scaling), which ensures high availability of the application, is effective. With the clustered environment, the user gets a seamless experience. This kind of environment can be configured to maintain the user’s web sessions in case any of the servers go down. Most of today’s application servers provide clustering as an inbuilt feature. Using proper load balancing mechanisms in place, one can have different servers of different capacity in the same cluster.

Clustering

Performance

Performance refers to how efficiently a site responds to browser requests according to predefined benchmarks. The application performance can be designed, tuned, and measured. As said earlier, it can also be affected by many complex factors, including application design and construction, database connectivity, network capacity and bandwidth, back office services (such as mail, proxy, and security services), and hardware server resources. In the scope of this post, below are some of the considerations for performance while architecting the system.

Load Balancers

In a clustered environment, it may be possible that all the servers are not of the same capacity in terms of CPU, RAM, etc. Software load balancers are available which can enforce a policy on the site while distributing the load across the servers. The simplest policy could be of a “round robin” type where requests are passed sequentially to all servers, thus utilizing cycles of each server in the cluster. Some of these tools also allow configuring the rules for individual servers on the basis of its CPU capacity, RAM or current load on the server. For example, servers having low capacity would serve comparatively lesser number of requests to maintain the performance benchmarks.

Delegating the Traffic

While loading any web page, a browser sends several HTTP requests to the server to download associated content such as images, CSS and JavaScript files, video files etc., which are required to be rendered on the page. It is possible to distribute the implicit requests for this content across different servers to allow the main application server to serve the dynamic contents of the main page. Several techniques can be adopted to achieve this, as discussed next.

  • Proxy Web Server

This is a commonly used technique where the web server acts as a proxy to the application server. All the static content (such as images, CSS, JavaScript and video files) used by the site is deployed and served by the web server. Only relevant requests are forwarded to the application server, which reduces the direct load on the application server. These web servers can also form a cluster in front of the application server cluster.

  • Use of CDN

A content delivery network or content distribution network (CDN) is a system of computers placed at various geographical locations in a network so as to maximize bandwidth for access to the data from clients throughout the network. All the servers in the network deploy and serve the same content. A client accesses a copy of the data nearest to it, as opposed to all clients accessing the same central server, so as to avoid a bottleneck near that server. These systems implement routing algorithms such that the nearest server serves the request for the fastest delivery.

Various vendors in the market provide this service with a high quality, low cost and low network load. A CDN can offer 100% availability, even with large power, network or hardware outages.

Content distribution network

  • Third Party Storage Services

This approach refers to using third party services to store the data on their servers. These services help in reducing the initial investments in infrastructure. The storage space can be bought on demand. Generally, these services are used to store contents uploaded by users.

There are services such as Amazon S3 which provide online storage through a simple web services interface at a very nominal cost to store and retrieve the contents.

Although this approach is generally useful in reducing the hardware cost, it can also help in performance improvements in this context. Since the contents are stored on third party servers and are also available as URI, the overall load on the main server is reduced to some extent.

Conclusion

In summary, some of the important architectural considerations for designing high traffic web sites and portals have been discussed in this blog. There are also several other factors at different phases of the design which need to be considered to achieve good concurrency and performance.


Ajit Mahajani
Ajit Mahajani– Technical Architect

07
Jul

A BlackBerry phone is primarily a business phone with additional features like Email, Phone, Maps, GPS, Organizer, Social Networking and games. Developers can take advantage of various BlackBerry APIs to take the user experience to a new level. In this article, I am going to talk about BlackBerry and Location API,that allows you to develop Location based (LB) applications.

Compatibility

BlackBerry is packed with advanced features, but they are not supported in all models. Let us quickly have a glance at some of the models.

In general there are two options for using GPS with a BlackBerry. You either have a device with an internal GPS receiver, or you will need an external Bluetooth GPS receiver, which will provide the GPS data to your BlackBerry. Refer to this link to find out the models which support GPS http://na.blackberry.com/eng/devices/features/gps.jsp

Do not be disappointed if your preferred model is not the list, you can always download the simulator from https://www.blackberry.com/Downloads/entry.do

Though, the above list mentions about GPS support by default, it should also be noted that there will be existing applications developed based on JSR 179 java ME api even if the model doesn’t not have inbuilt GPS support. GPS capabilities could also be obtained by connecting to an external GPS device over Bluetooth, but this comes with its own set of challenges. Another option is for old blackberry models (RIM 857/957), which works with a serial GPS receiver attached via cable.

Overview

You must enable GPS on your device, for applications to retrieve the current location. The location is nothing but coordinates for latitude, longitude and altitude.

Additionally, support for JSR 179 Location API for Java ME comes with device software 4.0.2 and later. If you want BlackBerry extensions to JSR 179, you will need device software 5.0.0 and later.

To obtain a location via the GPS support in your device, your application has to do the following:

○   Specify the GPS mode

○   Get the location provider

○   Make GPS request

○   Retrieve the GPS location of a BlackBerry device

Code sample: Specifying the GPS mode

/* JSR 179 */
Criteria myCriteria = new Criteria();
/* JSR 179 extension */
BlackBerryCriteria myBlackBerryCriteria = new BlackBerryCriteria(…);

Dig Deep

There are three GPS modes and they have speficic properties that are described below. You will need to select one based on your application requirements.

○   Autonomous – relies on the GPS satellite only. This mode uses the GPS receiver on the BlackBerry device to retrieve location information. This mode cannot be used indoors or in close proximity to many physical obstructions, and it can take several minutes to fully synchronize with four or more satellites for the first GPS fix. An example application that can use this mode is a Car Parking Spot application.

○   Assisted Mode – GPS satellite and servers on the wireless network only. This mode uses the wireless network to retrieve satellite information. This mode can achieve a fast retrieval of the first GPS fix. An example application that can use this mode is a Nearby Restaurants application.

○    Cell site Mode – Geolocation service or the wireless network to provide on the location information of current base station. This mode uses the wireless network to achieve the first GPS fix, and is generally considered the fastest mode. This mode does not provide BlackBerry device tracking information such as the speed and the bearing. An example application that can use this mode is a Weather Application.

Let us look at the code samples to use the BlackBerry API to get location and satellite information. The code fragments are used to highlight the API rather than give a fully working GPS Application that also provides additional value added information.

First, let us look at a Java class GPSSatteliteInfo listed below. This is a utility class in which we will wrap all the GPS related sample code. The thread implementation is currently empty.

/* packages to import */
import java.util.*;
import java.lang.*;
import net.rim.device.api.gps.*;
/* create public class */
public class GPSSatelliteInfo {
	/* member variables */
	…
	public GPSSatelliteInfo() {
		gpsThread = new GPSThread(); //private thread class reference
		gpsThread.start();
	}
	/* private thread class */
	private static class GPSThread extends Thread
	{
		public void run()
		{
			//do something
		}
	}
}

○   Next, specify the GPSMode inside the run() method of Thread class

BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);
//OR  to be on safer side
BlackBerryCriteria myCriteria = new BlackBerryCriteria();
if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST))
	myCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS))
	myCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);

○   Next, get the LocationProvider and create a BlackBerryLocation object to retrieve the GPS fix including a 300 second timeout expiry.

BlackBerryLocationProvider myProvider;
myProvider  = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria);
BlackBerryLocation myLocation;
myLocation = (BlackBerryLocation) myProvider.getLocation(300);

○   Retrieve the satellite information

satCount  = myLocation.getSatelliteCount();
signalQuality  = myLocation.getAverageSatelliteSignalQuality();
dataSource  = myLocation.getDataSource();
gpsMode  = myLocation.getGPSMode();
SatelliteInfo si;
StringBuffer sb = new StringBuffer("[Id:SQ:E:A]\n");
String separator = ":";
for( Enumeration infoEnum  = myLocation.getSatelliteInfo(); infoEnum != null; infoEnum.hasMoreElements();){
	si = (SatelliteInfo)e.nextElement();
	sb.append(si.getId() + separator);
	sb.append(si.getSignalQuality() + separator);
	sb.append(si.getElevation() + separator);
	sb.append(si.getAzimuth());
	sb.append('\n');
}

Note:The assisted mode can be used with BlackBerry devices that are associated with a CDMA network that utilizes PDE server technology. The assisted mode is designed to provide fast retrieval of a GPS fix. Assisted GPS capabilities are currently defined by wireless service providers. In many instances, you must enter into a formal relationship with wireless service providers before you can connect to their PDE server.

if ( !GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST) || !GPSSettings.isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST))
	return;

On similar lines, let us see how to retrieve location information.

static double lat, lon;
static float alt, spd, crs;
lat = myLocation.getQualifiedCoordinates().getLatitude();
lon = myLocation.getQualifiedCoordinates().getLongitude();
alt = myLocation.getQualifiedCoordinates().getAltitude();
spd = myLocation.getSpeed();
crs = myLocation.getCourse();

This covers how to retrieve satellite information and location coordinates.

However, there is a lot more that an application should do to provide a good user experience. Majority of times it is driven by the kind of application being developed. For example, if the application is designed to display my location on a map at a given time, then retrieving GPS location one time should suffice. But, at the same time, if the application is designed to keep retrieving the GPS coordinates as person moves some distance, then something more needs to be done. One way is to use the  setLocationListener() by passing the interval value, timeout value, and maximum age as parameters to add a LocationListener.)

myProvider.setLocationListener(new handleGPSListener(), 10, -1, -1);

In the class, implement the LocationListener interface. Implement the basic framework for the locationUpdated () method, and the providerStateChanged() method.

public static class handleGPSListener implements LocationListener
{
	public void locationUpdated(LocationProvider provider, Location location)
	{
		if (location.isValid())
		{...}
		else
		{... }
	}
	public void providerStateChanged(LocationProvider provider,	int newState)
	{
		if (newState == LocationProvider.AVAILABLE)
		{...}
		else if (newState == LocationProvider.OUT_OF_SERVICE)
		{...}
		else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE )
		{...}
	}
}

This gets invoked at a fixed interval to any location changes. This is ideal for application that is plotting user movement over a map. (Similar to the GPS navigation device to get directions).

We have now covered how to use the BlackBerry JSR 179 extension (aka GPS API) to get satellite and location coordinates. The code covered so far provides a basic working example to retrieve the satellite and location information. The same could be extended to  make complex applications. There are other areas which are “good to know” like GPS error code, Location error codes, control the power consumption, preferred response time, manage cost allowed, setting the failover mode (fall back on other available options if one is not available), etc and the reader is advised to refer to the available documentation.

Location Based Services and applications are growing in importance. The BlackBerry platform provides good support for you to get started with building location based applications today. In future posts, we shall delve into deeper topics that help you to take advantage of the full range of BlackBerry location based APIs.

Pawan Sachdeva
Pawan Sachdeva– Technical Architect

, ,

06
Jul

This blog post covers how one can maintain state in an iPhone application. Everyday interactions with the environment require us to save some form of information or data either for immediate use or maybe later.

Take for example:

  • Saving phone numbers on your mobile.
  • Backing up electronic data on a portable hard drive.
  • Performing the “Save Game” routine while playing a critical mission of your favorite console game.
  • Saving drafts of emails.
  • Saving code during development! (I too am saving this document to spare the agony of re-typing by an accidental application Quit.)

All these actions of saving, give the ability to record all information that is gathered.

Likewise, saving the state of an application is an essential, although not commonly used practice in iPhone Application Development.

In this post I intend to throw some light on aspects of  ‘state saving’.

Need for saving the state:

Consider the following situations -

  • A user can quit the application at any point in time.
  • The application is quit by the iPhone OS on an external event such as a phone call.
  • The application quits on an internal event such as the launch of the native Web Directions app/ Google Maps app.

For an application with a large number of screens (by screens I mean ‘views’), navigating through many screens to view desired information and then having the application quit accidentally or unexpectedly can get annoying. Especially if the applications flow (sequence in which views load on user interaction) requires executing search queries, entering criteria or just navigating a dozen screens!

In such cases saving the state along with the required user data helps to restore the same view that the user was on before the application quit, upon application re-launch.

What data to save?:

In order to save the state, it is absolutely crucial to save all the necessary data to bring back the correct screen on application re-launch.

This section I suppose is self explanatory, hence i’ll resort to just listing the data one may need to save.

  • User information( username, password )
  • User preferences( settings within the application )
  • Application flow data( user-saved criteria, searches executed )

When to save data?:

The answer to this question could vary depending on the context of an application. Data could be saved at regular intervals during application flow or on specific screens or just before the application quits. In iPhone projects there exists a method that is called just before the application quits.


- (void)applicationWillTerminate:(UIApplication *)application{

}

Any logic, if you choose to save data just before the application quits should go in there.

Keep in mind the priority of data to be saved, you would not want to add more overhead than already exists.

How to save the data?:

Lets get started.

1. NSUserDefaults:

The NSUserDefaults object is simply a great way to save data. The best part being that no pre-requisite database knowledge is required to use it.

Saving Data -

Using the setObject & like methods, one can save different type of data as shown below.

forKey represents the key to associate with the value.


NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];

// to save a Float

[savedData setFloat:3.14159 forKey:@"valueOfPi"];

// to save an NSInteger

[savedData setInteger:18 forKey:@"userAge"];

// to save an NSString

[savedData setObject:@"JackSparrow" forKey:@"username"];

[savedData synchronize];

The synchronize method syncs the in-memory cache with the defaults database.

You could also setBool, setDouble, setUrl.

Retrieving Data -

Retrieving the saved data is even simpler & self-explanatory!


NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];

// getting an Float

float dearPi = [savedData floatForKey:@"valueOfPi"];

// getting an NSInteger

NSInteger theAge = [savedData integerForKey:@"userAge"];

// getting an NSString

NSString *theUsername = [savedData stringForKey:@"username"];

2. .plist file:

The .plist (Property List) is a file containing a list of nested {key-value} pairs of data types such as strings, numbers, arrays & dictionaries. Plists are simple & effective, much like NSUserDefaults.

The Setup -

i.    Create a plist file in your application’s Xcode project, say savedData.plist.
ii.    Create a list of paths, we will use one of the paths to save the plist.

NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

iii.    From this list of paths, get a path to the documents directory.

NSString *documentsDir = [pathList objectAtIndex:0];

iv.    Now get a file path to the plist


NSString *plistPath = [documentsDirectory  stringByAppendingPathComponent:@"savedData.plist"];

Writing data to the plist -

[<SOME DATA> writeToFile:plistPath atomically:YES];

Reading data from the plist -

NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:plistPath];

In addition to the above methods you could also experiment with using SQLite or CoreData.

How to save data using them requires a separate post and as such, is out of the scope of this article.

What Next?:

Now that we are done with saving all that we need, a little bit of common sense & planning will go a long way in restoring the application to its previous state on re-launch. Depending upon the heaviness of the screen the user needs to see on re-launch, one may execute any number of methods within the application code to perform the necessary processing. However, let the user know that the application hasn’t hung up and is just processing things before the last viewed screen is shown, using waiting/activity indicators and alerts with appropriate messages. Preferably, build a view that continues to show as long as the required view doesn’t show up. If for some reason, restoring state is not possible, don’t let the application stare blank at the user. Instead, load an appropriate view from where the user can continue. If all fails, take the user to the first view of the application with the indication that probably the data required to load the appropriate view is insufficient or the application was unable to restore the state.

A few pointers to consider:

  1. Do not try saving excessive amounts of data, it results in latency while the application is running.
  2. Whatever you save, make sure its complete.
  3. When you are retrieving what you have saved, make sure the data exists. Null or no values spell doom.
  4. Let the user know the application hasn’t given up on him/her. Indicate processing where required.
  5. Free what is not required. Memory is vital, use it wisely.

I hope this post benefits all those looking to understand the need of saving an application state.

Anup Dsouza
Anup Dsouza– Member of Mobile Center of Excellence