Click to Rate and Give Feedback
Related Articles

If you want to apply static analysis to your databases, connect to remote computers, find out more about the Entity Framework, or just check into some cool podcasts for your daily commute, then you'll want to read more about these latest tools and resources.

Scott Mitchell

MSDN Magazine July 2009

...

Read more!

This article describes how to use XHTML and ASP.NET MVC to implement REST services.

Aaron Skonnard

MSDN Magazine July 2009

...

Read more!

Cobra, a descendant of Python, offers a combined dynamic and statically-typed programming model, built-in unit test facilities, scripting capabilities, and much more. Feel the power here.

Ted Neward

MSDN Magazine June 2009

...

Read more!

In this month's column, we’ll explore the pros and cons of both ASP.NET Web Forms and ASP.NET MVC.

Dino Esposito

MSDN Magazine July 2009

...

Read more!

In this column, the author lays out some guiding principles that you should follow when working with the ASP.NET MVC framework.

Scott Allen

MSDN Magazine July 2009

...

Read more!

Also by this Author

Paul Yao presents an overview of Windows Embedded CE 6.0.

Paul Yao

MSDN Magazine December 2006

...

Read more!

Check out the cool new features in Windows XP Tablet PC Edition, including a number of Ink types, and ink that's stored as ink. Here Paul Yao takes you on a tour of everything you need to know to get started.

Paul Yao

MSDN Magazine December 2004

...

Read more!

Windows CE .NET, the newest member of the .NET family, includes a number of improvements over previous versions of Windows CE. For example, there are quite a few new APIs and enhancements to security and connectivity, the user interface, the kernel, and the emulator. In addition, DirectX support has been added and C++ in Windows CE .NET now supports C++ exceptions, STL, and runtime type information. In this article the author takes a tour of Windows CE .NET, starting with the New Platform Wizard that allows you to code for your choice of devices. ...

Read more!

This article provides an overview of writing applications for Windows CE 3.0. Unicode support in Windows CE, the kernel, memory management, the object store, and COM and DCOM are discussed. The article also covers the user interface, graphics, the Internet, and how Windows CE compares to the desktop in each of these areas. eMbedded Visual Tools 3.0 is discussed in depth. To help the reader decide which tools to use, development with Visual Basic, Win32, MFC, and ATL are explained. Text editor samples with this article have been developed with ...

Read more!

Handheld device users need to be able to synchronize with a main data store when it's convenient and, preferably, when the back-end database server isn't busy. SQL Server 2000 Windows CE Edition allows you to build a traveling data store that can be displayed and run on a variety of devices. SQL Server CE supports a subset of the full SQL Server package, and can be used as a standalone server or in tandem with SWL Server and IIS. The architecture of SQL Server CE, along with data manipulation, synchronization, and connectivity issues, are discussed ...

Read more!

Popular Articles

James Avery does it again with his popular list of developer tools. This time he covers the best Visual Studio add-ins available today that you can download for free.

James Avery

MSDN Magazine December 2005

...

Read more!

Jason Clark

MSDN Magazine July 2003

...

Read more!

WPF is one of the most important new technologies in the .NET Framework 3.0. This month John Papa introduces its data binding capabilities.

John Papa

MSDN Magazine December 2007

...

Read more!

The MVP pattern helps you separate your logic and keep your UI layer free of clutter. This month learn how.

Jean-Paul Boodhoo

MSDN Magazine August 2006

...

Read more!

Paul DiLascia

MSDN Magazine August 2002

...

Read more!

Wireless Web
Microsoft Mobile Internet Toolkit Lets Your Web Application Target Any Device Anywhere
Paul Yao and David Durant
Code download available at: MMIT.exe (53 KB)
Browse the Code Online

This article assumes you're familiar with ASP.NET
Level of Difficulty 1 2 3
SUMMARY
If you've built Web sites using ASP.NET, you'll welcome the Microsoft Mobile Internet Toolkit (MMIT). MMIT extends the Visual Studio .NET IDE you already know by providing new controls for handheld devices letting you easily develop applications for wireless devices. This means you can write less code while adapting it to more devices. Not only does MMIT integrate with Visual Studio .NET, it extends ASP.NET as well. This article gives you the background you need to write, test, and deploy a site with MMIT and make all your code able to target specific devices for a custom fit.
Anyone who has worked in the world of raw markup languages knows it's like swimming in an ocean of tags. While HTML and WML seem tame on the surface (like a giant squid ), developers can easily get lost in their long and spindly tentacles. The problem is that these languages can't be avoided—not even for mobile applications.
The Microsoft® Mobile Internet Toolkit (MMIT) enables ASP.NET programmers to target their Web sites for mobile Internet devices without jumping back into the messy world of tag languages. If you have been studiously ignoring all things mobile and WML-based, you might have missed the article ".NET Mobile Web SDK: Build and Test Wireless Web Applications for Phones and PDAs" by Eric Griffin, which was written when MMIT was in beta. That article explores the idea of building Web sites that support WAP-based phones. It shows you how much better it can be with an ASP.NET approach. Surprisingly few features have changed in the release version of MMIT, which makes Griffin's article a good source for background information.
This article focuses on the key features of the released Microsoft Mobile Internet Toolkit. We will begin by describing how MMIT supports multiple markup languages and multiple mobile devices to help simplify the addition of mobile device support to ASP.NET-based Web sites. Then we will discuss how MMIT integrates with Visual Studio® .NET. You'll learn how to use familiar drag and drop actions to build mobile forms and how the mobile controls are supported by C# and Visual Basic® .NET code the same way that regular ASP.NET controls are supported. Then we'll dig deeper into the way that MMIT extends ASP.NET, showing you the relationship between the namespaces and classes of both sets of controls. And finally, we'll demo a sample mobile Web application—MovieFinder. We'll demonstrate how MMIT lets a single application appear on both an HTML-based Pocket PC (and Pocket PC Phone Edition) device, and on WAP/WML-based cell phones.

ASP.NET Makes Mobile Development Easy
To ASP.NET programmers, the morass of commingled tags and script is a thing of the past (except, of course, while maintaining legacy Web pages). The separation of content from code, for one thing, means that your HTML can live in an ASPX file and your server-side code in a C# or Visual Basic file. The code behind the HTML reaps the benefits provided by the Microsoft .NET Framework, such as the tidy organization of namespaces, the features of an object-oriented language (including inheritance, polymorphism, and containment), common data types, and the consistent programming interface.

