MSDN Magazine > Issues and Downloads > 2001 > June >  .NET Mobile Web SDK: Build and Test Wireless We...
.NET Mobile Web SDK: Build and Test Wireless Web Applications for Phones and PDAs
MSDN Magazine

.NET Mobile Web SDK: Build and Test Wireless Web Applications for Phones and PDAs

Eric Griffin
This article assumes you�re familiar with WAP, WML. and .NET
Level of Difficulty     1   2   3 
SUMMARY Cell phones, PDAs, and other wireless devices that connect with the Internet enjoy growing popularity, making wireless applications more important and especially useful to companies with remote employees. This article presents an overview of the .NET Mobile Web SDK for building wireless apps. The technologies and design decisions that influence the development of mobile Web applications are discussed along with specific strategies for setting up a development environment using an emulator and building a real-world mobile Web application.
The abstracted programming model of mobile application development makes the Microsoft® .NET Mobile Web SDK the right tool for developing your mobile Web application. The controls isolate you from the differences between devices, allowing you to create write-once, display on any device applications, simplifying the process of mobile applications development.
      In this article I will explain how to use the Microsoft .NET Mobile Web SDK to build Wireless Application Protocol (WAP) and WAP gateway-based Web applications.

Understanding Mobile Technology

      Because the wireless industry was at first headed down a proprietary road, Ericsson, Nokia, Motorola, and Phone.com (now Openwave) founded the WAP Forum in 1997 to unify mobile access technologies. The WAP Forum, now numbering more than 400 members, has contributed to the adoption of WAP and Wireless Markup Language (WML) as de facto standards. You will find WAP and WML in almost every Web-enabled digital mobile phone in the U.S. today, and all of the major communications service providers support WAP. You can still find remnants of older proprietary standards like Handheld Device Markup Language (HDML) supported in existing mobile phones, but the industry has settled on WAP for now.
      WAP is a suite of specifications (including WML) that is based on variations of modern, open Web standards. WML, for example, is based on XML. Wireless specifications were needed because the current Web protocols, TCP and IP, are not well-suited to mobile devices. They were designed for a continuous carrier over which small packets of information (IP datagrams) are transmitted.
      But on a mobile phone network, the radio link frequently goes down temporarily. (This happens to me at a specific spot on my route home every day.) This could dramatically degrade the performance of a protocol such as TCP, which was built for hardwired networks with stable connectivity. When TCP detects that the link is down, it assumes that congestion has occurred in the network and responds by significantly slowing down the transmission rate. When it detects that the link is back up, it takes time for it to return to full speed. Add this to the limited bandwidth available to mobile devices and TCP becomes unacceptable.

How WAP Works

      In the typical Web scenario, a user types a URL into the browser. The browser sends an HTTP request to the Web server, which interprets the request and determines which resources to retrieve or execute. If the URL specifies a file, then the server sends it back. If the URL specifies an ASP page, its code is executed before returning the results to the client. In both cases, the Web server writes an HTTP header to the file or ASP output and sends it back to the browser. The browser interprets the response and displays the contents to the user. Figure 1 compares the typical server/Web browser process with a mobile Web application scenario.

Figure 1 Desktop Versus Mobile
Figure 1 Desktop Versus Mobile

      To access a Web site on a mobile phone, the user types the URL in the browser. Using Wireless Transport Layer Security (WTLS), the mobile phone browser creates an encrypted URL request that contains the subscriber's identification and sends it over Wireless Session Protocol (WSP) to a WAP gateway server. WSP is a variant of HTTP that transfers information in binary format, rather than text-based format. Web protocols such as HTTP and languages such as XML have been designed to be human-readable. But this makes them too big for the wireless world. An HTTP header for a 10KB Web document will be about 100 or 200 bytes. To overcome this problem, WSP converts the HTTP header text into binary data, making the amount of data transferred much smaller. The WAP gateway handles the translation between text and binary. WSP uses the Wireless Transaction Protocol (WTP), instead of TCP, to manage each request-response transaction.
      The WAP gateway server interprets the request, translates it into a conventional HTTP request, and sends it to the Web server. This presents a security risk because during the translation, the data must be decrypted and re-encrypted. Vendor-specific solutions for WAP gateway servers from Microsoft and Openwave address this issue by securing the translation throughout the entire process.
      After receiving the request, the Web server interprets it and determines which resources to retrieve or execute. If the URL specifies a file, the server sends the file to the client. If the URL specifies an ASP page, then the Web server executes the ASP code before sending the results to the WAP gateway server. In this scenario the returned content must be in the form of a WML document.
      The gateway server removes the unnecessary headers, translates the WML document into binary, and sends the response to the mobile phone browser. The browser interprets the WML and displays it to the user.

