The objectives of this chapter are to
This chapter discusses data access in hybrid mobile applications and service-oriented architecture. The major focus is on accessing JSON and XML data in hybrid application(s) through web services and Windows Communication Foundation (WCF) Service. We also discuss ways to secure this communication. Let’s start by discussing various ways to transfer data.
Exploring Data Access Possibilities
If we consider only server-side endpoints to transfer data, there are many options available from Microsoft, .NET, Java, and PHP. As discussed earlier, for hybrid applications, it does not matter which server-side technology or tools you use. As long as the server returns data to the client application in an understandable and well-known format—such as JSON, XML, String, or Arrays—the client side is always happy.
Tables 6-1, 6-2, and 6-3 list the technology and languages provided for data access on the server side.
Table 6-1. Microsoft: Data Access on the Server Side
Let’s look at sample code snippets. All code snippets assume that we need to transfer the Employee class object from server side to client.
// comments added in the code denotes important statement
Employee class layout is like:
public class Employee
{
public int No { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
The code snippet for the handler:
//Code is written in file with .ASHX extension
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//IMPORTANT: One can set contentType in the following line:
context.Response.ContentType = "application/json";
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.Write(jss.Serialize(new Employee()));
}
public bool IsReusable{ get{ return false; }}
}
The code snippet for web services:
// Code is written in file with .ASMX extension
[Webservice] //This line conveys this class is available for call remotely
public class TestWebService
{
[Webmethod] //This line conveys; that this method is available for calling
public Employee GetEmployee()
{
return new Employeee();
}
}
Code snippet for WCF services:
//Code is written in file with .SVC extension
//The following line conveys that implementation of this interface
//is available for call remotely
[ServiceContract]
public interface ITestWCFService
{
//The following line conveys; that method implementation is available for calling
[OperationContract]
Employee GetEmployee()
}
//The following is actual implementation of an interface inside class
public class TestWCFService:ITestWCFService
{
public Employee GetEmployee()
{
return new Employeee();
}
}
The code snippet for the Web API controller in ASP.NET MVC:
// Code is written in plain code file (eg. C# files like .cs extension)
// APIController is base class offered by ASP.NET MVC Framework
public class ValuesController:ApiController
{
//While calling The following method; use url like - "http://<server>/api/values/<id>"
//GET conveys that only "GET" requests can reach to this method
public Employee Get (int id)
{
return new Employeee();
}
}
Table 6-2. Java / Oracle: Data Access on Server Side
(+/–) |
Servlet |
Web Services |
---|---|---|
(+)points |
Easiest option available for data transfer. Content type of the response can be set manually. You can even set it to XML / JSON. GET, POST request data can be collected using QueryString and getParameter() method respectively This can be clubbed with any back-end business logic written using EJB or any legacy code! Host is web server. |
Old and easy option available for data transfer. Data is always passed using SOAP format. Internally uses XML over Http Plain Old Java Objects are formed automatically while data is received from client. Conversion tools like JaxB, JiBX can be used to create POJO. Deserialization part is handled automatically. Host is web server. REST is supported through REST APIs; also known as JAX-RS |
(–) points |
Only HTTP carrier can be used Security of data is not automatically given; rather provided through Java APIs Primarily used for HTML like output generation. |
Only HTTP carrier can be used. Data security is applied through code. |
The code snippet for servlet returning employee’s data in JSON format:
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
{
//set contentType to anything here. The following code sets up type to 'json'
response.setContentType("application/json");
// The following, employee related data is written in JSON format
// One may use custom code for achieving the same or
// use 'jsonobject' class
response.getWriter().write("{Name:'James',Address:'London'}");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
// TODO Auto-generated method stub
doGet(request, response);
}
}
The code snippet for Java web service endpoint using the Java API for XML Web Services (JAX-WS):
import javax.jws.WebService;
//The following code '@Webservice conveys that the code open for call remotely
@WebService
public class TestWebService
{
//The following code '@WebMethod' conveys that the method is open for call remotely
@WebMethod
public Employee GetEmployee() {
return new Employee();
}
}
Table 6-3. PHP: Data Access on Server Side
(+/–) |
PHP Page Using Content Type |
---|---|
(+)points |
Easiest option available for data transfer. Web server is a host. Content type of the response can be set to anything including XML / JSON. REST support can be added optionally. PUT and DELETE request complex implementation needs to be handled. |
(–)points |
Only HTTP carrier. Data security needs to be provided through code. |
The code snippet for the PHP endpoint using content type JSON:
<?php
//The following line conveys about content type being returned from PHP
header("Content-Type:application/json");
//return employee data
echo '{"No":1,"Name":"sachin","Address":"mumbai"}';
?>
Usually, data can be easily transferred in the form of XML or JSON from the server side by simply setting the content type. However, in an earlier section, we discussed many ways to achieve the same. At a high level, if we try to categories most the techniques, we see two groups:
What is the difference between the two? What are the advantages and disadvantages of each? Let’s look at this now.
SOAP is the default protocol for accessing web services. It’s been in the technology market for a while. SOAP was developed by Microsoft. SOAP is a bit difficult to use in some languages, while in others, it’s a piece of cake. SOAP relies completely on XML to transfer data. Microsoft’s goal in developing the SOAP protocol was to replace older technologies that don’t work well on the Internet; an example of such a technology is Distributed Component Object Model (DCOM).
After launching the first draft of SOAP, Microsoft handed over the details to a community called the Internet Engineering Task Force (IETF), where it was standardized and made open to the technology world. Many standards were built around SOAP afterward, such as WS-Policy and WS-ReliableMessaging, and so forth.
SOAP-based web services also completely rely on a concept called Web Service Description Language (WSDL), which is a file that contains all the information any client ever requires to call the service. This information includes information such as where to call, how to call, and what data to pass on.
A call to SOAP-based services through JavaScript is difficult. The formation of a request in JavaScript with XML is not handy at all. If the response comes in the form of XML, then before DOM version 2, very difficult and nonstandard ways of dealing with XML were used. What happened in DOM2? We got an extra object, since then called XmlHttpRequest [XHR], along with documents, Windows, and Navigator into the DOM tree. So, compared to SOAP, which relies on XML, REST simply relies on URL.
REST is new to the market compared to SOAP. A call can be given to the server using a REST URL, but you have to use the HTTP 1.1 verbs GET, POST, PUT, and DELETE. SOAP web services only use XML, whereas REST uses different data formats, including JSON, RSS (Really Simple Syndication) feeds along with XML.
So, what you should you prefer: SOAP or REST? The consultant’s answer is—It depends!
The decision depends on many factors, such as the following:
Tips to GET or SET Data
To pass data between the client and the server, two techniques or verbs are used very frequently: GET and POST. Other —like DELETE, PUT, and HEAD—are not as frequently used because they have specific purposes.
As HTTP is a protocol, data travels in packets. A packet has a header and a body. If the data travels in the header, then it’s a GET request. If the data travels in the body, then it’s a POST request. POST is safe compared to GET, because GET data can be seen in the URL.
Table 6-4 is a basic comparison between GET and POST requests.
Table 6-4. GET and POST Comparison
GET |
POST |
---|---|
• Data entered travels in the header part of the HTTP • Data can be seen in the URL itself, so not safe. • This method should not be used to transfer critical data • Only ASCII data is allowed to be passed • If one does refresh the page or hits back button, then it does not cause any harm • Contents passed using this method is allowed for caching • Data + URL <= 2048 characters |
• Data entered travels in the body part of the HTTP • Data cannot be seen directly. However, with the tools like fiddler it can be seen. • This method is generally used to transfer critical data like username and password • No restrictions • If one does refresh the page or hits back button; then it does re submit the content • Contents passed using this method does not get cached • Generally, a maximum size of 4GB is recommended. |
Let’s look at certain tools that help debug and test client-side code. We will use the hybrid application developed in Chapter 4 as a base for debugging and testing.
The content looks like what is shown in Figure 6-1.
Figure 6-1. Open first HMAD project
Output like what’s shown in Figure 6-2 must appear in the open default browser.
Figure 6-2. Recheck the code
Now, that we are sure that the code is still working, let’s test network traffic with tools such as the browser’s built-in helper and Telerik Fiddler.
Figure 6-3. Developer Tools in Chrome
Figure 6-4. Developer Tool: Network
The Network tab displays downloadable resources, like JQuery and Bootstrap files; without these resources, index.html cannot function. The Network tab also displays other information (see Figure 6-5).
Figure 6-5. Developer Tools: Network
More details are shown in Figure 6-6.
Figure 6-6. Developer Tools: Request details
Figure 6-7. Developer Tools: Response and Preview details
Figure 6-8. Developer Tools: Time tab
You can get more information on where the delay is in entire cycle of request and reply. At this time, if someone clicks the Call Server button, one more request is added in the pool on the left side (see Figure 6-9).
Figure 6-9. Developer Tools: New request on Call ServerClick
Now, if you want to see the response contents, click the Response tab. It shows data in JSON format, as shown in Figure 6-10.
Figure 6-10. Developer Tools: JSON after GET
In Figure 6-11, a call to SayHello.ashx was made as a GET call using AJAX.
Figure 6-11. Developer Tools: Explicit GET AJAX Call
What will happen if we make the same changes to POST? The results are shown in Figure 6-12. Data passed (if any) travels in the body of the HTTP packet. As you can see in Figure 6-12, nothing changes except the request method as POST. Pulling data out of the body is automatically done by the browser. The browser first dissects the content type and then decides what to do with it.
Figure 6-12. Developer Tools: Explicit POST AJAX Call
You can also use Telerik Fiddler to the do the same job. However, it is more advanced than the default supplied browser-based developer tools. Telerik Fiddler can help to generate a request to do tests only. You may even dissect HTTPS details to a certain extent with the help of Telerik Fiddler.
Let’s use Fiddler and have a glimpse.
Figure 6-13. Telerik Fiddler
Figure 6-14. Telerik Fiddler: default session tracking
Figure 6-15. Telerik Fiddler: AJAX call being tracked
So far, we have used Fiddler for tracking the calls over network. We can also use fiddler for raising different kind of requests as if client.
Figure 6-16. Telerik Fiddler: Composer window
Figure 6-17. Telerik Fiddler: Inspectors window
This is similar to when we explicitly offered a POST call to server. By using Composer, we can save a lot of time when testing calls to the server over multiple verbs.
Browser-based Debug, Monitor, and Trace
Debugging is needed to find logical errors in code. For managed code like C#, Java editors provide very rich support for debugging. However, JavaScript remains ignored by many editors. Today, browsers do have extended support for debugging JavaScript. Let’s look at the support given by Google Chrome. Similar support is provided by other browsers.
Let’s use our first hybrid mobile application to learn about debugging.
Figure 6-18. Add debugger inside JavaScript code
Figure 6-19. Google Chrome with Developer Tools
Figure 6-20. Debugger in success function
Figure 6-21. Result manipulation using Console window
Figure 6-22. Resume Script Execution
Changes to the result received can be observed in UI (see Figure 6-23).
Figure 6-23. UI after result manipulation
Similarly, you can debug and manipulate with Firefox, IE (EDGE), and other browsers.
Code and Data Security
Now let’s discuss another important concept in hybrid mobile applications. For hybrid apps, UI testing can be easily done with the help of browsers only. It is preferable that the code be written in JavaScript or JQuery. The deployable output in Android and Windows Phone hybrid applications is an internally compressed file. You can uncompress and find internal files like index.html. Afterward, finding JavaScript or JQuery code inside the index.html file is not tough.
Similar issuess are faced by web programmers when most of the code is written in JavaScript. Since JavaScript runs on the browser, you can read the JavaScript code contents by viewing the source.
How to protect JavaScript code? Two options exist:
Providing JavaScript files or resources on demand is a feature of server side and custom logic. However, obfuscation and minification of JavaScript can be done through tools. Let’s talk about the frequently used tools for minification:
To demonstrate what minification means, consider the following JavaScript code and store it in the sample.js file because it may be asked as an input by the compressor. Figure 6-24 explains.
Figure 6-24. Sample page
Figure 6-25. ShrinkSafe web page
JavaScript obfuscation is a process through which we make JavaScript unreadable! This protects your code and prevents it from being stolen. The obfuscation process is done through a utility called the Obfuscator. While doing obfuscation, some obfuscators shrink the size of the JavaScript, which makes the JavaScript code download faster. So, obfuscation does many good things.
There are many obfuscators available on the market. To demonstrate the process, let’s consider the following JavaScript code snippet from a case study appended after last chapter in this book. Save this script in the sample.js file. The code snippet size on disk is 932 bytes.
var modulesSize = $(jsonResult.survey.Modules.Module).size();
for (modulescnt = 0; modulescnt < modulesSize; modulescnt++) {
moduleData = null;
if (modulesSize == 1) {
moduleData = jsonResult.survey.Modules.Module;
}
else {
moduleData = jsonResult.survey.Modules.Module[modulescnt];
}
ModuleText = moduleData.ModuleText[0].value;
ItemsCount = null;
ItemsData = null;
ItemsCount = $(moduleData.Items).size();
for (itemscnt = 0; itemscnt < ItemsCount; itemscnt++) {
if (ItemsCount == 1) {
ItemsData = moduleData.Items;
}
else {
ItemsData = moduleData.Items[itemscnt];
}
}}
Now, let’s do the obfuscation.
As discussed earlier, there are many obfuscators, such as JScrambler and Jasob. You must pay for most of these tools. The price varies from $30 to $50 annually. However, we will evaluate it through a trial edition. Let’s use JSOB obfuscator.
Figure 6-26. Jasob JavaScript Obfuscator
Figure 6-27. Jasob: analyze source file
This analyzes variables, which are lines that can be reduced and further obfuscated. More details can be observed in Figure 6-28. Also note that the Obfuscate Source File button is now activated.
Figure 6-28. Jasob: analyze and obfuscate source file
Figure 6-29. Jasob after obfuscation
After obfuscation, the code looks like this:
Code Snippet: Size of the code on disk = 509 bytes
-----------------------------------------------------------------------
var modulesSize=$(jsonResult.survey.Modules.Module).size();for(modulescnt=0;modulescnt<modulesSize;modulescnt++){moduleData=null;if(modulesSize==1){moduleData=jsonResult.survey.Modules.Module;}else{moduleData=jsonResult.survey.Modules.Module[modulescnt];}ModuleText=moduleData.ModuleText[0].value;ItemsCount=null;ItemsData=null;ItemsCount=$(moduleData.Items).size();for(itemscnt=0;itemscnt<ItemsCount;itemscnt++){if(ItemsCount==1){ItemsData=moduleData.Items;}else{ItemsData=moduleData.Items[itemscnt];}}}
-----------------------------------------------------------------------
var modulesSize = $(jsonResult.survey.Modules.Modul
If you notice, the size of the code has drastically reduced to 509 bytes from 932 bytes and has no or less readability. So, using minification and obfuscation, we can successfully make JavaScript secure with a lower size. Obfuscation can protect code, but it may not help in the security of data, which comes dynamically from the UI.
How do we securely pass data to and from the server? There are multiple ways:
Figure 6-30. HTTPS communication
> Joseph Myers (http://www.myersdaily.org/joseph/javascript/md5-text.html)
> Paul Johnston
(http://pajhome.org.uk/crypt/md5/)
> Masanao Izumo
(https://gist.github.com/dsc/2970392)
For credentials (like the username and password, which needs to be passed to server), the usage of a POST request is always advised.
Encode or encrypt? Many people get confused about these terms. The purpose of encoding data is to transform data in such a way that the data-receiving party can understand it. Keep it in mind, encoding never assures security. ASCII, binary, and Unicode are forms of encoding.
Encryption, however, makes data secure.
Summary
This chapter discussed the different ways available to transfer data in a hybrid mobile applications. We also learned the basics of GET and POST request.
The next chapter discusses responsive CSS and related style classes.
18.119.103.204