Support for Multiple Markup Languages
It's hard work building Web sites using raw markup languages. When something is not rendering properly, you can spend hours studying the tags to figure out why. Even though MMIT manages most of the tags, they will sometimes need your attention. Also, MMIT provides a set of controls for you, but just like ASP.NET, you can add custom controls if the standard ones don't do everything you need them to do. Building MMIT custom controls definitely requires you to understand the associated markup.
When a targeted device uses an MMIT-supported markup language, most of your work is done for you. If it doesn't, then you might have to go back to the coding-by-scratch approach. For example, MMIT does not support the Handheld Device Markup Language (HDML) tags used in older cell phone browsers, nor does it yet support the newest WML 1.3 tags. Figure 1 summarizes the four markup languages that are supported.

Language Comments
HTML 3.2 Pocket Internet Explorer on Pocket PC, Pocket PC 2002, and Pocket PC Phone Edition
cHTML 1.0 A subset of HTML 2.0 and HTML 3.2 designed for battery-powered, modest memory devices such as mobile phones
WML 1.1 and WML 1.2 Wireless Markup Language (WML) is a standard for an HTML-like text markup language built for mobile wireless devices; WML is part of a larger set of protocols called the Wireless Application Protocol (WAP)
Keep in mind that at any time another version might ship or a Device Update Pack may add new functionality to MMIT. To keep up to date, you can look in the MMIT documentation for the MobileCapabilities class. For ASP.NET programmers, this is an extension of the HttpBrowserCapabilities class that adds elements for mobile Web devices. To see what other markup languages are supported by MMIT, you should refer to a member of MobileCapabilities named PreferredRenderingType. MMIT 1.0 supports the following values for this read-only property: html32, wml11, wml12, and chtml10.

HTML 3.2
For the sake of comparison, remember that the latest version of HTML is version 4.0—it's supported by the latest version of Microsoft Internet Explorer, version 6.0. HTML 3.2 is a more basic kind of HTML. It is the version supported by the Pocket Internet Explorer that ships on the Pocket PC, on the Pocket PC 2002, and in the Pocket PC Phone Edition. (Developers who use the Windows® CE .NET Platform Builder need to know that this is the same Pocket Internet Explorer you find under the Internet Client Services folder in the Platform Builder.)
So how does HTML 3.2 compare to HTML 4.0? HTML 3.2 supports tables and nested tables, which is how Web developers organized Web pages before frame support became available. HTML 3.2 doesn't support Cascading Style Sheets (CSS), so all formatting needs to be hardcoded the old-fashioned way instead of being centralized in nicely named styles. HTML 3.2 does not support client-side processing, so you cannot use DHTML to validate data or animate a user interface. (Note that animated GIFs have historically not been supported in Pocket Internet Explorer, which displays them as non-animated images.) Nor is client-side data-binding supported (the DATASRC and DATABIND tags that call an ActiveX® control to query databases). Note, however, that this is different from server-side data-binding support, which is available in ASP.NET.
Figure 2 summarizes the HTML tags available in HTML 3.2. It's a pretty reasonable set of tags for creating rich text, tables, and data entry forms. You can create hyperlinks, display bold text, and have data entry input boxes, selection lists, and form submission buttons. This subset is certainly enough to support help text, which is why the standard help file format on the Pocket PC is plain HTML.

HTML Tag HTML 3.2 cHTML
A
ACRONYM    
ADDRESS  
APPLET    
AREA  
B  
BASE
BASEFONT  
BGSOUND  
BIG  
BLINK    
BLOCKQUOTE
BODY
BR
BUTTON    
CAPTION  
CENTER
CITE  
CODE  
COL    
COLGROUP    
COMMENT  
DD
DEL    
DFN  
DIR
DIV
DL
DT
EM  
EMBED    
FIELDSET    
FONT  
FORM
FRAME  
FRAMESET  
Hn
HEAD
HR
HTML
I  
IFRAME    
IMG
INPUT
INS    
ISINDEX    
KBD  
LABEL    
LI
LINK    
MAP  
MARQUEE    
MENU
META
NEXTID  
NOBR  
NOFRAMES  
NOSCRIPT  
OBJECT    
OL
OPTION
P
PARAM  
PLAINTEXT
PRE
Q    
S  
SAMP  
SCRIPT  
SELECT
SMALL  
SPAN    
STRIKE  
STRONG  
STYLE    
SUB  
SUP  
TABLE  
TD  
TEXTAREA
TFOOT    
TH  
THEAD    
TITLE
TR  
TT  
U  
UL
VAR  
WBR  
XMP  
HTML 3.2 also supports JavaScript, JScript®, and ECMAScript. While it does not provide the same level of client-side processing as DHTML, JavaScript does offer you some options. JavaScript support is important because MMIT uses it for data validation and for sending form data from a client device to the server. Read about the HTML 3.2 standard at http://www.w3.org/TR/REC-html32.

cHTML 1.0
Compact HTML (cHTML) describes an HTML derivative that was created for devices that are simpler than desktop browsers. It consists of a set of tags from HTML 2.0 and HTML 3.2 (and a subset of attributes for the supported tags) that are appropriate for small-screen devices that have one font, no pointing device, and are typically navigated by a small set of keys. See Figure 2 for a comparison of HTML 3.2 tags and cHTML tags. Such devices have limited memory and are often battery-powered.
In other words, cHTML describes a tag language that is based on HTML and can be used with HTML development tools for mobile phones. As you probably know, a properly designed HTML parser ignores all unrecognized tags, so a cHTML browser can sometimes make sense of Web pages that don't have too many bells and whistles. Unfortunately, the bad news is that when a Web page relies on those bells and whistles to communicate some important information, such as navigation, those elements are lost on users of cHTML-based browsers.
cHTML supports many important HTML features, including the ability to display text, scroll through the text, display and navigate a hyperlink, display a form, and send data collected from a form back to a server. So what HTML features are not supported? First, none of the HTML 4.0 features are supported, including frames and cascading style sheets. The FONT tag is not supported because there is only a single font on such devices. The TABLE tag is not supported since cHTML-targeted devices have such small screens, and JPEG images are not supported (but fortunately GIFs are) because such devices have a very limited amount of memory.
There is also no support for JavaScript or any other scripting language. Where MMIT relies on a scripting language for tasks such as data validation and form data submission, such things have to be handled differently on a cHTML device. Some tasks that you'd want to perform on a client device, like data validation, must be handled by the MMIT server. For submitting form-based data through a cHTML device, the MMIT relies on the postback data to retrieve values entered into form fields. The W3C Web site provides a note on cHTML that can be read at http://www.w3.org/TR/1998/NOTE-compactHTML-19980209.

