Stay Ahead of the Curve

Add mobile accessibility to an existing Web site with the MMIT.

Bill Block

October 30, 2009

13 Min Read
ITPro Today logo

asp:coverstory

LANGUAGES: VB

TECHNOLOGIES: Mobile Applications | MobileInternet Toolkit

 

StayAhead of the Curve

Addmobile accessibility to an existing Web site with the MMIT.

 

By Bill Block

 

Adeadline is quickly approaching. Your project manager walks over and asks, "Howmuch effort would it take to add XYZ to the Web site?" If you're like mostdevelopers, you've heard such a question dozens of times. And, like mostdevelopers, you're likely to answer with an estimate that is either much lesstime (because of developer machismo) or much more time (because of developerexperience) than the actual time such a change would take. Armed with a littleknowledge about the technology and some implementation examples, you can reducethe gap between the estimated effort and the actual effort greatly.

 

In thisarticle, I'll show you how to add mobile capabilities to your existing Website. For the sake of the article, I'll focus on a fictitious retail store'sexisting Web site, the Acme Retail Store (ARS) Gift Registry site. The changesyou'll make to this site likely will be similar to changes you'd make to yourown. Figure 1 shows the current Web site, developed as a series of ASP pagesusing VBScript and JavaScript along with a series of COM components written inVisual Basic 6. In the first phase of ARS' go-mobile initiative, companyofficials want to allow consumers to browse existing gift registries using amobile device. The company has plans to purchase tablet-based devices for theretail store, but company officials also would like to make the systemavailable to consumers who have their own personal devices.

 


Figure 1. This diagram depicts thefictitious ARS' existing Gift Registry Web site as well as the new Web pagesthat will be added to expand the functionality to include mobile devices.

 

Take the First Step

To manydevelopers, the thought of starting a Web site for mobile devices soundsominous. Fortunately, the Microsoft Mobile Internet Toolkit (MMIT) givesdevelopment teams the ability to add this functionality to the existing Website quickly and easily. Development begins in the same place it does for mostWeb projects - the home page. In the example, ARS has an existing gift registryhome page (see Figure 2). Company officials want to continue using the existinghome page's URL for all browsers (PC and mobile devices). To use it, ARS needsto install the .NET Framework (including ASP.NET) and the Mobile InternetControls Runtime (part of the MMIT) on a Web server running Microsoft'sInternet Information Server (IIS).

 


Figure 2. The existing Web site allows usersto search for gift registry information by entering a name and clicking on theSearch button. When users click on the Search button, the ASP page calls a COMcomponent that performs a database query and returns results to the browser.

 

Aftersetting up the Web server, developers can begin working on Default.aspx, thenew home page for all browser types. The new page has one purpose: to redirectusers either to the existing home page (for PC-based browsers) or to the newhome page (for mobile devices). Start by opening the existing Web site under VS.NET, adding the new home page by selecting Add Web Form from the Project menu, and selecting the Mobile Web Form template.

 

Next,add logic to the Page_Load event in the form's code-behind to performthe redirect based on which type of browser is requesting the page:

 

Private Sub Page_Load(ByVal sender As System.Object, _

 ByVal e As System.EventArgs) HandlesMyBase.Load

  If Not (Page.IsPostBack) Then

    If (Device.IsMobileDevice) Then

      RedirectToMobilePage("MobileDefault.aspx")

    Else

      Response.Redirect("default.asp")

    End If

  End If

End Sub

 

The Device.IsMobileDevicemethod allows you to determine whether the calling browser is a mobile deviceor a PC-based browser. The Device class is part of the System.Web.Mobile.MobileCapabilitiesnamespace and allows you to query various aspects of the caller's device,including style options, pagination ability, screen size, and device-specificfunctionality. Also, because a standard Response.Redirect method isbeing used to redirect PC-based browsers to the existing home page, you coulduse any Web page on any Web server.

 

Once youset up your home page, you can begin adding content to your mobile site. One ofthe best things about the MMIT and VS .NET is you can develop mobile solutionson top of existing Web sites through the IDE. Although you could develop thetwo sites independently, placing them in a single Web site allows for easydesign and development as you'll see later.

 

Themobile home page, MobileDefault.aspx, will display a search screen similar tothe one shown in Figure 2 to allow the user to enter a bride or groom's nameand retrieve a list of products for which they have registered. Begin by layingout the form in the IDE, using some of the mobile Web Form controls included inthe MMIT. Because you will be working with a small amount of screen space onmost mobile devices, you should begin development with only the core user-interfaceelements and add content, where appropriate, later in the development cycle(see Figure 3). Besides adding the basic visual elements, set the Actionproperty of the mobile Web Form to MobileDefault.aspx. The HTML in Figure 4shows the completed form.

 


Figure 3. As with ASP.NET Web Forms, thedesigner allows developers to lay out user-interface elements quickly andeasily.

 

<%@ PageLanguage="vb" AutoEventWireup="false"

Codebehind="MobileDefault.aspx.vb"

