Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: windowsphone7

Struggling with SSL and Cloud-Backed Mobile Applications

While it is still certainly very common for mobile developers to build applications that stand on their own and do not communicate with the Internet, every day more and more mobile applications are released that are what we used to call “Smart Clients”. These apps sit on your mobile device (and are not browser apps or browser-shell apps). They might store data locally as a cache or back-up mechanism but the bulk of the application’s information comes from the Internet or, if you’re really upping the buzzword quota, the Cloud.

Let’s say you’re building a recipe application for mobile devices. This app is designed to let people access their recipes from any location so long as they have network data access. When you start the app, it queries a cloud-hosted server for your recipes and probably does so using some kind of secure authentication mechanism. Based on how a lot of cloud service providers are working lately, it’s very realistic to assume we’re doing Basic HTTP authentication over SSL.

Now we get into the real benefit of putting the data in the cloud – cross-platform access. I decide to write a Windows Phone 7 app and an iOS app. They both talk to the same recipe database and I should be able to share data among them seamlessly. Why would I do this? Because many people own a non-Apple phone and an iPad. Additionally, families often share service accounts where different family members have different mobile devices. Think Evernote here – they have apps for Mac, Windows, iPhone, iPad, Android – all access your shared, cloud-hosted store of notes.

Here’s the rub, the sticky bits, the source of the last 3 nights of frustration for me: not all services provided in the cloud surface clean, valid SSL certificates.

What does that mean? It means that when you make HTTP requests over SSL from an SDK, you are at the mercy of the limitations of that SDK. For example, if I am writing a desktop or server application in .NET and I know that a cloud database I’m talking to has SSL certs that don’t match their host names, I just write code that looks like this to manually override the cert validation:

ServicePointManager.ServerCertificateValidationCallback =
    ((sender, certificate, chain, sslPolicyErrors) => true);

I can put conditional logic in there to only let certain certificates from certain hosts go through, but you get the idea. Bottom line is I have some back-up plan where I can write code to counteract what most people consider “bad net citizenship” (SSL certs that trigger warnings or worse, fail outright).

What about with iOS? What happens if my iPhone application runs into a bad SSL certificate. Again, I should not have to write this kind of code, but it is possible. When you are picking your cloud service providers, I would add a lot of extra weight to providers whose data comes through on clean SSL certs.

Here’s the juicy part of the iOS code (part of an NSURLConnection delegate class) that manually overrides the SSL cert by responding to an authorization challenge:

- (BOOL)connection:(NSURLConnection *)connection
   canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    NSString *challenge = [protectionSpace challenge];
    if ([challenge isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        return YES;
    }
}

- (void)connection:(NSURLConnection *)connection
    didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSURLCredential *credential = nil;
    NSURLProtectionSpace *protectionSpace;
    SecTrustRef trust;

    protectionSpace = [challenge protectionSpace];
    trust = [protectionSpace serverTrust];
    credential = [NSURLCredential credentialForTrust:trust];

    // say "yes" to everybody... Note, this is BAD
    [[challenge sender] useCredential:credential
          forAuthenticationChallenge:challenge];
}

Why do I say this is bad? Well, the whole point of an SSL certificate is to establish a secure connection between you and the remote server. If someone gets between you and the remote server (called a man-in-the-middle attack) they can do all kinds of nasty crap to your data and, because you’ve written the above code, they might be able to get away with it.

But let’s say that you’re willing to accept that risk and you plow on. So now you decide to write a Windows Phone 7 app that reads from the same cloud database. Your code fails because the SSL cert doesn’t match the host name (again, this is a really common problem when cloud hosts do things to support massive numbers of clients). Well, you just use the ServicePointManager class like you did with the desktop .NET app, right? Ooops. No, actually, you’re utterly screwed. No such class exists in the WP7 SDK. In fact, there is absolutely no way in WP7 to override the validation of SSL certificates. In short, if an SSL cert chain fails and your WP7 app is on the client side of it, your app will not be able to talk to the remote server.

