现在的位置: 首页 > 综合 > 正文

利用ASP.NET2.0进行Mobile Web开发

2012年12月21日 ⁄ 综合 ⁄ 共 15348字 ⁄ 字号 评论关闭

Mobile Web Development with ASP.NET 2.0

Download the PDF 

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 http://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("http://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

抱歉!评论已关闭.