ControlFreak
LANGUAGES:VB.NET | C#
ASP.NETVERSIONS: 2.x | 3.5
Create iPhone Applications
Using ASP.NET AJAX
By Steve C. Orr
Thankfully, most existing Web applications will workreasonably well on the iPhone with no modification necessary. However, if youwant to create a first class iPhone application, you should study the iPhonedevelopment tips detailed here.
What Is an iPhone Application?
When Apple?s iPhone was released to the public, Steve Jobsannounced that its development platform would be ?Web 2.0.? The iPhone?sintegrated Safari Web browser is clearly the most sophisticated Web browserever built into a handheld device. This strength is multiplied by the iPhone?salways connected design (thanks to its Wi-Fi capabilities and AT&T?subiquitous EDGE network). When all this is added up, the sum equals powerfulclient-side Web application support (see Figure 1).
Figure 1: The iPhone displays nearlyall existing Web sites without issue, but there are some details you may wantto keep in mind for creating optimal iPhone interfaces.
In other words, iPhone application development techniquesparallel modern Web application development techniques. The foundations areHTML, AJAX, and a healthy dose ofJavaScript to utilize client-side capabilities and minimize the impact ofserver communication.
Unfortunately, the iPhone does not currently supportplug-ins, such as Flash, Silverlight, Java, or ActiveX controls. It can,however, display PDFs. The integrated Safari Web browser has surprisingly richJavaScript support ? virtually everything you?d expect from a modern desktopbrowser, but with a few logical exceptions. Because finger dragging is reservedfor users to scroll their way around the Safari viewport, client-side dragevents are not supported. Hover and mouse-over events are also not supported,as there is no mouse. For the same reason, there are no tooltips. Cookiesupport and intelligent caching capabilities are indeed present, but keep inmind that the iPhone has a limited amount of space for such things, so youshould try to be conservative.
Does Size Really Matter?
The iPhone?s screen can rotate, stretch, and scaleintuitively to make it feel enormous at times ? even though physically theiPhone is diminutive enough to slide into any pocket.
When a user double taps the iPhone?s screen, Safariautomatically zooms into and enlarges the HTML block in which the user clicked.Users don?t generally see or understand such HTML blocks (like divs, tables,images, etc.), but you should understand this significance so your iPhone userscan more easily focus on your application?s most important content. As is thetrend these days, tables should generally be avoided in favor of divs, spans,and CSS when possible. This helps the iPhone render and wrap page sections inuseful ways.
Page elements such as text boxes and submit buttons tendto display a bit undersized on the iPhone, so you may choose to enlarge themfor iPhone users. Also keep in mind that handheld devices will probably neverbe optimal for extensive textual data entry, so try to lean away from textboxinput, when possible, in favor of list controls, checkboxes, and other simpleinput elements.
To enable a Web application to display optimally for bothPC users and iPhone users, you might want to detect iPhone users and takeaction to display some page elements differently for them. To detect iPhoneusers you simply need to look for the word ?iPhone? in the browser?s user agentstring, as shown below:
If Request.UserAgent.ToLower.Contains("iphone;") Then'VB
if (Request.UserAgent.ToLower.Contains("iphone;")) 'C#
if (navigator.userAgent.match(/iPhone/i) 'JavaScript
Now that the revamped iPod Touch has been released (whichhas virtually identical Web browsing capabilities to the iPhone) you might alsowant to look for the word ?iPod? in the user agent string to add support for it,too.
It can sometimes be helpful to tell the iPhone whatresolution you feel would be best for displaying your application?s content. Thiscan be done by adding a ?viewport? meta tag into the page?s header section, asshown in this example that suggests a width of 728 pixels:
<meta name="viewport" content="width=728"/>
You can add other suggestions for the iPhone as well,either by creating multiple viewport meta tags or by combining the parameterswith semicolons:
<meta name="viewport"content="width=320;user-scalable=no"/>
<meta name="viewport"content="initial-scale=1" />
Tinkering with these meta tags can be a useful way to getcontent to display at desired sizes on the iPhone.
Does ASP.NET AJAXWork on the iPhone?
The short answer to this question is: Yes! Unfortunately,there also is a long answer involving which firmware version your iPhone usershave installed. Users can update their iPhone?s firmware by plugging theiriPhone into a Mac or 32-bit version of Windows with iTunes installed. iTunesthen guides them through the simple upgrade process.
If your users have never upgraded their firmware, thenthey are using version 1.0 of the iPhone firmware and ASP.NET AJAX will workperfectly. The next two minor firmware version updates released (versions 1.01and 1.02) accidentally broke compatibility with ASP.NET AJAX ? although thereis a workaround. When version 1.1 of the firmware was released, compatibilitywas gratefully restored. The iPod Touch (which benefited from a later releasedate) has always been compatible with ASP.NET AJAX. So, in summary, if yourusers have never upgraded their firmware, or they have the latest version ofthe firmware installed, ASP.NET AJAX will work perfectly with no workaroundsnecessary.
Microsoft and Apple have recently improved theircommunication to ensure similar incompatibilities do not occur with futureupdates. The iPhone?s firmware version number can be extracted from the browser?suser agent string, an example of which is shown here:
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en)
AppleWebKit/420+ (KHTML, like Gecko) Version/3.0
Mobile/1A543a Safari/419.3
In the above example, ?1A543a? signifies the original 1.0version of the iPhone firmware. Version 1.01 displays ?1C25? instead, andversion 1.02 is represented by ?1C28?. Version 1.1 (which restored standardASP.NET AJAX support) is signified by ?3A109a?. This is summarized in the tableshown in Figure 2.
| iPhone Firmware Version | Time Frame | ASP.NET AJAX Supported? | Version Details | User Agent Version String |
| 1.0 | iPhone Launch/Early 2007 | Yes | The original iPhone firmware version. ASP.NET AJAX worked perfectly. | 1A543a |
| 1.01 | Summer 2007 | No | Contained Safari security updates. Also accidentally broke compatibility with ASP.NET AJAX. A workaround is possible. | 1C25 |
| 1.02 | Summer 2007 | No | Contained more Safari security updates. Standard ASP.NET AJAX support still broken. | 1C28 |
| 1.1 | Late September 2007 | Yes | Contained significant new iPhone features, security updates, and finally restored standard support for ASP.NET AJAX. | 3A109a |
Figure 2: ASP.NET AJAXsupport history for the iPhone.
I?ve written a couple server-side functions that use theabove information to extract the iPhone firmware version and determine if it?sa version that supports standard ASP.NET AJAX or not. Those functions arelisted in Figure 3.
Public Shared Function iPhoneFirmwareVersion() As String
Dim useragent As String =Request.UserAgent.ToLower
Dim i As Integer = useragent.IndexOf("version/3.0") + 12
Dim i2 As Integer =useragent.IndexOf(" ", i)
Dim v As String =useragent.Substring(i, i2 - i)
Returnv.Replace("mobile/", "").Trim()
End Function
Public Shared Function iPhoneSupportsAJAX() As Boolean
Dim v As String =iPhoneFirmwareVersion()
If v.Length < 1 ThenReturn False
Return (v ="1a543a" OrElse v.StartsWith("1") = False)
End Function
Figure 3A: TheseVB.NET functions determine the user?s iPhone firmware version and whether itsupports standard ASP.NET AJAX.
public static string iPhoneFirmwareVersion()
{
string useragent =Request.UserAgent.ToLower();
int i =useragent.IndexOf("version/3.0 ") + 12;
int i2 =useragent.IndexOf(" ", i);
string v =useragent.Substring(i, i2 - i);
return v.Replace("mobile/","").Trim();
}
public static bool iPhoneSupportsAJAX()
{
string v =iPhoneFirmwareVersion();
if (v.Length < 1)return false;
return (v =="1a543a" || v.StartsWith("1") == false);
}
Figure 3B: Theseare the C# equivalent of the VB.NET functions shown in Figure 3A.
You could use the above functions to detect users withproblematic firmware versions and instruct them to upgrade their firmware touse your application. Or you could use these functions to display an alternateuser interface to users with a problematic firmware version. Or you couldchoose to put the burden upon yourself as the developer by implementing aworkaround that will support all iPhone users, regardless of their firmwareversion.
The Workaround
As mentioned previously, supporting all iPhone firmwareversions (including the two problematic ones) requires a workaround. Thisworkaround requires changing one line in Microsoft?s client-side AJAXJavaScript library.
First, make a copy of MicrosoftAjax.js (found by defaultin the Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAXExtensions\v1.0.x\MicrosoftAjaxLibrary\System.Web.Extensions\v1.0.x\ folder). Thenlocate this problematic line of JavaScript:
Sys.Serialization.JavaScriptSerializer._stringRegEx=new
RegExp('["\b\f\n\r\t\\\\\x00-F]',"i");
And change the line to this:
Sys.Serialization.JavaScriptSerializer._stringRegEx=new
RegExp('["\\b\\f\\n\\r\\t\\\\\\x00-\\x1F]', 'i');
Save your modified version of MicrosoftAjax.js to anappropriate public folder within your Web application. Then, for every page inyour application that has a ScriptManager control, add the file?s path to theScriptManager control?s Scripts collection property, as shown here:
<asp:ScriptManager ID="ScriptManager1"runat="server" >
<Scripts>
<asp:ScriptReferencePath="../js/MicrosoftAjax.js" />
</Scripts>
</asp:ScriptManager>
You might also choose to take the above steps with thedebug version of MicrosoftAjax.js, named MicrosoftAjax.debug.js. The onlydifference between the standard and debug files is white space. The debugversion is more readable and therefore more useful for during development,while the standard version is more compact and thus more appropriate forrelease.
Should I Use ASP.NET AJAXfor iPhone Development?
Just because you can use ASP.NET AJAX for iPhonedevelopment doesn?t necessarily mean you should in all cases. Like anytechnology decision, there are tradeoffs to consider.
ASP.NET AJAX support means you can use ASP.NET 3.5?sUpdatePanel, Timer, and UpdateProgress controls (for example) to easilyimplement cutting edge AJAXcapabilities into your iPhone compatible Web applications. They ?just work,?with no special iPhone code needed. You can go a step further and use theopen-source controls from the ASP.NET AJAX Control Toolkit, as well. Most ofthem work fine on the iPhone, with the only exceptions being a few that rely onthe unsupported events listed earlier in this article.
However, you should keep in mind that utilizing ASP.NETAJAX requires its moderately sized client-side JavaScript library to bedelivered to the iPhone. This isn?t much of an issue for users with strong Internetconnections. However, adding the additional libraries of the AJAX ControlToolkit can cause a noticeable delay upon page load. Even so, this can beworthwhile, considering the rich functionality provided. If you go this route,it?s generally best to keep the user on that page so they needn?t suffer thatpage load delay repeatedly.
Because users will sometimes have weak Internet connectionsfrom remote locations, it can be good to move as much logic as possible to theclient side to minimize the amount of client-server communication. In fact,many simple iPhone applications consist purely of JavaScript and HTML, withlittle or no server-side interaction at all.
Conclusion
Apple has indeed hit another homerun with the iPhone. It?sselling like hotcakes, and is destined to take over the world of handhelds muchas the iPod did. As a Web developer, if you?ve managed to ignore the iPhone sofar, you should realize that your time for such luxuries is running out. TheiPhone is evidence that mobile applications truly are destined to play a vitalpart in all our futures. Luckily, the iPhone is also evidence that the ?mobilerevolution? predicted for so many years may instead end up being more of asofter and gentler evolutionary change. We won?t have to use special toolkitsor mobile frameworks to create alternate front ends for our applications. Instead,we can continue to create applications very much like we always have, and they?llsimply work.
While the Web 2.0 development platform enabled by theiPhone unleashes a vast array of development possibilities, it also imposessome significant limitations. For example, we currently have no direct accessto the data or files contained within the iPhone. Wouldn?t it be great to writean application that interacts directly with the iPhone?s music library, photocollection, or contact list? Unfortunately, this currently isn?t possible. However,there are rumors that Steve Jobs will soon open up the iPhone platform toenable more integrated kinds of applications. But until then, we still haveplenty of creative and exciting development possibilities at our fingertips. It?stime to dig in and start exploring the future of handheld development!
Useful iPhone References
Apple Developer Connection: http://developer.apple.com/iphone/designingcontent.html
iPhone Simulator: http://www.testiphone.com/
Google?s iPhone Development Forum: http://groups.google.com/group/iphonewebdev
iPhone compatible Games & Apps: http://SteveOrr.net/games/
Steve C. Orr is anASP Insider, MCSD, Certified ScrumMaster, Microsoft MVP in ASP.NET, and authorof the book Beginning ASP.NET 2.0 AJAXby Wrox. He?s been developing software solutions for leading companies in the Seattlearea for more than a decade. When he?s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:Steve@Orr.net.