WML
The third set of tag languages supported by MMIT is WML versions 1.1 and 1.2. WML is loosely based on HTML, and there are some tags that the two markup languages have in common, such as those you can see listed in Figure 3. If you are familiar with HTML, you will find it easy to jump right into the world of WML.

Tag Description
<a> Anchor (hyperlink)
<b> Bold text
<big> Large font text
<br> Line-break
<head> Document header
<hr> Horizontal rule
<i> Italic text
<img> Embedded image
<input> Accept user input
<meta> Meta information
<p> Paragraph
<select> Display selection list
<small> Small font text
However, there are many differences between the two languages. While they do share some common tags, far more tags are unique to each language. For example, HTML 3.2 supports tables (TABLE tag) and multiple fonts (FONT tag). WML, for its part, supports the idea of card-decks and cards (with the card tag), and exception handling (catch and throw tags). Even among common tags such as <a> and <input>, there are differences in how each language handles them.
An important difference is that WML is an XML-based language, which means that WML documents must follow stricter rules than HTML documents. XML is case-sensitive and HTML is not. While <P> and <p> mean the same thing in HTML, only one of them (the lowercase version) is valid in WML. Like all XML documents, WML documents must be well-formed; all opening and closing tags must match. To give some common examples, you cannot have a <p> tag that doesn't have a matching </p>, nor can you have a <br> tag that isn't closed by a </br> tag. What you can do, however, is combine an opening and a closing tag together, so that <p/> and <br/> are legal.

A Simple Example: Hello MMIT
To make sense of all of these tag markup languages, let's look at an example of what each of them looks like for the same MMIT content. The supported tag languages come together in source tags that MMIT itself creates and uses. We've decided to keep it very simple with the classic "Hello" output. Figure 4 shows the output on a Pocket PC and on a cell phone (actually, on the OpenWave simulator). There's nothing fancy here, just two pieces of text that say "Hello MMIT".
Figure 4 Hello Output 
The purpose of this example is to show differences between the tag languages that MMIT supports, not to show off everything that MMIT can do. Toward that end, the text on the page is not inside any control (like a textbox or a label), but rather sits by itself on the page. Admittedly, this is not a realistic example because without the wrapping of the control, there is no programmatic access to the text. But we wanted to keep it simple. To be able to type text directly into Visual Studio .NET, you have to change the pageLayout property of the DOCUMENT to FlowLayout from the default of GridLayout.
Here's a tiny bit of HTML that simply displays the text "Hello MMIT" without any frills—no formatting, no tables, just the plain text. In spite of our attempt to keep things simple, there are obviously many lines of text. For one thing, everything is inside an HTML form. The basic framework for collecting data from a user and posting it to the server is already in place, although it won't do much for us until we add some more code to the very simple page that's shown in Figure 5.
<html><body>
<form id="Form1" name="Form1" method="post" 
  action="HelloMMIT.aspx?__ufps=971469">
<input type="hidden" name="__EVENTTARGET" value="">
<input type="hidden" name="__EVENTARGUMENT" value="">
<script language=javascript>
<!--function __doPostBack(target, argument){
  var theform = document.Form1
  theform.__EVENTTARGET.value = target
  theform.__EVENTARGUMENT.value = argument
  theform.submit()
}//-->
</script>
Hello MMIT</form>
</body></html>
The cHTML markup generated by MMIT looks just like the HTML it generated, but without the JavaScript code. Here is our "Hello MMIT" Web page again:
   <html>
      <body>
         <form id="Form1" name="Form1" 
             method="post"     
             action="HelloMMIT.aspx?__ufps=976002">
          <input type="hidden" 
             name="__EVENTTARGET" value="">
          <input type="hidden" 
             name="__EVENTARGUMENT" value="">
             Hello MMIT
          </form>
      </body>
   </html>
Here are the WML tags generated by MMIT for a WML-based browser (we added the indentation in order to make it easier to read):
  <?xml version='1.0'?>
  <!DOCTYPE wml PUBLIC '-//WAPFORUM//DTD WML   
     1.1//EN' 'http://www.wapforum.org/DTD/w   
     ml_1.1.xml'>
  <wml>
    <head>
        <meta http-equiv="Cache-Control" content="max-age=0" />
    </head>
    <card>
        <p>Hello MMIT</p>
    </card>
</wml>
Finally, Figure 6 shows the same page, this time from the point of view of the contents of the .aspx file as it appears in the ASP.NET server with MMIT installed. We copied this directly from Visual Studio .NET, from the editor's HTML tab. This is unlike any HTML that you are probably used to seeing. What you see is a set of XML tags which provide an abstraction of the tags of the three supported languages.
<%@ Register TagPrefix="mobile"
   Namespace="System.Web.UI.MobileControls"
   Assembly="System.Web.Mobile, 
   Version=1.0.3300.0, 
   Culture=neutral, 
   PublicKeyToken=b03f5f7f11d50a3a" %>

<%@ Page language="c#" 
    Codebehind="HelloMMIT.aspx.cs"
    Inherits="HelloMMIT.MobileWebForm1" 
    AutoEventWireup="false" %>

<meta name="GENERATOR" content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" content="C#">
<meta name="vs_targetSchema"
    content="http://schemas.microsoft.com/Mobile/Page">
<body Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm">
   <mobile:Form id="Form1" runat="server">
      Hello MMIT
   </mobile:Form>
