Mobile Web Development in Visual Studio 2005

Visual Studio 2005 Brings New Choices and New Capabilities

Andy Wigley

October 30, 2009

18 Min Read
ITPro Today logo

CoverStory

LANGUAGES: C#| VB.NET

ASP.NETVERSIONS: 2.0

 

Mobile Web Development in Visual Studio 2005

Visual Studio 2005 Brings New Choices and New Capabilities

 

By Andy Wigley

 

Visual Studio .NET 2003 supports development for mobiledevices with the ASP.NET Mobile Controls server controls that have the uniquecapability of rendering different types of markup according to the type ofmobile browser making the HTTP request. This allows the mobile Web developer tocreate a single ASP.NET Web site that renders successfully on HTML 3.2, HTML4.01, Compact HTML (i-mode), WML 1.1, and XHMTL 1.1 browsers (including WAP2.0). This technology has been used successfully on many mobile Web developmentprojects.

 

If you create a new Web site in Visual Studio 2005, you llfind that on the New Web Site dialog box the ASP.NET Mobile Web site projecttype is no longer offered. So has support for mobile Web development beendropped in the new product?

 

Not at all! There are some differences to the way youbuild mobile Web sites as is clearly evident from the New Web Site dialog box but in fact, the functionality available to mobile Web developers has beenincreased.

 

In Visual Studio 2005, mobile Web developers have twodistinct technology choices for building Web sites for mobile browsers:

  • You can continue to use the ASP.NET MobileControls to develop ASP.NET Web sites that render successfully to differingmobile browsers. You can also take advantage of ASP.NET 2.0 features such asMembership, Profiles, and Personalization though there are someimplementation differences compared to a PC browser Web site. You are probablyan ASP.NET developer building a mobile portal for wide public access; youshould use the ASP.NET Mobile Controls if you don t know which mobile deviceswill access your Web site and you need to support a wide range of differentdevices and markup languages.

  • You can use the regular ASP.NET 2.0 servercontrols if you know your Web site will be accessed only by high-end mobilebrowsers such as Pocket Internet Explorer (Windows Mobile 2003 and later) orOpera Mobile. You can take advantage of advanced formatting, including CSS andall ASP.NET 2.0 features. There are a few ASP.NET 2.0 controls, such as theMultiView and View, that specifically support mobile Web development.

 

Use the regular ASP.NET 2.0 controls if you don t need tosupport lower-end devices. You are probably an enterprise developer where yourIT department has approved a known set of high-end Smartphones or Pocket PCdevices, or similar smart devices for use by company personnel. Figure 1 showshow Microsoft has released technologies for mobile Web development since thelaunch of .NET Framework 1.0.

 


Figure 1: Timeline for ASP.NETMobile Web technologies.

 

Microsoft s Roadmap for Mobile Web Development with ASP.NET

