Exploring the Microsoft Mobile Internet Toolkit


Wireless devices, such as Web-enabled cellular phones, serve a different function from PDAs. Rather than storing data such as contact information, messages, and schedules locally, cellular phones are used exclusively for communication and information retrieval. The simplest example of information access via cellular phone is an everyday call to 411 for information. Web-enabled cellular phones have taken this concept to the next level by removing the human element on the information provider side and replacing it with Web content. This is the basis for the Microsoft Mobile Internet Toolkit (MMIT).

Essentially, MMIT is an extension to the existing ASP.NET services. Mobile applications are composed of source files that abstract a user interface. When a mobile device connects to the server, its device profile is detected and the abstracted user interface is formatted specifically for the connecting device. The connecting mobile device does not need to install any local software to interact with the enterprise application.

Communication between the mobile client and the server is typically conducted over port 80 using the Wireless Application Protocol (WAP). WAP is similar to the standard HTTP Web protocol but is optimized for mobile devices. WAP leverages a binary transmission for improved compression of data optimized for low bandwidth. WAP sessions are also forgiving to intermittent and unreliable connections.

Content displayed within a mobile device is formatted in the Wireless Markup Language (WML). Like its Hypertext Markup Language (HTML) counterpart , WML is a tag-based format for describing content. WML addresses many of the inefficiencies found in HTML, including the large amounts of text-based data to be sent across a low bandwidth connection. Also, HTML content is unable to be cleanly displayed on the small displays of mobile devices.

In Visual Studio .NET, a mobile application's user interface uses the same form designer used to build ASP.NET Web applications. There are only a few noticeable differences. First, a number of user interface controls have been removed from the Toolbox, and new device-specific controls have been added. Next, you can draw multiple content forms per page. Also, there is no support for absolute positioning of form controls, only relative positioning. Finally, there are a number of limitations related to session management.

Understanding the Platform Architecture

MMIT enables applications to be rendered on mobile devices produced by different manufacturers with different device capabilities. Its underlying platform architecture is based on three elements: device detection, device formatting, and Web communication. Figure 11-15 illustrates the MMIT platform architecture.

click to expand
Figure 11-15: The MMIT platform architecture

The only way to render an application on different mobile devices is to apply the appropriate formatting. That begins with device capability detection. Both the HTTP and WAP protocols embed information about Web requests within their request headers. These incoming request headers determine the device capabilities of the connecting device and determine the best method of formatting a response. There are a number of available output formats for a variety of mobile devices, including HTML, Compact HTML (cHTML), and WML.

You compose the user interfaces created for mobile applications generically. In other words, the application developer has little influence over the final positioning of user interface controls when rendered on a specific device. Device filters manage the specific layout mapping between the abstract user interface defined in the form designer and the final output of the mobile application.

The functionality that binds everything together is the existing ASP.NET framework. This includes page processing and life cycle, request and response communication, and session management. Adding capability detection and device formatting to existing ASP.NET services makes MMIT a logical choice for building mobile applications.

Building Mobile Applications for the Enterprise

Developing mobile applications for the enterprise requires even more planning than Compact Framework device applications or their natural Web application counterparts. This is largely because of the tighter restrictions on resources, such as display area, memory capacity, and speed. Therefore, mobile applications require additional design constraints to those imposed by Compact Framework applications. These include the constraints of portability and speed.

Where Compact Framework applications could expect to operate on devices running the WinCE or Pocket PC operating systems, MMIT applications may not know for sure which device platforms they will support. As a result, you need to design mobile applications with broad functionality in mind and a simple user interface. Furthermore, you need to design mobile applications to integrate custom device filters that can bridge the gap to unknown devices.

With a low-bandwidth Internet connection, especially one that charges per minute, mobile application speed is important. Mobile applications must take even greater care than their Web application counterparts when it comes to optimizing for performance.