Case in point: I’ve been doing some experimenting with hosting an instance of CouchDB on Cloudant as an add-on to an application hosted in AppHarbor. This is great and they give you a nice SSL URL with a username and password embedded so that you can do awesome JSON goodness with CouchDB’s HTTP API. However. The certs from Cloudant fail validation on both iOS and WP7. About the only place it doesn’t fail validation is when using curl from the command line. If you’re using iOS you’ll be forced to hack around the SSL cert validation. If you’re using WP7, you’ll be totally boned.

So, what are the key points I want you to take away from this blog?

  1. If you’re using WP7, complain and never stop complaining until the folks at Microsoft catch up to all the other mobile operating systems and actually give us the ability to intercept auth challenges in the cert chain. Not having the ability to override SSL validation in a WP7 app is assinine. I realize that MS wants us all to be secure, but for the love of all that is good, even Apple allowed us to have this ability, and they are notoriously paranoid about mobile security.
  2. E-mail, phone, or smoke-signal the provider of your cloud service and complain that their SSL certs aren’t good enough. Many of them will have a facility that will let you use your own certificate purchased from one of the authorities on both Microsoft and Apple’s root authority whitelist, but that won’t fix the host name problem. If you are comparing two providers (e.g. two hosts of CouchDB) and one has certs that fail and the other doesn’t, definitely give more weight to the one with good certs.

Again, this is not a pandemic or a problem that affects the entire universe. This problem only occurs when you’re trying to access resources over SSL from mobile devices and the SSL certificate fails validation. This validation failure happens a lot when hosts do creative things with their certificates and their host names. If this applies to your host, give them a call or an e-mail and see if they have workarounds available. The last thing you want to do is write your own proxy to compensate for bad certs, because that’s just going to make the gap between your proxy and the cloud host as vulnerable to MITM attacks as your mobile device would be without the proxy.

So, go forth and consume cloud resources over SSL – just make sure your mobile SDK can override bad certs or your cloud provider has ways of making the certs look valid.

What I’ve Been Up To Lately

I was originally thinking of framing this post in the form of an apology. For example, “I’m so terribly sorry that I haven’t been posting to this blog lately.” I’m not going to do that, however. While I freely admit that the blog has been barren for the last couple of months, it hasn’t been without reason.

Firstly, I have been wrapping up my work on the Windows Phone 7 for iPhone Developers book. I’m really proud of this book and I really like the way it came out. If I had it to do over again and was able to add a few hours to every day I spent working on it, I would’ve spent more time building parallel samples so that the code downloads for the book included nearly as much iOS code as it did WP7 to allow iOS developers to compare real-world, full-functioning scenarios. Oh well, perhaps I’ll include that kind of depth in a future “Mango” edition of the book (if there is such a thing).

Second, I’ve been in the process of moving. I’m packing up stuff, throwing stuff out, and staging my old house for sale. This is time consuming when you’re still working on copy edits, tech edit reviews, oh and trying to squeeze in a little family time in there here and there.

Thirdly, I’ve started working on a new book. I can’t yet tell you the title, but here is a hint: all of the code is written in Objective-C 🙂

Fourth, I’ve been working on a series of articles for the SilverlightShow.net website, all about WP7 for iPhone and Android developers. Check out that series here.

WP7 for iPhone and Android Programmers – Intro to Xaml and Silverlight

In this 2nd article in my 12-article series, I provide an introduction to the generic instantiation language Xaml and how you can use Xaml to produce the most basic Silverlight UI elements on Windows Phone 7.

Click here to read the article.

Zombie Apocalypse Trainer Now Available

As some of you may know, up until very recently I’ve been working on a book called Windows Phone 7 for iPhone Developers. This book is all about learning how to build Windows Phone 7 applications, even if you’ve never written any code for Windows or for the iPhone before. Despite the iPhone name in the title, the book is just as useful for any new mobile application developer, regardless of background. Comparisons to the iPhone are made just to make some of the concepts in the book easier to grasp for new developers.

Anyway, the last chapter in that book deals with deploying applications to the Windows Phone Marketplace. In order to get screenshots for that chapter and to be able to accurately describe the application submission process, I had to create an application and submit it to the Marketplace.

That application is called Apocalypse Trainer. It’s a simple calorie counter and weight log application, with a twist. Instead of just calling itself a calorie counter, it disguises the act of counting calories with preparing for the zombie apocalypse. Every time you eat 100 calories, a zombie gets close to attacking you. Every time you burn 100 calories, you outrun a zombie. Finally, it keeps track of the number of consecutive days you’ve been under your calorie budget and refers to this as the number of days since the last mauling.

Here’s a screenshot of the application as it looks in the Zune Marketplace:

Apocalypse Trainer

Apocalypse Trainer in the Zune Marketplace

Make no mistake, this is not an application that I intend to make a million dollars from. In fact, I sincerely doubt anyone will actually purchase this application. I deliberately set the application at $2.99 to avoid using up any of my “free app” quota and because I know the application lacks the fit and finish of a commercial application. If, by some random freak chance, people actually start buying and using this application, I’ve engaged the services of an actual designer (I may be a great programmer, but I’m a horrible designer). I figure if 20 people buy the application, I will have enough money to pay him to do the layout and artwork for version 1.5. I’ve seen some preliminary designs and am really happy.

Anyway, I will also be doing a series of blog posts recounting my experiences while writing this application. This is for the benefit of readers of my book (publish date is I believe February or March 2011) and for the readers of this blog who are interested in Windows Phone 7 and the overall experience of deploying an application to the Marketplace.

WP7: Presenting ListBox Items inside a WrapPanel

This morning I was trying to figure out how to display a list of items that ran horizontally across the screen. At first I tried a StackPanel but that didn’t work the way I wanted. After a few minutes of searching I remembered that the WP7 Control Toolkit from Codeplex includes a WrapPanel control. This control does exactly what it says – it lays out the child elements and then wraps them when an element might otherwise be clipped by the edge of the screen or the edge of the parent container.

So then I tried to figure out how I could get this WrapPanel to display items from a data-bound list. This is when I remembered that I wasn’t really thinking in Xaml. I don’t want to bind the child elements of the WrapPanel, what I want to do instead is tell a ListBox that it should use the WrapPanel as a content presenter instead of the default panel that it uses.

The Xaml for this was remarkably simple:

<ListBox x:Name="myList">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel ItemHeight="150" ItemWidth="150"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="103-Person.png" Height="48" Width="48"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextSubtleStyle}"
Width="100" TextAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

When you supply this listbox with some data (in my case,  just Person objects with a Name property), it might look something like the screen below. I numbered them when setting the people’s names so you could see how the WrapPanel is laying items out horizontally and then wrapping them down to the next level.

A WrapPanel-based ListBox

A WrapPanel-based ListBox

Changing your ListBox so that it uses a WrapPanel to present items is a simple trick, but it can come in really handy and save you a lot of trouble if you want this wrapped layout style.

Apple’s GameCenter vs. Windows Phone 7 and Xbox Live

As many of you know, I’m currently writing a book to help iPhone developers (as well as non-iPhone developers) adopt the Windows Phone 7 platform called Windows Phone 7 for iPhone Developers. In the course of writing this book, I’ve discovered a lot about the Windows Phone 7 development platform and SDK that I truly love. It really is an awesome platform on which to develop mobile applications and even mobile games.

It’s mobile gaming that is at the heart of this blog post. After version 4.0 of the iOS SDK was released, Apple’s GameCenter was made available. This is an area in which iPhone users can go to see a list of GC-enabled games, find friends, see the status of their friends, and even take part in multi-player games with those friends. Additionally, GameCenter games sport global leaderboards and an unlockable achievement system. I have a few GameCenter games on my phone and, with the release of iOS 4.2, I even have a few GameCenter games on my iPad. The user’s view is that GameCenter’s feature list is incredibly similar to that of Xbox Live as implemented on WP7. However, the similarities disappear altogether when you examine the developer experience.

