Adding AJAX Support to Windows Mobile Applications

Introduction

Web applications designed for browsers on desktop computers have already for a long time used scripts to create more usable user interfaces. Add AJAX support on top of this, and you are getting close to the rich set of features available in traditional desktop applications. However, the world is getting more and more mobile, and users start to utilize your web applications from their mobile phones.

Because the browsers available in mobile phones have been previously quite limited, using advanced scripting functionality has been difficult. However, Microsoft's Windows Mobile platform includes the Pocket or Mobile Internet Explorer browser (usually abbreviated PIE or WMIE), and the most recent versions of this browser support AJAX. AJAX support has been available in a limited way already since Windows Mobile 5.0, and the later 6.0 versions already contain nice support for AJAX applications. This brings many possibilities for application developers.

In this article, you are going to learn how you can use Visual Studio 2008 (Windows Mobile development is not currently available in the beta releases of Visual Studio 2010) and C# to develop a simple AJAX-enabled web application that works on a Windows Mobile Professional 6.0 phone or later. For testing purposes, you are going to learn how to use a phone emulator. This makes at least initial testing easier, as you don't need to have a real phone right away.

Getting ready to develop web applications for WM 6.0

When Visual Studio 2008 became available a few years ago, Windows Mobile 5 was the main mobile platform that the tool supported out of the box. This means that if you are interested in developing applications for Windows Mobile 6.0, you would need to separately download the Windows Mobile 6.0 SDK package, and install it on top of Visual Studio 2008 SP1.

The SP1 (Service Pack 1) for Visual Studio is also required to test the code shown in this article. For information on where to download both Visual Studio 2008 SP1 and the Windows Mobile 6.0 SDK, see the Links section at the end of this article.


Figure 1. The Windows Mobile 6.0 SDK can be freely downloaded from Microsoft's web pages

Installing both the Mobile SDK and the SP1 for Visual Studio is straightforward, although installing especially the SP1 can take a long time. Even on a fast computer, it can take an hour or more to get both installed. However, the process is highly automatic, and your intervention is basically needed only to launch the installation process or log in after a reboot.

Once the installation is complete, you can start Visual Studio (you will need to close it to install the updates) and create a new project for your web application. Since the focus of this article is on adding AJAX functionality to ASP.NET web applications, you do not need to start a Visual Studio Smart Device (Windows Mobile) project, but instead a regular web project.

For the purposes of this article, you will see how you can use ASP.NET MVC for web application development, but you are free to use the more traditional WebForms model just as well. Even so, the new MVC model contains good support for AJAX, and if you haven't already investigated this new technology, it is a good time to start. Remember that ASP.NET MVC is not a native part of Visual Studio 2008, and thus you will need to separately download a small installation package for it, too.

Creating a simple MVC application skeleton

To get started with development, create or open an ASP.NET MVC project. Then, add a new controller class to the Controllers folder in the project, and give it an appropriate name, such as "MobileAJAXController". The name of the controller indicates that it will handle requests for the relative path /mobileAJAX. This information becomes handy later.

Since you need to be sure a Windows Mobile phone can connect to your ASP.NET MVC application, it's best to initially create a very simple controller action method to serve content to the mobile phone. ASP.NET MVC supports, in the simplest scenario, action methods that return plain strings. You could then add the following method for testing purposes. You can later on improve it to do some real work:

  public string Hello()
  {
      return "Hello, World!";
  }

If you want, you can test that your MVC application works as expected by hitting the F5 key in Visual Studio (or by choosing the Start Debugging command from the menu) and testing the controller action you just added in your computer's browser. The address should be something like http://localhost:1234/mobileAJAX/hello. The port number will change dynamically, but Visual Studio will automatically launch your browser with the correct URL.

If your tests succeed, the next step would be to make sure the application is running on a real web server, namely IIS. IIS is required so that you can really test the application on a mobile phone; the development web server that comes with Visual Studio will not allow network connection from outside localhost.

Because of this limitation, you will need to find a server running IIS (preferably a Windows Server 2008 system with IIS 7.0 or 7.5, as these versions contain best support for ASP.NET MVC applications).


Figure 2. IIS must be properly configured to test mobile applications, even with the emulator

This article will not focus on setting up IIS for MVC applications, but you can find detailed instructions from the MVC documentation. The following sections assume that you have IIS installed, and that you can access the application with an URL such as:

http://myserver/mobileAJAX/hello

Of course, your real URL will vary, so be sure to adjust the URL accordingly when testing.

Adding AJAX Support to Windows Mobile Applications

Connecting the mobile emulator to the network

Once you have the Web application running on IIS, you can start testing it from the mobile phone emulator. Visual Studio comes with support for phone emulators, and some of these phone emulators can also support network connections. You will need such a connection when testing your web application. The only difficulty with the emulators is that the network connection setup is somewhat complex. The following paragraphs quickly walk you through this setup.