Before we look at how you develop mobile Web sites withVisual Studio 2005, I must draw your attention to the Microsoft Roadmap forMobile Web Development with ASP.NET, which you can find at http://www.asp.net/mobile/mobileroadmap.aspx?tabindex=6.This document, published in spring 2005, explains Microsoft s plans for mobileWeb development and contains important information for existing and futuremobile Web developers. To summarize the important points:

  • ASP.NET 2.0 includes the ASP.NET 1.x MobileControls. You can run existing ASP.NET 1.x Mobile Controls applications on anASP.NET 2.0 Web server without any modification required.

  • The implementation of ASP.NET 1.X MobileControls in ASP.NET 2.0 includes the device adapter classes and deviceconfiguration compatible with Device Update 4. (For full details of whichdevices were supported by each device update, see http://www.asp.net/mobile/testeddevices.aspx?tabindex=6).However, Microsoft will not be releasing any more Device Updates. Instead, theyhave released tools to allow developers to create their own deviceconfiguration.

  • Regular ASP.NET 2.0 controls have a newarchitecture, modeled on that used by the ASP.NET 1.x Mobile Controls. Thisarchitecture separates the developer view of a control (how the developerprograms the control in the ASP.NET page) from the rendering functionality (implementedin device adapter classes) which spits out the markup sent back to therequesting device. In effect, this means that all ASP.NET 2.0 controls could beextended to support different markup languages (be fully mobile-enabled ),although in the release version of ASP.NET 2.0, only XHTML 1.1 device adaptersare shipped for the regular controls.

 

The second bullet point above deserves much moreexplanation. The ASP.NET 1.x Mobile Controls worked their chameleon-like magicby separating the design view of a control from the rendering duties. That way,a developer can build a single ASP.NET mobile page that will work with verydifferent mobile browsers. The device adapter classes are responsible forwriting the correct markup to the output stream that is sent back to therequesting devices. The architecture is completely extensible, so you couldhave as many different device adapter classes for each control class as youwant the extreme position being to have a single device adapter for everydifferent requesting browser. However, to go to that extreme would clearly beunmaintainable; so instead, the standard mobile controls have a device adapterclass for each markup language (HTML, cHTML, WML1.1, and XHTML 1.1) that canfurther customize their output by reading XML configuration files that furtherdescribe the capabilities of each requesting device. Figure 2 shows how thecontrol class and device adapter classes were configured, taking the example ofthe List control.

 


Figure 2: Control and device adapterclasses.

 

A Device Update then, was a release from Microsoft of newXML configuration files describing the newer browsers that had come to market,and on rare occasions a new release of device adapter classes supporting a newmarkup language (Device Update 2 added device adapters to support XHTMLbrowsers).

 

However, as the Roadmap document states, Microsoft willnot be releasing any more Device Updates. The main reason is that, althoughMicrosoft released Device Updates on a regular basis, they still didn t comeout quickly enough for some users. A new device could be available on themarket for some months before a new Device Update was released to provide theconfiguration files for the device. If you request an ASP.NET mobile Web sitefrom a device browser that is not recognized by the configuration system, thenthe runtime simply sends back HTML 3.2. The device browser may or may not beable to render HTML 3.2, but even if the browser can render it, it s likely toprovide sub-optimal presentation, with text misaligned and incorrect linewrapping. Correct device configuration is important for ensuring your mobile Website renders correctly on the requesting device. Many users requested theability to create their own device configuration for devices rather than waitfor Microsoft to release a new update.

 

Instead of releasing Device Updates, Microsoft hasreleased the configuration tools to allow you to develop your own deviceconfiguration files. What you have to do is point your desktop browser to http://www.asp.net/mobile/profile/default.aspx,register for the service, and then follow the instructions. After you registera new device, point your device browser at the URL listed in the instructionsand run through a series of tests. At the end of the process you can downloadthe device configuration file. At present, this file is an ASP.NET 1.x format.config file, but Microsoft will be releasing an update to this tool to createASP.NET 2.0 .browser files instead (more on those later in this article).

 

Building ASP.NET Mobile Controls Apps in Visual Studio 2005

In a follow-up to this article in a future issue of asp.netPRO, I ll explain how to use theASP.NET 2.0 Server Controls to target high-end mobile browsers those that canrender XHTML 1.1 markup, such as Pocket Internet Explorer. However, if you wantto target a broad range of browsers with differing capabilities, you ll need touse the ASP.NET Mobile Controls which I ll explain how to do in this article.

 

To get started, create a new Web site in Visual Studio2005. Choose the Empty Web Site template in the New Web Site dialog box. Onetip here: I m sure you ll be aware that Visual Studio 2005 supports developmentof IIS-hosted Web sites just as we re used to doing in Visual Studio .NET 2003,but that it also supports development of Web sites hosted by the file systemthat you access using the Visual Studio 2005 built-in development Web server.Hosting Web sites in the file system is great for developing many ASP.NETapplications and allows many developers to avoid installing IIS on theirdevelopment machines. Unfortunately for mobile Web developers, you can t reallytake advantage of this feature because the Visual Studio 2005 development Webserver only supports connections from a browser running on the local machineand not remote connections (for security reasons). Inevitably, mobile Webdevelopers test Web sites using browsers running on real devices that areconnected to your LAN via WiFi or are synced to your desktop PC or on emulateddevices running in virtual machines. These devices make remote connections toyour development machine (even the Smartphone and Pocket PC emulators builtinto Visual Studio 2005), so the development server blocks the connections.Consequently, you ll need to ensure you have IIS installed on your developmentmachine, and make sure you select HTTP as the Web site location when you createit (see Figure 3).

 


Figure 3: Make sure you select HTTPas the location for your new mobile Web site.

 

When Visual Studio 2005 has created the Web site,right-click on the project in Solution Explorer and use the Add New Item dialogbox to add a Mobile Web Form and a Mobile Web Configuration File. ExistingASP.NET Mobile Controls developers will immediately feel on familiar ground! Ifyou switch to the Design view on your Mobile Web Form, you ll see the familiarMobile Web Designer from Visual Studio .NET 2003, and in the Toolbox all theMobile Controls are listed in the Mobile Web Forms tray (Figure 4).

 


Figure 4: MobileWeb Designer and Mobile Web Controls in the Toolbox.

 

If you are new to developing applications with the ASP.NETMobile Controls, unfortunately I don t have space to provide a primer here. Thesample code for this article (available for download, see end of article fordetails) will give you a brief introduction, but to learn more, you can workthrough the Quickstart samples at http://samples.gotdotnet.com/mobilequickstart,or purchase my book Building ASP.NETApplications for Mobile Devices, published by Microsoft Press.

 

Design-time Data Binding

Whenever you start to play with a new technology, one ofthe first things you are likely to do is drag a database table onto a Form totry out the RAD data binding. Of course, you are not very likely to want to dothis in a real production application, being a million miles away from buildingscaleable applications that implement good n-tierarchitecture, but it s a useful tool for building quick demo applications, orfor giving flashy demonstrations at conferences.

 

If you try this with the application we ve just started tobuild, you ll run into problems. Make a connection in Server Explorer and draga table onto your Web Form. If you do this with an ASP.NET 2.0 project, you geta GridView control in your Web Form bound to a SqlDataSource instance thatconnects to the database. In our Mobile Web form, you simply get an errordialog with the message Non-mobile controls are permitted only insidetemplates. Please delete this control or move it into a template. When youdismiss the dialog, it does carry on and insert the GridView and SqlDataSource,but there s no point in trying to continue with this, as the GridView can onlyrender XHTML and so will be useless with many mobile browsers.

 

The workaround for this limitation and to still retainthe RAD data binding is to add another New Item to your project, this time aDataSet. (When you do this, another dialog box pops up asking if you want toplace the DataSet in the App_Code folder; reply Yes to this). After VisualStudio adds the DataSet to your project, the DataSet designer starts and asksyou for a connection string and the SQL statement to select the data in which youare interested (the sample code for this article uses the Authors table fromthe SQL Server Pubs sample database). When the wizard completes, you have astrongly typed DataTable with a TableAdapter class to connect with the database.You can drag tables from Server Explorer onto the DataSet Designer toauto-generate TableAdapters and strongly-typed DataTable objects for any tablein the database.

 

To display the data on the form, drag onto your Web Form asuitable control from the Mobile Web Forms tray in the toolbox, such as anObjectList, then add code similar to that shown in Figure 5 to fill an instanceof the DataSet with data from the database and to manually databind the controlto the DataSet.

 

protected void Form1_Load(object sender, EventArgs e)

 {

   if (!this.IsPostBack)

   {

     PubsDataSetTableAdapters.authorsTableAdapter ta =

         newPubsDataSetTableAdapters.authorsTableAdapter();

     PubsDataSet.authorsDataTable dt =

         newPubsDataSet.authorsDataTable();

     ta.Fill(dt);

     ObjectList1.DataSource = dt;

     ObjectList1.LabelField = dt.au_lnameColumn.ColumnName;

     ObjectList1.DataBind();

   }

 }

Figure 5: Fill aninstance of the DataSet with data from the database and manually databind thecontrol to the DataSet.

 

As long as you have configured database security to allowread access to the account running your application (by default, ASPNET on IIS5.1 on Windows XP or Network Authority on IS 6.0 on Windows Server 2003), thiswill display a list of author surnames as links that you can click to displaythe individual fields of the author s record.

 

Using ASP.NET 2.0 Features: Membership and Profiles

The RAD data binding restriction I ve just explained isthe only place where it could be argued that Visual Studio 2005 offers reducedfunctionality over its predecessor. Any inconvenience from that is faroutweighed by the ASP.NET 2.0 features that we can take advantage of, such asMembership and Personalization.

 

The Membership system makes it a breeze to implement FormsAuthentication, something that required a great deal of work under ASP.NET 1.x.The ASP.NET 2.0 Membership system is highly configurable, although spaceconstraints prevent me from going into detail here. However, if you want toenable Membership using the default configuration, simply open the ASP.NETConfiguration tool from the Visual Studio 2005 Web site menu, go to theSecurity tab, click the Select Authentication Type link, then select From theInternet. This is sufficient to cause Visual Studio 2005 to configure a SQLExpress database to store Membership data in the App_Data folder of your Web site.You can then use the ASP.NET Configuration Tool to define user accounts. Thefinal step is to configure access rules to deny access to your site toanonymous (unauthenticated) users and instead redirect them to your login form,called login.aspx by default. To do this, get to the Security tab in theConfiguration tool, click Create Access Rules, and on the Access Rules page selectAnonymous Users and Deny, then click OK.

 

The next step is to build the login.aspx page. If this wasan ASP.NET 2.0 Web site, all you d need to do is to create a Web Form calledlogin.aspx and drag the Login control from the Toolbox onto the Form. Unfortunatelythat won t work for mobile clients because the Login control and the rest ofthe controls in the Login tab of the Toolbox only render XHTML markup, and thusare useless with the diverse mobile clients we need to serve.

 

Instead, we must access the Membership APIs directly.First of all, add a new Mobile Web Form to the project called login.aspx. Thenadd controls to accept the username and password and a button to post back tothe server, as shown in Figure 6.

 

<%@ Page Language="C#" AutoEventWireup="true"

 CodeFile="login.aspx.cs" Inherits="login" %>

<%@ Register TagPrefix="mobile"

 Namespace="System.Web.UI.MobileControls"

 Assembly="System.Web.Mobile" %>

 

         Runat="server">Username:           Runat="server">          Runat="server">Password:           Runat="server">          Runat="server">          OnClick="Command1_Click">Login   Figure 6: Addcontrols to accept the username and password and a button to post back to theserver.   In the Click event handler, call the Membership API toauthenticate the user:  protected void Command1_Click(object sender, EventArgs e) { if(Membership.ValidateUser(UserName.Text, Password.Text))  {    FormsAuthentication.RedirectFromLoginPage(      UserName.Text,false);  }  else {    ErrorMessage.Text ="Login failed. Please try again.";  } }   This simple example shows how easy it is to take advantageof ASP.NET 2.0 subsystems, such as the Membership system. You can also use thePersonalization features of the Profiles feature and you can use Role Management.Unfortunately, you can t use all the new ASP.NET 2.0 features; Web Parts,Master Pages, and Themes are not supported in ASP.NET Mobile Controls projects.  Inside .browser Files: Handling Device Configuration Before leaving the subject of ASP.NET Mobile Controlsprojects, I must return to the subject of Device Updates, as this is a big areaof change for Mobile Web developers since Visual Studio .NET 2003.   I mentioned earlier that Microsoft won t be releasing anymore Device Updates, that the responsibility for writing configuration filesfor new device browsers passes to the developer. This task is eased by usingthe Microsoft online profiling tool, available at http://www.asp.net/mobile/profile/default.aspx.You must register on this site, and after you login you can view a list ofdevices you ve already profiled, or click the Start Profiling a New Device linkto start the configuration process for a new device (see Figure 7).  
Figure 7: The ASP.NET profiling tool.   When you start profiling a new device, you must firstselect which markup language the browser requires: WML, HTML, XHTML, or desktopHTML. Then you are told to access a particular URL using the device browser.The pages you then run through on the device browser consist of a series oftests that are used to establish the precise characteristics of the browser. Atthe end, you can save the configuration for later download, as shown in Figure 7.   The download page provides instructions on how to use theconfiguration file on ASP.NET 1.0 and ASP.NET 1.1 Web servers, but does not atthe time of this writing describe how to configure a device for ASP.NET 2.0. Asstated in the Roadmap document, Microsoft plans to update this profiling toolto generate ASP.NET 2.0 .browser files; but until that happens, you mustmanually convert the .config file to a .browser file.   You can find the supplied .browser files in theWindowsMicrosoft.NET Frameworkv2.0.50727CONFIGBrowsers folder. If youview the contents of one of the .browser files, you ll see that modifying theseis not for the faint hearted! If you need to support a new device, my advice isto wait for the updated Device Profiling tool if you can; but if you can t,study the files carefully to ensure that you make appropriate changes.   Frequently, a new mobile browser is simply a new versionof an existing one, without substantial differences in its capabilitiescompared to its predecessor. If this is the case, you can take advantage of theinheritance capabilities of the .browser configuration system.   For example, the release version of ASP.NET 2.0 does notcontain support for the Openwave SDK V7.0 simulator, but does support V6.0 andearlier. To support the V7.0 browser and inherit settings common to allOpenwave SDK browsers, use a .browser file such as that shown in Figure 8.                        match="OPWV-SDK UP.Browser/(?'majorVersion'[7-9]).*" />                               value="V${majorVersion}.x Mobile Browser" />              value="true" />             value="text/html" />              value="xhtml-mp" />             value="true" />              value="Openwave ${majorVersion}.x Browser" />       Figure 8: Supportthe V7.0 browser and inherit settings common to all Openwave SDK browsers.   In Figure 8, the parentID attribute specifies the parentsettings to inherit. The match attribute of the element specifiesa regular expression used to match the User Agent HTTP header that everybrowser sends with each HTP request.   How do you work out whether ASP.NET 2.0 already supportsyour new device or not, and how do you discover the User Agent string for abrowser? The easiest way is to write a simple WhoAmI and call it from yourdevice (see Figure 9). If it returns a device type of Unknown , your device isnot configured and will receive HTML 3.2 markup from your application withoutany formatting optimization. You should create a .browser file for it to ensureyou get satisfactory results.  <%@ Page Inherits="System.Web.UI.MobileControls.MobilePage"    Language="c#"%> <%@ Register TagPrefix="mobile"    Namespace="System.Web.UI.MobileControls"    Assembly="System.Web.Mobile" %> <%@ Import Namespace="System.Web.Mobile" %>          void Page_Load(objectsender, System.EventArgs e)    {      MobileCapabilitiescap=((MobileCapabilities)Request.Browser);      lblBrowser.Text ="Browser: " + cap.Browser;      lblBrowserid.Text ="Browser ID: " + cap.Id;      lblManu.Text ="Manufacturer: " + cap.MobileDeviceManufacturer;      lblModel.Text ="Model: " + cap.MobileDeviceModel;      lblContent.Text ="Pref Render Type: " +                        cap.PreferredRenderingType;      lblHeight.Text ="PxlsHeight: " + cap.ScreenPixelsHeight;      lblWidth.Text = "PxlsWidth: " +cap.ScreenPixelsWidth;      lblUA.Text = "UAstring: " + Request.Headers["User-Agent"];    }                         ID="lblTitle">Browser Identification            
                                                Figure 9: Write asimple WhoAmI and call it from your device.   One word of warning: unlike ASP.NET 1.x, changes to filesin the WindowsMicrosoft.NET Frameworkv2.0.50727CONFIGBrowsers folder arenot detected dynamically. If you make any changes to files in that folder, youmust recompile the browser definitions using the aspnet_regbrowser.exe utilityin WindowsMicrosoft.NET Frameworkv2.0.50727. This does not apply to.browser files you place in the app_browsers folder of your Web site thoseare detected dynamically at run time, similar to ASP.NET 1.x.  Conclusion In this article, I ve summarized Microsoft s Roadmap forMobile Web Development with ASP.NET, showed how to create ASP.NET MobileControls applications in Visual Studio 2005, as well as how to take advantageof ASP.NET 2.0 features such as Membership, Profiles, and Roles. I ve alsointroduced you to .browser files, the new format for describing browsercapabilities in ASP.NET 2.0.   In a follow-up article, I ll demonstrate how to use theASP.NET 2.0 Server Controls to build Web sites targeting mobile browsers.   The sample code inthis article is available for download.  Andy Wigley is theauthor of Building ASP.NET Applications forMobile Devices and lead author of Microsoft.NET Compact Framework (Core Reference), both from Microsoft Press. Heis an independent consultant who helps customers implement solutions usingASP.NET, the .NET Compact Framework, and .NET Framework 2.0, and is an MVP forthe .NET Compact Framework. Contact him at mailto:[email protected].Andy lives in the beautiful mountains of North Wales, UK and unwinds by walkingand climbing in the hills, or by performing with his rock band, Rainbow Bridge. Look out for us in the pubsof Bangor or Caernarfon!      

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