Inherits="GiftRegistry.MobileDefault"%>

<%@ RegisterTagPrefix="mobile"

Namespace="System.Web.UI.MobileControls"

Assembly="System.Web.Mobile,Version=1.0.3300.0,

Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" %>

Xmlns:mobile="http://schemas.microsoft.com/Mobile/WebForm">      StyleReference="Body">         StyleReference="HeaderBody"runat="server">             BreakAfter="False">                                      Please enter either the bride or groom'sname:                               First Name                                      Last Name                            runat="server">Search        StyleReference="Body">                        Figure4. Here is themobile version of the gift registry search page. Like ASP.NET controls thathave the prefix "asp," all mobile Internet controls have the prefix "mobile."The @Register header directive tells the run time where to find the namespaceand assembly that map to the mobile prefix.   You'llalso notice in Figure 4 that I grouped the label and text-box pairs in tags. Besides logical grouping of items, panels allow you to define the stylefor all controls contained within them. You also should use panels whenbuilding a page that can include pagination. Items grouped inside of a panelinform the run time that those visual elements should be grouped together onone page.   Leverage Existing Technologies Afterlaying out the basic form, you need to add some functionality to your newmobile Web Form. Because ARS has an existing Web site with the same searchcapabilities, you'll reuse a COM component written in Visual Basic 6.0 withinyour mobile application. First, add a reference to the COM component byright-clicking on the References folder in the project and selecting the Add Reference... option. Next, select the COM tab, scroll down until you findthe ARSGift Registry Searchcomponent, select it, and click on OK.As with standard ASP.NET references to COM objects, adding the reference willcause VS .NET to create a managed wrapper object to allow interoperabilitybetween the COM object and the mobile application. Because the existingcomponent also returns ADO Recordset objects, a reference to the ADODBlibrary is included.   Once youhave a reference to the object, you can begin coding against it. Use the BrowseByNamemethod of the existing COM GiftRegistrySearchcomponent to retrieve a list of products for which a person has registered (seeFigure 5). Double-click on the mobile form's Search button to be taken to the code-behind for the button. After youhave the results of your query, loop through the results and display them on asecond form, SearchResults. Notice that after you retrieve the results, youswap the current form with the SearchResults form by using the ActiveFormproperty of the System.Web.UI.MobileControls.Form class. Using multipleforms on a single mobile Web Form is generally a good practice when sharingsimilar pieces of data because both forms can leverage the page state. Youshould avoid placing all mobile Web Forms on a single page for your entireapplication, however, because that might cause performance to suffer.   Private Sub btnSearch_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles btnSearch.Click  Dim ARSGiftRegistrySearch As _   ARSGiftRegistry.GiftRegistrySearchClass  Dim ResultsRecordset As ADODB.RecordsetClass  Dim LoopCounter As Integer    ARSGiftRegistrySearch =New _   ARSGiftRegistry.GiftRegistrySearchClass()    'Call the existing COMcomponent to return  'gift registry product info  ResultsRecordset =ARSGiftRegistrySearch.BrowseByName _    (Me.txtFirstName.Text, Me.txtLastName.Text)     ActiveForm =SearchResults    If Not(ResultsRecordset.BOF And ResultsRecordset.EOF) _   Then    ResultsRecordset.MoveFirst()      'Loop through resultsand display them in a list box    For LoopCounter = 0 To ResultsRecordset.RecordCount-1      Dim NewListValue As String      NewListValue =ResultsRecordset("ProductID").Value _      & " - " &ResultsRecordset("Name").Value() & " (" & _      ResultsRecordset("Price").Value() & ")"         lstResults.Items.Add(NewListValue)       ResultsRecordset.MoveNext()    Next  Else    'No results found during search, displaymessage    lblResultMessage.Text = "No resultsfound."   End IfEnd SubFigure5. Leverageexisting components within mobile Web Forms. Developers familiar with ASP andASP.NET technologies should feel right at home with MMIT. Reusing existingcomponents and data sources works the same when you're working with a Web Formor a mobile Web Form.   At thispoint, the mobile gift registry search functionality is ready to be executedand unit-tested. However, you could continue to build in additionalfunctionality by using both existing and new technologies. When building mobileWeb Forms, you can use XML Web Services, COM components, other .NET components,and all other back-end services you are using today in your ASP and ASP.NETapplications.   Maintain the Look and Feel Now thatyou've added some real functionality to the mobile site, it's time to do somelook-and-feel updates to bring your mobile site in line with the style anddesign of your existing Web site. Like Web Forms, mobile Web Forms allow you todefine customized style sheets, so you can reuse style elements throughout yoursite. For your mobile site, you'll add a style sheet and repeat some of the colorsand fonts used in your existing site to keep a consistent look and feel.   First,drag and drop a StyleSheet control onto the designer window for theMobileDefault.aspx page. One point concerning mobile style sheets: They pertainonly to one mobile Web Form, not to the entire Web project. You can link to anexternal style sheet, but I would recommend avoiding this practice becausestandard Cascading Style Sheets (CSS) styles might not be rendered properly forcertain devices. Once the style sheet is on the mobile Web Form, right-click onit and select EditStyles.... A dialogbox such as the one in Figure 6 appears and allows you to set the font,alignment, and colors. Once you change the colors to match the existing ARSstyles, you can go back to MobileDefault.aspx and set each form's StyleReferenceproperty to your new style. If you're not a fan of designer editing, you stillcan edit styles using the HTML view. The underlying HTML for the style youdefine would look like this:        BackColor="#B0C989"Name="Body">  
Figure 6. The StyleSheet mobile Internetcontrol includes a style editor that helps you define font and colorcombinations for mobile styles. Like CSS classes, the editor's defined mobilestyles can be referred to, by name, from multiple controls.   At thispoint, you might be wondering what would happen if the mobile device yourcustomers are using doesn't support a back color of #B0C989. The MobileInternet Controls Runtime is intelligent enough to render content specific tothe device making the request. In most cases, the run time will select the bestmatch for the style and layout of the form.   You can,however, be proactive in your development and tell the run time how to docertain actions based on the capabilities of the device. To illustrate this,add the Acme Retail Store Gift Registry banner to the top of your searchscreen. On devices that support images and have a large enough screen, you candisplay both an image and the text header. For all others, you can display onlya text header.   First,drop a Panel control onto your form and place an Image controland a Label control within the panel. Next, rename the Labelcontrol lblHeader and rename the Image control imgHeader.From within the Solution Explorer window, right-click on the MobileDefault.aspxpage and select ViewCode. Add the codefrom Figure 7 to the page's Page_Load event. By adding conditionaldevice logic to the Page_Load event, you can have greater control overhow your mobile application is displayed to the user.   Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) HandlesMyBase.Load  If (Device.IsColor) And(Device.ScreenCharactersWidth > _   50) Then    ' Display color image and full text banner    Me.imgHeader.ImageUrl = "imgplate_small.jpg"     Me.imgHeader.Visible = True      Me.lblHeader.Text ="Acme Retail Store Gift Registry"   Else    ' Display a shortened, text-only banner    Me.imgHeader.Visible = False      Me.lblHeader.Text ="ARS Gift Registry"   End IfEnd SubFigure7. The easiest wayto do device-specific rendering is to use theSystem.Web.Mobile.MobileCapabilities.Device class to check various deviceproperties, then perform logic based on those properties.   Once you'veadded your formatting and header information, your first release of the mobilegift registry application is code-complete (see Figure 8). You could add manythings to the application before production release, such as error handling andsecurity, but the core functionality of the application is ready to go.  
Figure 8. The new mobile page allows usersof mobile devices, such as Internet-enabled phones, to access the same searchcapabilities the existing Web site offers. Using the MMIT device capabilities,developers can determine dynamically what content to display based on thedevice type.   Expanding the Scope Althoughthe scenario I've used is complete, you should consider several additionalthings as you add mobile functionality to your Web site. As I mentioned, errorhandling and security are obvious items to address before a production release.Fortunately, most ASP.NET developers will be comfortable with the MMITerror-handling and security model - it is the same as ASP.NET, from a codeperspective. You can use validation controls to perform text-entry validations,and administrators can manage security settings using the web.config file andIIS security settings as they would with an ASP.NET application.   Also, becareful using cookies when building a mobile Web application. Some devices donot support cookies, so you need to consider this as you design and implementportions of your application. Without cookies, for example, the ASP.NET enginewould look for forms-based authentication credentials in the query string.Unfortunately, this requires you to write code to persist the ticket in thequery string for devices that have this limitation.   Anotherarea to focus on is the use of redirects within your applications. Most devicescan deal with all forms of redirects, but some devices do not handle relativeredirects properly. I recommend dealing with this issue by coding all redirectsas root-relative redirects. For example, if a file is two directories up in thefolder hierarchy from the page you're redirecting from, you should use aroot-relative path of /content/secured/file.aspx instead of a relative path of../../file.aspx.   As theavailability of mobile-device technology and high-speed wireless networksincreases, consumer demand for mobile-based content and features also willincrease. As a result, more and more businesses will be looking to push theirproducts and information to consumers through reliable, mobile Webapplications. The MMIT offers developers a great opportunity to get ahead ofthe curve. With the MMIT, you can begin to leverage existing technologies andWeb site infrastructures to build robust systems that integrate well with thelook and feel of existing systems.   For more information about this topic, see http://msdn.microsoft.com/vstudio/device/mitdefault.asp.   The files referenced in thisarticle are available for download.   Bill Blockis a consultant at Clarity Consulting Inc. (http://www.claritycon.com),a Chicago-based IT consulting firm and Microsoft Gold Certified Partner. Inaddition to designing and developing scalable Web-based solutions, Bill haswritten articles for several technical publications. E-mail Bill at mailto:[email protected].   Tell us what you think! Please send any comments aboutthis article to [email protected] include the article title and author.      

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like