Mobile Web Development with ASP.NET 2.0

Download the PDF

Mobile Web Development with ASP.NET 2.0

Overview

Over the years Web application development has evolved from static HTML to more dynamic ASP.NET pages. However, this model has focused almost exclusively on delivering content to the Internet connected PC running a desktop browser. The term Mobile Web is used to describe Web applications targeting a mini-browser running on a smaller form factor device like a cellular phone or PDA. Mini-browsers are quite different from their desktop counterparts. By default they tend to support non-HTML markup standards like HDML, cHTML, WML, WAP, and xHTML. Also, these devices tend to include reduced processor speed, smaller input displays, limited battery lifetimes and limited input options. However, even with their unique hardware and software they still represent a viable platform for targeted Web based applications.

 

The goal of Mobile Web development is to provide applications to these devices that are as simple, easy and convenient to use as the desktop browser. For building these types of applications the .NET Framework implements the System.Web.Mobile namespace. This namespace includes authentication, special device features and error handling for building ASP.NET Mobile Web applications. Also included is a set of ASP.NET server controls contained in the System.Web.UI.MobileControls namespace that provides the user interface elements for rendering Mobile Web applications. It is the combination of these two that enables a single Mobile Web application to render on multiple devices and mini-browsers. In this article we look at how these types of Mobile Web applications can be built using Visual Studio 2005 and ASP 2.0.

Introducing Mobile Web Development

The most common business use of the Internet is to locate and interact with real time business information. For many different reasons it isn’t always possible or convenient to access an Internet connected PC.  However, with the proliferation of cellular phones and PDA’s these Internet connected devices are typically as close as your coat pocket or purse. Fundamentally the main difference between an ASP.NET application and an ASP.NET Mobile Web application is the targeted browser. ASP.NET applications are targeted into a rich desktop browser capable of fully rendering HTML, storing cookies and executing client side JavaScript. Mobile Web applications are targeted for a mini-browser running on a mobile device. These smaller footprint browsers may render non-HTML based markup and don’t always support cookies and client side scripting. This means that given the range of devices Mobile Web application need to adaptively render for a wide range of protocols, device specific behaviors and browser types.

 

The .NET Framework 2.0 provides several namespaces that are used to implement the run time and design time behavior of mobile components and controls. These namespaces shown in Table 1 contain the interfaces and base classes for implementing mobile attributes, classes, controls and user interface elements.

Table 1: The ASP.NET Mobile Namespaces

Namespace

Description

System.Web.Mobile

Provides the core mobile capabilities.

System.Web.UI.MobileControls

Provides the ASP.NET mobile controls

System.Web.UI.MobileControls.Adapters

Provides the core adapter classes for targeted mobile devices.

 

Figure 1 The adaptive rendering process.

 

 

The combination of these namespaces provides the adaptive rendering engine for the ASP.NET mobile control model as shown in Figure 1. For example, when a user with a WAP enabled mobile phone makes a server page request the MobileCapabilities class of the System.Web.Mobile namespace examines the HTTP headers to determine the browser and the device. Based on this the server instantiates the control in the System.Web.UI.MobileControls namespace and selects an appropriate device adapter from the System.Web.UI.MobileControls.Adapters. When the server rendering process is complete, device specific markup is returned to the requesting device.

 

The Basics of Browser Identification

The architecture pattern of an ASP.NET Web Site that contains mobile pages is to segregate these into different application folders. This separation between the mobile pages and ASP.NET helps to ease the deployment and maintenance of the Web site.

However, to provide a consistent end user experience both types of applications are usually made available from a common URL. As HTTP Web requests are received they are interrogated and redirected to application paths based on the properties of the incoming request.   

 

Inside the HTTP headers request made by any browser is the user agent string. This string describes the browser making the request. The System.Web namespace contains the HTTPRequest class that provides information about the current request, the HTTPResponse class which manages HTTP output to the client and the HTTPServerUtility class which provides access to server side utilities and processes. Also, within the System.Web namespace is the HTTPBrowserCapabilities class that gathers information on the capabilities of the browser that is running on the client. For example, Listing 1 retrieves the requesting browser capabilities.

Listing 1: Determining a browser’s features.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim bc As HttpBrowserCapabilities = Request.Browser

        Response.Write("<p>Browser Capabilities:</p>")

        Response.Write("Type = " & bc.Type & "<br>")

        Response.Write("Name = " & bc.Browser & "<br>")

        Response.Write("Version = " & bc.Version & "<br>")

        Response.Write("Major Version = " & bc.MajorVersion & "<br>")

        Response.Write("Minor Version = " & bc.MinorVersion & "<br>")

 

        Response.Write("Is a Mobile Browser = " & bc.IsMobileDevice & "<br>")

        Response.Write("Mobile Device Manufacturer = " & bc.MobileDeviceManufacturer & "<br>")

        Response.Write("Mobile Device Model = " & bc.MobileDeviceModel & "<br>")

        Response.Write("Is a Mobile Browser = " & bc.IsMobileDevice & "<br>")

        Response.Write("Number of soft keys = " & bc.NumberOfSoftkeys & "<br>")

      

        Response.Write("Platform = " & bc.Platform & "<br>")

        Response.Write("Is Beta = " & bc.Beta & "<br>")

        Response.Write("Is Crawler = " & bc.Crawler & "<br>")

        Response.Write("Is AOL = " & bc.AOL & "<br>")

        Response.Write("Is Win16 = " & bc.Win16 & "<br>")

        Response.Write("Is Win32 = " & bc.Win32 & "<br>")

        Response.Write("Supports Frames = " & bc.Frames & "<br>")

        Response.Write("Supports Tables = " & bc.Tables & "<br>")

        Response.Write("Supports Cookies = " & bc.Cookies & "<br>")

        Response.Write("Supports VB Script = " & bc.VBScript & "<br>")

        Response.Write("Supports JavaScript = " & bc.EcmaScriptVersion.ToString & "<br>")

        Response.Write("Supports Java Applets = " & bc.JavaApplets & "<br>")

        Response.Write("Supports ActiveX Controls = " & bc.ActiveXControls & "<br>")

        Response.Write("CDF = " & bc.CDF & "<br>")

 

    End Sub

 

