I’ve been thinking about supporting mobile devices on this website for a while now. It’s not that the website doesn’t work on mobile devices, but the whole experience could be more optimized for phones and PDA’s. The weight of the HTML and CSS had to be reduced and I thought a simpler interface would improve the readability.

The plan was to auto-discover when a mobile client accessed the site and then apply the mobile theme at runtime. To determine if the client was a mobile device I used the Request.Browser.IsMobileDevice property, but then I realized that it isn’t bullet proof. New devices and manufacturers are popping up all the time and the .NET Framework is relatively old in that regard.

So, instead I used a combination of the Request.Browser.IsMobileDevice property and a custom regular expression lookup.

The code

First of all, I used a very simple regular expression and added it to the appSettings in the web.config.

<add key="MobileDevices" value="(nokia|sonyericsson|blackberry|samsung|sec-|windows ce|motorola|mot-|up.b)" />

Then I wrote a property called IsMobile which tries the Request.Browser.IsMobileDevice property first, and then tries the regular expression afterwards.

private static readonly Regex MOBILE_REGEX = new Regex(ConfigurationManager.AppSettings.Get("MobileDevices"), RegexOptions.IgnoreCase | RegexOptions.Compiled);

 

public static bool IsMobile

{

  get

  {

    HttpContext context = HttpContext.Current;

    if (context != null)

    {

      HttpRequest request = context.Request;

      if (request.Browser.IsMobileDevice)

        return true;

 

      if (!string.IsNullOrEmpty(request.UserAgent) && MOBILE_REGEX.IsMatch(request.UserAgent))

        return true;

    }

 

    return false;

  }

}

The reason I didn’t use some of the web.config features such as browserCaps is because then the web.config would be filled with browser related markup. There is nothing wrong with that, but I like to keep the web.config as clean as possible.

With this method it is now easy to apply a special mobile theme for mobile clients only. You can test it out by visiting this website using your phone or PDA or force the theme.

The upcoming geek dinner in Copenhagen, November 14th at 7pm is getting closer. So far about 12 people have decided to participate and you can still sign up if you haven’t already. In about a week from now, I’ll find and make reservations at a restaurant in Copenhagen. The choice of restaurant is based on the number of participant, but if you have any preferences please let me know.

Some of the better known people attending are

Niels Hartvig (Umbraco)
Jeppe Rørbæk (Microsoft Evangelist)
Daniel Frost (ActiveDeveloper)

So if you’re interested in joining the dinner, write me a comment or send a mail.