A lot of the performance impact depends on how the mobile application is laid out. WML specifies the organization of content differently than HTML. In HTML, the contents of each page are completely viewable. In WML, however, a page may be composed of separate viewable forms of related content. When a mobile page is referenced, the page and all of its embedded forms are downloaded into local memory. Switching between the individual display forms appears to be fast because there is not a request to the server.

You need to organize content, therefore, into related blocks. In the case of IssueTracker , searching for an issue, viewing a list of issues, and viewing a specific issue's details are all implemented as different forms within a page. The application requires only a single request to the server to pull down all the necessary forms.

Implementing a Mobile Internet Application

Visual Studio .NET provides a development environment for creating mobile applications. With MMIT, developers can create and distribute applications that run on just about any mobile device capable of Web browsing. Implementing a mobile application typically involves creating the project, adding forms and controls to pages, adding event handlers that accomplish specific business tasks , and deploying the application.

Creating the New Project

Creating a new project for a mobile application follows the same general process as creating a new Web application project. To create a mobile project, click Add ˜ New Project from the Solution Explorer's context menu. In the Add New Project dialog box, select the ASP.NET Mobile Web Application template, enter the project name as shown in Figure 11-16, and then click the OK button.

click to expand
Figure 11-16: Adding a new mobile Web application project

This creates the mobile application project along with a handful of supporting files. The MobileWebForm1.aspx.cs file contains the source code for handling events and user interface formatting. The assemblyInfo.cs file contains attributes that describe the assembly built by the project. The global.asax file responds to application-level events sent by ASP.NET or by HttpModules. The web.config file contains settings specific to the mobile application.

Adding Pages and Forms

The foundation element of a mobile application is a page. Like any other Web application, a mobile application page is referenced by a specific URL. As mentioned, a page is composed of one or more display forms, each containing the user interface controls that implement the user experience. An important difference between mobile applications and standard Web applications is that only one form displays on a mobile device at a time. In a mobile application, the first form within a page is considered to be the default form displayed.

The reason for supporting multiple display forms per page is based largely on state management and performance reasons. There is little support for saving state between mobile application pages. By implementing multiple display forms per page, applications can more easily pass state information from one form to another.

Another reason for supporting multiple display forms within a page is to optimize for performance. Rather than slowly downloading one page after another, it requires a single performance hit to download one larger page and then quickly navigate among locally cached forms. Also, mobile applications are able to pass state data between forms within a page, rather than slowly pass state data back to the server. All forms within a page share a single code-behind source file, supporting sharing and reuse of methods as well as minimizing the mobile application's overhead.

Adding Forms and Controls

Unlike the design of Web applications, mobile applications have limited influence over how user interface controls appear with the mobile application. Forms do not support the absolute placement of controls. You must place controls into a form in their logical order of use from left to right and from top to bottom. You cannot set controls to specific dimensions. As a result, building display forms in the form designer does not provide an accurate representation of how they will be rendered on a mobile device. Figure 11-17 illustrates the minimal control that application developers have over mobile form layout. User interface controls fall vertically down a form with the expectation that there is little display width.


Figure 11-17: Setting the BreakAfter property to true renders one control per line.

The only exception to the limited placement of controls within a form relates to line breaks. Some devices are capable of displaying multiple controls on a single line, and other devices display only a single control per line. If devices are capable, the BreakAfter property enables side-by-side placement of form controls. Devices supporting line breaks automatically adapt the rendering for side-by-side layout. Setting the BreakAfter property to false places controls side by side on all capable devices. Figure 11-18 sets the BreakAfter property to false to produce a user interface that is a bit easier to use.


Figure 11-18: Setting the BreakAfter property to false renders multiple controls per line.

Panels are another tool that help organize user interface controls within a form. Panels work well for applying specific styles across multiple controls. Typically, forms will try to render as many user interface controls as possible on a device display. Panels, however, can define pagination and grouping of related controls. You add them from the Toolbox to the form and later fill them with additional user interface controls. All embedded controls inherit the properties defined for the panel. This creates a clean method of showing or hiding multiple controls all at once.

Adding Event Handling