.NET Mobile Web SDK

      In November 2000, Microsoft released Beta 1 of the .NET Mobile Web SDK. Before the .NET Mobile Web SDK, mobile application developers used a combination of ASP and XML APIs to generate WML. For a good example of this technique, see "Info on the Go: Wireless Internet Database Connectivity with ASP, XML, and SQL Server" in the June 2000 issue of MSDN Magazine.
      Now, not only can you build mobile Web applications for both cell phones and Pocket PCs, you can do it from a single ASP.NET page. These controls generate WML 1.1 or HTML 3.2 for different devices in an intelligent manner.
      The current release of the .NET Mobile Web SDK is not integrated into the Beta 1 release of Visual Studio®. Full integration into the Visual Studio IDE is expected with the next public beta. You can use the Visual Studio editor, but you won't be able to get context-sensitive help, syntax checking, or IntelliSense code completion. I decided to use the old standby—Notepad—instead.

Getting Started

      The first thing you should do after installing the .NET platform and the .NET Mobile Web SDK is get an emulator, such as the Openwave UP.SDK (http://www.openwave.com). This SDK provides an emulator of a WAP browser (UP.Browser) and other reference material on WAP standards. The UP.Browser is popular, so it's a good choice for testing mobile apps that are targeted at the U.S. market. The Microsoft phone emulator, Microsoft Mobile Explorer, is available at http://www.microsoft.com/mobile/phones/default.asp. Figure 2 shows a simulation of an emulator running on a desktop.

Figure 2 WAP Browser Emulator
Figure 2 WAP Browser Emulator

      As stated previously, WML is an industry standard for displaying content on WAP-enabled mobile phones. You can find the formal Document Type Definition (DTD) at the WAP Forum Web site at http://www.wapforum.org. Let's look at the classic Hello World, as a mobile application written in WML.
<?xml version="1.0">
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
    http://www.wapforum.org/STS/wml_1.1.xml>
<wml>
    <card>
        <p>
            Hello World!
        </p>
    <card>
</wml>
      WML defines its user interface components with XML elements and attributes. The top-level container of components is called a deck. Figure 3 shows the relationships between containers in WML.

Figure 3 WML Container Relationships
Figure 3 WML Container Relationships

The deck can contain one or more cards that the user is likely to access in one session. When a WAP-compliant browser receives a deck, it displays the first card. Subsequent cards can be navigated to by a link or programmatically. Now let's see it implemented in the .NET Mobile Web SDK.
<%@ Page Inherits="System.Mobile.UI.MobilePage" Language="C#" %>
<%@ Register TagPrefix="mobile" Namespace="System.Mobile.UI" %>
    <mobile:Form runat="server">
        <mobile:Label runat="server">
            Hello, world!
        </mobile:Label>
</Mobile:Form>
You can copy this code into Notepad and create a new HelloWorld.aspx document in a virtual directory you create for Internet Information Services. Obviously, the code doesn't look like WML. But the displayed result is the same. If you are using the UP.Browser, select the Source menu item from the Info menu; this shows you the WML output, which will look like Figure 4.
      As you can see from comparing the code snippets, they are virtually identical. Now if you access the same URL in Microsoft Internet Explorer or the Pocket Internet Explorer browser on a Pocket PC, you can see the same "Hello World" text. Internet Explorer doesn't support WML, so what gives? If you select View Source in Internet Explorer, you can take a look at the code (see Figure 5). If you ignore the ASP.NET plumbing code in the top of the source, you can see that it is virtually the same code, but in HTML. Figure 6 shows both browsers.

Figure 6 WAP Browser Emulator and Internet Explorer
Figure 6 WAP Browser Emulator and Internet Explorer

      From a single code base you can address a variety of different devices. The Mobile Web controls detect the device and generate the device-specific code for proper display.

Device Independence with MobileCapabilities

      The key behind-the-scenes component of this feature is the MobileCapabilities object. This object inherits from the HTTPBrowersCapabilities object in ASP.NET and extends its functionality to include characteristics of mobile devices. You can access the MobileCapabilities object through the Browser property of the Request object.
Dim capabilities as MobileCapabilities
capabilities = (MobileCapabilities) Request.Browser
      Once you have a reference to it you can use the HasCapability method to evaluate device properties. You can call the method in one of two ways. You can pass a property you want to access or you can add an optional argument to compare to the property value. Both ways are shown here:
bolHasCap = 
 capabilities.HasCapability("IsColor",null)

bolHasCap = 
 capabilities.HasCapability("PreferredRenderingMIME","text/html")

Mobile Web Control Application Model

      The .NET Mobile Web SDK contains ASP.NET server-side controls. This means that all of the control's runat attributes are set to "server." If you want a good start learning ASP.NET Web controls, read Dino Esposito's latest Cutting Edge columns starting with the February 2001 issue of MSDN® Magazine.
      Figure 7 shows the System.Mobile.UI namespace. If you are familiar with the System.Web.UI namespace controls, then you will recognize several controls in this namespace. The user interface controls in the System.Mobile.UI namespace—Link, Panel, Image, TextBox, Label, AdRotator, Calendar, and List—provide similar functionality to their System.Web.UI.Web control counterparts. The validation controls—CompareValidator, CustomValidator, RangeValidator, RegularExpressionValidator, and RequiredFieldValidator provide similar functionality.
      Three controls provide unique functionality: ObjectList, Call, and StyleSheet. The ObjectList object is a control that provides the ability to bind to data. The Call object allows you, on a cell phone, to render a command to dial a phone number specified in its PhoneNumber property. And the Stylesheet object helps organize the styles of a group of controls.

Figure 7 .NET Mobile Control Class Hierarchy
Figure 7 .NET Mobile Control Class Hierarchy

      There are several classes not shown in Figure 7 which are helper classes that make it easier to work with the user interface. They include: MobileListItem, ListCommandEventArgs, ListDataBindEventArgs, ListStyle, and ObjectListCommand.
      In contrast to WML, the .NET Mobile Web SDK container relationship starts with the System.Mobile.UI.MobilePage. The MobilePage can contain one or more forms that the user is likely to access in one session. When the browser receives an HTML file it displays each form as a page. Subsequent cards can be navigated to by a link or programmatically.
      Now that I have gone over the history and technology of the wireless industry and I've introduced you to the .NET Mobile Web SDK, let's apply this knowledge in a real-world application development case study.

Loan Officer Wireless Service

      There are many people behind the scenes who process mortgage information, but the loan officer is at the forefront of the process. He is the salesman for the mortgage company. And like salesmen in other businesses, he is always on the move, making mobile computing important to him. This case study will focus on providing a support application for a typical loan officer.
      With a potentially unlimited amount of RAM and hard disk space available on today's desktop machines, developers are less constrained in the software they design. Of course, you don't have that luxury with mobile applications. You have to remember that mobile phones have small screens with low resolution, limited memory and processing power, and less bandwidth than desktop networks. With this in mind, I decided to focus on activities that required the least amount of input, complexity, and logic flow, so I chose the ordering of credit reports.
      Once I had chosen an activity that I wanted to create with System.Mobile.UI controls, I had to examine the scope of the activity. Ordering a credit report requires you to input the borrower's name, Social Security number, credit report provider (Equifax, Experian, and so on), type of credit report (Infile, RMCR), and the type of order (New, Cancel, Conversion, Reissue, Status). Because a credit report can be dozens of pages long, the first design decision was to not display it on the mobile phone.
      Most mortgage companies have back-end systems that integrate credit reports and other loan documents into a centralized system. Also, loan officers have to order credit reports through the mortgage company, so the choice of credit provider and type of credit report is often predetermined. Therefore, I decided to eliminate one more input variable: credit report provider. I'll assume that the system will read the credit provider configuration information from the database. For simplicity's sake I will not support joint credit reports (this would require one more set of borrower name and SSN).
      When you are designing mobile applications, a good strategy is to limit the amount of input by configuring business logic on the server. The purpose is not to duplicate the robust functionality of the desktop, but to focus narrowly on functionality that is absolutely essential. Less is more in the world of mobile applications.
      After creating a virtual directory, I created the .aspx file to contain the mobile application. The first two lines of code set up the namespaces required to use the .NET Mobile Web SDK.
<%@ Page Inherits="System.Mobile.UI.MobilePage" Language="VB" %>
<%@ Register TagPrefix="mobile" Namespace="System.Mobile.UI" %>
The ASP.NET common language runtime (CLR) dynamically compiles and creates an instance of a page class that inherits from System.Mobile.UI.MobilePage. As indicated in the Language attribute, the language is Visual Basic. The second line registers "Mobile" as shortcut for "System.Mobile.UI". This is used in control elements to avoid writing <System.Mobile.UI:ControlName> .
      Security is a key design consideration regardless of application platform. Since mobile devices aren't clients of Windows®, the matter of authentication becomes important. Fortunately, there are ways to ensure who the user is. Every mobile phone has a unique ID assigned to it. Outside of hardware- or platform-specific authentication, the MobileCapabilities object provides a way to identify a user using the UniqueDeviceID property.
      Place this code in the Page_Load method of the MobilePage.
Dim capabilities as MobileCapabilities
Dim strDeviceID as String
capabilities = Request.Browser
strDeviceID = capabilities.UniqueDeviceID
Now you can query a database or file for IDs that match; in this case, the loan officer's mobile phone. If no match is found, deny permission or route to another page.
      The first form in the system will be a menu. Like desktop applications, mobile applications must provide easy navigation to functionality. In this app I'll have two menu items: Credit Report Request and Credit Report Status. These are created with the List control.
<Mobile:Form  runat="server">
    <Mobile:Label runat="server" 
     StyleReference="title">Loan Officer Services</Mobile:Label>
    <Mobile:List runat="server" OnItemCommand="Menu_OnItemCommand">
        <Item Text="Credit Report Request" Value="1" />
        <Item Text=" Credit Report Status" Value="2" />
    </Mobile:List>
</Mobile:Form>
The First element defines the System.Mobile.UI.Form with an attribute of runat="server". The next line is a System.Mobile.UI.Label that is the title of the application. The Stylesheet class defines a default stylesheet that supports a number of styles. The StyleReference attribute is assigned the default title style, which translates into a font style of bold and a font size of large. Immediately following the label is the System.Mobile.UI.List. The System.Mobile.UI.List component (see Figure 8) has a different appearance than a List control in Windows.

Figure 8 A List
Figure 8 A List

Each item has the Text and Value attributes set. The List control has an event attribute called OnItemCommand. Here it is set to specify a method, Menu_OnItemCommand, that is called when a list item is selected. For an item selected using the Go button to be posted back to the server, the Menu_OnItemCommand method is executed with the sender and event arguments being passed.
Sub Menu_OnItemCommand(sender as Object,
                       e as ListCommandEventArgs)
Select Case e.ListItem.Value

        Case 1
            ActiveForm = frmCreditRequest
        Case 2
            ActiveForm = frmLoanStatus

    End Select
End Sub
ListCommandEventArgs contains a reference to the List controls properties. Remember, with ASP server controls, all state information is maintained on the server, so property values will hold their values across posts to the server. The Select Case statement determines which menu item was selected and sets the ActiveForm to the corresponding form. That form is displayed to the user.
      Now let's get to the heart of the system: the credit report request form. The credit report request form is defined simply.
<Mobile:Form id="frmCreditRequest" runat="server">
</Mobile:Form>
An ID is assigned as frmCreditRequest for reference by other parts of the application.
      I've determined that the inputs needed are borrower name, Social Security number, type of credit report, and type of order. The borrower name and SSN will be defined as System.Mobile.UI.TextBoxes with matching labels. This is accomplished with the code that is shown in Figure 9.
      Both label controls will appear plain because they are left without a StyleReference. IDs of Name and SSN are assigned to each TextBox, respectively, so they can be referenced in code later.
      Let's consider another standard application design concern: data validation. The List controls are of less concern because a valid default selection is the first item in the list. Validation on the two TextBoxes, however, should be required. So a System.Mobile.UI.RequiredFieldValidator is assigned to each TextBox by the RequiredFieldValidator's ControlToValidate attribute to make sure the user enters data.
      The SSN TextBox, however, needs further validation. A CustomValidator control is used in this case. The ControlToValidate is assigned to the SSN ID like the RequiredFieldValidtor. Two additional attributes, OnServerValidate and ErrorMessage, define the Boolean function (SSN_ ServerValidate) on the server to invoke validation and get the text to display to the user when the function returns false. The code to enable this validation process is shown in a function called SSN_ServerValidate (see Figure 10).
      The type of credit report and type of order will be defined as lists. The Items are defined as shown in Figure 11. Notice the SelectionMode attribute in each of the lists. In this mode, the List control allows users to select from choices in the list. This selection does not generate immediate events as it does when the list is in interactive mode. Another user interface element, such as a command, is required to submit the selection back to the server. Therefore, I provide a Command control to do just that.
<Mobile:Command runat="server" 
 OnClick="cmdSubmitCreditRequest_OnClick" Text="Submit" />
In the Command control, the OnClick attribute indicates the event that the server will execute. In this case, it is cmdSubmitCreditRequest_OnClick.
      The code in the cmdSubmitCreditRequest_OnClick method makes frmCreditSubmit the active form.
ActiveForm = frmCreditReportSubmit
      To complete the entire credit report submission process, the frmCreditRequest submits the data from frmCreditReportRequest to some asynchronous process such as MSMQ, and displays results of the submission process. This is a multistep process, so let's start by looking at the code (frmCreditReportSubmit_OnActivate) that is fired when the form is activated.
Dim bolSubmitted as Boolean 
'Submit the request to an asynchronous (MSMQ?) process and respond 
'back to the Loan officer 
'if it was successfully submitted
'Let's assume it was successfully dropped.
bolSubmitted = True
if bolSumitted = true and Page.IsValid = True then 
    lblSubmission.Text = "was successful"
    frmCreditReportSubmit.DataBind
Elseif bolSubmitted = False or Page.IsValid = False then
    lblSubmission.Text = "was unsuccessful"
End If
      Because credit requests are submitted to credit providers, it is not wise to have the mobile phone user waiting for a reply. However, asynchronous notification is beyond the scope of this article, so I've set bolSubmitted to true.
      There are several other lines of code worth noting in the previous snippet. The IsValid property is inherited from the MobilePage's parent System.Web.UI.Page class. The Page object has a reference for all of the validation controls it contains. The property indicates whether any validation control within it has failed. Remember, all of these controls and forms are defined on a single MobilePage.
      Before I move to the other areas of the frmCreditReportSubmit_OnActivate code, let's examine the definition of the frmCreditReportSubmit form (see Figure 12). Here I am trying to show the results of the submission via a Label named lblSubmission and redisplay the values submitted with frmCreditRequest. If you look at the event code in frmCreditReportSubmit_OnActivate (see Figure 13) you can see that I am doing this in two ways. Based on the value of bolSubmitted, I assign the Text value of the lblSubmission control to "was successful" or "was unsuccessful". This displays at the bottom of the frmCreditReportSubmit form. A Label control is defined in frmCreditReportSubmit for each corresponding submitted control values (txtName, txtSSN, lstReportType, lstOrderType) from frmCreditRequest. The labels are bound using a combination of inline ASP.NET code between label definition elements and the frmCreditReportSubmit.DataBind method call in the frmCreditReportSubmit_OnActivate event.
frmCreditReportSubmit.DataBind
      The Databind method creates a binding between a server control property and a data source. When called, it initializes the properties of the control with the data specified. The form with no validation errors at runtime can be seen in Figure 14.

Figure 14 Credit Report
Figure 14 Credit Report

      At the top of the frmCreditReportSubmit definition is a definition of a ValidationSummary. It collects the values from the ErrorMessage property of each control where the validation test failed, and can present these messages to the user within the page. Otherwise, each error would appear on a separate screen. Once the user is presented with all of the errors, a link is provided to bring them back to where the errors occurred. With a mobile phone's limited screen size, it is important to avoid any extra screen navigation.
      The remaining menu item, Credit Report Status, follows the same code pattern. A form called frmCreditReportStatus is defined to receive an input of a Social Security number (see Figure 15).
      The form validates the Social Security number and calls cmdSubmitCreditReportStatus_OnClick when the Submit button is pressed.
Sub cmdSubmitCreditRequest_OnClick(sender as Object, e as EventArgs)
    ActiveForm = frmCreditReportSubmit
End Sub
Validation of the control is done in the frmCreditReportStatusSubmit form with a SummaryValidation control, as shown in Figure 16. If there are no validation errors, a default value of "received" is displayed to the user.

Conclusion

      Since .NET Mobile Web SDK components are ASP.NET-based, they can be deployed on any ASP.NET-enabled Web server. While most mobile network carriers like Sprint and AT&T support WAP/WML-based mobile Web applications with a WAP gateway server, it's best to check with your mobile phone carrier to make sure their servers are compatible.
      The .NET Mobile Web SDK provides a way to build mobile applications easily using a rich set of user interface components. These components intelligently render themselves based on the device capabilities. Using this SDK protects you from the winds of changing standards by abstracting the development model for mobile applications. The .NET Mobile SDK is expected to be renamed in Beta 2 to Mobile Internet Toolkit. Plans are for it to include support for additional devices, an extensibility model for adding new device support and a drag and drop user interface that works within the Visual Studio.NET environment.
For related articles see:
http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml

Eric Griffin is a senior development manager for Mortgage Originations and Servicing at London Bridge Group. He can be reached at egriffin@lbss.com.

From the June 2001 issue of MSDN Magazine.


Page view tracker