Home > Software, Web > Mobile device filter in ASP.net

Mobile device filter in ASP.net


The mobile web is increasing rapidly. Creating different web sites for mobile users is not a solution, rather having the same content, but customized through CSS for different browsers and devices. But this article will not focus on this part, but rather on what is before: recognizing the browser/device of the user so you can choose the right CSS file(s).

For recognizing the devices we will use WURFL, on open source database containing device capabilities. I will also not cover here the mobile device recognition topic.

What I will describe, will be an HTTP filter for pages that will try to recognize the mobile device and store it in the context items for future use. Of course you can add your own custom tasks to it (e.g. redirect to another page if a page is not available for mobile devices or select automatically the right CSS).

The filter is implemented as an HTTP module that is executed before the actual request is processed. Then it matches the User Agent string against the WURFL database for getting the device id. Because some mobile providers are rewriting the User Agent and putting the information into the X-Device-User-Agent HTTP header we will also look into that one as well. (Later edit) And just to be sure that you also recognize Opera Mini (and actually the real device) you can inspect the information in the X-OperaMini-Phone-UA header. As a consequence the filter will use a list of headers.

And now the code:

public class WURFLFilter : IHttpModule
{
    /// 
    /// The HTTP headers inspected for the User Agent string. The headers are inspected in this order.
    /// User-Agent - the standard header containing the user agent string
    /// x-device-user-agent - some mobile providers overwrite the User Agent,
    ///     but they put the real user agent in this header
    /// X-OperaMini-Phone-UA - Opera mini overwrites the standard header, 
    ///     but moves the information in this header
    /// 
    private static String[] UA_HEADERS = new String[] 
                { "HTTP_USER_AGENT", "X-DEVICE-USER-AGENT", "HTTP_X_OPERAMINI_PHONE_UA" };

    private HttpApplication httpApp;
    private deviceFileProcessor wurfl
    {
        get 
        {
            // get the WURFL processor from cache or load it from file
            deviceFileProcessor d = (deviceFileProcessor)httpApp.Context.Cache["wurfl"];
            if (d == null)
            {
                String wurflPath = httpApp.Server.MapPath(ConfigurationSettings.AppSettings["wurfl.path"]);
                d = new deviceFileProcessor(wurflPath);
                httpApp.Context.Cache.Insert("wurfl", d, new CacheDependency(wurflPath));
            }
            return d;
        }
    }

    public void Init(HttpApplication httpApp)
    {
        this.httpApp = httpApp;
        httpApp.PostAcquireRequestState += new EventHandler(OnRequest);
    }

    void OnRequest(object sender, EventArgs a)
    {
        HttpContext context = ((HttpApplication)sender).Context;
        String mobileDeviceId = null;
        Hashtable userAgents = wurfl.getsdUserAgentAndId;

        for (var i = 0; i < UA_HEADERS.Length; i++)
        {
            String ua = context.Request.Headers[UA_HEADERS[i]];
            mobileDeviceId = (String)(String.IsNullOrEmpty(ua) ? null : userAgents[ua]);
            if (mobileDeviceId != null)
                break;
        }
            
        context.Items.Add("mobileDeviceId", mobileDeviceId);
    }

    public void Dispose()
    {
    }

}

Some improvements can be made, like caching the mobileDeviceId into the session (we suppose that you cannot change your device during the session :) ). You probably noticed that I cached the WURFL file processor (the WURFL data file is quite big and it doesn’t make sense to read it every time). The cache dependency is made on the WURFL data file (the path is stored into application settings under the wurfl.path key) so you can update the file without any worries.

About these ads
Categories: Software, Web Tags: , ,
  1. January 23, 2009 at 2:21 pm

    Another way, I think more simple if you want to use “Apache Mobile Filter”. Is an Apache module that resolve the problem of device fragmentation, he use WURFL.

    For more info: http://www.idelfuschini.it/apache-mobile-filter.html

  2. January 24, 2009 at 1:44 pm

    Very nice! I actually had to cope only with IIS, that’s why I choose this solution.
    But your filter is definitely something to keep in mind. I also like the integrated resize image feature. I also had to write something similar in ASP.Net and I took a different approach on calculating the optimum sizes.
    How are the device capabilities sent to the final page?

  3. May 19, 2009 at 3:56 pm

    I have published the new version of Apache Mobile Filter, now the filter is give to you the information of capabilities as apache environment.
    Now you can develope in any language (php,jsp, ruby etc.) and have the information of mobile capability.

    Read more info here: http://www.idelfuschini.it/it/apache-mobile-filter-v2x.html

  4. August 23, 2009 at 8:25 pm

    I have published the last version of “Apache Mobile Filter”, this open source project has in the first 8 months, more than 1100 downloads from sourceforge and I suppose the same from CPAN.

    The Apache Mobile Filter allows you to access WURFL from any programming language, not just Java and php that is traditionally used for dynamic mobile web sites.

    The module detects the mobile device and passes the WURFL capabilities on to the other web application as environment variables. It can also be used to resize images on the fly to adapt to the screen size of the mobile device.
    Try it and let me know your opinion.

    For more info: http://www.idelfuschini.it/it/apache-mobile-filter-v2x.html

    I have made two test pages:

    PC Test Page: http://apachemobilefilter.nogoogle.it/php_test.php

    Mobile Test Page: http://apachemobilefilter.nogoogle.it

  1. October 10, 2008 at 2:17 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 25 other followers

%d bloggers like this: