Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: mobile (page 1 of 2)

Slide Deck from my NYC Code Camp Presentation

For those of you who attended my Code Camp NYC presentation on casual and indie gaming with Windows Phone 7 and “the cloud”, I have finally managed to find and upload the PPT slide deck. Ironically enough, the reason it took me so long is because I had trouble with the cloud drive on which the deck was stored 😉

I will be posting code samples that go along with this presentation in one form or another soon… so stay tuned!

Indie and Casual Game Development with Windows Phone 7

WinRT Distilled

Since Microsoft showed off the features in Windows 8 at their Build conference, the internet and many office water coolers have been riddled with discussions about WinRT.. what it is, how it works, why should you use it versus something else, etc. Hopefully in this post I can provide some clarity.

First, a little history lesson: Microsoft originally wrote this thing they called the Win32 API. The Win32 API was written in C++ and littered with data types like the “lpzstr” and where developers had to do black magic tasks like “cracking messages” (it’s more benign than it sounds, honestly). We couldn’t pass big, bloated, complicated data structures around on the call stack so the use of the Win32 API was typified by the act of bundling up all your parameters to an API method into some obtuse, bit-packed “thing”, making the call, and then getting a response, which could be just as obtuse and bundled. Heaven help you if you wanted to hook into the bowels of the API so you could receive notifications and messages in your own code.

Then along came COM (yes, I’m skipping OLE and DDE for you history buffs… it’s too traumatic for me to write about). COM, which stands for Component Object Model, was an API. More than an API, it was a binary standard for allowing components written in (virtually) any language to communicate with each other. Those of us who had to write our own COM components or consume them are familiar with “DLL hell”. This is when the act of trying to make versioned components make sense on your system goes straight to hell in a handbasket. An important thing to note is that while COM provided an object-oriented, component-style layer to expose and consume functionality, the Windows UI was still very much the Win32 API.

Now we finally get to the .NET Framework, a managed runtime environment that claims to solve the problems of DLL at the same time as making UI development easier, more developer-friendly, and much more intuitive. We start with Windows Forms and eventually get technologies like XAML, WP, and Silverlight to build our user interfaces. Despite support for 64-bit and being a boatloat more powerful and complex, we’re still all sitting on top of something that strongly resembles the original Win32 API … we’re just insulated from it, and by insulated, I mean we’re sitting in a warm cozy ski lodge while the underlying API is freezing its ass off on the top of the mountain. This brings us all the way up to .NET 4.5. That’s right, .NET 4.5 is still going through a similar stack of abstractions to get to the underlying system that we go through today. This point is important.

Now we get WinRT. Contrary to popular belief, WinRT is not just a re-branding of the Windows API. It isn’t a codename for .NET 4.5. WinRT is actually a UI (among other things, including file system & device access) library written in C++. The reason I took so long getting to this point with the history lesson is this:

WinRT is the biggest single change to the Windows desktop development story since the arrival of the Win32 API.

WinRT takes many of the classes and features that we’re used to having available to us in .NET and re-writes them in native C++. Much of the .NET BCL (Base Class Library) that we take for granted has now been cleaned up and made available within WinRT – again, in native code. Rather than making us suffer through yet another poor interop layer, WinRT is also built with its own self-describing metadata. This allows Microsoft to generate C#, JavaScript, and C++ class libraries. These class libraries aren’t just cheap shunts, but rather they surface the concepts available within WinRT in ways that seem familiar and, more importantly, idiomatic, to the developers who have been working in those environments for years. When your “appx” (Silverlight devs, think “.xap” here) bundle is loaded, WinRT figures out what kind of host process is needed (an HTML engine, a CLR process, or a C++ process) and then fires up your app within the WinRT sandbox.

So, regardless of how it is implemented in the underlying WinRT C++, a collection exposed to JavaScript will look like a vector whereas it will look like a .NET collection complete with Add() and Remove() methods to a C# developer and it will look as it should in C++ as well.

