January 2015

Volume 30 Number 1


Cutting Edge - Mobilize an Existing Web Site

By Dino Esposito | January 2015

Dino EspositoIt’s a common scenario. You arrive at a hotel, airport or some other public space. You connect to the local wireless network and you’re redirected to a login page to enter your credentials. The login page on your mobile device is tiny. All you can do is pinch-and-zoom the screen, take the input form to a reasonable size and then type in your credentials.

This is an annoying experience, yet it happens more often than not. And it’s more than simply an annoyance. The future of Web sites that don’t render well on all devices is bleak. Not offering mobile users a good experience can cut into business profits by driving users away from the site and toward a competitor’s site.

The magic wand too many developers wave to cast Web spells is responsive Web design (RWD). RWD is definitely an option, but, like anything else, it has its pros and cons. The problem with RWD is—for the most part—it requires a new project.

The basic idea of RWD is everything is fluid. Any elements will never be wider than the screen. So by definition, RWD adapts to an infinite number of screen widths. The point of RWD is to create a new Web site inspired by a new idea of content and targeting a fixed and smaller number of break points. Pushing RWD or a library like Twitter Bootstrap onto an existing Web site designed for the desktop is hardly a viable option.

Furthermore, selling the RWD approach is easy. There’s one site, one brand and one code base serving multiple UIs. Implementing RWD is less easy, as it changes the Web development experience. You need a clear and strong vision of how the site will present information. RWD may be easy to sell, but it doesn’t support improvisation. Content adaptation isn’t magic. It comes from attentive and diligent planning.

RWD also changes the consolidated rules of project management and commonly ends up costing more than developing a plain non-responsive site. Gantt charts tracking progress make little sense as any new step requires team members to measure effects across the full spectrum of supported views. So in the end, when having one responsive Web site isn’t an option, what can you do to meet your customers’ expectations and make their life easier?

Add a Connected Mobile Site

When your Web site helps your company stay in business and plays a central role in attracting, maintaining and serving customers, then providing a mobile-specific experience is vital to keep those customers coming back. The simplest approach that doesn’t require a full-site rewrite and won’t break any existing features is to create a separate site specific for your mobile audience. This approach is referred to as building an m-site.

An m-site, much like a native application, is most likely to be consumed by users on the move—people who are standing up, in a hurry, busy or waiting in line. Users willing to connect to a site under these conditions and using a tiny device truly expect some benefit from the site. Therefore, the site must be direct, concise, accurate, and fast to load and respond.

Taking the m-site approach can be inexpensive for two reasons. It’s a brand-new project, but it’s expected to inherit core services from the existing site. More often than not, it inherits large shares of the business logic, which doesn’t mean it duplicates code base. Also, an m-site usually implements the 80/20 rule. It typically supports no more than 20 percent of the features available in the full site. The selection of the 20 percent features, though, isn’t a walk in the park.

When planning an m-site, you should reason with the mindset of a site user on the go. Which pieces of information does a user on the go really expect to consume on your site? Which functions does the user expect to perform? What can you do to smooth and speed up interaction as much as possible? This latter point involves using HTML5 features to the fullest.

On a site you know will be used on mobile devices, it’s arduous to not set the type attribute of an input element to a number or date when numbers or dates are expected. This would greatly simplify typing. By the same token, there may be new use cases introduced on top of similar business logic to make life easier and more enjoyable to mobile users.

Accessing Your M-Site

Because an m-site is a discrete Web site, which URL should visitors use? Is a subdomain like m.yourserver.com the best option? Would a .mobi top-level domain name or /mobile subdirectory under the desktop work better? An m. subdomain is easier to manage than a .mobi domain simply because it’s a subdomain and not a new domain name. A directory is probably more error-prone as it means the mobile site will be hosted under the same application as the desktop. This can make the whole solution more brittle.

The simplest approach is to use an m. subdomain with some redirection logic that automatically sends mobile users to the m.yourserver.com site. This solution is good for users because they can use the direct m. subdomain and the canonical URL. For developers, though, it has the drawback of requiring device detection logic on both the desktop and the mobile site.

Implement Site Redirection

When two sites are in place and work under the same URL, you should process the host name and decide what to do for every request. If the host name belongs to the desktop site and the requesting browser is detected to be a desktop browser, then everything works as expected.

Otherwise, the user should see a landing page, and be informed they’re trying to access a desktop site with a mobile device. Then they’ll have a chance to save their preference for future similar situations. That preference is stored to a cookie and checked next. If the request refers to a URL in the mobile site and the user seems to have a desktop browser, consider showing a different landing page or just let the request go as usual. Finally, if a request is placed from a mobile device to the mobile site, it will be served as expected. You can have your site look into the device capabilities and determine the most appropriate view. Figure 1 presents a diagram of the algorithm.

The Desktop/Mobile View Switcher Algorithm
Figure 1 The Desktop/Mobile View Switcher Algorithm

In ASP.NET, you can implement the routing algorithm as an HTTP module and register it on both the desktop and the mobile site. The module captures the BeginRequest event and uses plain redirection or—if possible—rewriting the URL to change the target page as appropriate, as shown in Figure 2.

Figure 2 Implementation of a Mobile Router HTTP Module

