.NET Web Services On Mobile Devices
By Anthony Hart
  Download C# Source Code

If you haven't heard about Web Services or PDAs (personal digital assistants such as the iPAQ) by now, I don't know what rock you've been hiding under, but it's high time you got out from under it - and this is just the article to help you step into the daylight.  In this article we'll demonstrate how to design a client application for the PocketPC platform in VisualStudio.NET 2003 and use it to connect to a Web Service.
Web Services
Before we begin our little demonstration, we should briefly review some general concepts - especially if you really have been hiding under a rock for the past few years.  In case you have, Web Services are quite possibly one of the most interesting technologies to emerge in the business world recently.  To keep it simple, we can think of Web Services as modules of code that we can access over the Internet.  They are very similar to class libraries, only they physically reside on a remote server rather than in our own application code.
We can design client applications that communicate with Web Services, sending them parameters to receive generated results in true black-box fashion.  The protocol used in this kind of communication is Simple Object Access Protocol (SOAP), an XML-based mark-up language.  When Web Services first came on the scene, developers had to be able to understand, and be able to write, SOAP messages. With VisualStudio.NET (VS.NET), though, most of that is hidden from us and we can concentrate more on application design.
Because SOAP is a form of XML, it is platform-agnostic. Any platform or application can theoretically read it - of course, a proper parser is needed to be able to do so.  This platform independence opens up some exciting possibilities.  We can write a Web Service in Java, for example, and host it on some Linux server on the other side of the globe and then access it, via the Internet, from a VisualBasic application running on a Windows desktop machine.  In this way, organizations can expose certain data stores or applications to the public if they so choose - and they don't have to be concerned with providing the data in varying formats in order to appease varying platforms.


Personal Digital Assistants
Another beautiful technology to surface in recent years is the personal digital assistant (PDA).  The public has been quick to adopt this technology for use in organizing schedules, reading email on the go, and even keeping a library of eBooks in one's pocket.
The two main competing platforms in the PDA world are the Palm OS and Microsoft's PocketPC.  Both platforms have been ported over to a variety of devices by a variety of manufacturers and both have quite a few models that allow for access to the Internet in one way or another.
Right about now the savvy reader will be putting two and two together and starting to imagine some interesting possibilities regarding the mixture of Web Services and PDAs.  That savvy reader is right!  If Web Services can be used by any computer with a proper parser, why not use a PDA to access them as well?  Why not indeed?  As a matter of fact, we're going to show you how to do just that.
Setting Up a Client Application
For the rest of this article we'll be using VS.NET 2003 to target the PocketPC platform.  We'll be connecting to a language translation Web Service to give the PDA user a way to translate words and phrases to and from several different languages.  Although the concepts presented herein are fairly general, there are some specifics that may not jibe with other versions of VS.NET or other IDEs.  In addition, we'll be using the PDA emulator that is installed with VS.NET in order to do our debugging.  If you wish, you may debug and test by deploying the application directly to a PDA, but that method is a bit more time-consuming than using the emulator.  We usually find it more efficient to test thoroughly using the emulator and then deploy the application to a PDA once it has received our first stamp of approval.
Without any further ado, then, let's fire up VS.NET. First of all, select File|New|Project from the main menu and then in the "New Project" dialog select the "Smart Device Application" item for the .NET language of your choice (in this article we'll be using C#).  Don't forget to give the project a name. We named it "Translator".
Once we've chosen to create our new project, another dialog appears, asking us to specify what PDA platform to target and what type of PDA project we wish to create.  We want to target the PocketPC platform (as opposed to the Windows CE platform) and to create a Windows Application (as opposed to a class library, etc.), so make the selections as shown below:
Once that's done, we're ready to start designing.  First, we'll add the controls we'll need (a ComboBox to hold a list of languages, a TextBox to allow for the entry of the phrase we wish to translate, another TextBox for displaying the resulting translation, and a Button to execute the translation process).
Something worth noting is that PDAs currently have some limitations when it comes to memory and some functionality.  Consequently, we often have to make allowances for these limitations (much as we do for senior citizen drivers).  In our sample application, communication between the PDA and the translation Web Service takes several seconds.  To keep users from wondering what the delay is during the process, we will place a reminder on the screen for them.  So far your form should look similar to the screenshot below:
Connecting to the Web Service
Now that we've got the rudiments of a client application fleshed out, we can add in a reference to the translation Web Service, but before we do, there is something worth noting to those new to Web Services.  We make this note so that you will better appreciate the work that is saved by tools such as VS.NET.
When Web Services were still young and innocent, we developers had to write proxy classes that would act as an intermediary layer between our client application and the Web Service.  The proxy class would reflect in code the methods and parameters of the target Web Service.  Obviously, this required some amount of knowledge of what public methods were available in the Web Service.
Enter Web Services Description Language (WSDL). WSDL is yet another XML-based mark-up language.  It describes the data types, methods, parameters, etc., that a Web Service contains - all those exposed publicly, of course. Application such as VS.NET read the WSDL of a Web Service in order to provide more developer-friendly ways of creating a proxy class to communicate with the Web Service.  In the case of VS.NET, for example, all we have to do is set a reference to the valid URL of a Web Service (or its accompanying WSDL) and a proxy class is automatically generated for us.  We don't have to play around with SOAP or WSDL or any other unpleasant thing.
Having explained all of that, we will now show you how easy it is to generate a proxy class in VS.NET. Right-click on the References folder in your Solution Explorer.  When the pop-up menu appears, select "Add Web Reference" and the following dialog will appear:
In the dialog's "URL" textbox, type in the URL of the Web Service you want to use.  For our example, we're using the free translation Web Service provided by WebServiceX at: http://www.webservicex.com/TranslateService.asmx.  After you've got that typed in, click the "Go" button.  If the Web Service is found, you'll be treated to the following display in the dialog:
If all is well, all you have to do now is click the "Add Reference" button in the dialog and the proxy class will be created for you.  You should notice a new "Web References" folder in your Solution Explorer containing an item entitled, "com.webservicex.www", as shown here:
Finishing Up the Client Application
With the proxy class created to allow a connection to the Web Service, we can now return our attention to the client application.  First, we'll add a "using" statement to the code so we won't have to write out the entire reference to the Web Service every time we want to access it.
using Translator.com.webservicex.www;
			