User interface controls within a mobile form define events in the same manner as their Web application counterparts. The only difference is that all event handling is processed on the server rather than the client. When a button control is clicked, the containing page is posted back to the server where the event parameters are examined. Event handlers that correspond to events execute on the server. When the event handler completes, the server sends the page back to the mobile device with the applied changes.

Applying Style Sheets to Mobile Forms

A style sheet defines one or more styles that specify the appearance of controls when they are rendered. When placed into a display form, the style sheet control enables specific style information to be defined and applied to a specific user interface control, a collection of controls within a container, or all controls within the same page. You can attach only one style sheet control to a page or control, but not within a form or panel.

After adding a style sheet control to a page, the Styles Editor defines its specific properties. The dialog box displays the styles that have been defined in the Defined Styles dialog box. All defined styles must be based on a style type shown in the Style Types list. When you select and add a style type to the Defined Styles list, you add the defined style as an instance of that style type. In addition, you can create multiple defined styles based on the same style type.

Testing Mobile Applications with Device Emulators

Mobile device emulators are valuable tools for testing mobile applications. Most manufacturers of mobile devices encourage application developers to build and test solutions for their mobile devices. Companies, such as Ericsson and Nokia, provide toolkits freely downloadable to registered users. These toolkits include mobile device emulators that simulate the look and feel of a specific device. As Figure 11-19 illustrates, you can use these emulators to test mobile applications, saving you the cost of purchasing the physical devices.


Figure 11-19: The IssueTracker mobile login form displayed in the Nokia 7210 emulator

By default, when a mobile device application starts within Visual Studio .NET, the application interface is rendered in plain HTML and displayed within the default Web browser. You can quickly modify Visual Studio to start a third-party device emulator instead. After downloading and installing the emulator, open Visual Studio. Select File ˜ Browse With from the menu. In the Browse With dialog box, click the Add button and enter the executable file path and label for the device emulator.

Note  

Most emulators can accept a parameter representing the URL to a starting page. Specify a %URL variable where Visual Studio should insert the starting page's location.

From the Solution Explorer, select the starting .aspx mobile form and choose Browse With from its context menu. In the Browse With dialog box, select the newly added device emulator. The next time the mobile application launches, it should appear within the selected device emulator.