GameKit is the portion of the iOS SDK that revolves around gaming. Through this API, developers can access a user’s GameCenter profile. They can read to and write from global leaderboards stored somewhere within Apple. For a developer, this is as simple as configuring a leaderboard from within iTunes Connect and then setting some numeric value on the gamer’s profile. This value is compared globally and the leaderboard is computed automatically. For example, if I wanted a leaderboard for “Monster Kill Count”, I would just set the monster kill count for the current player and the leaderboard takes care of itself thanks to Apple’s infrastructure and the GameKit API.

Further, GameKit provides APIs for establishing multi-player gaming sessions with either nearby players (Bluetooth, ad hoc via the Bonjour protocol) or players scattered across the globe. The GameKit API is so easy to use, there are simple method calls for sending data to individual players or broadcasting to all of them. And if you thought that was plenty, add to this the fact that GameKit gives you the ability to, in just a few lines of code, add an overlay channel for in-game voice chat between all connected players. Now if you’re starting to get impressed, think about the fact that NONE of this requires you to stand up a back-end server to support any of this. All of this can be done for ZERO up-front cost, making this an absolute goldrush ripe for the picking for Independent developers as well as prime target for commercial games that support GameCenter features. Oh, and don’t forget the fact that the GameKit API lets you unlock achievements on a player’s profile and those achievements are defined quickly and easily by a developer through the iTunes connect portal.

So how does Xbox Live on Windows Phone 7 fare? Well, this is where the waters get muddy. Xbox Live games have at their disposal leaderboards, lobbies for finding and grouping players, APIs for multiplayer gaming, and APIs for unlockable achievements. So what’s the problem? The first problem is that right in the Marketplace list of conditions for acceptance into the application marketplace is a rule that says your Silverlight application may NEVER make any API calls to any of the core gamer libraries provided for Xbox Live. This immediately rules out casual games written using Silverlight that have multi-player, social aspects.

That’s OK you might be thinking, you’ll just use XNA to build an Xbox game using DirectX9 / Direct3D. You don’t need Silverlight and you do get a flaming truckload of high-end graphics features by going the XNA route. Here’s the rub: You can’t access the Xbox Live APIs unless you’re an approved Xbox Live partner. This means that you must e-mail Microsoft and ask to be admitted into the elite group of Xbox Live partners. Conditions for entry to this club aren’t simple, either. You must already have published an Xbox game to be considered for Xbox Live partnership. I think there are also company size requirements and possibly even a “commercial revenue” requirement. In short, if you’re an indie developer looking to use Xbox Live features, you’re hosed.

With all that said, I wouldn’t be telling the whole story if I didn’t at least explain a bit about why you’re hosed if you want XBL features in your WP7 game as an Indie developer. Xbox Live isn’t just a suite of APIs, it’s an ecosystem. This ecosystem has a currency: gamerscore. This is a point value that every single Xbox Live gamer has on their gamertag. Every Xbox Live game a gamer plays will earn them both points and unlockable achievements. These are global. This means that every XBL gamer can see which achievements you have unlocked and what your total gamer score is – it’s part of your public profile. This is the currency by which relative wealth in the Xbox Live world is measured. Those with higher game score and rarer achievements are this ecosystem’s elite… the upper class.

If an independent developer were to be given unfettered access to the ability to unlock achievements and add points to a gamer’s score, it is entirely likely (if not simply inevitable) that a well-meaning Indie developer would make a game that was too easy, with too many achievements, that awarded too many points. The simple act of a single gamer playing this game and easily racking up its thousands of points and hundreds of achievements would immediately devalue the currency of the entire ecosystem. The hard work, time, effort, and (hopefully) fun players invested in earning their gamer score and unlocking their achievements would mean little in the face of the onslaught of indie developers able to create unbalanced games that respect neither the relative difficulty in unlocking achievements nor their relative worth ecosystem-wide.