Next, we'll write an initialization method to be called when the form loads up.  The translation Web Service exposes an enumeration called "Language" that delineates how the translations can take place (e.g., EnglishTOJapanese, FrechTOGerman, etc.).  Unfortunately, the limitations inherent to the PDA once again restrict our ability to write the most efficient code possible.  In other words, we'll have to hard-code the language items for the ComboBox instead of being able to do so dynamically.  We would much rather have accessed the language enumerations contained in the Web Service itself and populate the ComboBox based on that, but the Enum class for the Compact Framework doesn't allow us to do that.  So, we're stuck with hard-coding the list as follows:
private void Init(){
	try{
		//Load the dropdown
		this.cboLanguage.Items.Add(Language.ChineseTOEnglish);
		this.cboLanguage.Items.Add(Language.EnglishTOChinese);
		this.cboLanguage.Items.Add(Language.EnglishTOFrench);
		this.cboLanguage.Items.Add(Language.EnglishTOGerman);
		this.cboLanguage.Items.Add(Language.EnglishTOItalian);
		this.cboLanguage.Items.Add(Language.EnglishTOJapanese);
		this.cboLanguage.Items.Add(Language.EnglishTOKorean);
		this.cboLanguage.Items.Add(Language.EnglishTOPortuguese);
		this.cboLanguage.Items.Add(Language.EnglishTOSpanish);
		this.cboLanguage.Items.Add(Language.FrenchTOEnglish);
		this.cboLanguage.Items.Add(Language.FrenchTOGerman);
		this.cboLanguage.Items.Add(Language.GermanTOEnglish);
		this.cboLanguage.Items.Add(Language.GermanTOFrench);
		this.cboLanguage.Items.Add(Language.ItalianTOEnglish);
		this.cboLanguage.Items.Add(Language.JapaneseTOEnglish);
		this.cboLanguage.Items.Add(Language.KoreanTOEnglish);
		this.cboLanguage.Items.Add(Language.PortugueseTOEnglish);
		this.cboLanguage.Items.Add(Language.RussianTOEnglish);
		this.cboLanguage.Items.Add(Language.SpanishTOEnglish);
	}

	catch(Exception ex){
		ErrMsgOut(ex);
	}
}
			