You can download the Ericsson WML toolkit and emulator from the Ericsson Mobility World Web site ( http://www.ericsson.com/mobilityworld ).

The mobile emulator used for the examples in this chapter is the Nokia 7210, bundled with the Nokia Mobile Internet Toolkit 4.0. You can download the toolkit and emulator from Nokia's developer forum ( http://www.forum.nokia.com ).

In addition to downloading and installing an emulator, you should download and install the Device Update 2 for .NET Framework 1.1. This update includes updated browser capabilities for new mobile devices. You can download it from http://www.asp.net/mobile/deviceupdate.aspx .

Enhancing Mobile Internet Enterprise Clients

There is much more to building a mobile client for the enterprise than creating forms, adding controls, and processing events. Features such as enabling a secure login, pulling data from Web services, dynamically binding form controls, and displaying graphics are necessary to round out the functionality. These features help shift the enterprise mobile client from being a useless showpiece to being a valuable extension of the enterprise application.

Implementing a Secure Mobile Login

Security in mobile applications is just as important as within the other application platforms. MMIT provides services that help validate user access. The IssueTracker mobile client uses the FormsAuthentication object to ensure user identity. To implement the login functionality, add a new mobile Web form to the project and name the page app_login.aspx . Add the user interface controls as shown in Figure 11-20.


Figure 11-20: The mobile application login page, app_login.aspx

The System.Web.Security namespace provides many security-related objects described later in Chapter 13, "Understanding .NET Security and Cryptography." In the app_login.aspx.cs code-behind file, begin with an additional namespace reference to the Security services:

 using System.Web.Security; 

Add an event handler that responds to the Login button's Click event. Rather than process the user login with a Web service, as with the Compact Framework version of the application, the mobile login can be performed with the FormsAuthentication object. Listing 11-10 outlines the login authentication process.

Listing 11-10: Implementing Forms Authentication for Mobile Clients
start example
 private void btnLogin_Click(object sender, System.EventArgs e) {     try     {         if( FormsAuthentication.Authenticate( txtUsername.Text, txtPwd.Text ) )         {             FormsAuthentication.SetAuthCookie( txtLogin.Text, false );             MobileFormsAuthentication.RedirectFromLoginPage( txtLogin.Text, true );         }         else         {             lblMessage.Text = "Login Failed.";         }     }     catch( Exception x )     {         EventLog systemLog = new EventLog();         systemLog.Source = "IssueTracker";         systemLog.WriteEntry( x.Message, EventLogEntryType.Error, 0 );     }     retrun; } 
end example
 

The event handler performs the user authentication. When a user requests any page belonging to the mobile application without having been authenticated, they will be redirected to this login page. The FormAuthentication object performs the user authentication based on the supplied username and password. If the authentication fails, the page displays a message and the user is not permitted to continue. Otherwise, if the authentication succeeds, the user is redirected to the originally requested page.

The application logout uses the same security object. The logout event handler invokes the FormsAuthentication's SignOut method to close the user session. The user is then redirected to the login page where the process can start again:

 private void btnLogout_Click(object sender, System.EventArgs e) {     MobileFormsAuthentication.SignOut();     RedirectToMobilePage( "app_login.aspx", true );     return; } 

To support Forms Authentication, you need to modify the web.config file to identify the valid credentials. The settings shown in Listing 11-11 should replace (not append to) the existing authentication settings. Specifically, you need to specify the authentication mode to Forms. If two separate <authentication> blocks exist within the web.config file, it will generate a configuration error.

Listing 11-11: Form Security Changes to the web.config File
start example
 <authentication mode="Forms" >     <forms loginUrl="app_login.aspx" name="issuetracker" timeout="60" path="/" >         <credentials passwordFormat="SHA1">             <user name="jkanalakis"                 password="5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8"/>             <user name="mwilliams"                 password="5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8"/>         </credentials>     </forms> </authentication> <authorization>     <deny users="?" /> </authorization> <sessionState cookieless="true"/> 
end example
 

The changes to the <authentication> block specify the use of FormsAuthentication as the mode of user authentication. The <credentials> block specifies the encoding format of the included passwords, either the SHA1 or MD5 format. This block also specifies the valid usernames and passwords for application access. The HashPasswordForStoringInConfigFile method within the FormsAuthentication object created the encoded value for the passwords. The following short method demonstrates how a utility application can use the HashPasswordForStoringInConfigFile method:

 public string GetEncodedPassword( string strPassword ) {     return FormsAuthentication.HashPasswordForStoringInConfigFile( strPassword,     "SHA1" ); } 

The changes to the <authorization> block specify that anonymous users should be denied access to the application. Also, because of the security risks associated with cookies, the <SessionState> tag specifies that cookies should not be used to manage the session.

Integrating XML Web Services

Web services can be just as useful for mobile applications as they are for Web applications. There should be some special considerations before implementing Web services connectivity, specifically relating to performance. Mobile applications are fairly slow to start with; integrating Web services will only slow the application further. Also, without a busy cursor or progress bar, there is not a clean way to give the user the sense that something is still happening. Listing 11-12 integrates a Web service to retrieve the list of issues from the enterprise database.

Listing 11-12: Integrating Web Service Data into a Mobile Application Form
start example
 private void FormViewIssue_Load( object sender, System.EventArgs e ) {     try     {         IssueCollection issues = "";         //instantiate the Web service proxy         net.mynamespace.www.IssueServices wsIssues =             new net.mynamespace.www.IssueServices();         //invoke the Web service method         issues = wsIssues.GetAllIssues();         if( strWebServiceResponse.StartsWith( "ERR" ) == false )         {             foreach( Issue objIssue in issues )             {                 lstIssues.Items.Add( "[" + objIssue.IssueID + "]" +                     objIssue.Summary.Substring(0,10) + "..." );             }         }         else         {             System.Windows.Forms.MessageBox.Show( "Login Failed." );         }     }     catch( Exception x )     {         EventLog systemLog = new EventLog();         systemLog.Source = "IssueTracker";         systemLog.WriteEntry( x.Message, EventLogEntryType.Error, 0 );     }     return; } 
end example
 

This method begins with an instantiation of the Web service proxy object, where all of the SOAP-based connections to the Web service are implicitly made. Next, the GetAllIssues Web service method is invoked and its resulting XML is stored in a local string variable. Next, a new DataSet object is instantiated . An XmlTextReader object is also created and initialized with the string returned from the Web service. The XmlTextReader is passed to the DataSet's ReadXml method. This results in the DataSet interpreting and forming the data structure of the returned XML document as well as populating itself with the XML data. From then on, the DataSet's rows are iterated and the issues list is built for display. The issue summary text is intentionally truncated to shorten the displayed text. Figure 11-21 illustrates the resulting list of issues that displays.


Figure 11-21: Displaying issues extracted from a Web service

The user is able to scroll through the list of issues and select one to view its details. The load time for the page is based on the size of the underlying data.

Data Binding Mobile Form Controls

You can data bind mobile form controls to a data source in the same manner as you do for the rest of the ASP.NET framework. The only difference between the two is capacity. Because the mobile client will be connecting over low bandwidth and will have a small display area, it is important to minimize the amount of data exchanged. In Figure 11-22, the IssueTracker mobile application has an intermediate step that helps minimize the volume of data accessed when displaying issues.


Figure 11-22: Helping the user navigate large DataSets

The intermediate step to data retrieval is data filtering. In the IssueTracker application, data comes into three categories: issues related to the user, issues resulting from a search, and all issues stored in the database. Categorizing the underlying data reduces the user's frustration over waiting for the whole list of issues to be retrieved.

For smaller data collections, such as validation data, it is usually safe to continue with standard data binding to mobile form controls. In the case of FormSearch, you implement the drop-down list entries that contain searchable issue types, priorities, and the status using data binding (see Listing 11-13).

Listing 11-13: Data Binding to Mobile Form Controls
start example
 private void Page_Load(object sender, System.EventArgs e) {     try     {         DataAccess.DataAccessComponent data = new             DataAccess.DataAccessComponent();         lstType.DataSource = data.GetDataSetIssueTracker().Val_IssueType;         lstType.DataBind();         lstPriority.DataSource = data.GetDataSetIssueTracker().Val_Priority;         lstPriority.DataBind();         lstStatus.DataSource = data.GetDataSetIssueTracker().Val_Status;         lstStatus.DataBind();     }     catch( Exception x )     {         EventLog systemLog = new EventLog();         systemLog.Source = "IssueTracker";         systemLog.WriteEntry( x.Message, EventLogEntryType.Error, 0 );     }     return; } 
end example
 

Listing 11-13 creates an instance of the DataAccessComponent object to retrieve the application's DataSet object. For each mobile form control, the code assigns the DataSource property to the respective DataSet table. The code then sets the DataTextField and DataValueField properties to the Description and ID columns of the table. Finally, the DataBind method is invoked to establish the binding. Figure 11-23 demonstrates the results, where the user can select from a list of options pulled from the DataSet.


Figure 11-23: Selecting an issue status from a data-bound list control

Displaying Graphics Within a Mobile Form

Some mobile devices are capable of displaying graphics. Graphics are an effective way to communicate information in a quickly recognizable format. As more mobile devices become available with support for graphics, you can develop more usable mobile interfaces. In the meantime, it is important to target specific devices and test their graphical support through emulators. It may take time to determine which graphic format, such as .bmp or .gif, renders best on each targeted device.

A practical use for images within mobile clients is to present a chart to the user. You can place any static image into a mobile form with the help of the MobileControls.Image object. After placing the image control into a mobile form, set its ImageUrl property to the source of the graphic. Presenting a chart based upon dynamic data works similarly. Instead of placing an image control within a mobile form, you can create a new mobile user control.

Mobile user controls function similarly to the Web user controls described in Chapter 7, "Building Web Applications." They also serve a similar function, bringing consistency to an online application. In this case, a mobile user control will implement a simple mobile chart. Begin by selecting the IssueTracker_MobileUI project within the Solution Explorer. Next, select Add ˜ Add New Item from its context menu to create a new mobile Web user control named MobileChart.ascx , as shown in Figure 11-24.

click to expand
Figure 11-24: Creating a new mobile user control

Place an image control, imgChart, into the new user control. Double-click the control's design surface to create a Page_Load event handler. In the page's event handler, you can add code to dynamically create a chart, save it as a .gif, and return it to the mobile client. Listing 11-14 lists the completed event handler.

Listing 11-14: Creating a Dynamic Chart in a Mobile User Control
start example
 private void Page_Load(object sender, System.EventArgs e) {     Point pointStart;     Point pointEnd;     try     {         SolidBrush brush = new SolidBrush( Color.Blue );         Bitmap bmpChart = new Bitmap( 80, 80 );         Graphics g = Graphics.FromImage( bmpChart );         g.Clear( Color.White );         pointStart = new Point( 1, 1 );         pointEnd = new Point( 10, 40 );         g.DrawLine( new Pen( brush, 2 ), pointStart, pointEnd );         pointStart = pointEnd;         pointEnd = new Point( 20, 20 );         g.DrawLine( new Pen( brush, 2 ), pointStart, pointEnd );         pointStart = pointEnd;         pointEnd = new Point( 30, 50 );         g.DrawLine( new Pen( brush, 2 ), pointStart, pointEnd );         pointStart = pointEnd;         pointEnd = new Point( 40, 45 );         g.DrawLine( new Pen( brush, 2 ), pointStart, pointEnd );         pointStart = pointEnd;         pointEnd = new Point( 60, 45 );         g.DrawLine( new Pen( brush, 2 ), pointStart, pointEnd );         Font fontLabel = new Font( "Arial", 8 );         g.DrawString("1  2  3  4  5  6", fontLabel, brush, 1,50 );         bmpChart.Save( @"c:\inetpub\wwwroot\issuetracker_mobileui\chart.gif",             ImageFormat.Gif );         imgChart.ImageUrl = "http://127.0.0.1/issuetracker_mobileui/chart.gif";     }     catch(Exception x)     {         EventLog systemLog = new EventLog();         systemLog.Source = "IssueTracker";         systemLog.WriteEntry( x.Message, EventLogEntryType.Error, 0 );     }     return; } 
end example
 

The Page_Load event handler begins by creating SolidBrush, Bitmap, and Graphic objects. The brush specifies that the color of the chart should appear in blue. The bitmap specifies the dimensions of the drawing surface as being 80 pixels wide by 80 pixels high. The code then creates the graphics engine based on the bitmap specifications and immediately sets it to a white background. The next few lines of code arbitrarily draw lines from point to point to simulate a line chart. Ideally, they should reflect useful values such as sales or losses over time. Finally, the chart is written to the image file chart.gif.

After you have implemented the MobileChart.ascx control, you can place it into a mobile form to render it like any other static image. Figure 11-25 illustrates the use of the MobileChart mobile user control. If a mobile user control does not appear as expected or at all, check the AppliedDeviceFilter settings and apply available device filters as needed to display the control within your emulator.


Figure 11-25: Using the MobileChart mobile user control

Although accessibility to enterprise data is the primary function of an enterprise mobile application, it must also be easy to use. Using graphics in mobile forms works best when they serve a functional purpose. When creating the images, be sure to keep the file size and display size as small as possible. Always test different image formats with different emulators for the best results.




Developing. NET Enterprise Applications
Developing .NET Enterprise Applications
ISBN: 1590590465
EAN: 2147483647
Year: 2005
Pages: 119

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net