</body>
The @ Register directive in the code in Figure 6 indicates that this page uses nonstandard ASP.NET controls. For example, you would use this directive to add a custom control to a standard ASP.NET Web page. Here the directive establishes a connection to the MMIT controls. To an experienced ASP.NET Web developer, the @ Page directive is familiar as it sets up the page attributes for a Web page. This is where the connection to the compiled source code (the code behind the Web page) is established. It is also where the source language is specified—in this case, C#. This code resides and runs on the server, providing server-side processing no matter what final tag language is used. As you can see, the core elements of the Web page are within the <body> tags. The Hello MMIT message lives in a pair of <mobile:Form> tags.
The secret is out: MMIT supports three different sets of markup tags. It does this with a fourth XML-based tag language. You may be grumbling right now about how you have yet another tag language to learn, but wait a second. Although you will need to know how to read this other language, you will rarely need to write it from scratch. The reason is that MMIT is tightly integrated with Visual Studio .NET, and that add-in does all the work of assembling and managing the underlying tags and text.

Integration with Visual Studio .NET
Figure 7 Mobile Web Application Project 
Just like in ASP.NET, projects get stored at the URL for a Web server (http://localhost/HelloMMIT in this case). Just like ASP.NET Web applications, Visual Studio .NET provides a drag and drop interface for building mobile Web applications. But the set of controls that are supported are not the same set of controls as in ASP.NET. For that reason, there is a different toolbox to work with (see Figure 8). It is a bit different from the one that you work with in ASP.NET, as some old friends (including Button, Table, CheckBox, CheckBoxList, RadioButton, and RadioButtonList) do not appear. Actually, some of these are supported, but under different names. Figure 9 shows the controls supported in the toolbox and some specific details about what each one does.

Control Description
Form A container for all other controls. It can hold panels, controls, or plain text. Corresponds to a WML "card." The contents of a form get sent to browsers as a contiguous whole.
Panel A container to group controls in a form.
Label Simple read-only text display.
TextBox Text display and editing control.
TextView Displays large blocks of text.
Command Allows users to post data back to the server. This can appear to the user as a button, a hyperlink, an image, or a label for a softkey (on devices that support them).
Link A text hyperlink (images cannot have a hyperlink associated with them).
PhoneCall Link to make a phone call.
Image Displays a graphic image such as a JPEG or GIF image.
List Displays a list of text items in HTML with optional bullets.
SelectionList Displays a list of items. A list can have the form of a combobox, a listbox, a set of radio buttons, or a set of checkboxes.
ObjectList Similar to an ASP.NET DataGrid. Allows a link between a database and items displayed in the browser.
DeviceSpecific Generates tags for special case handling based on device filters. Examples of device filters include the tag language of the target device (IsWML11, IsHTML32), a specific browser (isPocketIE, isUP3x), or a specific device (isNokia7110, isEricssonR380).
StyleSheet Document-level control to hold formatting information for groups of controls.
Calendar Allows input of dates. On HTML-based devices, this involves showing a calendar and letting the user select a date. On WML-based devices, this involves showing a sequence of screens that allow a user to pick a date.
AdRotator Displays and rotates advertisements.
RequiredFieldValidator Like the ASP.NET implementation, identifies required fields in a form. Displays an error message if the field is not filled in.
CompareValidator Like the ASP.NET implementation, checks a field's values against a known good list. Displays an error message when bad values are entered.
RangeValidator Like the ASP.NET implementation, checks that entered value of currency, dates, float, integer, or string values are within a specified minimum and maximum.
RegularExpression Like the ASP.NET implementation, uses a regular expression syntax to check that the contents of a field match the specified pattern.
CustomValidator Like the ASP.NET implementation, provides server-side validation for the contents of a form.
ValidationSummary Like the ASP.NET implementation, sets aside an area for showing the user all errors encountered when validating the contents of a form.
Figure 8 Controls 
Aside from the different controls in the Mobile Web Form toolbox, a developer experienced with ASP.NET will find that Visual Studio .NET provides the same support for mobile Web applications that it does for regular ASP.NET Web applications. In addition to the design view of Web pages, there is also the familiar HTML view for viewing the actual tags created. As we mentioned earlier, the contents of that window are not regular HTML 4.0. Instead, when working with MMIT you see an XML-based markup language.
A third view provided by Visual Studio .NET is the codebehind view. That is, you can edit the code behind the Web page. Adding event handlers for individual controls is a simple matter of double-clicking a control, and you can also select events in the Properties window to add event handlers.
All of the controls provided reside on the server; that is, they all have runat set to "server". For this reason, you get the full support of the .NET Framework even when the supported device is a tiny low-memory cell phone. As you'll see in the MovieFinder example (in the section coming up), this means your MMIT application can use server-side services such as SQL Server 2000 with ADO.NET.

MovieFinder—an MMIT Sample
To give you an idea of what is involved in building a real-world application, we present MovieFinder. You need this application. We're sure you'll recognize the story: you are on your way home from work and get stuck in traffic. You get a call from someone who wants to meet you at a movie, but you don't have access to your work computer. Fortunately, you have figured out how to use your Global System for Mobile Communication (GSM) phone to browse the Web and off you go to find a movie that starts soon at a local theater.
MovieFinder displays movie listings and start times for a given area and date. To find a movie and its starting times, the user navigates three forms. One specifies the geographic area and desired date (see Figure 10), one lets you select a theater and a movie (see Figure 11), and one lets you choose movie start times (see Figure 12). Our sample data represents a 50 mile stretch of the Columbia River that separates Washington from Oregon and is home to 10 towns, 3 movie theaters, and the programmer who wrote the application. (Movie theater names have been changed for the purposes of this article.)
Figure 10 Time and Location 
Figure 11 Theater and Movie 
Figure 12 Starting Times 

The Database
We use SQL Server™ 2000 as our server-side database. In our database, all towns, theaters, and films have both full and abbreviated names. Meaningful abbreviations are something of a necessity in the world of limited space devices. The town abbreviations were taken from a local phone book, while the others were made up by the authors. Fake zip codes of 99990 thru 99999 were used in order to make testing easier.
To simplify our development, we define two SQL stored procedures. The first is procFetchMovies, which requires a postal code, distance, and date as input and which returns a theater/town/movie list for all movies being shown in that area on that date. The other is procFetchShowings, which requires theater, movie, and date as input and which returns the list of start times for that movie at that theater on that date.
The source code for this application is available for download from the link at the top of this article. Refer to the README.HTM file for details on setting up the application. In particular, to set up the database and the stored procedures, you need to run the CreateDatabase.sql script.

Server-side Components
Our completed application design resulted in the three Web forms just mentioned and requires the user to navigate across all three to obtain a movie start time. We used session variables to maintain state information as the users navigate from form to form. In the past, we have not been fans of session variables, preferring to either avoid state altogether or use hidden fields when necessary. But .NET makes it easier and safer to use session variables, and session variables in turn make our code simpler to read and write. This, in turn, lets us concentrate on our task.
In fact, the subject of maintaining state further illustrates that the server-side programming involved in developing mobile apps is not much different from what's required to develop traditional Web apps. The difference between the two is the limited display space of mobile devices, the smaller set of server-side controls available, the different browser languages that those controls must generate, and the differences between the client browsers. Server-side aspects, such as accessing a Web Service, connecting to a database, and maintaining state, remain the same.
Two Toolkits for Smart Mobile Devices
If you are developing software that is targeted for mobile devices, there are two development tools that you need to know about: Microsoft Mobile Internet Toolkit and Smart Device Extensions (SDE). This article focuses on MMIT, but because some developers will need both, it makes sense for you to at least understand how they compare to each other.
Today, there are two basic kinds of applications: standalone GUI applications and browser-based applications. In the world of .NET, these two are sometimes called Windows Forms and Web Forms applications, respectively. In .NET, you build GUI applications using the Windows Forms library (the System.Windows.Forms namespace, among others). The world of .NET supports the creation of Web browser applications in ASP.NET, represented by System.Web and related namespaces. A Web Forms application resides on an ASP.NET-based Web server and generates the HTML and script needed to communicate with Web browsers.
The same distinction exists for smart mobile devices, and there is a toolkit for each kind of application. When you want to build a standalone GUI application, you use the SDE. This toolkit contains the .NET Compact Framework, a special version of the Windows Forms libraries that have been tuned for small-screen mobile devices like the Pocket PC. To run applications that use the .NET Compact Framework, a device must have the framework libraries installed. As of this writing, the framework is in beta. When it ships, it is expected to have a 1 to 2MB footprint.
To build an app for a Web browser, you use MMIT. The contents of this toolkit reside entirely on an ASP.NET-based Web server. MMIT provides a set of server-side controls that support a broad range of browser-based devices. These devices range from WAP/WML cell-phones to HTML 3.2-based Pocket PC and Pocket PC 2002 PDAs.
While they are used to build different types of applications, these two toolkits have quite a few features in common. With both toolkits, you'll use the latest version of Visual Studio .NET for development. You can see this most clearly when you create a new project and you have both toolkits installed (see Figure 7). You get two new types of project templates: one for a smart device application and the other for a mobile Web application. When you write code for both, you write in managed code using the .NET common language runtime (CLR) and store data in the standard set of common data types. Both are, in short, full players in the .NET world.


Building Mobile Web Forms
From Visual Studio .NET, we start by creating a new project and selecting the Mobile Web Application template. Next, we create three Web forms by selecting the following menu three times: Project | Add New Item | Mobile Web Form. We name the three new Web forms Criteria, Movies, and Showings.
The Criteria form lets a user enter a postal code and geographic radius in which the search will be performed, and a date. We add five separate controls from the Mobile Web Forms toolbox to this form, as you can see in Figure 13.
Figure 13 The Criteria Form 
Now we need to add some code to our form to respond to two events. The first is the FormLoad event, which will initialize the two text boxes and the calendar with the default radius, default postal code, and today's date:
Private Sub Page_Load _
            ( _
               ByVal sender As System.Object, _
               ByVal e As System.EventArgs _
            ) _
            Handles MyBase.Load
   If Not Me.IsPostBack Then
      txtDistance.Text = "12"
      txtPostalCode.Text = "99999"
      datePick.SelectedDate = DateTime.Today
   End If
End Sub
Next, we'll need to write code to respond to the user's input. Notice that our form does not have a submit button. There is a reason for this, and it illustrates a difference between mobile Web pages and regular Web pages. The mobile:Calendar control that we added to our form from the Mobile Web Forms tab of the toolbox is similar, but not identical, to an ASP.NET asp:Calendar control. For one thing, the mobile calendar is always in auto-postback mode, and there is no property that will turn auto-postback on and off. A postback occurs whenever the user selects a date. Thus, our form does not need a submit button.
Keep in mind, however, that because clicking a Calendar control causes the form to post back, regardless of whether any other controls have been completed, the calendar should always be the last control on a form. Of course, "last" is a different location in the left-to-right, top-to-bottom world of European languages than it is in Arabic or Asian languages. The process of internationalization, like so many things, is affected by the slight differences between the mobile Web controls and the standard Web controls.
This auto-posting of the calendar control also raises another issue: when the postback occurs, we need to save the user's entries into session variables and redirect to the next page. The code itself is simple and looks like this:
   Session("Distance") = 
      txtDistance.Text
   Session("PostalCode") = 
      txtPostalCode.Text
   Session("Date") = 
      datePick.SelectedDate
   Me.RedirectToMobilePage("Movies.aspx")
But where do we put this code? In what event handler does the code belong? Experienced Web developers will tell you that the Click event for the submit button is the place, but in this case there is no submit button.
We considered several different events for handling this postback: one in the calendar control and two in the form. We tried using the calendar control's SelectedDateChanged event, but it only fires if a date has actually changed. If the user accepts the current setting in the calendar control—today's date, which is what we used to initialize the control—the code in the SelectedDateChanged handler does not get executed.
Since the calendar control cannot handle this event, the next set of events to consider are those sent to the form that contains the calendar control. Unfortunately, neither the Load event nor the Unload event work, since one is too early and the other too late. The user-entered values are not yet in the control properties when the Load event fires, and the option of redirecting to a different page has passed by the time Unload fires.
The only event that always fires, has the new values in the controls, and can still permit a redirect is the form's PreRender event, so that's where we put our code:
Private Sub Page_PreRender _
            ( _
               ByVal sender As System.Object, _
               ByVal e As System.EventArgs _
            ) _
            Handles MyBase.PreRender
   If Me.IsPostBack Then
      Session("Distance") = txtDistance.Text
      Session("PostalCode") = txtPostalCode.Text
      Session("Date") = datePick.SelectedDate
      Me.RedirectToMobilePage("Movies.aspx")
   End If
End Sub
Experienced ASP.NET developers will most likely expect to call Response.Redirect in order to navigate to the next page. However, that method cannot be used in the mobile Web environment to navigate between pages. Instead, you need to use the form's RedirectToMobilePage method, as shown in the preceding code fragment.
It might seem strange to place code that has nothing to do with rendering in the PreRender event handler, but if you think of PreRender as "Last chance to do anything before the Response writing begins," it makes sense.
Since we have redirected to Movies.aspx, the page that shows the available movies for the specified area and date, let's now take a look at that page. We developed movies.aspx much like we would develop a regular Web page when there were no mobile Web-specific issues (see Figure 11).
The page consists of two labels, one selection list, one submit button, one ADO.NET connection, and one ADO.NET command. The connection and command objects are the same ADO.NET objects that you use in regular Web programming, and they were placed on the page using the same drag and drop method that you would use to place them on a standard ASP.NET page. The code that is used to create, open, execute, and bind these objects is also the same code that you use in regular Web programming.
The SQL Server stored procedure used by the Command object is the procFetchMovies procedure mentioned earlier. Its input parameters are postal code, distance, and date; its output is a theater/town/movie recordset of all movies being shown in that area on that date. One column, named TMText, contains a concatenation of the theater abbreviation, town abbreviation, and movie abbreviation. Another column, named TMKey, contains a concatenation of the theater ID and movie ID.
In the form's Load event we'll echo the user's criteria back to them by placing text in the labels, then use ADO.NET to present the user a list of movies in the SelectionList control (see Figure 14).
Private Sub Page_Load _
            ( _
               ByVal sender As System.Object, _
               ByVal e As System.EventArgs _
            ) _
            Handles MyBase.Load
   Dim drdrFetchMovies As _
            System.Data.SqlClient.SqlDataReader
   If Not Me.IsPostBack Then
      With lblCriteriaA
         .Text = "Movies within " _
               & Session("Distance") _
               & " kms of "
      End With
      With lblCriteriaB
         .Text = Session("PostalCode") _
               & " on " _
               & Session("Date") _
               & "."
      End With
      With cmndFetchMovies
         .Connection.Open()
         .Parameters(1).Value = Session("Distance")
         .Parameters(2).Value = Session("PostalCode")
         .Parameters(3).Value = Session("Date")
         drdrFetchMovies = _
            .ExecuteReader(CommandBehavior.CloseConnection)
      End With
      With slstMovies
         .DataSource = drdrFetchMovies
         .DataTextField = "TMText"
         .DataValueField = "TMKey"
         .DataBind()
      End With
      With drdrFetchMovies
         .Close()
      End With
   End If
End Sub
Once the user selects a theater/movie combination, we'll store that information in session variables and redirect to the final page, which displays the movie's start times. That code is extremely simple, as you can see here:
Private Sub slstMovies_SelectedIndexChanged _
               ( _
                  ByVal sender As System.Object, _
                  ByVal e As System.EventArgs _
               ) _
              Handles slstMovies.SelectedIndexChanged
   Session("TMKey") = slstMovies.Selection.Value
   Session("TMText") = slstMovies.Selection.Text
   Me.RedirectToMobilePage("Showings.aspx")
End Sub
This completed page moves the user to the final page, Showings (see Figure 12), which lists the start times for the selected movie at the selected theater on the selected date. Like the previous page, (shown in Figure 11) this page uses ADO.NET and a stored procedure to present information to the user. The only cryptic code is the part that parses the theater ID and movie ID that were concatenated by the previous stored procedure, which is done at the start of the form's Load event.
In fact, since this page is the last in the chain, there is no need to receive a response from the user. The form's Load event is the only event we need to handle (see Figure 15).
Private Sub Page_Load _
            ( _
               ByVal sender As System.Object, _
               ByVal e As System.EventArgs _
            ) _
            Handles MyBase.Load
   Dim arryTheaterMovie() As String = _
                  Split(Session("TMKey"), ".")
   With lblHeading
      .Text = "Showtimes for:"
   End With
   With lblTheaterMovie
      .Text = Session("TMText")
   End With
   Dim drdrFetchShowings As _
            System.Data.SqlClient.SqlDataReader
   If Not Me.IsPostBack Then
      With cmndFetchShowings
         .Connection.Open()
         .Parameters(1).Value = arryTheaterMovie(0)
         .Parameters(2).Value = arryTheaterMovie(1)
         .Parameters(3).Value = Session("Date")
         drdrFetchShowings = _
            .ExecuteReader(CommandBehavior.CloseConnection)
      End With
      With lstShowings
         .DataSource = drdrFetchShowings
         .DataTextField = "ShowingTime"
         .DataValueField = "ShowingTime"
         .DataBind()
      End With
      With drdrFetchShowings
         .Close()
      End With
   End If
End Sub

Device-specific Rendering
Now we'll address the biggest difference between developing mobile Web apps and standard Web apps: writing one application that can service the wide range of different devices. When you develop standard Web applications, you design and code for browsers that run on the desktop, can be resized up to the screen maximum, and which speak HTML 4.0. This is not the case with mobile devices. For example, as mentioned earlier, mobile phones speak WML and have less display area than Pocket PCs, which might speak HTML 3.2 and have more space than a mobile phone, but less than a detachable flat screen. MMIT provides some automatic capability for adjusting to different devices and rendering languages, and it provides capabilities for you to programmatically modify your application to make it device-specific. In this section, we'll look at three different ways to build device-specific support into an MMIT application. The three options available to you are:
  • Fine-tuning individual controls for different devices.
  • Providing a different set of controls for different devices.
  • Providing a different set of HTML pages for different devices.

Fine-tuning for Different Devices
MMIT automatically adapts its server-side controls for different devices and renders them accordingly. For some controls, this adjustment is just a minor check to see which kind of tags to render: HTML 3.2, cHTML, or WML.
For other controls, a lot more adjustment is required. For example, there is a significant difference between a calendar control on a WML-based cell phone (see Figure 13) and a calendar control on an HTML-based Pocket PC (see Figure 10). On a WML device, the calendar control renders itself as a series of different pages that walk the user through the process of specifying a date. The result is the same functionality, but a very different appearance. All of this device-specific handling, by the way, is accomplished for you without your having to do anything special. There is, however, one important thing that you must remember when using calendar controls on WML devices, at least for version 1.0 of MMIT: calendar controls conflict with TextBox controls. If your form has a calendar control, you must put all TextBox controls on a different page (see Figure 16).
Figure 16 Pages in the Emulator 
But what if you want your app to behave differently for different devices and you want to specify these differences yourself? Perhaps you want something as simple as shorter text for a Label control on a mobile phone than on a Pocket PC, or perhaps something more complex, like one set of controls for rendering data on a Pocket PC and a different set for rendering to a mobile phone.
MMIT provides support in this area, and that support starts with the Web.Config file that is generated by Visual Studio .NET for any mobile Web application. If you create a new mobile Web application and then immediately look at its Web.Config file, you'll see that it contains the XML shown in Figure 17.
<deviceFilters>
    <filter name="isHTML32" compare="PreferredRenderingType" 
       argument="html32" />
    <filter name="isWML11" compare="PreferredRenderingType" 
       argument="wml11" />
    <filter name="isPocketIE" compare="Browser" argument="Pocket IE" />
    <filter name="isUP3x" compare="Type" argument="Phone.com 3.x Browser" 
       />
    <filter name="isEricssonR380" compare="Type" argument="Ericsson R380" 
       />
    <filter name="prefersGIF" compare="PreferredImageMIME" 
       argument="image/gif" />
    <filter name="supportsJavaScript" compare="Javascript" 
       argument="true" />
</deviceFilters>
This is not the complete list, but it is representative, and you can add your own filters once you understand what they are. To understand device filters, you need to understand the System.Web.Mobile.MobileCapabilities class. As mentioned earlier, this class contains read-only properties that hold browser-specific information, such as the PreferredRenderingType property, whose value might be html32, chtml10, or wml11. Think of a device filter as something similar to a Boolean function that compares a MobileCapabilities property value to an argument value and returns true if they are equal. We can specify the property name and target value at design time (which is what the Web.Config XML data is doing), and then at run time we can access the MobileCapabilities object in order to make decisions about the proper way to handle a particular device.
In order to use device filters at run time, you must cast the Request.Browser object as a MobileCapabilities class and then call its HasCapability method, specifying the filter name as an input argument. The following code, taken from a PageLoad event handler, shows this technique:
Dim browserCaps As System.Web.Mobile.MobileCapabilities
browserCaps = Request.Browser
If browserCaps.HasCapability("isHTML32", vbNullString) Then
•••
Since isHTML32 is a true/false filter, we can ignore the second argument of the HasCapability method.
We can also use device filters at design time. They are not actually invoked until run time, but there are times when it's advantageous to specify them at design time. For example, suppose we want to specify a short string for a label when it is being rendered in WML and a longer string if it's being rendered in HTML. We could use the code just shown to set the label's Text property based on the appropriate device filter, such as isHTML32, but it's also possible to do the same thing at design time.
To use a device filter at design time, we modify the HTML that defines the page. Do not confuse the HTML that is used to define the page—that is, the HTML that specifies the server-side objects, with the HTML/cHTML/WML that the page renders and sends to the browser. We are going to modify the design-time HTML so that the rendered HTML/cHTML/WML will be device-specific.
When we placed our mobile Web label control on the form and then modified its properties, the resultant design-time HTML looked like the following:
<mobile:Label id="lblPostalCode" runat="server">
   kilometers of postal code
</mobile:Label>
To specify that we want a short label when the browser requests WML and a long label when the browser requests HTML, we modify the design-time HTML to the following:
<mobile:Label id="lblPostalCode" runat="server">
   <DeviceSpecific>
      <Choice Filter="isHTML32" text=" kilometers of postal code ">
         </Choice>
      <Choice Filter="isWML11" text=" km of pc "></Choice>
   </DeviceSpecific>
</mobile:Label>
In doing so, we have made the Text property of our lblPostalCode label control device-specific. It will show the longer string when rendered on an HTML 3.2 device and the shorter one when rendered on a WML device.

Different Controls for Different Devices
What if you wanted your page to display completely different controls depending upon the capabilities of the browser? For the sake of example, suppose we did not like the way that the MMIT calendar control rendered itself in WML, making the mobile phone user go through several steps to specify the date. After all, we only have movie schedules for the next four weeks available to us, so the date requested by the user must fall within this month or next month. We would like to display a calendar that consists of a day-of-the-month textbox and a two-month selection list.
Could we use filters at design time to specify that an MMIT calendar control should be displayed for HTML 3.2 devices but that our textbox/listbox combination should be used for WML browsers? Yes we can, but it is much more complex than our previous example in which we made a single control device-specific. Here we show how to do it as an example, not necessarily as a recommendation.
We modify our Criteria.aspx page to hold a Panel control, which will contain an MMIT Calendar when accessed by HTML 3.2 devices, but which will contain the textbox/listbox combination when accessed by a WML device. We then place an MMIT DeviceSpecific control within the panel and add the filter-dependent HTML to it, as shown in Figure 18. Not only is this HTML more complex than our single-control example, but our code must be more complex as well. That's because the controls located inside the <CONTENTTEMPLATE> tags do not have any code automatically generated for them. Specifically, your project won't get either Protected variables that hold a reference to the control or skeleton event-handling procedures. Thus, you have a few more manual operations to perform when creating device-specific code than would be required with stock MMIT Web controls.
<mobile:Panel id="pnlCalendar" runat="server">
    <mobile:DeviceSpecific id="dspcCalendar" runat="server">
        <Choice Filter="isHTML32">
            <CONTENTTEMPLATE>
        <mobile:Calendar
            id="datePick"
            runat="server">
        </mobile:Calendar>
            </CONTENTTEMPLATE>
        </Choice>
        <Choice Filter="isWML11">
            <CONTENTTEMPLATE>
                <mobile:Label
                    id="lblDate"
                    runat="server">Date</mobile:Label>
                <mobile:TextBox
                    id="txtDay"
                    runat="server" 
                    Size="2" MaxLength="2"></mobile:TextBox>
                <mobile:SelectionList
                    id="slstMonth"
                    runat="server" SelectType="Radio"
                    Rows="2"></mobile:SelectionList>
           </CONTENTTEMPLATE>
       </Choice>
    </mobile:DeviceSpecific>
</mobile:Panel>
In the example, the Criteria's FormLoad event handler now becomes the code shown in Figure 19.
Private WithEvents datePick As MobileControls.Calendar
Private WithEvents lblDate As MobileControls.Label
Private WithEvents txtDay As MobileControls.TextBox
Private WithEvents slstMonth As MobileControls.SelectionList
Private WithEvents bttnFetch As MobileControls.Command

Private browserCaps As Mobile.MobileCapabilities

Private Sub Page_Load _
            ( _
               ByVal sender As System.Object, _
               ByVal e As System.EventArgs _
            ) _
            Handles MyBase.Load
   browserCaps = Request.Browser
   With pnlCalendar.Controls(0)
      If browserCaps.HasCapability("isHTML32", _
                                    vbNullString) Then
         datePick = .FindControl("datePick")
      ElseIf browserCaps.HasCapability("isWML11", _
                                       vbNullString) Then
         lblDate = .FindControl("lblDate")
         txtDay = .FindControl("txtDay")
         slstMonth = .FindControl("slstMonth")
      End If
   End With

   If Not Me.IsPostBack Then
      txtDistance.Text = "12"
      txtPostalCode.Text = "99999"
      If browserCaps.HasCapability("isHTML32", _
                                    vbNullString) Then
      ElseIf browserCaps.HasCapability("isWML11", _
                                       vbNullString) Then
         txtDay.Text = DateTime.Today.Day
         With slstMonth
            .Items.Add((Split( _
               DateTime.Today.ToLongDateString))(1))
            .Items.Add((Split( _
               DateTime.Today.AddMonths(1).ToLongDateString))(1))
            .SelectedIndex = 0
         End With
      End If
   End If
End Sub
Note that we had to manually declare the Private variables to hold the control references and that we had to use the FindControl method of the container control to obtain references to the controls that were defined in the <CONTENTTEMPLATE> tags. Our code that responds to the users input must also be device-specific, for only by knowing the device type do we know which set of controls were used. That code is shown in Figure 20. You can see that being device-specific across multiple controls is more difficult that being device-specific within a single control.
Private Sub bttnSubmit_Click _
               ( _
                  ByVal sender As System.Object, _
                  ByVal e As System.EventArgs _
               ) _
               Handles bttnSubmit.Click
   Session("Distance") = txtDistance.Text
   Session("PostalCode") = txtPostalCode.Text
   If browserCaps.HasCapability("isHTML32", _
                                 vbNullString) Then
      Session("Date") = datePick.SelectedDate
   ElseIf browserCaps.HasCapability("isWML11", _
                                 vbNullString) Then
      Session("Date") = _
         DateTime.Today.AddDays(txtDay.Text - _
         DateTime.Today.Day).AddMonths(slstMonth.SelectedIndex)
   End If
   Me.RedirectToMobilePage("Movies.aspx")
End Sub
Also, to make our code simpler, we left something out. You should always specify default values for the browser type. Many of the examples that we've shown are dependent upon the browser using either HTML32 or WML11 when it might be neither.

Different Pages for Different Devices
The third possibility for adding device-specificity to your app would be to have different pages for different devices. We do not illustrate it here because it's straightforward, only involving combining the runtime filter testing shown in the examples with the RedirectToMobilePage method. Although it is a simple technique, it has the disadvantage of having multiple pages for the same functionality, and that usually results in duplication of code and difficult maintenance of your page.
All in all, the best solution to the need for device-specific code is "None of the above." That is, let the device detection and rendering capabilities of the MMIT server-side controls do the work for you whenever possible. If you still want to provide your own device-specific capability, start with enhancing individual controls first. Move on to the different sets of controls for different devices or different pages for different devices only if you absolutely must.
WAP and WML
You can read more about WAP and WML at the Web site of the Open Mobile Alliance, which is an industry standards group for the promotion of WAP and WML (http://www.openmobilealliance.org). Openwave Systems Inc. hosts a detailed Web site providing information about the WML tag language. The developer programs, which provide an SDK with a WML simulator, are available at http://developer.openwave.com. The simulator is a great tool because it lets you test your application without requiring you to have an actual device. By downloading the OpenWave Software Development Kit, you can get access to lots of detailed information and samples that relate to WAP/WML devices.


Conclusion
In this article, we introduced MMIT as the way to build support for mobile wireless Internet devices into ASP.NET-based Web sites. You use the same development environment (Visual Studio .NET) that you use to build ASP.NET Web sites. You have many of the same controls as you do in ASP.NET. What you get is support for the wide range of small-screen, battery-operated, mobile wireless Internet-enabled devices.
Along the way, we showed you MovieFinder—a pretty capable little MMIT application that you can download from the link at the top of this article and use to experiment with building mobile Web applications. When you do, just be sure to change the SQL server name to a server that is accessible to your device. We also showed you how you can build device-specific elements in your mobile applications to handle situations when the default rendering does not meet your own requirements. We have only scratched the surface of what is possible, but hopefully we have whetted your appetite for exploring this toolkit.

For background information see:
Two Toolkits for Smart Mobile Devices
WAP and WML
http://www.w3.org/TR/REC-html32
http://www.w3.org/TR/1998/NOTE-compactHTML-19980209/
http://www.openmobilealliance.org
http://developer.openwave.com
Development Tools for Mobile and Embedded Applications

Paul Yaois a programming guru, expert in Windows CE, and coauthor of the first book published on Windows programming. His company specializes in training programmers in Windows and Windows-related technologies. Visit his Web site at http://www.paulyao.com.

David Durantis an independent consultant and trainer specializing in .NET Web application development and in SQL Server. He lives in White Salmon, WA with his wife and every animal that she can adopt. He frequently travels to Redmond to visit the home of .NET and his grandchildren. Reach David at DavidDurant@gorgc.net.

Page view tracker