Now we'll write a method to handle the translation process.  When the "Translate" button is clicked, we want to make sure, first of all, that a translation language was chosen.  If not, we'll send a message to the user informing him that the language selection was invalid.  Otherwise we'll check to make sure the user has specified a word or phrase to translate.  If he hasn't, he'll get a message telling him to shape up, otherwise we'll move on to the actual translation.
The translation is the easy part. The Web Service does most of the work for us.  All we have to do is instantiate the proxy class that communicates with it and call its Translate() method, sending it the language choice and the phrase to translate.  Behind the scenes the proxy class then connects to the Web Service, sends it the information we specified, retrieves the result, and sends the result back to us in the form of a string.  All we have to do then is spit the string out to the user.  Notice that we didn't even have to dirty our hands with any SOAP.  The method we wrote to handle the translation process and display the result to the user is shown here:
private void DisplayTranslation(){
	try{
		//Make sure a valid language selection is chosen
		object oLang = this.cboLanguage.SelectedItem;
		if(oLang!=null){
			//Make sure we've got a string to translate
			string sPhrase = this.txtPhrase.Text.Trim();
			if(sPhrase!=String.Empty){
				//Clear out anything that might be in the results box
				this.txtTranslation.Text = "";

				//Perform the translation
				Language lang = (Language)oLang;
				TranslationService ts = new TranslationService();
				string sResults = ts.Translate(lang, sPhrase);

				//Display the results
				this.txtTranslation.Text = sResults;
			}
			else{
				WrnMsgOut("Enter a phrase to translate.");
			}
		}
		else{
			WrnMsgOut("Invalid language selection.");
		}
	}

	catch(Exception ex){
		ErrMsgOut(ex);
	}
}
			
Debugging
Except for some error and event handling our client application is now all but complete.  To test the application we'll use the emulator that we mentioned earlier in the article.  To do so, we'll simply press F5 (or select Debug|Start from the main menu) to compile the application and start the debugger.  The following dialog will appear, asking us whether we want to debug using the emulator or deploy the application to a PDA to debug:
It's normally a better idea to use the emulator for preliminary debugging, so we'll select that option and then click the "Deploy" button.  The first time VS.NET fires up the emulator takes a little while.  What's happening is that VS.NET is "installing" the application to the emulator - virtually, of course.  Once the pseudo-insallation is complete, the emulator starts the application.  If all went well, we should see the following:
Now we can try it out.  We can choose to translate the imaginative phrase, "translate me", from English to Spanish, for instance, and click the "Translate" button.  As we mentioned earlier, due to the memory limitations of the PDA device, the communication with the Web Service will probably take several seconds.  If we wait patiently, however, we should be rewarded with the following screen:
Deploying
Playing around with the emulator is all fine and dandy, but the whole point of this application is to allow the user to get his urgent translations on the go.  Eventually, then, we'll have to install this application on a real PDA.
As with just about everything in VS.NET, installing to a PDA is pretty intuitive and simple.  Since we're dealing with the PocketPC in this article, we need to make sure our PDA is connected to our computer via ActiveSync.  Next, we go to our project in VS.NET and select Build|Deploy Solution from the main menu.  The deployment dialog that we saw when we started our debugging process appears.  This time, however, we will select to deploy to a device instead of to the emulator - and then click "Deploy".  In a few moments our application should be sitting on our PDA, awaiting our eager attention.  We should be able to find it there using PocketPC's File Explorer.  It should be sitting in the "My Device/Program Files/Translator" directory (if you have followed the same naming conventions as indicated in this article).  A tap on the Translator application icon will execute the program and, provided your PDA is connected to the Internet, you can now translate trite phrases on the go.
An alternate way to deploy the application would be to select Build|Build CAB File from the main menu in VS.NET.  Several command line windows pop up and then disappear again as the CAB file is being built.  Once completed, you can use ActiveSync to drag and drop the appropriate CAB file over to your PDA.  While this deployment method allows you more control over the process, the former method tends to be a lot easier to use.
Conclusion
In this article we have discussed Web Services and PDAs.  We have also used the example of an translation application to show how to design a PDA application that exploits a remote Web Service over the Internet.  We encourage the reader to download the source code that accompanies this article and to also experiment with his own ideas.  There are many free Web Services available and the only limit is our imagination - and the money to pay for a mobile Internet account.