Figure 2 Browser features exposed by Internet Explorer.

 

When accessing this page from various browsers there are definite differences between the desktop Internet Explorer client as shown in Figure2 and the Openwave mobile emulator shown in Figure3.

Figure 3 Browser features exposed by a cellular phone.

 

***Insert Note***

There are a variety of mobile emulators available on the market. For this article we are using the Openwave emulator (available from https://www.openwave.com) for non Windows based mobile phones. For Windows based devices like Pocket PC’s and Smart Phones we are using the Windows Mobile 5 emulators available within Visual Studio 2005.

 

Using the exposed properties of the HTTPBrowserCapabilities you can discover and then redirect requests. For example, using the code in Listing 2 you can redirect an incoming browser request to an ASP.NET Mobile Web site based on the isMobileDevice property.

Listing 2: Redirecting a mobile browser request.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim bc As HttpBrowserCapabilities = Request.Browser

        If bc.IsMobileDevice = True Then

         Response.Redirect("https://localhost/mobileapplication/default.aspx")

        End If

End Sub

Mobile Page Processing

The life cycle of a .NET Mobile Web Forms page and its controls are very similar to a regular ASP.NET page. However there are some differences as shown in Table 2.

Table 2: Comparison of an ASP.NET and Mobile Web Page.

ASP.NET Page Life Cycle Stages

Mobile Page Life Cycle

Initialize

Device adapters are chosen by using the <mobileControls> section of web.config.

Device-specific customizations are applied.

Load view state

Same as ASP.NET

Process postback data

Same as ASP.NET

Load

The MobileControl base class implementation calls the OnLoad method of the control to perform device adapter–specific loading of information.

Send postback change notifications

Same as ASP.NET

Handle postback events

Same as ASP.NET

Pre-render

Pagination is performed.

Save state

Same as ASP.NET

Render

The adapter is responsible for accessing and rendering child controls in the appropriate order.

The ASP.NET page framework renders each control by calling the Render method of its adapter.

Unload (Dispose)

Performs device adapter-specific cleanup and unloading.

Unload (Dispose)

Performs device adapter-specific cleanup and unloading.

 

Creating a Mobile Web Application with Visual Studio 2005

Figure 4 Creating an empty ASP.NET project.

 

Although Mobile Web applications are built using the same underlying infrastructure as any ASP.NET applications technically they are a unique Web form and set of controls. To create a Mobile Web application start by selecting an empty ASP.NET project within Visual Studio as shown in Figure4. This creates an ASP.NET application project that contains only the solution root as shown in Figure5.

 

Figure 5 The empty ASP.NET solution.

 

Due to the range of device specific settings and unique markups Mobile Web applications often contain unique application settings. Visual Studio 2005 provides a default Mobile Web Configuration file that can be added as shown in Figure6. This file contains both a default set of ASP.NET Web configuration settings and Mobile Web configuration information. However, as we will see later depending on the application functionality and devices accessing the application further customization of this file may be required.

Figure 6 Adding a default Mobile Web.Config file.

 

The Web.config file is a required component of any ASP.NET application and is designed to separate configuration and application code. The application level Web.Config is inherited from the ASP.NET root configuration file which by default is located in systemroot\Microsoft.NET\Framework\versionNumber\CONFIG\Web.config. This system wide configuration includes settings that apply to any ASP.NET application running under a specific .NET framework version. Application level files are used to override these system wide defaults. The application level Web.config file stores the configuration settings for the current directory and any subdirectories applying the same inheritance model as the root configuration file.

 

***Insert Note***

Configuration settings in the Web.Config file can also be optionally applied to individual files or subdirectories by specifying the path in the Web.Config <location> element.

 

At run time ASP.NET uses the web.config files to hierarchically compute a unique collection of configuration settings for each incoming URL request. These settings are initially created with the application domain and then cached on the server. At runtime ASP.NET automatically detects and applies any changes to the configuration files.

The Mobile Web Page

Figure7 Adding a Mobile Form to an application.

 

Like the ASP.NET Web Form the Mobile Web form page acts as the visual design surface for Mobile Web applications. The page is added through the “Add New Items” menu as shown in Figure7. It’s the Mobile Web Form Page as shown in Figure8 that is directly associated with the application URL.

 

Figure 8 The default Mobile Web Form page.

All ASP.NET pages are represented by the Page class specified by the @ Page directive. This class is used to define page-specific attributes used by the ASP.NET page parser and compiler. At run time these files are compiled as Page objects and cached into server memory. Inheriting from the base Page class is the MobilePage class. By default, when a new Mobile Web page is added it contains the declarations shown in Listing 3.

 

Listing 3: Default mobile page declarations..

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

 

 

Within any ASP.NET page, the page directive appears as the first set of attributes. The Page directive sets attributes on the global page object like the programming language and code behind file. The next page level directive registers a TagPrefix for the mobile namespace. This is used to declare a unique namespace for any mobile controls on the page.

 

The Mobile Web page contains one or more Mobile Web Form controls that serve as the container for the individual rendered screens. One Mobile Web Form Page or card deck is considered an entire Mobile Web application. The combination of the Mobile Web Form Page and Mobile Web Form control change the design paradigm of Web sites from multi-page ASP.NET Web Forms to a single page with discrete groups of Mobile Web Forms. With this approach each Mobile Web Form page contains smaller Web Form control sections that like a single index card represent one screen of rendered data. Designing applications this way makes it easier to view and understand data with potentially lower resolution devices and smaller screens.

 

With this design it is important to keep all the data in one card deck to reduce the amount of server round tripping. By default all headers within the same deck are transferred and made available locally on the mobile device. It is also important to keep in mind that putting to much detail in one deck may exceed the rendering mobile device limitations which varies but is generally about 2k of compiled data.

The ASP.NET Mobile Web Controls

Figure9 The mobile controls toolbox

 

Within the Visual Studio IDE Mobile controls appear in the Mobile Web Forms Toolbox as shown in Figure9. Logically, these controls are broken into categories of use. Container controls are a set of mobile controls that are used to create logical groupings of other mobile controls. A set of standard controls that provide common user interface tools for displaying text, navigation and collecting user input. List controls that are especially important for smaller form factor devices. A set of validation controls used to verify user input. Finally, a set of specialized controls that aren’t rendered at run time and are used to define styles and templates for device specific behaviors.

 

Controls are placed on a form or panel in the order they will appear when rendered to the mobile device. There are some important differences between the standard set of ASP.NET controls and mobile controls as shown in Table 3. The ASP.NET Mobile Designer sets the initial size for all controls on the designer. The process of adaptive rendering doesn’t support absolute control positioning due to the range of possible rendering devices. This means that changing the size of the form within the designer has no effect on the rendered output. This is one of the fundamental differences from the standard set of ASP.NET controls that support side by side controls and absolute positioning.

 

Table 3: Comparing Mobile and ASP.NET Controls.

Web Form Control

Mobile Web Form Control

Comments

Control Category

AdRotator

AdRotator

Functionality is similar. However, Mobile controls add the ImageKey and NavigateUrlKey Properties.

Standard Control

Button, ImageButton, LinkButton

Command

Combined into a single set Mobile Web Form Cotnrol

Standard Control

Calendar

Calendar

Mobile control does not provide HTML-specific properties directly but exposes an underlying Web Forms Calendar control through the WebCalendar property.

Standard Control

No Equivalent Control

PhoneCall

Used to drop the data line and initiate a phone call on dial-capable devices.

Standard Control

DataList, Repeater

List

Similar Functionality.  Mobile Controls can apply templates on a per device basis.

List Control

GridView

ObjectList

Similar functionality. The ObjectList control provides multiple views to show the data collections

List Control

No Equivalent Control

DeviceSpecific

Enables property overrides and templates for mobile controls.

Special Control

No Equivalent Control

Form

Similar to a page in an ASP.NET Web application. Mobile Web Forms pages can contain multiple Form controls.

Container Control

Image

Image

Mobile controls can select an image from a set of device-specific images.

Standard Control

Label

Label

Identical

Standard Control

HyperLink

Link

ASP.NET cannot render the mobile control as an image. Use the Image control to create an image link.

Standard Control

Panel

Panel

Mobile panels can be used to provide device-specific rendering by using the ContentTemplate device templates to replace the panels.

Container Control

RangeValidator

RanegValidator

Identical

Validation Control

RegularExpressionValidator

RegularExpressionValidator

Identical

Validation Control

RequiredFieldValidator

requiredFieldValidator

Identical

Validation Control

CompareValidator

CompareValidator

Identical

Validation Control

CustomValidator

CustomValidator

Identical

Validation Control

ValidationSummary

ValidationSummary

Identical

Validation Control

CheckBox, CheckBoxList, DropDownList, ListBox, RadioButton, RadioButtonList

SelectionList

Mobile control combines the functionality of the corresponding ASP.NET Web server controls.

Standard Control

IStyleSheet

StyleSheet

Web Forms use cascading style sheets rather than StyleSheet controls.

Special Control

Table

No Equivalent Control

Within Mobile Web pages use the List, ObjectList, and SelectionListmobile controls

 

TextBox

TextBox

Mobile control does not provide automatic postback, read-only, or multiline functionality.

Standard Control

No Equivalent Control

TextView

Used to display large blocks of text and supports basic text formatting.

List Control

 

Figure10 The effect of setting the BreakAfter property.

Mobile applications cannot guarantee control over the rendering layout on the device. This is particularly true of WML based devices. However, to help with this many of the Mobile Web Form controls provide a BreakAfter property. Setting this property to “False” on devices that supports it causes the next control to start on the same line as shown in Figure10. It is important to understand that this property is used by the ASP.NET rendering engine and not the actual mobile designer.

Container Controls

Container controls are used by ASP.NET Mobile Web Application to organize the content of a Mobile Web Forms page. There are two primary container controls available within a Mobile Web page; Form and Panel control.

 

***Insert Note***

During design when adding a control from the toolbox onto a form or panel ensure that the designer’s cursor is on the right side and toward the bottom of the existing control that you want the new control to follow.

Mobile Form Control

Figure11 The Mobile Form control

 

The Mobile Form control as shown in Figure11 is a required control for every Mobile Web page. By default when a new Mobile Page is added this creates an initial instance of this control. The Mobile Form control provides the interface between the browser capabilities of a page object and the code that renders the page. Mobile Web application can contain multiple form controls; however, only one is rendered at a time. The first form control placed on the Mobile Web page is displayed on the initial page load. The HTML syntax for the form control is shown here.

 

<html xmlns="https://www.w3.org/1999/xhtml" >

<body>

    <mobile:Form id="Form1" runat="server" StyleReference="StyleReference" OnActivate="Onactivatehandle" OnDeactivate="onDeactivatehandle">

 

    </mobile:Form>

</body>

</html>

 

The Id attribute is used to create a unique identifier for the Mobile Form control in the source file. This is important because a single Mobile Web Page may contain multiple Mobile Form controls. The ID property enables navigation within the Mobile Web Page. The StyleReference attribute is used to apply a style sheet to any control inside the Mobile Form control. The OnActivate and onDeactivate attributes are used to point to functions that can be called either before or after the form is called.

 

From the developer’s perspective, a Form control represents an individually addressable set of controls that allows navigation within the mobile page. For example, if you have two mobile form controls on a page and want to navigate to the second form you would use the MobilePage.ActiveForm property to set the current display form. This property is used to reference the Forms’ ID property as shown in following code.

 

ActiveForm = Form2

 

Each individual Form control is considered separate units of interaction and isn’t URL addressable. Even if the mobile device has adequate screen real estate, ASP.NET never combines the panels into a single presentation. By default when you browse to a mobile page the first form placed on the page is automatically displayed and active.

Panel Control


Figure12 The Panel control placed within a Mobile Formcontrol.

 

A Panel control as shown in Figure12 is an ASP.NET mobile control that can be included within a Form control. The HTML syntax for a Panel control nested in a form control is shown below.

<mobile:Formid="Form1"runat="server">

<mobile:PanelID="Panel1"Runat="server">

</mobile:Panel>

</mobile:Form>

 

A panel is used as a grouping mechanism within a form or other Panel controls for better Mobile Form organization. Panels are typically used to perform the following application features:

  • Define styles and the flow of information for a group of controls and visually group a set of controls together.
  • Used to group show or hide controls.
  • As a container for dynamic controls.
  • Provide ASP.NET with information about how to group controls on a screen.

 

Unlike the Mobile Form control the panel isn’t considered a separate unit of interaction. This means that it can’t serve as a jump location within a Mobile Web Page.

Standard Controls

The standard controls of the mobile designer are similar to their corresponding ASP.NET Web Form controls. They are used to display and collect user information on a mobile device.

Label Control


Figure13 The mobile Label control

 

The label control as shown in Figure13 is identical to the standard ASP.NET label control. It is used to display text that the user is not able to able to edit. This control can be rendered in either the Panel or Label control. The HTML syntax for the control is shown below.

 

<mobile:Formid="Form1"runat="server">

<mobile:LabelID="Label1"Runat="server">Label</mobile:Label>

</mobile:Form>

 

With mobile devices it is important to remember that this control might not render well on smaller screens. Therefore it is best to use the label control for shorter strings.

 

TextBox Control


Figure14 The Textbox control

 

The Textbox control as shown in Figure14 is used to capture data input from users. Due to the reduced rendering capability of Mobile devices, the mobile textbox control accepts short text input and does not provide a multi-line format. It is placed within the Form or Panel control using the following HTML syntax.

 

<mobile:Formid="Form1"runat="server">

<mobile:TextBoxID="TextBox1"Runat="server"Numeric="True">

</mobile:TextBox>

</mobile:Form>

 

Like the standard ASP.NET textbox the initial string value can be set with the Text control. The size property is used to specify the expected character length of the string input. Through adaptive rendering this property is used to calculate left scrolling of the textbox during runtime. This is a mobile input feature that allows users to continue to see their input even when they have reached the right margin of the display area.

 

One of the most important differences with the Mobile Control textbox is that it allows the setting of the numeric property. This property prevents the mobile user from have to use the T9 editing to switch between text and numbers. This is a feature of the markup that the phone renders. Not all markup languages including HTML support this feature. Smaller devices tend to support WAP as their primary protocol. In this case the markup returned to the device contains a tag that forces numeric input as shown in Listing 4.

Listing 4: WAP markup setting textbox input.

<!-- WBXML public ID number 0x0001: <unknown or missing> -->

<html>

  <head>

    <meta http-equiv="Cache-Control" content="max-age=0"/>

  </head>

  <p:card>

    <p:onevent type="onenterforward">

      <p:refresh>

        <p:setvar name="TextBox1" value=""/><p:setvar name="TextBox2" value=""/><p:setvar name="mcsvdevfr0" value=""/>

      </p:refresh>

    </p:onevent>

    <p>Text Input<input name="TextBox1"/>Numeric input<input name="TextBox2" format="*N"/>Password Only<input name="mcsvdevfr0" type="password"/>

    </p>

  </p:card>

</html>

 

Command Control


Figure15 The Command control button

 

The Command control as shown in Figure3-15 provides mobile Web Forms with the ability to post user input to the server. When compared to the standard ASP.NET controls the Command control combines the features of the button, image button and link button. Like the other mobile controls all Command controls must be placed on a container control. The HTML to render this control is shown below.

<mobile:Formid="Form1"runat="server">

<mobile:CommandID="Command1"Runat="server">Command</mobile:Command>

</mobile:Form>

 


Figure16 The softkey label of a mobile phone

 

The appearance of the Command Control varies depending on its property setting and the type of device which it is being rendered on. It can appear as a button, image, link or Softkey. A softkey is a programmable button as shown in Figure16 available on many cellular phones.

TextView Control

Figure17 The text view control

 

Smaller screen based devices are ideal for reading text based documents. However, reading longer documents can cause memory and usability constraints. The Textview control is designed to solve this problem. It supports the display of larger text fields as shown in Figure3-17. The HTML syntax to render this control is shown below.

<mobile:Formid="Form1"runat="server">

<mobile:TextViewID="TextView1"Runat="server">This is the long text   

  that you want to have displayed</mobile:TextView>

</mobile:Form>

 

Unlike the other mobile controls the Textview controls supports a limited set of HTML markup tags as shown in Table 4.

Table 4: Markup tags supported by the Textview control

Markup Tags

Description

<a href = "URL">hyperlink</a>

Provides hyperlink capability. URL represents the navigation URL, and hyperlink represents the link text.

<b> </b>

Makes all text between these two tags bold.

<p> </p>

Contains a paragraph.

<i> </i>

Displays all text between these two tags in italics.

<br/>

Inserts a line break.

 

Image Control

Figure18 The Image Control

 

The Image Control as shown in Figure18 provides the capability to specify a device specific picture in a Mobile Web Form. Given the range of devices and the variety of support a single image may not be appropriate for all mobile devices. Many devices are incapable of supporting certain formats, sizes and color schemes. For example, a .gif image will display properly on an HTML formatted device, but will not display on a WML capable browser. By default WML supports only .wbmp formatted pictures. The Image control is independent of the selected image file. It supports any type of image file that is compatible with the targeted browser. The HTML syntax for this control is shown below.

<mobile:FormID="Form3"runat="server">

<mobile:Imagerunat="server"id="myImages"AlternateText=

"Sorry, this requested image cannot be displayed on this device.">

<deviceSpecific>

<choiceFilter="IsColor"

ImageUrl="ColorImage.gif"/>

<choiceFilter="Wml"

ImageUrl="WMLImage.wbmp"/>

</deviceSpecific>

</mobile:Image>

</mobile:Form>

 

 

The image control provides the ability to specify alternate image files using the <devicespecific> tag. When an Image control is rendered it evaluates the capabilities of the mobile device. Based on this evaluation it can display the text defined within the AlternateText property if the device is not capable of displaying images. If the device is capable of rendering images, the location of the image is specified with the ImageURL property. In order to identify the right image, the control extracts a value from a matching <choice> clause inside the image control. This value is then used to render the file on the device.

Calendar Control

Figure19 The Calendar control

 

The Calendar control is used for date selections as shown in Figure19. By default the calendar control displays a month of dates at a time. The HTML syntax to add a calendar control is shown below.

<mobile:Formid="Form1"runat="server">

<mobile:CalendarID="Calendar1"Runat="server">

</mobile:Calendar>

</mobile:Form>

 

By default the SelectedDate property is set to the rendering server date. However, using the code snippet in Listing 5 it can be changed to an arbitrary date like tomorrow.

Listing 5: Setting the default calendar date to tomorrow.

Protected Sub CmdSelTomorow_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmdSelTomorow.Click

        With Calendar1

            .SelectedDate = DateAdd(DateInterval.Day, 1, Today)

        End With

    End Sub

 

The VisibleDate property is used to determine what month appears on the calendar. This enables the application user to move from one month to the next changing the visible data without affecting the currently selected date..The Calendar control raises a SelectionChanged event whenever the user changes the current date selection. By providing a handler for this event, your application can customize the calendar's behavior and validate against business logic.

***Insert Note***

The calendar control is a great example of adaptive rendering. Based on the rendering device its appearance and selection methods are changed.

PhoneCall Control

Figure20 The phone call control

 

The PhoneCall control as shown in Figure20 enables applications to place phone calls using a provided number. The HTML syntax for this control is shown below.

<mobile:Formid="Form1"runat="server">

<mobile:PhoneCallID="PhoneCall1"Runat="server"AlternateUrl="https://www.company.com"

PhoneNumber="16035551212">PhoneCall</mobile:PhoneCall>

</mobile:Form>

 

On mobile devices that can place calls the PhoneCall control displays a string to the user. The string appears as a command that the user can select to activate the control. Phone numbers are set using the PhoneNumber property and the Text property displays the content of the command string to call.

 

***Insert Note***

The PhoneCall control requires a number to be entered once placed on the form. For dynamic applications this initial value is usually something like the main company number or a default help desk number.

 

If the user’s mobile device does not support phone calls, the PhoneCall control displays text according to the format string specified in the AlternateFormat property. By default this field contains {0} {1} as its formatting string. The PhoneCall control replaces the {0} with the string in the Text property. It replaces the {1} with the contents of the PhoneNumber property.

Figure21 The Link control

 

The Link Control as shown in Figure21 displays a text string that serves as a hyperlink. The hyperlink can lead to another Mobile Form on the same mobile page or another URL. The HTML syntax for this control is shown below.

<mobile:Formid="Form1"runat="server">

<mobile:LinkID="Link1"Runat="server"NavigateUrl="#Form2"SoftkeyLabel="Data">Customer Lookup</mobile:Link>

 

</mobile:Form>

<mobile:FormID="Form2"Runat="server">

</mobile:Form>

 

On all mobile devices a link is rendered by presenting the text property to the user. When selected the control changes to the page specified in the NavigateURL property. When navigating within the same Mobile Web Form set the NavigateURL using the “#Form” syntax as shown in Listing 6.

 

Listing 6: Setting the default link navigation within a Mobile Form.

<body>

<mobile:Formid="Form1"runat="server">

<mobile:LinkID="Link1"Runat="server"NavigateUrl="#Form2">Customer Lookup</mobile:Link>

 

</mobile:Form>

<mobile:FormID="Form2"Runat="server">

</mobile:Form>

</body>

AdRotator Control

Figure22 The AdRotator control

 

The ASP.NET mobile Web Forms AdRotator control as shown in Figure22 is based on the ASP.NET version to randomly display and cycle through a series of advertisement. The AdvertisementFile property in the properties window is associated with an XML file that contains the following format. (example included on companion CD ROM in Chapter 3/Sample/Advertisements)

<Ad>

  <ImageUrl>windows_masthead_ltr.gif</ImageUrl>

  <NavigateUrl>https://www.microsoft.com/Windows</NavigateUrl>

  <AlternateText>Windows Server 2003 R2</AlternateText>

  <Keyword>Software</Keyword>

  <Impressions>80</Impressions>

  <StartDate>1/27/06</StartDate>

  <EndDate>12/29/07</EndDate>

</Ad>

 

Although not required the advertisements file is typically contained in the current project. This helps to ensure that the file remains with the project through deployment. The control automates the cycling process through a series of advertisement banners each time the page is refreshed. Advertisements can be weighted to control the priority level of banners, making it possible to display certain advertisements more often than others. The HTML syntax for the control is shown below.

<mobile:Formid="Form1"runat="server">

<mobile:AdRotatorID="AdRotator1"Runat="server"AdvertisementFile="~/Ads.xml">

</mobile:AdRotator>

</mobile:Form>

 

***Insert Note***

Advertisements are displayed only at runtime.

 

Validation Controls

Figure23 The Validation controls

 

Validation controls as shown in Figure23 are used to verify data contained within an ASP.NET mobile controls. If the data is not valid according to the rules defined within the control, an error message is returned. These controls are similar to the standard set of ASP.NET validation controls.

Compare Validator Control

The CompareValidator control is used to validate data values in a SelectionList or Textbox control. The HTML syntax to add a CompareValidator to a form is shown below.

<mobile:FormID="FrmCompare"Runat="server">

<mobile:CompareValidatorID="CompareValidator1"Runat="server"ControlToCompare="Txthi"

ControlToValidate="txtlo"ErrorMessage="Text boxes are not equal"Type="Integer"

ValueToCompare="=">

</mobile:CompareValidator>

 

Validation is defined by setting the ControlToValidate property to the name of the control that is being compared and then using the ValuetoCompare property to specify the type of comparison.

 

Range Validator Controls

The RangeValidator control is used to validate that user input falls within a specified minimum and maximum range. The HTML to add a RangeValidator control to a form is shown below.

 

<mobile:FormID="FrmRange"Runat="server">

<mobile:RangeValidatorID="RangeValidator1"Runat="server"ControlToValidate="TextBox1"

ErrorMessage="Only Valid Ranges are 1-5"MaximumValue="5"MinimumValue="1">

</mobile:RangeValidator>

</mobile:Form>

 

Validation is defined by setting the ControlToValidate property to the name of the control that is to be checked and then using the MinimumValue and MaximumValue properties to specify the comparison values.

Regular Expression Validator

The RegularExpressionValidator control is used to test whether the data value in a textbox or Selection list control matches a regular expression. The RegularExpressionValidator control performs its validation by comparing the data value to the regular expression pattern specified in the ValidationExpression property. The HTML syntax to add a RegularExpressionValidator and check for a proper email is shown below.

 

  <mobile:Form id="Form1" runat="server"><mobile:TextBox ID="TextBox1" Runat="server">

        </mobile:TextBox>&nbsp; <mobile:RegularExpressionValidator ID="RegularExpressionValidator1"

        Runat="server" ControlToValidate="TextBox1" ErrorMessage="RegularExpressionValidator"

        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">

    </mobile:RegularExpressionValidator></mobile:Form>

 

Required Field Validator

The RequiredFieldValidator control is used to validate that the user entered a data value into a SelectionList of Texbox control. The HTML Syntax to add a RequiredFieldValidator to a form is shown below.

<mobile:Formid="Form1"runat="server"><mobile:TextBoxID="TextBox1"Runat="server">

</mobile:TextBox>&nbsp;<mobile:RequiredFieldValidatorID="RequiredFieldValidator1"

Runat="server"ControlToValidate="TextBox1"ErrorMessage="RequiredFieldValidator">

</mobile:RequiredFieldValidator></mobile:Form>

 

For example, when the ControlToValidate is set to a textbox it will ensure that the user has entered a value into the text field.

Custom Validator Control

Based on the business logic it may be necessary to customize the validation with the CustomValidator control. Like the other validator controls it checks either a textbox or selectionlist control. The custom validation is raised when the form is posted to the server through the ServerValidate event. The HTML syntax to add this control to the form is shown below.

 

<mobile:Formid="Form1"runat="server"><mobile:TextBoxID="TextBox1"Runat="server">

</mobile:TextBox>&nbsp;<mobile:CustomValidatorID="CustomValidator1"Runat="server"

ControlToValidate="TextBox1"ErrorMessage="CustomValidator">

</mobile:CustomValidator></mobile:Form>

 

Once the control is placed on the form and tied to a control. Custom validation is done using the ServerValidate event and setting the arguments property as shown in Listing 7..

Listing 7: Setting custom validation

Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate

        If TextBox5.Text <> "Administor" Then

            args.IsValid = False

        End If

    End Sub

Validation Summary

The ValidationSummary control presents the user with a list of validation errors that occurred when a form was posted to the server. The HTML to add this control is shown below

<mobile:FormID="FrmValidatorSummary"Runat="server">

<mobile:ValidationSummaryID="ValidationSummary1"Runat="server"FormToValidate="FrmValidatorSummary"

HeaderText="Form Errors">

</mobile:ValidationSummary>

<mobile:CommandID="Command6"Runat="server">Command</mobile:Command>

</mobile:Form>

 

List Controls

All applications especially Mobile application use lists to display items. However, for mobile applications this metaphor is an important UI element and makes data selection easier for limited input devices. Typically, the lists contain simple data items, such as string, or more complex data objects, such as records retrieved from databases.

List Control

Figure24 The list control

 

The List control is used to display static lists of items as shown in Figure24. Items added to the list can be exposed as URL’s which make this control idea for navigation and linking to other data sources. The HTML to add the control to the mobile page is shown below.

</mobile:Form>

    <mobile:Form ID="ListControl" Runat="server">

        <mobile:List ID="List1" Runat="server" ItemsPerPage="3">

        </mobile:List>

    </mobile:Form>

    <mobile:Form ID="SelectionList" Runat="server">

    </mobile:Form>

 

Adding items to the list can be done using the MobileControls items as shown in Listing 8.

Listing 8: Dynamically adding items to the list control

Dim myItem1 As New MobileControls.MobileListItem

        With myItem1

            .Text = "My Home Page"

            .Value = "https://www.myhomepage.com"

        End With

 

        Dim myItem2 As New MobileControls.MobileListItem

        With myItem2

            .Text = "My Banking Information"

            .Value = "https://www.bankInformation.com"

        End With

 

        Dim myItem3 As New MobileControls.MobileListItem

        With myItem3

            .Text = "My Sports Score"

            .Value = "https://www.sports.com"

        End With

 

 

        With List1

            ' render the list as a URL

            .ItemsAsLinks = True

            ' add the items

            .Items.Add(myItem1)

            .Items.Add(myItem2)

            .Items.Add(myItem3)

        End With

SelectionList Control

Figure25 The Selection List control

 

The SelectionList control shows a list of items as shown in Figure25 and allows the user to select one or more of them. The HTML to add the item is shown below.

<mobile:Form ID="SelectionList" Runat="server">

        <mobile:SelectionList ID="SelectionList1" Runat="server">

        </mobile:SelectionList>

    </mobile:Form>

 

Figure26 The Selection List property builder

 

 

This control is an ideal solution for short selection lists. Applications can render this control as a drop down list, selection list box, a set of checkboxes, or a set of option buttons. By default applications render the SelectionList control as a drop down list. At design time the using the SelectionList property builder items can be added directly as shown in Figure26. At run time this down through the SelectType property as shown in Listing 9.

Listing 9: Setting the selection list properties at run time.

With SelectionList1

            .SelectType = MobileControls.ListSelectType.CheckBox

            ' add the items

            .Items.Add(myItem1)

            .Items.Add(myItem2)

            .Items.Add(myItem3)

        End With

 

By default selecting items in a SelectionList control does not generate a response until it posted back to the server. This is usually accomplished by combining this control with the Command control. When the Command control posts the form back to the server, The SelectionList control generates a SelectIndexChanged event. Within this event you can write the event handler code that captures the selected item as shown in Listing 10.

Listing 10: Capturing the selected item.

Protected Sub SelectionList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles SelectionList1.SelectedIndexChanged

        TextBox2.Text = SelectionList1.Selection.Text

End Sub

 

ObjectList Control

Figure27 The ObjectList Control

 

The ObjectList control is used to display multiple views of data collections. Each item or object contains data groupings that in turn contain individual data elements. The HTML to render this control is shown below.

<mobile:Form id="Form1" runat="server">

        <mobile:ObjectList ID="ObjectList1" Runat="server" CommandStyle-StyleReference="subcommand"

            LabelStyle-StyleReference="title">

        </mobile:ObjectList>

 </mobile:Form>

 

The ObjectList control is a data bound control. When data bound the control contains a row of data for each object. The individual columns show the field values and the control displays a detailed view for each object. Applications bind to this control using the Data View, Dataset or any object that implements the IEnumerable interface. When an objectlist control performs databinding it can automatically generate the fields displayed for each publicly available list item.

Data Binding with the Object List

Figure28 Adding a Dataset designer.

 

The DataSet object represents a complete set of data. It includes the tables that define order and constraints, as well as the relationships between the tables. Applications bind to a specific field in a DataTable object contained in the DataSet object. Visual Studio 2005 provides a DataSet designer that can be added to a project as shown in Figure28..

 

Once added to the project the TableAdapter wizard connects and binds to the data source using the following steps to create the typed DataSet..

Figure29 Connecting to the datasource

1. Connect to the database

Figure30 Saving the connection string

 

2. Define the connection string that is stored in the web.config file.


Figure31 Specifying the Command Type

 

3. Define the command type that is used to retrieve the data.

 

Figure32 Binding the commands to the TableAdapter

 

4. Define the parameters and methods for retrieving data

 

Figure33 Defining the TableAdapter fill methods

 

5. Define the methods that are used to both fill and retrieve data from the TableAdapter.

 

Figure34 The system generated schema definition

 

Once the wizard is completed it generates a schema definition within the project as shown in Figure34.

 

Accessing the TableAdapter?

TableAdapters objects aren’t actually part of the .NET Framework. They are entirely generated by Visual Studio using the Configuration Wizard or the DataSet designer. TableAdapaters are designed to abstract the database away from application code.

 

The abstraction is created in two parts. The first part is the common language runtime (CLR) to database type conversion that happens inside the TableAdapter. Since the .NET programming languages do not natively contain data types for database access, a mapping is created between the type of the database column and a CLR type. By creating this mapping, a TableAdapter can expose methods and properties associated with columns in the database that can be accessed directly by your code. The second part of the abstraction is encapsulation of the database objects. Encapsulated within the TableAdapter are a DataAdapter, a connection object, and an array of command objects. The command objects are exposed publicly through method calls—for each command object, there is a public method on the TableAdapter. These command objects are exposed as TableAdapter queries in the dataset schema.

 

Within the Page Load event you can leverage this object with the ObjectList using the code in Listing 10.

Listing 10: Accessing the TableAdapter

If Not IsPostBack Then

            Dim ta As New DataSet1TableAdapters.EmployeesTableAdapter

            Dim dt As New DataSet1.EmployeesDataTable

            ta.Fill(dt)

 

            With ObjectList1

                .DataSource = dt

                .DataBind()

            End With

        End If

 


Figure35 the ObjectList lookup screen

 

Figure36 The ObjectList detail screen

 

When the application is run it provides two views of the data as shown in Figure35 and Figure36.

Special Controls

Special Controls are groups of controls that are not rendered at run time but instead affect the rendering of the page or control to which they are attached. The ASP.NET Mobile Designer presents these controls in the same way that it presents other controls. You can add special controls to the ASP.NET Mobile Web Forms pages, and configure them like any other control.

 

The ASP.NET mobile controls currently provide two special controls. The StyleSheet control defines the styles for your mobile Web Forms page. The DeviceSpecific Controls enables you attach templates or property overrides to a Form or Panel control.

StyleSheet Control

Figure37 The StyleSheet controls

 

The ASP.NET Mobile Designer facilitates the use of styles within an ASP.NET Mobile Web form through the StyleSheet Control. This control can be attached only to ASP.NET mobile Web Forms pages or to mobile user controls. There can be no more than one StyleSheet control within a Mobile Web Form Page. The HTML to render this control is shown below.

<html xmlns="https://www.w3.org/1999/xhtml" >

<body>

    <mobile:Form id="Form1" runat="server">

 

    </mobile:Form>

    <mobile:StyleSheet ID="StyleSheet1" Runat="server">

    </mobile:StyleSheet>

</body>

</html>

 

***Insert Note***

The ASP.NET Mobile Controls do not support Cascading Style Sheets.

 

Style Sheets are different from templates. Templates are used to specify reusable content and controls. Style sheets contain information about how controls and content will be rendered. In addition style sheets can contain templates within their styles. When you apply styles to controls, they replace the controls’ default style information and templates.

Figure38 The Styles Editor

 

You define styles in a StyleSheet control using the Styles Editor as shown in Figure38. The editor derives these from the styles provided in the ASP.NET mobile controls. By default, the mobile controls define the Style and PagerStyle styles. The style contains appearance properties common to mobile controls. The PagerStyle style contains the properties of the Style plus properties applicable to the paginated controls.

 

Style sheets provide a useful tool for giving page content and controls a consistent appearance. For example, you can apply a style to a group of command controls placed within a Panel and setting the Panels control’s Stylereference property to one of the styles in the style sheet as shown in Listing 11.

Listing 11: Applying styles to a Panel control.

<html xmlns="https://www.w3.org/1999/xhtml" >

<body>

    <mobile:Form id="Form1" runat="server">

        <mobile:Panel ID="Panel1" Runat="server" StyleReference="ButtonStyle">

            <mobile:Command ID="CmdLookup" Runat="server">Lookup Customer</mobile:Command>

            <mobile:Command ID="CmdAddCustomer" Runat="server">Add Customer</mobile:Command>

        </mobile:Panel>

 

    </mobile:Form>

    <mobile:StyleSheet ID="StyleSheet1" Runat="server">

        <mobile:Style Alignment="Right" BackColor="Transparent" ForeColor="Black" Name="ButtonStyle">

        </mobile:Style>

    </mobile:StyleSheet>

</body>

</html>

 

To provide a consistent look across multiple pages of an application, controls can reference external style sheets. An external style sheet is a mobile user control in an .ascx file which contains a stylesheet control. To gain access to external styles, a mobile Web Forms page must contain a StyleSheet control. Set the StyleSheet control’s ReferencePath property to the path name of the Mobile User control containing the .ascx file containing the external style sheet as shown in Figure39.

Figure39 Setting an external style.

 

The styles in the external style sheer are called external styles. The styles in the Stylesheet control attached to the current page are called internal styles. Controls on the page can reference both the internal and external styles by name. If an internal style and an external style have the same name only the internal style will be visible to the controls on the page.

 

DeviceSpecific Control

Figure The DeviceSpecific Control.

 

The DeviceSpecific control is used to target the appearance of a Mobile Form or Mobile Panel control to a specific type of hardware device. The HTML to add the control is shown below.

  <mobile:Form id="Form1" runat="server">

        <mobile:DeviceSpecific ID="DeviceSpecific1" Runat="server">

        </mobile:DeviceSpecific>

    </mobile:Form>

 

Whenever you place a DeviceSpecific control within a Form or Panel control, the designer displays the control ID on the top line of the control. In addition, the DeviceSpecific control displays information about the current TemplateDeviceFilter which by default is blank.

Figure41 Selecting the Templating Options of a DeviceSpecific control.

 

After you add a DeviceSpecific control to a container control, select Templating options from the shortcut menu as shown in Figure41 to define and apply device filters to the container.

Figure42 Defining a device filter.

 

Device filters test the browser that is accessing the page to determine if it meets certain criteria. For example to test if a device is running HTML you can set the device filter as shown in Figure 3.42. Once the filter is created this generates the HTML markup as shown in Listing 12.

Listing 12: Testing to see if a device supports HTML.

<mobile:Formid="Form1"runat="server">

<mobile:DeviceSpecificID="DeviceSpecific1"Runat="server">

<ChoiceArgument="true"Filter="isHTML32"Xmlns="https://schemas.microsoft.com/mobile/html32template">

<HeaderTemplate>

The browser that is running this Mobile Page has tested positive for HTML 32

</HeaderTemplate>

</Choice>

</mobile:DeviceSpecific>

</mobile:Form>

Looking at Pagination

ASP.NET mobile controls provide a mechanism for automatically separating content within a Mobile Form into smaller groups of rendered content. This mechanism is called pagination. When you use Pagination, groups of content are automatically formatted to fit the targeted device. The form also renders user interface elements that you can use to browse other pages.

Figure43 Enabling pagination in a Mobile Form.

 

By default, pagination is not activated for a form. By setting the Paginate property to true as shown in Figure43 you can turn it on. Without setting the form to true setting the Paginate property on any control within the form has no effect. The Form control also provides properties such as PageCount, CurrentPage and PagerStyle which allows you to perform pagination behavior. You can specify pagination for a specific control on a form using the form’s ControlToPaginate property with the ID of the control.

Figure44 A TextView control displays paginated.

 

It is recommended not to use pagination for smaller interactive forms in an ASP.NET mobile application such as input forms. In these cases, pagination is often redundant. However, for forms that display large amounts of text or data, pagination can be effective in displaying the information on appropriate pages as shown in Figure44.

 

When you have a large amount of data that changes over time, such as in the case of an en e-commerce site where data is being updated constantly, you might consider using custom pagination. Like any mobile Web application it is important to keep in mind the targeted devices. Some device may experience errors when you try to display more information that their memory can handle. Not only can pagination be effective in displaying form with large amounts of text or data, but also pagination may help to redice these types of errors.

 

Mobile controls that are capable of automatic pagination across multiple pages without child controls use internal pagination. The List control is an example of a control that uses internal pagination. For example, a List control can paginate its own items, allowing a form to break the single list into multiple pages. Controls that do not support internal pagination must either have child controls or appear on a single page.

 

Any control that support internal pagination use the PagedControl base class to derive pagination properties, methods, and events for internal and custom pagination. Properties such as the FirstVisibleItemIndex property provide access to the individual items on a page. Other properties provide the rest of an item and the count of visible items.

 

Controls that support internal pagination also provide a feature called custom pagination. Normally, controls require the data for all pages to be provided at once, but, in the custom paginated case, the controls raise an event to load only the items for the current page. Developers specify the total number of items in the ItemCount property. Changing the value of the ItemCount property from its default value of zero to the total number of items indicates that the control is to be custom paginated. When the control is custom paginated, it raises the LoadItems event, which can call an application-specified event handler to provide the items for the current page. The event handler retrieves the appropriate data and binds the data to the control.

Summary

In this article we have taken a look at the basics of building Mobile Web applications using the Mobile Controls. These controls help to solve many of the traditional problems that are the result of limited device and markup language support available within some mobile devices. The process of adaptive rendering by these controls allows the rendered markup rendered to depend on the browser requesting ASP.NET page. Even with adaptive rendering there are still some important design decisions in building any Mobile Web application.