First, you need to start the correct emulator. If you were writing a smart device (Windows Mobile) project with Visual Studio, then you could start the emulator by just starting debugging (or by pressing the F5 key). However, since the project you are creating is a web application, Visual Studio will not automatically start the mobile emulator. Instead, you must use the Device Emulator Manager manually. You can start the manager from Visual Studio's Tools menu.

[Manager.jpg]
Figure 3. The Device Emulator Manager lets you start, stop and configure available Windows Mobile emulators

The Device Emulator Manager allows you to start and stop mobile emulators. From the list, you should be able to see all supported emulators, including the Windows 6 Mobile emulators that you installed previously. To start the Windows Mobile 6 Professional emulator, right-click it and choose Connect from the menu.

When the emulator is running, you can start a so-called Cellular Emulator. This emulator, part of the Windows Mobile 6 SDK kit, allows you to emulate a real network connection. With it, you can also establish an emulated data connection to the Internet using your computer's Internet connection.

[Emulator.jpg]
Figure 4. The Cellular Emulator is part of the Mobile SDK kit

To set up networks, first start the Cellular Emulator (you'll find the icon from the Start menu; just type "cell" and you should find it if you are using Vista or Windows 7). At the bottom of the screen, you'll see the COM port to which the emulator has attached itself. You must connect the phone emulator to the same COM port. To do this, select the File/Configure command from the phone emulator's menu, and then go to the Peripherals tab. Once you have entered the same COM port (such as COM4) to the first text box, clicked OK and soft-reseted the mobile emulator, the network connection should become available.

[PeripheralSettings.jpg]
Figure 5. Specify the same COM port used by the Cellular Emulator to the phone emulator's serial port 0

Note that a network connection is different from an Internet connection on the phone. To establish an emulated GPRS (General Packet Radio Service) data connection for Internet access, return to the mobile emulator, and configure the phone to use the data connection for Internet access.

This can be done as follows. In the mobile phone, click Start, and then point to Internet Explorer (IE). Try to open any web address, such as www.bing.com. Since the connection has not been configured yet, IE will display an error message (see Figure 6). In this error message, click the Settings link. You will be transferred to the Connections screen, where you can find the Advanced tab at the bottom. On this tab, click the Select Networks button, after which you will see the Network Management window. Click the Edit button to edit the "My ISP" connection.

[NetworkError.jpg]
Figure 6. Even if you have configured the cellular network emulator and connected it to the mobile emulator, Internet Explorer cannot by default access the web

Next, click the New button, and in the Make New Connection dialog, enter any name you choose as the connection name. From the "Select a modem" combo box, choose "Cellular Line (GPRS)". This particular setting is important to make correctly. Once you are done, click the Next button at the bottom of the screen. In the next two screens, simply click Next and Finish, as you don't need to type in an access point name nor a username or password.

At this point, you should be back at the "My ISP" connection screen. Make sure your newly added connection is listed, and then point to Start and Internet Explorer. Then, try accessing any web site, and IE should be able to display the page. You can also try to access to your IIS web server to see if your web application is available. If you still cannot connect, carefully repeat the above setup steps.

Once all this is done, it's a good idea to save the emulator state by choosing the Save State command from the emulator's File menu. This way, you don't need to repeat all the network setup steps the next time you start the emulator.

Adding AJAX Support to Windows Mobile Applications

Adding AJAX functionality to the web application

Now that you have successfully deployed your initial ASP.NET MVC application version onto an IIS web server, configured an emulated network connection and accessed your application through the Pocket Internet Explorer browser, it is time to start adding some real functionality to your web application. Let's try to implement a button in the web application that can update a DIV element based on the server response. Although this is a very basic operation, it is a fundamental building block in every AJAX application.

In regular ASP.NET MVC applications, you can easily add such functionality with the AJAX helper object. However, the problem with these ready-made scripts is that the less advanced JavaScript engine in the Windows Mobile web browser cannot cope with scripts written for desktop PCs, and thus you cannot directly use the AJAX helper object.

Instead, you must settle for a bit less, and write the necessary JavaScript by hand. First, assume that you have written the following controller method to respond with a "Hello, World" type of message based on an input value. Of course, in real applications, you could return any other data in place of the string, such as JSON encoded database objects. For simple demonstration purposes like these, a simple string will do just fine:

  public string AJAXMessage(string country)
  {
      return "Hello, World from " + country + "!";
  }

With this method in place, you need to write some JavaScript code into the appropriate view page (.aspx file). If you were writing scripts for a desktop browser, you could write a tag similar to the following:

<%= AJAX.ActionLink("Show AJAX Message", "AJAXMessage",
 new { country="Finland" },
 new AJAXOptions { UpdateTargetId = "hello-message" }) %>

But as noted, the mobile browser is not capable of executing the more advanced JavaScript functions. Instead, if will need to directly access the Msxml2.XMLHTTP object that is part of the Windows Mobile operating system. If you wanted to update a DIV with the id of "mobileAJAXResponse" in response to a button click, you could write HTML code like this:

  <input type="button" value="Call AJAX" id="callAJAX"
  name="callAJAX" onclick="return callAJAXMethod();">
  <p>&nbsp;</p>
  <div id="mobileAJAXResponse"></div>

The OnClick event handler of the button is associated with a JavaScript function called "callAJAXMethod". This function is implemented as follows:

  <script language="javascript" type="text/javascript">
    function callAJAXMethod()
    {
      alert("Starting to call AJAX method");
      req = new ActiveXObject("Msxml2.XMLHTTP");
      req.onreadystatechange = showAJAXResponseOnScreen;
      req.Open("GET", "/mobileAJAX/home/"+
        "AJAXmessage?country=Finland", true);
      req.Send();
      alert("AJAX method returns: " + req.responseText);
      return true;
    }
  ...

The Alert message box calls aside, the call to ActiveXObject creates the request object capable of making AJAX calls. Then, the OnReadyStateChange event (name capitalized here for readability) is assigned so that the results of the asynchronous AJAX calls can be collected. The Open method of the request object selects the correct endpoint URL. Notice how you don't need to specify a host name; this makes things easier as the relative URL points always back to the same server from where the HTML code originated. Finally, the Send method causes the AJAX request to be sent to the server.

When the reply comes back, the request object will call the function pointed to by the OnReadyStateChange event. In the case of the sample application, this event handler is implemented as follows:

  function showAJAXResponseOnScreen()
  {
    if (req.readyState == 4) 
    {
      if (req.status == 200)
      {
        alert("showAJAXResponse Step 1");
        mobileAJAXResponse.innerText = req.responseText;
        alert("showAJAXResponse Step 2");
      }
    }
  }

The ShowAJAXResponseOnScreen function is called multiple times as the AJAX request is processed and sent to the server, and the server response is fetched back. The ReadyState property indicates the current state (it is a simple integer value), and a value of four means that the call succeeded and the server response has been read. At this point it is also worth checking the Status property, which indicates the HTTP status code of the response. The well-known code of 200 indicates success; codes like 404 or 500 would indicate failure.

If the request state is four and the status is 200, then the inner text of the selected DIV tag is set to equal the server's response text. Note how you can directly use any element that has a proper id attribute in your JavaScript code. This makes development easier.

[SampleApp.jpg]
Figure 7. The sample application has successfully updated its user interface in response to an AJAX call

At this point, the user interface has been updated according to the server's response. And this was the goal of the sample application! Remember that the JavaScript support is quite basic in the Windows Mobile browser. This means, among other things, that debugging JavaScript problems can be difficult. For instance, if you make a syntax error, no error messages or icons will be shown on the screen. Instead, the JavaScript just fails to run. Using the simple yet effective Alert message boxes in strategic places often saves you a great deal of debugging time.

Conclusion

In this article, you learned how you can create modern, AJAX enabled web applications for Windows Mobile devices and their humble Internet Explorer browsers. Testing these web applications can require multiple steps to make everything work correctly, but once you have deployed your web application to a real web server (physical or virtual), connected the mobile phone emulator to a GPRS data connection, all is set.

In the web application, you must currently write all the necessary JavaScript code by hand. However, this only requires around 20 lines of code, which is not much. With this code in place, you can easily update parts of your user interface based on the AJAX requests and server responses. This brings many benefits to the mobile phone user, even though you must take into account the limited HTML support and screen sizes on these devices. You could also add code to detect if the user is using a Windows Mobile phone or a full-blown desktop browser. This would allow you to use a single code base for both usage scenarios.

On the server side, ASP.NET MVC is a good technology as it contains nice built-in support for AJAX calls and even JSON encoding. Although you could almost as easily use the more traditional WebForms technology for your server-side code, the MVC pattern also brings easier unit testing. Happy hacking, and Happy New Year!

Jani JC$rvinen

About the Author

Jani JC$rvinen is a software development trainer and consultant in Finland. He is a Microsoft C# MVP and a frequent author and has published three books about software development. He is the group leader of a Finnish software development expert group at ITpro.fi and a board member of the Finnish Visual Studio Team System User Group. His blog can be found at http://www.saunalahti.fi/janij/. You can send him mail by clicking on his name at the top of the article.

Resource

ASP.NET MVC main page
Windows Mobile developer center
Windows Mobile 6 Professional SDK kit download
Visual Studio 2008 SP1 download
ASP.NET MVC 1.0 installation package download



About the Author

Jani Jarvinen

Jani Jarvinen is a software development trainer and consultant in Finland. He is a Microsoft C# MVP, a frequent author and has published three books about software development. He is the group leader of a Finnish software development expert group at ITpro.fi and a board member of the Finnish Visual Studio Team System User Group. His blog can be found at http://www.saunalahti.fi/janij/. You can send him mail by clicking on his name at the top of the article.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Webinar on September 23, 2014, 2 p.m. ET / 11 a.m. PT Mobile commerce presents an array of opportunities for any business -- from connecting with your customers through mobile apps to enriching operations with mobile enterprise solutions. Join guest speaker, Michael Facemire, Forrester Research, Inc. Principal Analyst, as he discusses the new demands of mobile engagement and how application program interfaces (APIs) play a crucial role. Check out this upcoming webinar to learn about the new set of …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds