A few weeks ago, the PercentMobile team came to me to see if I could help write some new libraries for them. Contemporary web and mobile web sites are written on a vast array of different platforms… and obviously the more that PercentMobile supports, the better.
Something I love about programming is that there are so many languages to choose from – why restrict yourself to learning or becoming an expert at one when the same problems are also being solved in other, sometimes better, ways? Each language or platform has strengths and weaknesses of course. But I believe that understanding the differences – and more often, the similarities – makes one a better programmer.
So, generous polyglot that I am, I took the challenge, and plunged in.
(Sign up for the free PercentMobile service to get the libraries described in this post.)
Python & Django
I love Python – its readability, its libraries, and its overall philosophies. In a web server environment, Python can be used in a fairly raw way, behind a generic Web Service Gateway Interface (WSGI), but there are also a number of powerful web application frameworks using the language – most notably Django. PercentMobile want to provide painless Django support, but also to make sure that other Python server environments were not precluded.
percentmobile.py is the single file that provides everything you need.
If you are running code in a WSGI environment, you will have a handle to the WSGI environment. This is normally called environ by convention, and is passed in to your application via your top-level WSGI callable. To make the PercentMobile tracking code work, you need only make one call to the percentmobile.tracker_cookie_insert function. It returns two values: the cookie that you’ll need to set in the HTTP response headers, and the HTML that you should insert into your page.
Say, for example, you had a very simple WSGI app. This responds to requests with an HTTP 200 status code, a single header and some simple HTML:
def my_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/html')]
start_response(status, response_headers)
return ["Hello world"]
To add PercentMobile tracking to this code, you need to firstly import the tracker library of course, and then call the tracker_cookie_insert function:
import percentmobile
cookie, insert = percentmobile.tracker_cookie_insert(environ, '1234555')
(Of course you should replace the final string with your own site ID!)
The cookie return value is actually a dictionary of the different parts needed to construct its string serialization. This will allow you to splice together multiple cookies, or alter the expiry time, path scope and so on. To convert the dictionary to a string, and to get the Set-Cookie header sent back in the request headers, the following code will suffice:
cookie = "%s=%s; expires=%s; path=%s" % (
cookie['name'],
cookie['value'],
cookie['expires'],
cookie['path']
)
response_headers = [('Content-type','text/html'), ('Set-Cookie', cookie)]
Finally, you need to make sure the HTML fragment, in the insert variable, gets placed in the HTML response:
return ["<html><body>Hello world %s</body></html>" % insert]
And that’s a wrap. The whole, PercentMobile-tracked WSGI application looks like this:
def my_app(environ, start_response):
cookie, insert = percentmobile.tracker_cookie_insert(environ, '1234555')
cookie = "%s=%s; expires=%s; path=%s" % (
cookie['name'],
cookie['value'],
cookie['expires'],
cookie['path']
)
status = '200 OK'
response_headers = [('Content-type','text/html'), ('Set-Cookie', cookie)]
start_response(status, response_headers)
return ["<html><body>Hello world %s</body></html>" % insert]
Pretty easy, huh? Well, not as easy as tracking an app if you’re using the amazing Django framework! Contained in the same percentmobile.py file is a class that can be used as Django middleware. It uses the same underlying function as the WSGI implementation, but also takes care of the headers and insertion for you.
Assuming you’ve placed the library file in your Python or Django path, you simply need to add two lines of code in the settings file. Firstly add the percentmobile.PercentMobileDjangoMiddleware class to your list of middleware:
MIDDLEWARE_CLASSES = (
...
'percentmobile.PercentMobileDjangoMiddleware'
)
And secondly, add your PercentMobile site ID to the settings file too:
PERCENTMOBILE_SITE_ID = '1234555'
Um… that’s it. The middleware will intercept the request, figure out the cookie that will need to be sent in the response, create the insertion code, and place it just before </body> in the response. You’re golden. I love Django.
ASP.NET: C# & VB.NET
Switching over to another world altogether, let’s take a quick look at the ASP.NET implementation of the tracking code. One of the great things about .NET is that you can choose between all sorts of different languages to write your applications and pages in. I decided to write the tracking library in C#, but you can use it declaratively in your page code, or programmatically from C#, VB.NET, or any other supported language.
The library is implemented as a User Control – that is, as a .ascx file. You need to download and add PercentMobile.ascx to your web application project.
To embed the tracking logic into a page (or probably preferably, a master page), you simply register the user control as residing in that file:
<%@ Register TagPrefix="pm" TagName="Tracker" Src="~/PercentMobile.ascx" %>
And then embed the control straight into the .aspx file contents, wherever you want it to be:
<pm:Tracker runat="server" SiteId="1234555" />
So a simple, tracked .aspx file might look something like this:
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register TagPrefix="pm" TagName="Tracker" Src="~/PercentMobile.ascx" %>
<!DOCTYPE html>
<html>
<head><title>Hello World</title></head>
<body>
<form id="form1" runat="server">
<div>Hello World</div>
<pm:Tracker runat="server" SiteId="1234555" />
</form>
</body>
</html>
To be honest, this is so simple that I would expect most people to use the control declaratively. But if, for some reason, the control needs to be inserted programmatically, that’s pretty easy too. You need to use the Reference directive, instead of Register, at the top of the file, but otherwise it’s not much harder. Here, we’re using VB.NET to programmatically achieve exactly the same result as above:
<%@ Page Language="VB" AutoEventWireup="true" %><%@ Reference Control="~/PercentMobile.ascx" %>
<script runat="server">
Private tracker As PercentMobile.Tracker
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
tracker = CType(LoadControl("~/PercentMobile.ascx"), PercentMobile.Tracker)
tracker.siteId = "1234555"
form1.Controls.Add(tracker)
End Sub
</script>
<!DOCTYPE html>
<html>
<head><title>Hello World</title></head>
<body>
<form id="form1" runat="server">
<div>Hello World</div>
</form>
</body>
</html>
(It should be fairly straightforward to see how to do this in other .NET languages – PercentMobile includes some examples in their install instructions.)
Java
Onwards. Let’s take a look at the tracking code for Java. There are numerous ways in which Java can be used for web or application server environments. To keep things simple, I decided that supporting JSP was more or less the most familiar and reusable approach.
JSP doesn’t enjoy the rich page event model that I was able to use in ASP.NET to intercept headers, write cookies, and insert HTML, all with one include. <jsp:include> is OK for adding the HTML snippets, but wouldn’t let me access the HTTP headers. <jsp:forward> does, but would only work if you weren’t planning to emit any HTML of your own after the tracking code – something of a radical assumption.
So I settled for an approach where an include directive creates an instance of an inner PercentMobile class defined within the JSP class. To cut a long story short, this means you merely add a reference to the library file at the top of the JSP file:
<%@ include file="percentmobile.jsp" %>
And then call the track method on that instance, somewhere within the page:
<%percentMobile.track("1234555");%>
The included JSP file takes care of instantiating the percentMobile object and giving it references to the request and response stream. This means it can read and write cookies, and later emit HTML. Your tracked Hello World in Java then? It’s as simple as this:
<%@ include file="percentmobile.jsp" %>
<html>
<body>
Hello World
<%percentMobile.track("1234555");%>
</body>
</html>
node.js
OK, OK. Python, ASP.NET, Java. No big deal, right? That’s all so 2003 or so, right?
Well, there’s an alternative future for web server technologies. It’s one that’s blazingly fast, lightweight, event-driven, and… where you write your server logic in Javascript.
node.js is one of the most exciting things I’ve seen for a long time, and I know I’m not alone. Fresh, fashionable, and somewhat unproven, admittedly, it’s had a lot of gushing coverage. But since it turns the web server model (almost literally) inside out, I do believe there’s something important going on.
Would it be possible to write a web app with node.js and still have it tracked by PercentMobile? My challenge.
I decided to rely on Connect, a middleware framework for node.js, which, if you are writing web applications, provides a whole host of other helpful web logic. Using Connect to create a simple node.js app is extremely easy:
var Connect = require('connect');
Connect.createServer(
function (req, res, next) {
res.simpleBody(200,
"<html><body>Hello World" +
"</body></html>",
{
"Content-Type": "text/html"
}
);
}
).listen(88);
To add PercentMobile tracking to this application firstly requires you to pull in the PercentMobile module:
var PercentMobile = require('./percentmobile');
(Where the percentmobile.js file has been placed in your node.js environment or in the common modules location.)
The module needs to be initialized as a piece of Connect middleware in the createServer function:
PercentMobile.init('1234555')
There are then two module functions, cookie and html, which both take a reference to the response object, and which return the cookie string and HTML to insert, respectively. These can be used in Connect’s simpleBody function, for example, meaning that our tracked application is as simple as this:
var Connect = require('connect');
var PercentMobile = require('./percentmobile');
Connect.createServer(
PercentMobile.init('1234555'),
function (req, res, next) {
res.simpleBody(200,
"<html><body>Hello World" +
PercentMobile.html(res) +
"</body></html>",
{
"Content-Type": "text/html",
"Set-Cookie": PercentMobile.cookie(res)
}
);
}
).listen(88);
That’s a wrap
So that’s it. A whistle-stop tour of the new languages and frameworks supported by PercentMobile. I’d love to hear your feedback on how easy (or hard!) these new APIs are to use.
And, oh… who will be the first to build a mobile web app on node.js?
A curious affliction of the mobile blogosphere is its propensity for annual predictions about what will happen next in our industry. It’s a badly-kept secret that this frustrates me. Mostly because:
- A year really isn’t a very long time, whatever the cliché tells you… very little surprising happens in 12 months an industry dominated mostly by large companies and continuous market dynamics.
- It doesn’t take a lot of research into any topic to be able to make a handful of sensible predictions about it. (Flat rate tariffs more common? Really? I should think Antarctic will thaw quicker than last year too, and there will be progress in HIV research.)
- They’re rarely actionable. I’m unlikely to buy shares on such vague tips, and I can’t wager against their accuracy at my local bookmakers. Do these lists exist to bolster the reader’s wealth or knowledge? Or perhaps demonstrate how perceptive the writers think they are?
- Wouldn’t it be better to spend the same effort actually helping to make the future come true in the first place?
But this week saw the publication of a collection of 40 or so pundits’ predictions mobile trends for the coming decade. Should I dislike this 400 times more? Well, fortunately no! Ten years gives more room for the predictions to breathe, and the collective nature of the project should mean broader trends can be spotted.
The document is curated by Rudy De Waele, for whom I have lot of respect. He’s got the enthusiasm and boundless energy that fits well with the promise of mobile. It must have taken a fair bit of effort to pull this project together: a set of slides containing the predictions from a large number of contributors. The document has already been very successful and well circulated. And there are some very clever people involved.
In choosing the contributors, Rudy describes them as his personal ‘mobile heroes’. Fair enough – but how has that affected the overall roundedness of the project? This, to me, is potentially a worry.
For example, it might have been interesting to have heard from at least one handset manufacturer. This will be a decade of bitter rivalry in that market between the old telecoms guard and already-successful new entrants. Exciting times: and I would love to know what the contenders foresee? And only 3 network operators? However conservative their ambitions, the networks’ plans and predictions are quite likely to shape mobile’s decade somehow.
Facebook is a good scalp – although not as revealing as I’d hoped – and so are the financier contributions. Most of the remainder of the contributions are from small startups, bloggers, authors, entrepreneurs, ‘strategic thinkers’ and ‘keynote speakers’.
Now, I have nothing against such individuals (since I know many of them, they’re very smart, and that’s how I’d probably describe myself too!). But having so many casts a slight pallor over the project: the patina of the developed world’s well-trodden mobile conference circuit. Punditry that’s been trotted out for years: affluent, Western, urban- and professional-centric reflections of how we’d like the industry to fulfill our own personal use-cases.
This is a shame. I wanted this document to surprise me more. The entire world – economically, politically, climatically – will change a lot in ten years. I would expect the mobile medium will flex to adapt to those seminal changes far more interestingly than it does to some tactical contemporary challenges.
In the same vein, a missed opportunity may have been to look further abroad. True, there are valid mentions of mobile’s cultural impact in Africa, but try keyword-searching the document for ‘China’, ‘India’, ‘Brazil’, ‘Russia’ (or even ‘Japan’!) and you’ll be out of luck. Who thinks nothing of interest will happen in those places in the next decade? (Now that would be a surprise).
This all made the predictions, a little, erm, predictable. Yes, yes, I think we all know battery technology will improve, but who was brave enough to make predictions like this?:
- most mobile web sites in 2020 will be in Chinese
- at least one major European operator will have been bought by an Indian conglomerate
- the Rio De Janeiro Olympics’ web site will have more mobile visitors than non-mobile
- Google’s home page will default to being mobile in all countries except the US
- roaming agreements will be used as collateral in carbon trading markets as the mobile-wielding populations of low-lying countries are resettled
Crazy? Sure. But these are just off the bat. I think the aims of such a project should be to inspire, question and provoke. Don’t give me some short-term platitudes about app stores and widgets. At least not when history is on the move like it will be in this decade.
OK, so perhaps I’m protesting too much. Despite these flaws, there are some real gems to be found in this document. “Digital syllogomania” is a brilliant piece of insight. A few touch on the very likely “always-on backlash”, and the promise of mobile-device-as-sensor is tantalizing. I also applaud those predictions that wonder whether mobile technology can change basic human behavior. I’m doubtful, but it’s a good question. As Tom Hume asks: “What happens to conversation when it’s all recorded, or any fact is a 5-second voice-search away from being checked?”
Anyway, it’s a few days old now, but do go read the document here. And more importantly, make up some of your own. Even more importantly, go and try make them happen. “It’s good to talk”, but the mobile world in the next decade probably belongs to those who make. And those who make the predictions come true.
Just a quick post to confirm that the WordPress Mobile Pack plugin is back online at wordpress.org.
Most WordPress plugins, if ‘GPL-compatible’, are hosted on wordpress.org – it provides an easy way for people to view and upgrade them. The increasingly popular Mobile Pack is no exception, and we’ve been happily listed there for over 6 months.
But what do you do when it suddenly disappears? About 3 days ago, that’s exactly what happened. I’m the administrator of the plugin and could see it when I logged in. But suddenly none of my collaborators – nor the general public! – could see or download the plugin.
Our sole channel for software distribution had mysteriously dropped into a black hole – without a word of notification from WordPress themselves.
- Assuming it could only therefore be a bug with the wordpress.org web site, I filed a number of support tickets. No response.
- Assuming it could only therefore be a permissions or licence issue, I raised a number of forum threads on the site (as, kindly, did Dennis Bournique, over at WAP Review). No response.
- Assuming I was somehow falling between the cracks, I even emailed Matt Mullenweg. Less surprisingly, no response. UPDATE: I received an apology shortly after this post.
Hmm. All rather unsatisfactory.
Well, this morning, a breakthrough. My WPMP partner in crime, Andrea Trasatti thought of joining the WordPress IRC channel. (Obviously he’s a bit more old school than me). But finally found someone who would be prepared to answer the puzzle.
At this point, I need to point out there there are (true!) other mobile plugins out there. One particularly popular one has been Andy Moore‘s. He hadn’t hosted his on wordpress.org due, I guess, to his choice of license, and his – disclosed – use of automatic ads in the resulting pages, which WordPress does not permit.
For whatever reason, Andy recently closed down his plugin’s page, and had kindly redirected it to ours. This probably accounts for our nice increase in traffic in mid-November. Thanks Andy!
However, one of Andy’s previous plugin downloaders apparently complained about an error message they had received. The WordPress administrators investigated by visiting Andy’s site, and of course got redirected to our Mobile Pack page. Thinking our plugin was at fault, they then disabled our plugin for violating the no-ads rule.
Oh, and no-one thought to drop me an email to tell me.
But Andrea’s investigations and protestations prompted us to get re-approved, and we’re back!
(In the process of investigating this, it also turns out that when WordPress says ‘GPL-compatible’ and points you to a list of licenses, that doesn’t mean much at all. You also have to work out that they actually mean ‘GPL2-compatible’, and not ‘GPL3-compatible’, as our more permissive Apache license is. So I guess we’ll have to change our license too – which is a shame.)
I don’t think WordPress covered themselves with glory here. In the interests of constructive criticism, I would suggest the company should:
- Inform a plugin owner whenever there is a complaint raised against it. I would have been able to point out the complaint was aimed at a different piece of software.
- Inform a plugin owner when – or better, before – disabling a plugin from the listing. I could have had a grace period to have investigated any issues, rather than hear it first as complaints from users.
- Respond to ‘site bug’ tickets raised on the site.
- Make the licensing requirements for plugins more clear. The phrase ‘GPL-compatible’ here, (and its link), is certainly not precise enough.
- Remember that plugin authors work hard to support your business of running the most popular blog platform in the world. Those individuals’ reputations, to a fair extent, rest on your responsible syndication of that code, and they get the grief when you pull the plug.
Anyway, thanks guys (and Mark in particular) for putting it back. And special thanks to Andrea, who now overtakes me in the chocolate-for-favours race.
Now… back to the roadmap of Mobile Pack coolness. Stay tuned.

























