Creating Your First Hybrid Application
By the time you complete this chapter, you will have your first hybrid application working on Android, iOS, and Windows Phone!
Choosing a Packaging Platform
It’s time to say hi by using a hybrid application. To create your first application, you need to set up a framework along with the packaging platform. As discussed in Chapter 3, many popular frameworks and tools are available for coding and packaging. Each has its pros and cons. However, because of its ease in coding and packaging, I prefer to go with Telerik AppBuilder.
Setting Up an AppBuilder Account
To get going, let’s set up a 30-day trial account with Telerik. Here are the steps to create a trial account:
Figure 4-1. First step: visit the Telerik web site
Figure 4-2. Second step: new user registration
Figure 4-3. After e-mail verification
Figure 4-4. Workspaces
Figure 4-5. Creating an app
Figure 4-6. Hybrid project templates from AppBuilder
On the right side of the solution windows, you will find index.html. This is the file in which you will code the maximum number of times.
However, as discussed earlier, because you’re going to call server-side code for getting data (JSON), you should first create the server-side code.
Let’s revisit the client side of AppBuilder.
Authoring a Basic Service Returning JSON
We have discussed the importance of JSON over XML. You can return JSON format data by using either code based on service-oriented architecture (SOA) or by returning JSON as a content type from web applications built using Microsoft .NET PHP, ASP, and JSP. Let’s start with the easiest way by creating an ASP.NET-based generic handler returning JSON data. If you are not from a Microsoft .NET background, you may use SOA base code to return JSON. (When used with Java server-side APIs, refer to https://docs.oracle.com/javaee/7/tutorial/jsonp005.htm.)
You are going to use Microsoft Visual Studio 2012 for the development. You can use an older edition such as 2010. The Microsoft Visual Studio Community 2015 edition is available for free and can be downloaded from www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx.
An Express web edition of Visual Studio may also help.
Let’s start by opening Visual Studio 2012 (Professional, Premium, Ultimate, or Express edition):
Figure 4-7. Create a new project by using Visual Studio
Figure 4-8. ASP.NET empty project template
Figure 4-9. HelloServer workspace
Figure 4-10. Adding a class in the project
Figure 4-11. Add class in project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HelloServer
{
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
}
}
This code is for creating a class whose object will store one person’s or one entity’s (hard-coded) basic information, such as name and address. This information will be converted into JSON format by using a generic handler to our hybrid mobile application.
Figure 4-12. Adding a handler in the project
Figure 4-13. Adding handler into project
// Below line is to convey client browser / hybrid
// application that we are returning data in JSON format
context.Response.ContentType = "text/json";
// Create a person class object
// Assign dummy information to the same
Person person = new Person();
person.Name = "James";
person.Address = "London";
string jsonResult = string.Empty;
// Create Javascript serializer helper object
// Need to refer below namespace for the same
// Put using "System.Web.Script.Serialization"
JavaScriptSerializer jss = new JavaScriptSerializer();
// Serialize person's data in JSON format
jsonResult = jss.Serialize(person);
// Write JSON data to browser / App
context.Response.Write(jsonResult);
Figure 4-14. Error: Forbidden
Figure 4-15. Viewing JSON in the Chrome browser
Figure 4-16. Viewing JSON in the Chrome browser
Writing a Code Snippet Based on HTML5
Now, you have to write client-side (mobile-side) code. You will start by writing code for a plain HTML file on the local drive. This will help you debug and analyze the code.
If you attempt to write the code directly into the AppBuilder project workspace, debugging it would be difficult as it compiles into the cloud and lets you download the final output based on the targeted device chosen.
So, let’s create a new folder named HelloClient under the earlier defined folder.
Follow these steps to complete the HTML5 code snippet:
Figure 4-17. HelloClient folder structure
Figure 4-18. Opening a file by using Visual Studio
<!DOCTYPE html>
<html>
<head>
<title>Say Hi</title>
<script src="jquery-1.11.3.min.js"></script>
<link rel="stylesheet" href="bootstrap.min.css" />
<script src="bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('#btnCallServer').click(function () {
$.ajax({
url: 'http://bonaventuresystems.com/Apress/BeginningHMAD/CH04/
SayHello.ashx',
type: 'GET',
success: function (result)
{
$('#txtName').val(result.Name);
$('#txtAddress').val(result.Address);
},
error: function (err) { alert('Error!'); }
});
});
});
</script>
</head>
<body>
<br /><br /><br />
<div class="container">
<div class="col-lg-3">
Name: <input type="text" id="txtName" value="" />
</div>
<div class="col-lg-3">
Address: <input type="text" id="txtAddress" value="" />
</div>
<div class="col-lg-3">
<input type="button" id="btnCallServer" value="Call Server" />
</div>
</div>
</body>
</html>
Figure 4-19. Running index.html on localhost using Internet Explorer
Figure 4-20. Run index.html on localhost using Google Chrome
Figure 4-21. Opening developer tools on Google Chrome
Figure 4-22. Google Chrome with developer tools
Figure 4-23. Tracking the error on Google Chrome
XMLHttpRequest cannot load http://bonaventuresystems.com/Apress/BeginningHMAD/CH04/SayHello.ashx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:57079' is therefore not allowed access.
This means that the server-side code that is on the domain bonaventuresystems.com does not permit calls from another domain (in this case, localhost:57079). This is a common issue with cross-origin calls, or calls made from one domain to another domain. Such calls have to be permitted through code. So you need to allow calls to SayHello.ashx (bonaventuresystems) from the pages that belong to a different origin (localhost:57079).
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
This line allows calls to SayHello.ashx as a resource from any other domain, as you have specified * in second parameter. After deploying the latest and revised SayHello.ashx file on BonavenutureSystems.com, now when you click the Call Server button, the code ends in Success! After redeployment, the output looks like Figure 4-24.
Figure 4-24. After solving a cross-origin error
Let’s now explore the important lines of HTML, jQuery, and Bootstrap code injected in index.html. This line conveys to the browser that the HTML page is written adhering to the HTML5 standard:
"<!DOCTYPE html>"
"<script src="jquery-1.11.3.min.js"></script>
<link rel="stylesheet" href="bootstrap.min.css" />
<script src="bootstrap.min.js"></script>"
Here referencing sequence matters:
Injecting jQuery into the Code
$ is shorthand syntax for jQuery. The following line asks jQuery to execute a function (which does not have a name—it’s anonymous). This function executes only after the Document Object Model tree (DOM tree) is ready. In simple words, it indicates to execute the function code when all controls in the HTML are loaded in the hierarchy.
"$(document).ready(function () {..........})"
The next line throws an error if it’s not written after the preceding “document ready” line. This line asks jQuery to find a control in the HTML hierarchy with an ID attribute value of btnCallServer. The # before btnCallServer conveys finding by ID. Further, this line also conveys a function (again which does not have a name—it’s anonymous), which needs to be called only when a Click event is raised with btnCallServer.
$('#btnCallServer').click(function () {
The next line makes an AJAX asynchronous call to bonaventuresystems.com/SayHello.ashx and collects the JSON data in an anonymous function conveyed after the success word.
$.ajax(....)
Also, the error is captured in a similar way. In short, the parameters convey the following:
In the following HTML, styles are added using classes given by bootstrap.css:.
<div class="container">
<div class="col-lg-3">
Name: <input type="text" id="txtName" value="" />
</div>
<div class="col-lg-3">
Address: <input type="text" id="txtAddress" value="" />
</div>
<div class="col-lg-3">
<input type="button" id="btnCallServer" value="Call
Server" />
</div>
</div>
These classes help you achieve a responsive UI! Although this code uses only a few classes out of many, the appearance of the UI and the alignment of the controls changes based on the screen of the device.
For example, when this application’s UI is seen on mobile devices and tablets, the alignment of the controls is not a cause for concern because of the responsive UI.
To understand the importance of this library, let’s look at how this page will look on different devices of different sizes! Let’s do the early testing!
Testing the Hybrid Application UI and Code by Using a Browser
Figure 4-25. Enter the site URL in the responsinator
Notice how responsive the UI looks on different devices, as shown in Figure 4-26. The responsinator helps display the UI for many screens.
Figure 4-26. Responsive web design in the responsinator
So all that you’ve done has tested the code on the browser. But, remember, you are deploying a mobile application! Now, let’s package the application using AppBuilder.
Packaging an Application for the First Time Using AppBuilder
Previously in this chapter, you created a trial account on the Telerik web site. Follow these steps to complete the demo packaging:
Figure 4-27. Code in index.html
Figure 4-28. Adding existing files
Figure 4-29. Adding existing resourcess
Figure 4-30. Adding existing resourcess
You don’t have to add index.html, as you already copied its contents into the default index.html from Solution Explorer. Solution Explorer will look like Figure 4-31.
Figure 4-31. Solution after adding existing resourcess
Figure 4-32. Choosing a simulator
Figure 4-33. Adding existing resourcess
Figure 4-34. Changing the simulator
Figure 4-35. Using the Android simulator
Figure 4-36. Windows Phone simulator
Figure 4-37. Choosing the Build option
Figure 4-38. Android packaging
At this point, you need to understand the options. If you choose iOS or Windows Phone, packaging won’t be as smooth as with Android. Why? iOS application packaging using AppBuilder requires that you code sign the application before it gets published!
The process for code signing is explained on the Telerik web site: http://docs.telerik.com/platform/appbuilder/code-signing-your-app/configuring-code-signing-for-ios-apps/configuring-code-signing-for-ios-apps
Windows Phone application packaging using AppBuilder requires a Telerik application enrollment token.
The process for getting a Telerik application enrollment token is explained on the Telerik web site at the following link: http://docs.telerik.com/platform/appbuilder/.
Figure 4-39. Progress of the Android packaging
Figure 4-40. Completed Android packaging
Figure 4-41. Final packaging output
Running a Local Test on the Device
After your package is ready, testing it on a real device requires meeting certain prerequisites of the platforms vendors. For example, the most common requirement is to purchase a developer license from the platform vendor. Costs vary from vendor to vendor. Let’s explore these licensing terms, costs, and obstacles while working on the major platforms.
To publish applications at the App Store, Apple offers a membership program. Membership is available to individuals, organizations, and educational institutions. Fees are always annual; for an individual, the developer program fee is $99 per year. The cost varies for organizations and educational institutions.
The Apple web site says, “This Membership includes access to beta OS releases, advanced app capabilities, and tools to develop, test, and distribute apps and Safari extensions. Developers enrolled as individuals will sell apps on the App Store using their personal name.”
Normally, 100 installations for each device (iPhone, iPad, iPod, and Apple watch) for testing purposes are allowed for each developer license per membership year.
If the app is paid, Apple gets 30 percent of the cost, and the developer takes 70 percent.
More details are available at https://developer.apple.com/programs/whats-included/.
To publish applications on Google Play (formerly the Google Play Store or Android Market), Google offers a membership program. The one-time fee for a publisher account is $25.
You can transfer app output files (APKs) directly to an Android mobile device by using an SD card, the Internet, or Bluetooth without this license. The license is required if you want to publish apps through Google Play.
The revenue model remains the same as that of Apple. More details are available at http://developer.android.com/distribute/googleplay/start.html.
To publish applications on the Windows Store, Microsoft offers a membership program. An individual account costs $19 per year. A company account costs $99 per year.
More details are available at https://msdn.microsoft.com/en-in/library/windows/apps/jj863494.aspx.
Summary
Although many packaging platforms exist, in this chapter you created a simple application with the help of the AppBuilder platform from Telerik.
Using JavaScript in a flavored form such as jQuery, CSS3 in the form of responsive CSS like Twitter, along with HTML5-based UI markup has become a trend nowadays for hybrid mobile application development.
You’ll learn about the internals of HMAD in the next chapter.
18.117.188.64