So – how do you decide if you’re going to use WinRT or if you’re going to continue with the standard desktop application story? Well, in general, if you want access to the “Metro” style, then you’re going to need to use WinRT. If your application just doesn’t fit with Metro (or has a complicated UI that makes no sense to expose to touchable surfaces) then you’ll continue using standard .NET 4.5 technology.

WinRT applications have the potentially to finally give Microsoft a good mobile and slate environment. Windows CE, PocketPC, and Windows Mobile were all terrible attempts at shoehorning a desktop operating system into a mobile form factor. Windows 8, with WinRT apps and the Metro style, has the potential to give both big-monitor desktops and slates/tablets a compelling and engaging experience.

For us developers, this means 400+ million potential happy customers.

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.

Creative Kryptonite and the Death of Productivity

I just noticed that Jonathan Fields quoted my “dopamine squirts” blog post in a great post of his own. Both of us agree on one thing – hyperconnectivity is addictive and, when not kept in check, can completely degrade someone’s quality of life, up to and including the reduction of their attention span, an increase in anxiety, reduction in patience, and even things like inability to concentrate and trouble “free thinking” (aka lack of creativity).

Here’s a link to his article: http://www.jonathanfields.com/blog/creative-kryptonite-and-the-death-of-productivity/

Though I’m a programmer and a writer and Mr. Fields is a jack of all trades, many of which surround the finance industry, both of us can see a bleak future on the horizon for people who can’t control their hyperconnectivity addictions.

Backing Your iOS App With WCF JSON Web Services

There is very little doubt that iOS is one of the most compelling targets for developers who want to build free or paid applications for mobile devices. The iOS SDK is, in my opinion, one of the best designed SDKs available. It is better, in fact, than many desktop and server SDKs that I’ve used. Unfortunately, Apple doesn’t have a server-side SDK so when it comes to building web services that support our connected mobile applications we’re left to look elsewhere.

Say what you want about Microsoft and their Windows Phone 7 SDK, but few people doubt that the .NET Framework is on the short list of go-to technologies for enterprise and server-side code. Unfortunately, not enough people know that it is possible to quickly and easily build cross-platform, mobile-friendly web services using Microsoft technologies. Partially their own fault for some of their early work with Web Services, Microsoft has a stigma of being proprietary and that none of their stuff server stuff is easy to consume from non-.NET clients.

This blog post will show you otherwise. For demo purposes I will use a subject that is near and dear to my heart, Zombies. This application is a zombie catalog that pulls a list of known zombie types from a catalog server and displays them in a table view (via a UITableViewController).

First, let’s build the service. To start, we’re going to build a simple C# object that represents the summary information we’re going to pull down to populate our table view:


[DataContract]
public class ZombieInfo
{
 [DataMember]
 public string Name { get; set; }

 [DataMember]
 public string Description { get; set; }

 [DataMember]
 public int TotalSightings { get; set; }
}

Now that we’ve got the data contract for the ZombieInfo class, let’s create a WCF service contract for the service:


[ServiceContract(Namespace="http://my.app.com/services")]
public interface IZombieInfoService
{
 [OperationContract]
 [WebGet(BodyStyle = WebMessageBodyStyle.Bare,
 RequestFormat=WebMessageFormat.Json,
 ResponseFormat=WebMessageFormat.Json,
 UriTemplate="/KnownZombies.json")]
 ZombieInfo[] GetKnownZombies();
}

I won’t bore you with the implementation of the service itself … for the purposes of this demo I just created a few instances of some zombies and returned them. You can choose to host the implementation of this service in IIS or you can self-host it using code like this:


Uri jsonbaseAddress = new Uri("http://" + Environment.MachineName + ":1111/ZombieService");
jsonServiceHost = new ServiceHost(singleton, jsonbaseAddress);
ServiceEndpoint jsonEndpoint = jsonServiceHost.AddServiceEndpoint(typeof(IZombieService), new WebHttpBinding(), jsonbaseAddress);
jsonEndpoint.Behaviors.Add(new WebHttpBehavior());
(jsonEndpoint.Binding as WebHttpBinding).Security.Mode = WebHttpSecurityMode.None;
jsonServiceHost.Open();