public class MobileRouter : IHttpModule
{
  private const String FullSiteModeCookie = "FullSiteMode";
  public void Dispose()
  {
  }
  public void Init(HttpApplication context)
  {
    context.BeginRequest += OnBeginRequest;
  }
  private static void OnBeginRequest(Object sender, EventArgs e)
  {
    var app = sender as HttpApplication;
    if (app == null)
      throw new ArgumentNullException("sender");
    var isMobileDevice = app.Context.Request.IsMobileDevice();
    // Mobile on desktop site, but FULL-SITE flag on the query string
    if (isMobileDevice && HasFullSiteFlag(app))
    {
      app.Response.AppendCookie(new HttpCookie(FullSiteModeCookie));
      return;
    }
    // Mobile on desktop site, but FULL-SITE cookie
    if (isMobileDevice && HasFullSiteCookie(app))
      return;
    // Mobile on desktop site => landing page
    if (isMobileDevice)
      ToMobileLandingPage(app);
  }
  private static Boolean HasFullSiteFlag(HttpApplication app)
  {
    var fullSiteFlag = app.Context.Request.QueryString["m"];
    if (!String.IsNullOrEmpty(fullSiteFlag))
      return String.Equals(fullSiteFlag, "f");
    return false;
  }
  private static Boolean HasFullSiteCookie(HttpApplication app)
  {
    var cookie = app.Context.Request.Cookies[FullSiteModeCookie];
    return cookie != null;
  }
  private static void ToMobileLandingPage(HttpApplication app)
  {
    var landingPage =
      ConfigurationManager.AppSettings["MobileLandingPage"];
    if (!String.IsNullOrEmpty(landingPage))
      app.Context.Response.Redirect(landingPage);
  }
}

Once installed in the desktop site, this HTTP module captures every request and checks the requesting browser. If the browser is running within a mobile device, the module redirects to the specified landing page. The landing page will be a mobile-optimized page offering a couple of links to the desktop site and the mobile site.

Where do you place the landing page to let mobile users decide what to do? Generally, it doesn’t matter. However, if you put it on the mobile site, you can deploy your mobile site with all the required routing logic without touching the desktop site code base. Changes to the desktop site are limited to configuring the HTTP module in the web.config file.

What Does Mobile Really Mean?

The world of the mobile Web isn’t simply split into two camps of desktop computers and all the rest. Mobile encompasses smartphones and tablets at the very least. An m-site that targets smartphones may not work as effectively for tablets and vice versa. Serving smartphone-optimized pages to tablets goes against the common user’s expectation of getting a desktop-like experience.

Should you have an additional t-site for tablets and a site for legacy devices and perhaps one for wearable devices? All in all, smartphones deserve an ad hoc experience and a dedicated site. Tablets may blissfully render the same content as desktop computers with minor adjustments, such as a different set of CSS files with more padding and larger fonts and some media query support for when the orientation switches to portrait or landscape. These adjustments require changes to the existing desktop site code base. However, it’s not too much of an intrusive change.

The problem remains of how to detect smartphones and what’s a definition of a smartphone that works for your business scenario.

Device Detection Tools

There’s no common definition for a smartphone. A smartphone isn’t a physical attribute like an OS version number. When browsers request a page, they send the user agent string, meaning some server-side code must process the user agent string and determine whether the device is a tablet, a smartphone or something else.

Device detection requires ad hoc tools, which have varying levels of reliability and accuracy. For example, you can use some Modernizr plug-ins or common routines to check user agents for known substrings. This may work reliably enough if all you want to do is separate desktops from everything else.

In this context, detecting anything like an Android OS tells the browser it’s not a desktop. However, detecting Android doesn’t help determine if it’s a smartphone or tablet. The WURFL framework (wurfl.sourceforge.net) is a popular choice with tools that work on-premises, in the cloud and even the Web server level (no code, just configuration) on IIS and other environments.

If you opt for building an m-site to serve ad hoc content to mobile users, you need to be clear which devices fall under the jurisdiction of the m-site (choosing among smartphones, tablets and more) and how you detect devices so users have a single URL to reach the site regardless of the device.

Wrapping Up

Users expect to seamlessly use Web pages on their smartphones and tablets just as they do on their desktops. Processing power or cache size is limited on mobile devices, but that can’t be an excuse to serve pages that require zooming and take seconds to load. Separating desktop from anything else isn’t an insightful choice, either. Some level of device detection is required to provide a good service. When it comes to device detection and form factors, complexity and development costs will grow.

Many companies think RWD is the classic Columbus Egg—an obviously simple and brilliant solution to a thorny problem. Responsive Web sites are more complex and expensive to create than commonly reckoned. More important, an RWD approach works for new or significantly reworked sites. You can’t just easily add RWD to mobilize an existing site that was devised for the desktop. Nevertheless, addressing the needs of your mobile audience is a business necessity. And the sooner you address it, the better.


Dino Esposito is the coauthor of “Microsoft .NET: Architecting Applications for the Enterprise” (Microsoft Press, 2014) and “Programming ASP.NET MVC 5” (Microsoft Press, 2014). A technical evangelist for the Microsoft .NET Framework and Android platforms at JetBrains, Esposito frequently speaks at industry events worldwide and shares his vision of software at software2cents.wordpress.com and on Twitter at twitter.com/despos.

Thanks to the following technical expert for reviewing this article: Jon Arne Saeteras