GameCenter, despite having the ability to put together players from across the globe, has no global currency. There is no continent-wide Euro with a relative worth standard like the Xbox Live gamerscore. Every game has private leaderboards. The points required to rise up on those leaderboards are not scaled relative to the time or effort required to ascend the ranks of any other game. It might take me 10,000 points to reach the top of a leaderboard in GameCenter Game “A” and only take me 1,000 points in Game “B” but Game “B” might take me 300 hours whereas Game “A” only took me 20 minutes. This type of scale disparity would ruin the value of Xbox Live gamer score but because each GameCenter game is isolated, it has no affect on global GameCenter economy. The same is true for unlockable achievements within GameCenter. GameCenter’s lack of a single, unified currency or score, gives it the ability to allow any developer unfettered access to points, leaderboards, achievements, and multi-player gaming without ruining the ecosystem.

So, in conclusion, it is my belief that until Microsoft creates a mobile, “lite” Xbox Live in which they give developers access to points, leaderboards, achievements, and mobile-isolated multi-player APIs but without access to the global gamer score value, Indie developers will be out of luck.

If anyone from Microsoft is reading this, this is my formal request for such an isolated, “lite” Xbox Live. I realize that Windows Phone 7 is a v1 product, but at least letting your customers (developers, especially Indies) know that you have plans in the works to give us an equivalent of GameCenter and GameKit would go a long way toward platform adoption by Indie developers for casual, multi-player, social games.

BTW, in case you’re curious… the top selling games on the iTunes app store, after you remove the blockbusters by companies like EA, etc, are… drumroll…. casual, multi-player, social games. Here’s to hoping that Microsoft throws us a bone in the near future, or at least something to chew on while we wait for WP7’s sandboxed Xbox Live, if such a thing will ever exist.

Windows Phone 7 for iPhone Developers

For those of you who have been reading my blog for a long time (back when I was still actively posting on the “.NET Addict’s Blog”) you know that I often work in bursts. There will be months where I have nearly 2 blog posts every day for the entire month, and then I will go dry for the next month.

Some of this is because I tend to post about what I’m working on. If I happen to be working on something that precludes me from posting publicly about said technology, then my blog will often appear to go silent for a long time. Other times its because I’ve decided that my personal life takes precedence over my ability to blog often enough to keep up my readership and to remain at the forefront of tech blogging.

A couple of years ago, the most important thing to me was in making sure that I was blogging regularly, learning constantly, and generally staying as far ahead of everyone else in the field as I possibly could. Today, these are still important to me, but they are not as important to me as family, friends, and generally enjoying life. I spend less and less time in front of a computer at home lately… with the exception of the project that has kept me busy for the last month or so.

This is the reason for this blog post.. I would like to announce my new book project, “Windows Phone 7 for iPhone Developers”.

Windows phone 7 for iPhone Developers

Windows phone 7 for iPhone Developers

This book, while initially marketed at those iPhone developers seeking to adapt their iPhone skills to the world of Silverlight and WP7, is for any developer looking to build WP7 applications. This includes people who have never written a mobile application before as well as those of you looking to build the same application for both iPhone and WP7 platforms and share as much code as possible.

Once I have the link to the Amazon landing page for “Windows Phone 7 for iPhone Developers” I will post that here.

Additionally, on November 6th, I will be presenting on this topic in a session shockingly entitled “Windows Phone 7 for iPhone Developers” at the Westchester / Fairfield Code Camp at the UConn campus. If you’re in Connecticut that weekend, stop by and get a preview of the contents of the book and hopefully have fun learning about the awesome Windows Phone 7 SDK.

This book is one of many reasons why my blog has been silent for a while lately and I hope the effort I’m putting into this book will pay off and give you and other readers a really educational, fun tour through WP7.