In the preceding code, the singleton variable is just an instance of my ZombieInfoServiceImpl class (a class that implements IZombieService).

Now that you’ve got this service running and self-hosted (or running in IIS – however you want to host your WCF services is up to you, but you’ll probably need IIS if you’re hosting them on the Internet somewhere) you can consume it. If you hit the /KnownZombies.json URL and you’ve provided some bogus data, then you should get a blob of information in typical JSON format. In our case, it’s a JSON array (this fact will be important when we get to the iOS code).

Now we can get started with our iPad/iPhone app. I’m not going to cover how to make this a Universal app because I did that in my previous blog post. The first thing you’re going to need is a UITableViewController. It doesn’t make any difference if you rig it through the designer (you are using Xcode 4 right??) or if you do it all programmatically. The key is that we’re going to hit our web service in the viewDidLoad: method.


- (void)viewDidLoad
{
 [super viewDidLoad];

 NSString *urlString = @"http://my.app.com/services/KnownZombies.json";
 NSURL *url = [NSURL URLWirthString:urlString];
 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
 [connection release];
 [request release];
}

Now we need to grab the data from the web service, which is going to come to us in the form of an NSData pointer. We’ll need to convert that to a string and then from that string, we need to parse the JSON and turn it into an Objective-C object. To do that, we’re going to use this JSON framework for iOS. I didn’t mess with trying to link the library, I just copied the code into a JSON folder and at the top of my view controller’s implementation file I added an import for “JSON.h”

Assuming we don’t get any errors, then our NSURLConnection delegate method is going to be called. This is where we use the JSONValue category extension provided by the JSON framework to give us an NSArray* object from the string:


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSDAta *)data
{
 NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 self.knownZombies = [jsonString JSONValue];

 NSLog(@"got zombies! : %@", self.knownZombies);

 [self.tableView reloadData];
}

In this little bit of code, my table view controller has a property on it called knownZombies. In a bigger application I might have gone with a repository pattern to separate the view controller from the actual web service calls and the data storage and so in my viewDidLoad: method I might have just done something like this instead:


[repository fetchZombies];

And then the rest of my table view controller pulls things like rowcount and data from the repository. The last thing we need to do is supply row counts and cells for the table view:


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
 return [self.knownZombies count];
}

- (UITableViewCell *)tableview:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 static NSString *CellIdentifier = @"ZombieCell";

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 if (cell == nil)
 {
 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStyleDefault reuseIdentifier:CellIdentifier] autorelease];
 }

 NSDictionary *zombie = [self.knownZombies objectAtIndex:indexPath.row];

 cell.textLabel.text = [zombie objectForKey:@"name"];

 return cell;
}

That’s pretty much all there is to it. When you expose your WCF services as RESTful, JSON-serialized services then they become an absolute piece of cake to consume from your iOS application. One main reason for this is due to the availability of frameworks like the JSON framework. The other reason is that the XML parsing capabilities you get out of the box with the iOS SDK suck. Also, you might think the difference is small but when you get into large numbers of rows, the difference in payload size between XML and JSON can actually make a big impact on your application’s performance. The other (final) also is that if you are hosted on a site that charges by bandwidth, every dime saved by using JSON over XML counts.

Dopamine Squirts, Intermittent Reinforcement, and Mobile Apps

Is this you? Your phone vibrates and you pull it out of your pocket to check and see if anything interesting caused the vibration. You have a moment of boredom in a store, in a checkout line, while waiting for your spouse to get dressed – so you pull out the phone and run through a checklist of information to peruse – looking to see if anything exciting has occurred in your digital universe be it Twitter, Facebook, or any of a thousand different things people can check on these days. Finally, after prolonged lack of exposure to your smart phone, your overall sense of boredom is heightened. You get fidgety, you get bored quickly, and you feel disconnected and out of touch. Often times you simply don’t know what to do with yourself w/out a laptop or your mobile phone.

