Archive for August, 2010
30
Aug

Introduction

This is the concluding part in a three part blog on Cascading Style Sheets, or CSS. In the first part, we saw what CSS is and where and why it is used. In the second part, we saw what Semantic Markup is, how it has been built into CSS and what enhancements it brings for Web pages.

In this part, we shall see how style rules are defined and what kind of issues may arise in displaying the same Web page across different browsers.

Defining style rules

  • Selectors

Every CSS style definition has three parts: a selector, a property and a value. The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon (:), and surrounded by curly braces as shown in the code sample below. Selectors can be grouped so that the same style rule can be applied to multiple elements. This selector needs to be separated by a comma to form a group.


h1, h2, h3, h4, h5, h6, p
{
color: green
}

  • The class selector

Using a class selector, you can define different style rules for multiple elements. The class selector is defined as a selector name prefixed by a dot (.). You can apply multiple classes to elements which give you the flexibility to define more rules, displaying the page accordingly, as shown next.

.contentarea
{
width: 200px;
}
.content
{
margin: 0;
padding: 0;
color: #cccccc;
}

Applying the above classes,

<p class=”contentarea content”>
Some content here …
</p>
<p class=”content”>
Some content here …
</p>
  • The id selector

You can define style rules to HTML elements with the id selector, which is defined as a hash (#). In the example below, the style rule will be applied to the element which has the id ‘someid’. With this, you can define different style rules for multiple elements. You can apply multiple classes to elements giving you the flexibility to define more rules and accordingly displaying the page, as shown below.

#someid
{
font-weight:bold;
}

Applying the above classes,

<p id=”someid”>
Some content here …
</p>

Note: As a rule, you can have only one element in a page with one id. Having multiple elements with the same id is not recommended and your scripts might not give you the desired output.

  • Adding comments in CSS

To explain what you are doing in the style rules, you can insert comments in CSS, using the /* and */ tags.

#someid
{
/* The following rule will make the font bold on screen!!! */
font-weight:bold;
}

Next, we shall see some cross-browser issues that we need to handle during the coding of our Web page.

Cross-browser issues

The designer of a Web page can never know what browser the user may use to browse his Web page. This is aggravated by the fact that users now have several lighter and faster browsers to browse the Web. This makes your task as a Web developer more difficult as unfortunately all these browsers follow standards in their own way.

Nonetheless, as the developer, you have a few tools to make sure that your Web page loads correctly in the majority of browsers. One of them is testing your page on as many browsers as possible, at least on Microsoft Internet Explorer versions 6 and 7, and Firefox versions 2.x and 3.x.

You can also use tools such as conditional CSS linking, improving the compatibility of your page for the browser on which it will be viewed. To link CSS files conditionally in your Web page, you can use the following conditional statements in your code for Internet Explorer versions 6 and 7:


<!–[if IE 6]>
<link src=“ieg_6.css” type=“text/css” />
<! [endif]– >
<!–[if IE 7]>
<link src=“ieg_7.css” type=“text/css” />
<! [endif]– >

This will do the following while loading your page: If the user is using Microsoft Internet Explorer 6, then styles from ieg_6.css will be applied to the page while the other CSS file will be ignored.

On the other hand if the user is browsing using Internet Explorer 7, styles will be applied from ieg_7.css. This approach provides you the flexibility to maintain separate CSS files specific to Internet Explorer 6 and 7. We can have a common file in which all the common rules can be specified and in these specific files, we can override the rules for these specific browsers. The obvious advantage of using this method is improved code management since in case of a problem, we need not go through the entire hierarchy of code files for the site. We can straight away look into the specific file and apply the necessary fixes.

Further study and references

A lot of material on CSS is available on the Web; some of the links are mentioned below.

Amit Sheth
Amit Sheth– Sr. Technical Writer

27
Aug

Introduction

This is the second in a three part blog on Cascading Style Sheets, or CSS. In the first part, we saw what CSS is and where and why it is used.

In this part, we shall see what Semantic Markup is, why it is recommended and what enhancements it brings for Web pages.

Basics of Semantic Markup

The closest literal meaning of the word ‘semantic’ is the word ‘meaning’. As applied to Web pages, the term ‘semantic markup’ means using the correct tag to accurately describe the type of content of a Web page.

Before CSS was introduced, designers had limited options to design and present the content of their Web pages, the most common way for which was to use table cells and font tags to create styles. This used to severely limit the presentation techniques for the content.

CSS was introduced to enable designers create a consistent technique to define the style information for Web documents.

Standard tags provided by CSS

  • Heading tags

As we had seen in part 1 of this blog, CSS enables Web page designers to separate the content of a page from its presentation. This is done using tags.

Heading tags are the equivalent of the ‘Level 1 heading’ style in any popular word processing program. A majority of the Web pages usually start with a heading tag, followed by several subheading tags (followed by their content) arranged hierarchically.

Except for the Web page’s title (which appears in the browser’s title bar), using heading and subheading tags is highly recommended to organize the page content in a sequential and logical flow. Heading and subheading tags are usually indicated in the Web page’s HTML code as ‘h1’ (for the heading), ‘h2’ (for the section heading), ‘h3’ (for the section subheading) and so on. An example of using heading tags in a sample Web page is shown below.

Using heading tags in a sample Web page

Using heading tags

  • Paragraph tags

Since the content of the page will usually be arranged in paragraphs, a tag is available for this purpose. This tag (<p>, </p>) enables the page designer to arrange the content in paragraphs. A code example followed by its output in a standard browser for the paragraph tag are shown next.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en-US”>
<head>
<title>A Simple Page</title>
<link rel=”stylesheet” type=”text/css” href=”styles.css” />
<style>
h1, h2
{
font-family: sans-serif;
color: #3306FC;
}
</style>
</head>
<body>
<h1>A ‘heading 1’ heading, followed by its paragraph</h1>
<p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p>
</body>
</html>
Using Paragraph tags

Using Paragraph tags

  • List tags

List tags, as the name suggests, can be used to create numbered or bulleted lists of items on a Web page. These are amongst the most underutilized tags, since the type and variety of options that they provide are almost limitless. Several options are also available for nesting of lists. This page provides several quick examples of the usage of list tags, with their types and categories.

  • Table tags

Tables should preferably be used to display data present in a tabular format, such as in a spreadsheet. Table tags are probably used incorrectly the most, that is, they are used to tabularize data that would be better presented, perhaps as a list. Several good examples of the usage of table tags for the formatting of tables and their cells are presented in this link.

To summarize part two of this blog, we saw how CSS offers us several tools enabling us to display our Web page in the correct and intended manner, while letting us keep the HTML code maintainable.

In the third and concluding part, we shall see how to define style rules, and look at some cross-browser implementation issues.

Amit Sheth
Amit Sheth– Sr. Technical Writer

23
Aug

Introduction

Cascading Style Sheet, usually used in its abbreviated form as CSS, is a style sheet language designed to enable the separation of a document’s content from the way it is intended to be presented. Introduced by the W3C consortium in 1996, CSS is used to describe the ‘look and feel’ of a document written in another markup language, such as XML or XHTML.

In this blog article, we shall go through the basics of CSS and see a few examples of how it is to be used. We shall also see some cross-browser techniques to make a piece of CSS code work in the same way on all the major browsers.

It is assumed that the reader knows HTML and how to create HTML pages.

What is CSS?

To understand CSS, we first need to understand the concept of a Style Sheet Language – a language used to describe the layout of structured documents. A bare-bones example of this requirement would be displaying a table on a Web page. In this case, the content of the table is distinct from its layout, meaning, the table can use any font, background color and design whilst conveying the same information.

A collection of such style-defining rules is known as a style sheet and a language which enables defining such rules for a particular application or purpose is known as a style sheet language.

Put another way, a style sheet allows a Website developer to define the content of the Web page in one file and the way that content is to be presented in another. Using a technique, these two files are ‘linked’ to generate the required output in the desired manner.

CSS is a powerful tool for a Website developer, allowing him to be consistent with the look and feel of his Web pages while giving him much more control over the layout and design than straight HTML ever did.

As mentioned in the preceding paragraphs, the styles take care of displaying the Web page and are defined in separate files. So if multiple styles are declared for an element, they will cascade into one and that is the reason these sheets are known as Cascading Style Sheets or CSS.

The cascading order of what style to be used when there is more than one specified for an HTML element depends on the following order, in increasing levels of priority:

  1. Browser default: Look for the style element that is created; if it is not in the document, use the default rules in the browser.
  2. External Style Sheet: Determine if any of the style rules are marked as important and apply those to the appropriate elements.
  3. Internal Style sheet (declared inside the <head> tag): Any style rules in the document will have precedence over the default browser settings.
  4. In-line style sheet (declared inside the HTML element – this has the highest priority): The more specific the style rule, the higher the precedence it will have.

So, an in-line style (inside an HTML element) has the highest priority, which means that it will override a style declared inside the <head> tag in an external style sheet or in a browser (a default value). Finally, if two rules apply to the same element, the one that was loaded last will have the highest precedence.

The basics of CSS

The basic purpose of CSS is to allow the designer to define style declarations (formatting details such as fonts, element sizes, and colors), and to apply the defined styles to selected portions of HTML pages using selectors – references to an element or group of elements to which the style is applied.

Let’s understand it with the help of a simple example:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en-US”>
<head>
<title>A Simple Page</title>
<link rel=”stylesheet” type=”text/css” href=”styles.css” />
<style>
h1, h2
{
font-family: sans-serif;
color: #3366CC;
}
</style>
</head>
<body>
<h1>First Title</h1>
<p>. . . </p>
<h2>Second Title</h2>
<p>. . .</p>
<h2>Third Title</h2>
<p>. . .</p>
</body>
</html>

It can be seen from the sample code above that both the content as well as the style of the Web page are separately defined (although for ease of understanding, they have been shown in the same file). The font and font colors to be used for the page are defined in the <style> block, whereas the actual content, that is, the text of the page, is defined separately within the <body> block.

Different ways in which styles can be applied

Now let’s understand the different ways in which CSS can be applied to a Web page.

  • In-line Styles

When the style rules are defined for an HTML element using the <style> attribute in the Web page itself, these are known as ‘in-line styles’. As mentioned above, these style rules have the highest priority. An example of inline styles is shown below:


<p style=”font-family: sans-serif; color: #3366CC;”>
Amazingly few discotheques provide jukeboxes.
</p>

With inline styles, there are some advantages such as:

  1. The styles are available in the page source itself.
  2. These rules will be applied as they have the highest priority.

    But there are also some disadvantages such as:

    1. No re-usability of rules: As the styles are specific to the element, you have to specify these styles for all the elements.
    2. Code maintenance: Since the styles are going to be a part of the Web page, code maintenance is a problem.
    • Embedded Styles

      When the style rules are defined in the <head> tag of the page, they are known as embedded styles. An example of embedded styles is shown next.

      <html>
      <head>
      <style type=”text/css”>
      /* Style rules here*/
      </style>
      </head>
      <!—rest of the html of the page –>
      </html>
      

      With embedded styles too there are certain advantages and disadvantages. The advantages are:

      1. The styles are available in the page source itself.
      2. The same style can be applied to multiple elements.

        The disadvantages are:

        1. No re-usability: Though the style rules are now part of the page instead of the element, if the same style rules have to be applied to a different page, then the same rules need to be defined for the other page too.
        2. Code maintenance: Since each page is going to have rules, if a change is required to be made in the appearance of a particular element, then a change in all the pages where these style rules are defined will have to be made.
        3. External style sheets: When the style rules are defined in a separate file and used in the Web pages by providing a ‘link’, these are known as external style sheets. These files are saved with the .css file extension.

          An example of an external style sheet is shown next.

          /* START: External style sheet file name – eg.css */
          /* style rules go here */
          /* END: External style sheet file name – eg.css */
          To link this file to your Web page, we add the following line in the <head> tag of the page:
          <html>
          <head>
          <link rel=”stylesheet” type=”text/css” href=”eg.css” />
          </head>
          <!—rest of the html of the page –>
          </html>
          

          External style sheets are highly recommended for any application since they present an advantage of re-usability as well as ease in code maintenance. However, this does not mean that one should never use embedded or in-line styles in Web pages, but it is recommended to use them only where absolutely necessary.

          Before moving on to see more about style definition, we will understand one more term from Web 2.0 – Semantic Markup covered in next part of the blog. Watch this space for more.

          Amit Sheth
          Amit Sheth– Sr. Technical Writer

          16
          Aug

          Overview

          Today, non brick-and-mortar companies such as Google, Amazon and Yahoo! generating revenues in billions of dollars is quite well-known. What may not be so well-known, though, is the level of investment these companies have to make in ensuring that their systems and servers are always available to their customers 24×7, and to make sure that their data centres are able to handle the amount of traffic needed to be processed to keep their business going.

          Little wonder then, that testing forms an important part of managing their business infrastructure.

          Introduction

          This blog is intended to explain to the reader the most important factors that are involved in the testing of high-traffic Web portals. For such Websites, security and performance become the key factors in testing along with other concepts such as usability, functionality and navigation.

          Unit Testing

          Unit testing must be performed by the developers against their components prior to integration. Custom unit tests only exercise functionality but neglect performance, which becomes a bottleneck later; hence component performance needs to be analyzed during their unit tests. This is usually done using the following tools:

          • Memory profilers
          • Code coverage and coding standard tools

          Usability Testing

          Usability testing helps to create and maintain a user-friendly and user-centric portal that a visitor will find easy to use and will want to visit again. Some of the usability practices tailored for high traffic Websites are listed below:

          • User friendly layout: Use language and concepts which are familiar to the user. Try to present information in a sequential and logical order.
          • Maintain consistent conventions: Concepts which are similar should be shown using similar terminologies and graphics. Details of maintaining uniform conventions for aspects such as layout, formatting, typefaces, labelling, etc should not be ignored.
          • Minimize users’ memory usage: Try not to force visitors to remember important information across multiple documents.
          • Using a flexible and efficient design: Try to arrange screens in a way such that frequently required data is found easily, providing instructions and directions wherever necessary.
          • Keeping an aesthetic yet simple design: Do not present or display information which may be distracting or irrelevant.
          • Arrange a progressive level for details: Information should be organized such that generic information is presented first, followed by more details, as requested or searched for.
          • Provide navigational feedback. Moving between related topics should be made easy. The user should be allowed to find out where he/she presently is on the website (by providing a site-map) and it should be easy to return to any previously visited point on the site.

          Globalization

          For high traffic portals, there is increasing demand for supporting local languages as the end user base is increasing from every corner of the world. Globalization testing is the process of testing the Website which has to work uniformly across multiple regions and cultures. There are two aspects to an international website: world readiness (globalization), and localization. World readiness refers to the process of designing, coding and testing the website such that it can be easily localized for different regions. Localization involves translating and customizing the products for different regions. Ensuring world-readiness is different from testing localized program versions, and it is broader than just functionality testing. It also includes realizing the implications of globalization, plus verifying that those implicit requirements are met throughout all the design and development steps.

          AJAX Bridging

          It is well known that AJAX applications can only connect back to the website from which they have originated and this is a security measure in AJAX. For instance, JavaScript code developed with AJAX and obtained from a certain site cannot launch a connection to another site. The AJAX service bridge was developed to enable a third-party Website connection in this way.

          This is how it works: Inside the bridge, first, a host provides a Web service acting as a proxy and allowing traffic forwarding between the JavaScript code running on the client and the third-party Web site. Since a bridge can be considered as a ‘Web service to Web service’ type of connection, an attacker can use this to gain access to sites with restricted access. Hence, it is required to check whether the website is vulnerable to attacks or not.

          HTML/AJAX Injection

          The heart of AJAX is XMLHttpRequest which allows for synchronous server communications and browser updates. The browser can be updated with just simple HTML (DOM), XML, or another structured data format. These XMLHttpRequest calls are just normal HTTP requests. Check if every request for authentication checks for the behavior of application after introduction of HTML injection. The same security vulnerabilities and controls apply to AJAX websites.

          • AJAX often requires additional or stronger controls because they are usually complex, bidirectional, and asynchronous.
          • AJAX applications often have weak authentication, session management, and error handling.

          Cross Site Scripting

          Additionally, check the Web application for XSS (Cross site scripting). Any HTML, such as <HTML>, or any script such as <SCRIPT> should not be accepted by the application. If it is, the application can be prone to an attack by Cross Site Scripting.

          Cross-Browser Compatibility

          Cross-browser compatibility generally is a big issue. It is magnified a few times when you consider high traffic Websites with AJAX. Browsers either do not support AJAX or render AJAX differently. More stress on browser compatibility testing of high traffic Websites comes when you consider different browsers with different versions such as Internet Explorer, Netscape, Firefox, Safari, Opera and Chrome.

          Security Testing

          Because AJAX is still a recent technology, several of its security issues are still to be fully understood. AJAX must not be deployed in security-sensitive applications, such as credit card verification portals. Some of the security concerns to be considered while designing the test cases while using AJAX are listed below:

          • It increases the available attack surface and requires many more inputs to be secured.
          • It exposes the internals of the application.
          • It enables access to third-party resources for the client without any built-in security and encoding mechanisms.
          • It has no mechanisms to avoid failures in protecting authentication information and sessions.
          • The line between client and server-side code is highly blurred, which results in security mistakes.

          Testing Search Engine Optimization

          Testing teams of such high traffic portals need to deeply understand the basics of search engine optimization (SEO). This is all the more important, especially because Website technologies like AJAX and Flash are not search engine friendly. Listed below are some important SEO items that the testing teams should be aware of:

          • Ensure that static URLs are used widely and IP addresses are used only when absolutely necessary.
          • Ensure that there is no excessive use of tables which is considered a bad SEO practice.
          • Ensure that non-compliant HTML is not used.
          • Ensure that images have ‘ALT’ and ‘Title’ attributes.
          • Ensure proper use of ‘Meta’ tags and keywords.
          • Ensure the presence of an ‘Admin’ screen to dynamically update keywords based on feedback from search engines.
          • Check hyperlink updates for use of domain name instead of IP address.
          • Avoid excessive use of JavaScript based menus which have a negative impact on SEO.
          • Ensure that all searchable text is available to search engines.
          • Test the Website on all search engines for which the site is optimized.

          Special Test Cases for Websites Heavily Loaded with AJAX and Flash

          • Absence of an IDE for AJAX makes unit testing and debugging a discouraging task. Hence, excessive dependency is always there on the regression testing teams who need to factor this and design the test suite more elaborately and cover each single unit for all its possible functionalities.
          • High traffic Websites with AJAX will not work if JavaScript is disabled. Make sure that the user is prompted to enable JavaScript and even if the user doesn’t do so, the site should not become totally inaccessible with JavaScript turned off.
          • The ‘Back’ button on the browser may not work until developers provide that functionality. Testing teams need to ensure that this functionality is available on pages where there is a high probability of users hitting the ‘Back’ button.
          • It may be difficult to bookmark a particular section of an AJAX site. Testing teams must ensure that pages users may want to bookmark are free from this limitation.
          • The Flash based interface must be tested on different speeds such as modem, broadband, LAN etc.
          • The audio and video synchronization for flash movies and animations must be checked.
          • Finally, the Flash/AJAX application on the machine with minimum configuration must be tested.

          Bandwidth Dependency

          Both AJAX and Flash have a heavy bandwidth dependency and do not work well on low bandwidths. Hence, testing the response on varying bandwidths to determine and ensure the comfort band is an important requirement. This adds a whole new dimension to testing such sites, and demands additional discipline, time and resources.

          Performance Testing

          For such high traffic Web portals, thousands of requests are usually being made to the server and during particular events and times, this count can go in millions. With such a high volume of traffic, server performance may become an issue and hence to ensure satisfactory performance, the following criteria should be met during performance testing:

          • It must be ensured that your site’s performance requirements and goals represent the needs of your users.
          • Load tests must be designed such that they replicate the actual workload at both normal and peak times.
          • Performance testing must be conducted using parameters such as data types, distributions and volumes which are similar to those used in actual business operations under actual production.
          • Whether the system can handle multiple concurrent requests performing the same transactions must be checked.
          • To properly identify the bottlenecks during performance testing, using a good and optimised profiling tool is also important.
          • Automated testing tools such as LoadRunner, Keynote and JMeter should also be used for evaluating various performance aspects.
          • Time-critical transactions in the performance tests must be included.
          • Even under peak traffic conditions, it must be ensured that the user can transfer large volumes of data.
          • The performance tests must also be conducted while regular system processes, such as a batch job execution or a virus definition update download, are in progress.
          • The performance must be measured under various load levels and mixed scenarios.
          • It has to be validated that all of the correct data was displayed and saved during your performance tests.
          • An important testing technique, known as Soak Testing, also has to be executed. This involves testing a system with a significant load extended over a significant period of time, to discover how the system behaves under sustained use.

          Summary of the Factors Important in Testing High-traffic Web Sites

          Standard testing methodologies must be adapted to the unique nature of Website testing environments. The following table lists some of the key aspects that testing teams should consider while designing test strategies for high traffic Web sites:

          Type of Check

          Parameters to be Validated

          Validation checks

          Validating HTML, input forms, check for broken links, validating CSS (such as fonts, colors, spacing etc)
          Security checks Testing cookies
          Performance checks Testing bandwidth dependencies
          Browser compatibility checks Using different browsers such as Internet Explorer, Netscape, Firefox, Safari, Opera and Chrome
          Other checks

          Testing the sever side interface, configuration, recovery and accessibility

          Phases in Testing Applications Running on such High-traffic Web Portals

          To ensure that the application is able to withstand the high volume of traffic, it must go through the following phases during specific points in the software development lifecycle:

          • Unit testing
          • Integration testing
          • Functional testing
          • End-to-end testing
          • Distributed testing
          • Usability Testing
          • Globalisation testing
          • Exploratory testing
          • Regression testing
          • Compatibility testing
          • Conformance testing
          • Fault tolerance and security testing
          • Load and stress testing
          • Performance testing

          Summarizing, we have seen in this blog that testing high-volume portals requires careful planning at every stage, starting from the site’s design right up to considerations such as the end user’s bandwidth availability.

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

          11
          Aug

          Introduction to Technology Stack

          In general terms, a technology stack consists of the parts or sections of any set of components or services that are used to deploy or provide any technical solution or application.

          When applied to the software industry, technology stacks might be examples such as the TCP/IP protocol stack and the seven layer OSI model.

          User Interface Technology Stack

          User Interface Technology Stack, as the name suggests, comprises of the technologies that are used for UI development. For the purpose of this blog, we will extend the same definition and call it technologies that could be used to develop the UI and need not primarily be UI technologies. The UI technology stack could be different for different kinds of applications. Hence, we will discuss the three most common kinds of applications being developed, which an ordinary user commonly gets to use:

          • Web applications
          • Desktop applications
          • Mobile applications

          In the following subsections, we shall cover these three kinds of applications and the UI technology stacks that are most prevalent in their respective areas.

          The figure below depicts the UI technology layer separation across Web and desktop applications (mobile applications have been intentionally left out in the diagram).

          UI technology layer

          UI technology layer

          Web Applications

          Web applications are the ones which can be accessed from a standard Internet browser, such as IE, Firefox or Google Chrome, on a desktop or laptop computer. This excludes ‘browser on a device’, which is covered later in mobile applications.

          The first and foremost thing coming to mind about Web applications is terms such as HTML, DHTML, JavaScript and CSS from a technology point of view, which have been there from the early days of browser based applications.

          Earlier, browsers could only render HTML and process JavaScript and CSS. But with the help of different plug-in components such as applets, Macromedia Flash, ActiveX, SilverLight and Flex, browser-based applications can now provide a very rich user experience. We shall now see a short overview of the different technologies available to develop Web applications.

          HTML/DHTML

          HTML today is the language all other programming languages render into after performing complex backend operations. HTML has transformed into a powerful language that can actually open sockets to server (HTML5). In January 2008, HTML5 was published as a working draft. It contains a set of new tags, CSS enhancements and JavaScript APIs.

          DHTML allows developing better-than-browser experience with features such as drag/drop, fading, animation effects etc. As a result, applications will continue to provide such user interfaces for years to come.

          AJAX

          Ajax (Asynchronous JavaScript and XML) is a standards-based technique/design pattern for developing better-than-browser user experiences for server-deployed applications. It is a server side technology, but invoked from the client side. Ajax is primarily used to make interactive Web applications by retrieving data from the server asynchronously in the background without interfering with the display and behavior of the existing Web page. Features such as auto-complete, submitting a form without page reload and displaying the success/failure of submission, performing local user input validations are some basic examples of the usage of Ajax. Google Maps is one of the best examples of the use of Ajax to resolve complex issues.

          JavaScript

          Like HTML, the decade-old JavaScript has become the most popular programming language on the Web. JavaScript is object oriented and has support for classes, callbacks, events, run-time evaluation and much more. Third parties have come up with libraries that let ordinary users to develop applications with ease. A few of them are listed below:

          • Prototype – Prototype is a JavaScript framework that aims to ease development of dynamic Web applications. Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the code-base of choice for Web application developers everywhere.
          • JQuery – JQuery is a fast and concise JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid Web development. JQuery is equally powerful and easy to use as Prototype, plus the library also supports animation, giving developers an additional tool to add more style and features. It may be a tough call for anyone to decide between Prototype and JQuery.
          • Both Prototype and JQuery are open source and free to use. There is an equally powerful paid JavaScript library called Ext JS, described next.
          • Ext JS – Ext JS is similar to the above two JavaScript libraries but with enhanced capabilities of providing an interface and features more similar to those traditionally associated with desktop applications. Ext JS, unlike JQuery and Prototype, is governed under the LGPL style license.
          • Java Server Faces – Java Server Faces (JSF) is a Java EE 1.4 component, allowing developers to develop user interfaced for their Java EE applications without much expertise on the UI technologies. It is a framework with a huge set of tag libraries and support for Apache MyFaces (Tomahawk) and many others, maximizing the developers’ productivity. Think about a traditional JDBC operation and displaying a record set using JSP on a webpage: JSF could do that by mapping a bean on the server side and the JSF DataTable widget would render the same results with using a simple tag, rather than iterating over the result set using JSP scrip-lets. The code looks neat and the objects are mapped on-the-fly to server-side managed beans. JSF also integrates seamlessly with CSS and JavaScript.

          However, it does come with its own limitations and complexities. Though the configuration is very simple, one has to design the implementation to minimize frequent changes. JSF being very easy to develop, many tend to ignore the performance aspects and use tags very loosely. Once a decision to use JSF is taken, it may be difficult to change the application development to any other framework midway.

          • Flex and OpenLaszlo – Flex and OpenLaszlo are similar declarative approaches to creating better-than-browser interfaces for Java EE applications. Flex and OpenLaszlo both are open source; Flex is Adobe’s product and also comes with a proprietary, license-based Charting supporting component. Both of them use scripts – either ActionScript (Flex) or JavaScript (OpenLaszlo).

          While the two technologies have many similarities, one key difference is the runtime environment they require. Flex requires Flex Data server running for the client to interact with the server. Alternatively, the server could be any as long as the interaction points are exposed as Web-services. OpenLaszlo requires its own server to be running for client-server interactions. OpenLaszlo version 3 introduced SOLO deployment mode, which eliminates the requirement for a presentation server in some configurations. While some components of Adobe Flex are licensed, the cost of the overall application could become an issue. OpenLaszlo being open-source, many companies have firm policy restrictions on usage of open source software for application development.

          Microsoft SilverLight

          SilverLight is a Web application framework that provides functionalities similar to those in Adobe Flash, integrating multimedia, graphics, animations and interactivity into a single runtime environment. It is supported by multiple browsers on Microsoft operating systems as well as mobile devices running Windows 7. Novell, in association with Microsoft, have come up with MoonLight to bring out the most of SilverLight functionalities on Linux and other open source platforms. Like any other Microsoft technology, SilverLight stands alone as the only technology that tightly binds with .Net and requires Windows for development purposes. If the overall technology stack is independent of Microsoft technology offerings, then SilverLight may not be an option.

          If the OS and .Net platforms are not a restriction, SilverLight stands in parallel to Adobe’s Flex and OpenLaszlo.

          Discussed next are UI technologies for desktop and mobile application development.

          Desktop Applications

          Java Swing

          Along with APIs from Java for Web development, Java AWT/Swing is a platform-independent, Model-View-Controller GUI framework for Java. Swing lost its edge with the introduction of many other GUI technologies, but is still in use by many products common in software development, typically IDEs such as Eclipse, BlackBerry (JDE), JBuilder etc.

          Adobe AIR

          Adobe Integrated Runtime (AIR), also known as Adobe AIR, is a cross-platform runtime environment developed by Adobe Systems for building rich Internet applications using Adobe Flash, Adobe Flex, HTML, or Ajax, that can be deployed as desktop applications.

          Typically when we talk about RIA (rich internet applications) we immediately think of browser based applications, but AIR gives Adobe an edge to have RIA applications to be browser-less. One of the interesting facts is that AIR gets installed with Adobe Acrobat reader v9.3 without user knowledge, making most of the desktops that have Acrobat reader installed ready to run AIR apps and not requiring any additional software to make AIR apps run. Adobe AIR has not really caught up in the market space to be recognized as a popular desktop application technology, but certainly it is gaining attention in developing light weight applications. Also, JavaScript frameworks such as JQuery, Ext JS and Dojo Toolkit have been updated to support Adobe AIR’s application sandbox.

          .Net(VB), .Net(C#) and VC++

          Like Java, Microsoft also has .Net, VC++ and VB to develop desktop applications, though they have existed for quite some time and are the technologies preferred by developers on Microsoft’s platforms. Barring VB, both .Net(C#) and VC++ allow applications to utilize core system functions, e.g., kernel level access, device drivers etc. Developers on VB find it very easy to switch to .Net(VB) as the coding syntax and style are almost similar.

          Mobile Applications

          For mobile application development, two things have to be kept in mind. Like the desktop and Web, the mobile platform in itself has two kinds of applications:

          • Native applications
          • Browser based applications

          Native Applications

          These applications primarily use the APIs and frameworks supported on the operating system, and to a certain extent, the particular Java Specification Request (JSR) implementation for a particular model. For e.g., for Bluetooth programming, the device manufacturer may or may not have all capabilities/support for Bluetooth communication on all his models. This could vary on different models from the same company. Hence, when it comes to mobiles, one needs to study the brand, model and the support for features that the application is going to use. The security aspects are also important to study and evaluate before deciding on the model and brand. One key point is that there cannot be the same application code that can run on iPhone (Objective C), Blackberry (J2ME) and Windows Mobile (.Net Compact Framework) primarily because these platforms have support for different programming languages.

          Browser Based Applications

          For the mobile platform, when a native application is not an option, the immediate solution is to have a browser based application developed in XHTML, and along with CSS and proper design, the application could be made compatible to most of the devices (from different manufacturers and with different screen sizes etc). But, this is easier said than done.

          There are far more technologies present than those discussed above to keep the article concise. The key is that none of these technologies is ‘one size fits all’ and hence not perfect for all situations. Each of these technologies has its own merits and demerits and can be a good fit depending on the requirement and expectations. So, how do we decide on the UI technology for the application?

          For starters, the best way to reach out maximum users is HTML and technologies that generate HTML before it hits the client’s browser. For the opposite, when it is essential to install the application on user’s machine, then AIR, Microsoft VC++, VB .Net and Swing are the options.

          The decision on which one to select is rather easy for desktops than for Web applications. Desktop UI technology is driven primarily by the technology used on the server side; rarely the UI technology would be on a different platform than that on the server side. If it is a stand-alone desktop application, the deciding factors are the features and extent of OS level operations that the application needs to perform. Microsoft technologies are the most preferred when it comes to low level programming. For RIA desktop applications, Adobe AIR and the Out of Browser solution from SilverLight could be an option.

          For Web applications, there are many options, and all are equally powerful in terms of functionality, usability and providing a rich user interface. The key to selecting the right technology is to let the application requirements drive the technology choice for the best user experience. This may look like a very generic and obvious recommendation. In many cases, developers tend to miss the obvious and jump into considerations that are best known to them rather than what should be the best.

          Some of the key points/suggestions that could be followed are:

          1. Knowing the technology/framework well is not always enough to decide on the UI technology to use. The best approach is to walk through the requirements and then evaluate by prototyping some complex features, which should give an early indication of the efforts and challenges lying ahead.
          2. Never hold on to a technology that you are most comfortable with. Experimenting with the newer versions, newer open source APIs, building sample UIs using newer technologies will always keep you a step ahead of competition. Many developers are still using Java Applets assuming that is the best for displaying graphics and dynamic data updates from server, whereas JavaScript libraries have been there for years now which lets them achieve far better results and in a very short development time.
          3. Always remember: It is the user who uses the application and so, providing a rich and friendly UI to the user is the only objective of the UI. Select the technology that works well with the backend binding and allows you to develop some really cool GUIs and the user would certainly keep coming back for more!

          So, we saw in this blog the ideal combinations of deployment technologies that can be used for each of the three primary application software platforms discussed – Web, desktop and mobile. Finally, it goes without saying that for any application to remain popular, it not only has to be technically robust, but also functionally easy and intuitive to use, and has to continuously evolve with emerging trends and technologies.


          Pawan Sachdeva
          Pawan Sachdeva– Technical Architect

          10
          Aug

          Do developers also have to test? How do developers test since they are supposed to be good at coding and not at testing? Well, then the solution is for them to code the test as well!

          This blog covers the basics of Junit – a framework designed to write repeatable tests. It is based on the xUnit architecture, which is basically a collection of code-driven testing techniques, allowing testing of various software units such as functions and classes and eliminating the need to write the same tests multiple times.

          JUnit is simple to use and write TestCases (written as one word and different from a ‘test case’) that could cover almost all testing scenarios if planned well and covered by the tests. Moreover, it plays a vital role in code maintenance and reduces regression testing usually added by new features or code fixes.

          So how do we start about JUniting? Well, the simplest rule of thumb to follow is to plan the input and output for any given scenario, be it a positive scenario or a negative one, and then write a test involving each of these scenarios. This ensures that each condition is checked well before the code release. Moreover, whenever the test suite is run for regression checks, it identifies immediate issues, introduced either due to additional fixes or addition of new features. This may mean that either the new code broke some valid scenario, or the broken scenario is no longer valid and you may turn it into a positive scenario by tweaking that test.

          JUnit is based on two key Java design patterns: Command pattern and Composite pattern. A TestCase constitutes the Command object whereas a TestSuite comprises Composite TestCases.

          Writing JUnit code is very simple and we would not get into the basics of it in this blog. If you are using Eclipse or any other IDE, it supports creation of JUnit tests for a given class in just a few seconds. However, we shall look at ‘from the scratch’ approach wherein we want to add a customized test suite.

          The prerequisite for this would be downloading JUnit 4.x and adding the junit-xxx.jar in your classpath.

          Implementing a TestClass

          A quick annotation preview for TestClass

          A TestClass is implemented using the ‘@Test’ annotation. There is no need to extend the TestClass now with JUnit 4.x and the method names need not start with ‘test’ as required by earlier versions of JUnit.

          The ‘@BeforeClass’ annotated method is executed as soon as the TestClass is initialized and the ‘@AfterClass’ annotated method is executed before the TestClass is being finalized. They run only once in the lifetime of the tests.

          The ‘@Before’ annotated method is executed before each test is run and the ‘@After’ annotated method is executed after each test has completed execution.

          The ‘@Ignore’ annotation is used to ignore the test for execution.

          The ‘@Timeout’ annotation takes the time in milliseconds as a parameter and fails if the test does not complete execution within the stipulated time.

          A simple TestCase example is given next.

          import static org.junit.Assert.assertEquals;
          import static org.junit.Assert.fail;
          
          import org.junit.AfterClass;
          import org.junit.BeforeClass;
          import org.junit.Test;
          
          import test.com.xoriant.testsuite.TestFinalizer;
          import test.com.xoriant.testsuite.TestInitializer;
          
          import com.xoriant.SingletonClass;
          
          public class SingletonClassTest
          {
              /**
               * @throws java.lang.Exception
               */
              @BeforeClass
              public static void setup() throws Exception
              {
                  if (System.getProperty(TestInitializer.TEST_INITIALIZED) == null)
                  {
                      TestInitializer.setUp();
                  }
              }
          
              @Test
              public final void testGetInstance()
              {
          	try
                {
                  SingletonClass singletonClass1 = SingletonClass.getInstance();
                  SingletonClass singletonClass2 = SingletonClass.getInstance();
          
                  assertEquals(singletonClass1, singletonClass2);
                }
          	catch(Exception e)
          {
          	  fail("Execution failed due to: " + e.toString());
          }
              }
          
              @AfterClass
              public static void tearDown()
              {
                  if (System.getProperty(TestFinalizer.TEST_FINALIZED) == null)
                  {
                      TestFinalizer.tearDown();
                  }
              }
          }
          

          Implementation of the TestInitializer class

          This is a common class utilized by the test cases for loading test data for the tests prior to any execution of the tests. This class may also be invoked for independent test cases.

          import org.junit.BeforeClass;
          import org.junit.Test;
          
          import static org.junit.Assert.assertTrue;
          
          public class TestInitializer
          {
              public static final String TEST_INITIALIZED = "com.api.testsuite.initialized";
          
              static
              {
                  logger.debug("Setting system property...");
                  System.setProperty(PropertyManager.BUNDLE_PROPERTY_NAME, "test_config");
                  System.setProperty(TEST_INITIALIZED, "Y");
              }
          
              /**
               * Sets up the test
               */
              @BeforeClass
              public static void setUp() throws Exception
              {
          	  // Initialize the data required for the tests
              }
          
              @Test
              public void dummyTest()
              {
                  assertTrue(true);
              }
          }
          

          Implementation of the TestFinalizer class

          This class is a common class for removing test data after all the tests in the TestSuite have completed. This class may also be invoked for independent test cases.

          import org.junit.AfterClass;
          import org.junit.Test;
          import static org.junit.Assert.assertTrue;
          
          public class TestFinalizer
          {
              public static final String TEST_FINALIZED = "com.api.testsuite.finalized";
          
              static
              {
                  System.setProperty(PropertyManager.BUNDLE_PROPERTY_NAME, "test_config");
                  System.setProperty(TEST_FINALIZED, "Y");
              }
          
              @AfterClass
              public static void tearDown()
              {
                    // Remove the test data that was required for the tests
              }
          
              @Test
              public void dummyTest()
              {
                  assertTrue(true);
              }
          }
          

          Implementing a TestSuite

          A TestSuite is implemented using the ‘@SuiteClasses’ and ‘@RunWith’ annotations. It takes a list of TestClasses as a class array parameter and executes each of them in that order.

          Here, we initialize the TestSuite by adding required test data into the database in the TestInitializer class. Similarly, we cleanup the data using the TestFinalizer class. The ‘@RunWith‘ annotation allows us to define a customized TestSuite with listeners that get triggered at appropriate events in the test execution cycle.

          import org.junit.runner.RunWith;
          import org.junit.runners.Suite;
          import org.junit.runners.Suite.SuiteClasses;
          
          import test.com.xoriant.SingletonClassTest;
          
          @RunWith(CustomSuite.class)
          @SuiteClasses( { TestInitializer.class, SingletonClassTest.class, TestFinalizer.class })
          
          public class AllTests
          {
          }
          

          Implementing a custom TestSuite

          import org.junit.runner.RunWith;
          import org.junit.runners.Suite;
          import org.junit.runners.Suite.SuiteClasses;
          
          import test.com.xoriant.SingletonClassTest;
          
          @RunWith(CustomSuite.class)
          @SuiteClasses( { TestInitializer.class, SingletonClassTest.class, TestFinalizer.class })
          
          public class AllTests
          {
          }
          

          Some of the best practices for JUnit tests that should be followed

          • Do not run tests with interdependent test data. This could create maintenance problems later on.
          • The source folders of the actual classes and the test classes should be different so that the tests are separate from the original source files and do not need to be shipped along with production code.
          • Keep the test class packages same as the class in question to be tested. This allows protected methods to be tested.
          • JUnit can be integrated with nightly builds and executed as an ant task. This would enable running the tests on a daily basis and avoiding production problems.
          • Utilize proper initialization and destruction methods. Never initialize test data in constructors.
          • Keep tests up-to-date to avoid revisiting the tests to be fixed.

          Summarizing, in this blog, we saw how to leverage the JUnit testing framework and its derivative API TestCase to increase the testing efficiency for Java based projects.

          It is to be noted that apart from Java, JUnit has also been ported for several other popular programming languages such as C#, C++, Perl, PHP and many others. The ultimate objective of using JUnit is to test before you code so that you can rest after you code!


          Anand Ved
          Anand Ved– Technical Lead – Cloud Computing Project

          06
          Aug

          Introduction

          In today’s connected age, almost everyone knows what the Internet is. However, very few people have an idea about the workings of this worldwide network. The Internet, as we know it today, has had a long history of evolution and like any other interesting and useful invention, is governed by a set of rules and protocols.

          This blog introduces the reader to the basics of the fundamental protocol behind the workings of the Internet – the Internet Protocol, and the current and upcoming versions of this protocol.

          Internet Protocol

          Internet Protocol (IP) is a set of rules used for data communication across a packet-switched network. It is also known as TCP/IP. The Internet Protocol is used as the mechanism for resolving host addresses and routing data packets from a source to a destination across one or more IP networks, such as the Internet.

          The major design principle behind IP was that the network infrastructure cannot be relied upon for data delivery, but it is dynamic in terms of the number of available links and nodes between the source and destination. The network is supposed to be self-sustaining and there is no central monitoring agency to track the state of the network.

          IPv4

          The first version of Internet Protocol to be publicly deployed and widely used is IPv4. It was designed by the Internet Engineering Task Force (IETF) and came into force in September 1981. RFC791 (http://tools.ietf.org/html/rfc791) provides the technical details of IPv4.

          Limitations of the Addressing Mechanism in IPv4

          Any computer or computing device connected to the Internet has to be allocated a unique address for identifying it on the worldwide network. This address is called the IP address. This address serves two main purposes: 1 – identifying a host system or a network interface on the Internet, and 2 – providing a logical address for a software application running on that computer.

          IPv4 uses 32 bits for computing this address. Using 32 bits provides a maximum of 232 or 4,294,967,296 (4 billion) unique addresses. Out of these 4 billion addresses, some are reserved for special purposes, such as private networks and for multicasting.

          Also, due to the phenomenal growth of the Internet in the late 80s and early 90s, empty or unassigned IPv4 addresses have started decreasing and are estimated to exhaust before 2012. This anticipated shortage has been the driving factor behind the design of a new version of the Internet Protocol, IPv6.

          IPv6

          IPv6 was designed as a successor to IPv4 and was described by the IETF in a standards document RFC2460 (http://tools.ietf.org/html/rfc2460) published in December 1998. IPv6 uses a 128-bit addressing mechanism, resulting in 2128 (3.4 x 1038) addresses. This vast increase in the address space provides more flexibility in allocating addresses for devices as well as for routing data traffic.

          Why not the name ‘IPv5’ after ‘IPv4’?

          The designers of the next generation IP networks could not use the number ‘5’ as a successor to IPv4 because it had already been assigned to ‘Flow Oriented Streaming Protocol’, an experimental protocol intended to support the transmission of streaming audio and video.

          Key Features and Advantages of IPv6 and Differences from IPv4

          IPv6 uses a new header format which is significantly different from that of IPv4, making the two protocols not interoperable. IPv6 also specifies a new packet format, designed to minimize the computing overhead in processing the packet headers. Some of the key features of IPv6 are listed below.

          • Larger address space

          The most important feature of IPv6 over IPv4 is that it provides a 128 bit address compared to a 32 bit one for IPv4, increasing the addressing capability by several trillions. An example of the addressing provided by IPv6 is shown below. (Source: link)

          IPv6

          IPv6

          • Stateless address autoconfiguration (SAA)

          SAA is a technical term describing a mechanism in which IPv6 hosts can automatically configure themselves using predefined handshake signals and messages defined by ICMPv6 – a protocol designed to augment IPv6. ICMPv6 provides for several messages which are used for diagnostic and error reporting activities.

          • Multicasting

          Multicasting is the ability of a host to send out a single packet to multiple destinations. IPv4 included multicasting as an optional feature (although it was most commonly implemented in all hardware and associated software) whereas IPv6 specifies multicasting as a mandatory feature.

          • Included network layer security

          IPv6 includes a protocol for encryption and authentication – IPSec. This feature too was optional in IPv4 (although it was usually implemented) but made mandatory in IPv

          • Simplified processing by routers

          To make the process of packet forwarding easier, a number of simplifications, the details of which are beyond the scope of this blog, were made to the IPv4 packet header forming the base for the IPv6 header. These changes were targeted at making data forwarding by routers simpler and hence more efficient.

          • Mobility

          Mobile IPv6 (MIPv6) dropped the concept of triangular routing, in which a packet is sent to a proxy before being sent to the intended destination. Hence, mobile IPv6 is as efficient as normal IPv6. IPv6 routers may also support Network Mobility (defined by RFC3933 – http://tools.ietf.org/html/rfc3963) allowing an entire network subnet to move to a new router connection point without being renumbered. Theoretically, this would also increase the efficiency of data flow.

          • Extensibility of Options and ‘Jumbogram’ Support

          Options in IPv6 are implemented as additional extension headers after the IPv6 header, providing the size of an entire packet for implementing an option. This is unlike IPv4, which limits the options parameters to a fixed size of 40 octets.

          IPv4 also limits packets to 65,535 (216 – 1) octets. IPv6 supports packets over this limit, known as ‘jumbograms’ which can be as large as 4,294,967,295 (232 – 1) octets.

          IPv6 Deployment

          Although IPv4 addresses are slowly getting depleted, their exhaustion has been significantly slowed down by the introduction of techniques such as classless inter-domain routing (CIDR) and the extensive use of network address translation (NAT). It has been forecasted that IPv4 addresses will be completely depleted sometime between 2011 and 2012.

          IPv6 still accounts for a very small fraction of the addresses used in the IPv4 dominated public Internet.

          The biggest deployment area for IPv6 is cellular telephony, which is slowly being transitioned from 3G to 4G technologies where voice is seen as a Voice over Internet Protocol (VoIP) service, mandating the use of IPv6.

          Hurdles to the Adoption to IPv6

          The spread of IPv6 usage has been slow due to several barriers to its availability and adoption.

          The biggest barrier to IPv6 adoption is its compatibility with legacy devices. Problems with such devices include manufacturers who either no longer exist, or make updates prohibitively expensive. Problems with these devices also include mask programmed firmware (ROM) which is impossible to upgrade as well as limitations of the device to support the IPv6 protocol stack.

          Newer equipment supporting IPv6 include newer and improved hardware, which also increases the cost of the device to the end customer and makes software development for such devices expensive.

          Lastly, a significant hurdle to the spread of IPv6 is the consumer’s lack of interest, since IPv4 is proving to be sufficient for all their needs right now.

          In summary, we saw in this blog the advantages that IPv6 promises to bring for tomorrow’s connected world. It only remains to be seen when IPv6 becomes as common as the Internet itself is, today.



          Amit Sheth
          Amit Sheth– Sr. Technical Writer

          05
          Aug

          An application menu is critical to any mobile application. This is because real estate in a mobile device is limited, so the developer has to make judicious use of menus to provide good application usability. Android provides us with various ways to introduce a menu. This blog post will cover the different types of menus that you can include in your Android application along with code samples and screenshots.

          Android Menus can be classified into 3 types:

          • Options Menu
          • Context Menu
          • Submenu

          Options Menu:

          Options Menu is the menu displayed when MENU key on the device is clicked.

          Options menu is divided into 2 types: Icon Menu and Expanded Menu, based on the number of menu options. Options menu can have any number of menu options, but only the first six options are shown directly when the MENU key is clicked and this is called as Icon Menu. In case there are more than six options then first five are show directly and remaining are available when More button is clicked and is called as Expanded Menu.

          Note: It is not mandatory to have icon for Icon Menu options. In case icons are associated with menu options,then the icons are displayed for Icon Menu only.

          Important Points:

          • onCreateOptionsMenu() method of the Activity is called when the user clicks the Menu Key of the device. So override this method in the activity and populate the Menu object passed as parameter to this method.
          • Multiple add() methods are available. Use the one that accepts itemId as a parameter.
          • onOptionItemSelected() method of the activity is called when a particular Item/Option of the menu is clicked. Override this method in the activity and implement your code to perform the corresponding actions based on the menu option selected.
          • setIcon() is used for assigning icon with the option.

          The listing below shows how to add a menu dynamically via code. We are overriding the onCreateOptionsMenu method that is automatically invoked when the User clicks on the MENU key on the device.

          public boolean onCreateOptionsMenu(Menu menu) {
          menu.add(0, MENU_ADD, 0, "Add").setIcon(R.drawable.ic_menu_add);
          menu.add(0, MENU_DELETE, 0, "Delete").setIcon(R.drawable.ic_menu_delete);
          menu.add(0, MENU_SAVE, 0, "Save").setIcon(R.drawable.ic_menu_save);
          menu.add(0, MENU_DONE, 0, "Done").setIcon(R.drawable.ic_menu_done);
          menu.add(0, MENU_HELP, 0, "Help").setIcon(R.drawable.ic_menu_help);
          menu.add(0, MENU_SETTINGS, 0, Settings").setIcon(R.drawable.ic_menu_settings);
          menu.add(0, MENU_EXIT, 0, "Exit").setIcon(R.drawable.ic_menu_exit);
          return true;
          }
          

          The listing below shows how to you can react to different menu items that are clicked. We are only displaying the template below. The actual implementation when a specific menu item is clicked depends on your application.

          public boolean onOptionsItemSelected(MenuItem item) {
          switch(item.getItemId()){
          case MENU_ADD:
          // Add
          <span style="white-space: pre;"> </span>return true;
          case MENU_DELETE:
          // Delete
          <span style="white-space: pre;"> </span>return true;
          case MENU_SAVE:
          // Save
          <span style="white-space: pre;"> </span>return true;
          case MENU_DONE:
          // Done
          <span style="white-space: pre;"> </span>return true;
          case MENU_HELP:
          // Help
          return true;
          case MENU_SETTINGS:
          // Settings
          <span style="white-space: pre;"> </span>return true;
          case MENU_EXIT:
          // Exit
          <span style="white-space: pre;"> </span>return true;
          default:
          <span style="white-space: pre;"> </span>return false;
          }   <span style="white-space: pre;"> </span>
          }
          

          Context Menu:

          Android provides the facility to open a menu in context with the object clicked. A Long-press on the view will bring up the registered Context menu.

          Important Points

          • Using registerForContextMenu() method view is registered for context menu.
          • onCreateContextMenu() method of Activity is called on click (long-press) of registered view. So override this method to populate Context menu options.
          • onContextItemSelected() method of activity is called whenever item/option from context menu is selected. Override this method to perform the appropriate operations depending on the option selected.
          public void onCreateContextMenu(ContextMenu menu, View v,
          
           ContextMenuInfo menuInfo) {
          
           super.onCreateContextMenu(menu, v, menuInfo);
          
           menu.add(0, MENU_ADD, 0, "Edit");
          
           menu.add(0, MENU_DELETE, 0, "Delete");
          
          }
          
          public boolean onContextItemSelected(MenuItem item) {
          
           switch(item.getItemId()){
          
           case MENU_ADD:
          
           // Add
          
           return true;
          
           case MENU_DELETE:
          
           // Delete
          
           return true;
          
           default:
          
           return false;
          
           }
          
          }
          

          For this example context menu is register to be shown on TextView. Here tv is an instance of a TextView that is present on the layout of this activity.
          registerForContextMenu(tv);
          Context Menu

          Menu Using XML

          Menu can also be defined and populated using XML. Following XML structure represents the same menu as of above.
          Create optionsmenu.xml under folder res/menu
          <menu
          xmlns:android="http://schemas.android.com/apk/res/android">
           <item android:id="@+id/MENU_ADD"  android:title="Add"
           android:icon="@drawable/ic_menu_add"/>
           <item android:title="Delete" android:id="@+id/MENU_DELETE" android:icon="@drawable/ic_menu_delete"/>
           <item android:title="Save" android:id="@+id/MENU_SAVE" android:icon="@drawable/ic_menu_save"/>
           <item android:title="Done" android:id="@+id/MENU_DONE" android:icon="@drawable/ic_menu_done"/>
           <item android:title="Help" android:id="@+id/MENU_HELP" android:icon="@drawable/ic_menu_help"/>
           <item android:title="Settings" android:id="@+id/MENU_SETTINGS" android:icon="@drawable/ic_menu_settings"/>
           <item android:title="Exit" android:id="@+id/MENU_EXIT" android:icon="@drawable/ic_menu_exit"/>
          </menu>
          
          public boolean onCreateOptionsMenu(Menu menu) {
           MenuInflater inflater = new MenuInflater(this);
           inflater.inflate(R.menu.optionsmenu, menu);
           return true;
          }
          

          Advantages of using XML for creating menu are:

          • Easily maintain/modify the menu structure due to a clear separation of the menu creation from the code.
          • The code in onCreateOptionsMenu() method is reduced.

          Submenus

          Sub menu can be added to any type of menu.

          Below code shows adding Submenu  for Options menu:

          public boolean onCreateOptionsMenu(Menu menu) {
          
            SubMenu sendMenu = menu.addSubMenu("Send");
          
          sendMenu.add(0,MENU_SMS,0,"SMS");
          
            sendMenu.add(0,MENU_EMAIL,0,"EMAIL");
          
           return true;
          
          }
          
          public boolean onOptionsItemSelected(MenuItem item) {
          
          switch(item.getItemId()){
          
           case MENU_SMS:
          
           // SMS
          
           return true;
          
           case MENU_EMAIL:
          
           // Email
          
           return true;
          
           default:
          
           return false;
          
           }
          
          }
          
          Submenu

          Submenu

          <menu
          xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:id="@+id/MENU_SEND"
           android:title="Send">
           <menu>
           <item android:id="@+id/MENU_SMS" android:title="SMS"></item>
           <item android:id="@+id/MENU_EMAIL" android:title="EMAIL"></item>
           </menu>
          </item>
          </menu>
          
          As covered in this blog post, Android provides several ways to include menus in your application. You should pick and choose them depending on your needs. Context Menus are typically expected now by users and should be used carefully in order to provide good application usability.

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