If this is you, don’t be ashamed. You’re just like millions of other people who are being conditioned by their “smart” mobile devices. Every time your phone vibrates to alert you of the possibility of something interesting, exciting, or even mundane (but new) – your brain is getting what psychologists call a “Dopamine squirt”. Over time, your brain links the phone vibration, ring, or the “new SMS” tone to a brief release of dopamine. You feel this tiny little rush of excitement that feels like adrenaline every time your phone vibrates, jingles, rings, or otherwise begs for your attention. Since this is dopamine we’re talking about, you actually suffer mild withdrawal symptoms when you are away from your phone or your phone is idle/quiet for a long period of time. You get fidgety, anxious, bored, etc.

Intermittent Reinforcement is another psychological term that is used to refer to the behavior of people tethered to their smart phones. Even if their phone has been programmed to alert them to the arrival of something new and noteworthy, millions of people will pull out their phones and do a quick scan for “new or interesting stuff”. The next time you’re in an airport, or a Starbucks, or any other crowded place (especially one with business people on their lunch break), sit back and do some people watching. Watch how often people pull out their phone, do a scan, then put their phone back. The scary part comes when you see the same person do this 4, 5, 10 times in a row while waiting in line for their coffee, sandwich, or standing on a street corner waiting for the “walk” signal to light up.

Intermittent Reinforcement is the addictive quality of video games and it is affects us at such a core, low level that no matter what kind of person we are – gamer, geek, artsy, whatever – we are still able to be conditioned using this pattern. The people holding these smart phones (I often call them “holsters”, referring to the level to which people have begun delegating all of their primary brain function to the little devices in their hands rather than thinking for themselves) have been conditioned to check their phones periodically for stimulation, to get the little squirt of dopamine. They pull out their phone, ask it “anything new?”, then put their phone back. 10 seconds later, they’ll pull the phone out again, repeat the process, and so on. The dopamine squirts that build up these subtle, low levels of addiction in people are what makes otherwise sane people crave the dopamine squirt even while driving, so they pull the phone out and check messages, send texts, and other horribly dangerous things.

In laboratory studies, rats are conditioned using Intermittent Reinforcement. They go over to a feeding tube, push a button, and sometimes food comes out. Eventually, the rat develops a pattern where it goes back to the feeding tube, pushes the button, and keeps checking over and over again to see if there is food available. Replace the rat’s food with the smartphone user’s news feed, twitter feed, facebook wall, gaming scores, etc.

Obviously some of these are extremes and the degree to which people are addicted to and conditioned by their mobile devices varies from person to person but here’s the scary part: Even if you are not one of the people I’ve described above, then you either know someone who is or you’ve seen someone who is recently.

My point here isn’t get on a high horse and complain about the state of modern technology. No, my point is that awareness of this phenomenon can make you a better application developer. If you’re aware of the patterns of Intermittent Reinforcement and you know how, over time, this can lead to “dopamine squirts” as people use mobile devices, you can design your application in such a way that it fits into this pattern and even takes advantage of it.

If you’re making a game, remember the rat. Give your users a little nugget of food every time they launch the application. Reward them and build the sense of Intermittent Reinforcement. Give them reason to come back to your game over and over again, day after day, to check and see if there is anything new worth doing, new rewards available, new progress to be made, etc. Your users aren’t rats, but like it or not, smartphone users are just as easily conditioned as rats (myself included, so please don’t think I’m being condescending here).

Even if you’re building a stuffy, boring business application, you can still take advantage of Intermittent Reinforcement and give your users dopamine squirts. Give the user a reason to come back to the app, to “check in” and see what’s new and what’s going on. When they do launch your app, give them something satisfying as a reward for having launched the application, something that will make them want to come back for more, no matter how boring the subject matter might be. One man’s insomnia cure is another man’s fetish.

I’ve said this before but it’s worth saying again – the usage patterns for mobile devices are not the same as the ones for apps in a browser, apps run from a laptop, apps used from a desktop, or even apps or games on a game console. Being aware of these patterns, especially how they affect the behavior of their users, will lead to building better applications that better suit the lifestyles of your users.

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.