Bill Reiss is a Windows Platform Development MVP and a Senior Consultant for AgileThought

Archive for January, 2013

I’ll be posting more details about this soon, since I’m going to be using Buddy APIs for my new Windows 8 game, but I wanted to let game devs know about Buddy if they’re writing games for Windows Phone or Windows 8 and want to provide a networked high score system.

It’s been a bit of a sordid history for networked high score systems for Windows Phone and Windows 8. OpenFeint (now Gree) promised support and had a private beta but never released anything. ScoreLoop released Windows Phone support, were bought by RIM, promised they would keep supporting other platforms, and today said don’t worry Android devs with no word of Windows Phone.

Even Microsoft tried to help through the Windows Azure Toolkit for Social Games, but that offering has died off as well. So what’s left? You can write your own high score server, but you need to worry about spoofing and other attacks and you need to protect your keys, etc.

Or you can check out Buddy.com that provides an API for Windows Phone (7.1 and 8) and Windows 8. Buddy.com does a lot more than high scores, such as analytics, messaging, location services, etc.

What makes Buddy very interesting is that you can get 500,000 API calls for free PER MONTH, and if you sign up for Nokia’s Premium Developer program for $100 a year that is doubled to 1 million free per month. They also support async and await on Windows 8 and Windows Phone 8. Their game services offering is very robust and they are very open to feedback, so if it doesn’t do what you need they might make it happen.

It’s been pretty clear for a while that XNA didn’t have a future. Key team members either left the company or moved to other groups, and XNA hasn’t been a part of any new announcements for over a year. Some of the most concrete proof so far came to light today when Promit Roy shared an email from Microsoft about the future of the XNA MVP program. Learn more about Microsoft MVPs here.

Disclaimer: I’m currently a Microsoft MVP in Silverlight, but my first MVP award was in XNA, and I still have a lot of good friends among the XNA MVPs. Silverlight MVPs also have a hazy future but that’s a post for a different day.

After April 2014 the XNA MVP competency will cease to exist. Fellow MVP Andras Velvart speculated that this means that either the current crop or the next crop of renewals will be the last for XNA, since the term for an MVP is one year. I tend to agree with this, and in my opinion this means that April 1 will be the last time that XNA MVPs are renewed/awarded. 

With the end of the XNA MVP competency, it’s pretty easy to assume that XNA itself is not a technology that Microsoft will focus on going forward. This isn’t a surprise since XNA isn’t supported in Windows Store apps for Windows 8 or in apps for Windows Phone 8. Any questions about XNA support in Windows 8 were dodged or answered with an “it’s not supported”. Windows Phone 7.1 apps using XNA will still run on Windows Phone 8, but can’t take advantage of new features such as in-app purchasing.

If you’re an existing XNA game developer, things can seem pretty dire, but I would recommend that you embrace the MonoGame project. MonoGame arose originally out of my open source SilverSprite project but has taken it a lot further and they support most of the popular platforms including iOS, Android, Windows Phone 8, and Windows 8. It’s not perfect, but it’s getting better all of the time and it may turn out to be better over time than XNA because Microsoft would probably never have ported XNA to the competitor’s platforms.

XNA gained a pretty strong following, and with good reason. The lead developers on the team had a long history of working on commercial games so they knew what was really needed to help game developers get their job done. Unfortunately I think some of what they implemented to help game devs also led to their demise. The very powerful and flexible content pipeline, a way to get pretty much any assets in any form into XNA, either through the built in content processors or through custom content processors, was tightly integrated into Visual Studio C#. This is one major reason why we never saw official support for XNA using VB or other .NET languages, and I think it’s also why we haven’t seen support for XNA in Windows 8 or Windows Phone 8. It probably became just too expensive to keep updating this content pipeline for every new platform they wanted to support.

Currently MonoGame uses existing XNB files. These are the files that the build side of the content pipeline creates, so this means that for MonoGame you have to use an install of XNA to create the XNB content files you use in your MonoGame project. I know they’re working on this, and it’s even more important now for them to have their own way of generating XNB files.

So why do I think the death of XNA might be a good thing? Overall I’d rather XNA was supported going forward, since I love the technology and there are a ton of existing games using it that would easily port to Windows 8 if the option was available. The reason I think it may be good is for the same reason that I think the death of Silverlight could be good, as long as something better comes out of it. Windows Phone 8 is very similar to Windows 8 for development and from what I hear the next release will converge even more. The best guess across the board is that the next Xbox will support a very similar programming model. If this is the case, we finally are at a point where apps that you write for one of the platforms in the Microsoft stack will easily port to the others.

While .NET has been a constant through the last 12 years of Microsoft development, the other technologies built on top of .NET including WPF, Silverlight, WinRT, XNA, ASP.NET, etc. have been in a fairly constant state of flux. Writing Windows 8 apps in XAML is similar to writing Silverlight apps in many ways but there are some fundamental differences since the underlying framework has been almost completely rewritten.

Contrast this with iOS and Mac development. There are still APIs in iOS development that prefix the function name with NS. Why NS? NS stands for NextStep, the OS that Steve Jobs pioneered with Next computers and brought with him in his return to Apple. So while WinRT has been around for little over a year, the roots of Apple development are a lot deeper, and Apple doesn’t keep pulling the rug out from under their developers. I feel that Microsoft needs to do the same, and even if what they have isn’t perfect, at this point it’s more important to just stick with it and evolve instead of starting over yet again. Microsoft developers are tired of the churn.

As long as the death of Silverlight and XNA are part of a consolidation and a stabilization of the platform, I’m all for it, and it should have happened long ago.    

A few months ago, I received an Ultrabook as a prize for a Windows Phone app contest. It was a sweet prize, but the resolution of the screen is the same as the Surface RT, specifically 1366×768. I tried to use this Ultrabook as my daily driver,  the screen looks great, plenty of storage, and an i5 CPU. The one problem was the screen resolution, but I thought I could deal with it.

After a couple of weeks I gave up on it and switched back to my work laptop. The sole reason was the vertical resolution, and the fact that many web sites didn’t provide a reasonable experience at a vertical resolution of 768 pixels.

Since the beginning of the web, developers coding to the resolution of their developer PC’s screen has been a common occurrence, but generally they’ve been forced to support either 800×600 or 1024×768, the most common resolutions of the time. Both of those resolutions fit into the resolution of my Ultrabook, so what’s happened since then? Are higher resolutions the norm now and my Ultrabook is relegated to the domain of Netbooks of the past where if you want to use one you’ll get by but you won’t have the ideal experience.

Let’s look at current statistics for the web. I think w3schools.com is a bit skewed but if it is, it’s skewed higher, so if anything these numbers are low.

At first glance, if you combine 1024×768 with 800×600, you’re looking at 14% of the market. This is much smaller than the number a year ago but still pretty big.

Now if we go to the “Higher” category, 1366×768 is at 18.7%, and 1280×800 is at 10.7%. Add the other resolutions 800 vertical and under and that’s another 3.3%. The total percentage of 800 vertical or lower is 14+18.7+10.7+3.3 or 46.7%. So almost half of the computers hitting the internet have 800 pixel vertical resolution or lower. Given this big percentage, more web developers should take a step back and not ignore this part of the market.

My post from a few days ago about how Microsoft should give up on their own rendering engine for IE and adopt WebKit got a lot of attention. This was thanks in large part to Mary Jo Foley of ZDNet tweeting about my post. Thanks Mary Jo, as you told me later when I was getting a lot of negative feedback, at least it caused people to think about the issue. It also led to a lot of very knowledgeable feedback, and based on that I’ve been convinced I was wrong.

Please understand that whenever I post to my blog, I strongly believe in what I posted at the time. It’s not link bait, or trolling, or whatever you want to call it, and I’ve been accused of all of these in the past. That being said I’m more than willing to be convinced and the longer I spend in the computer industry the more I know that there are many many people more knowledgeable than I am on any topic. So I only hope that my posts can spur some discussion and I am more than willing, and even eager, to be convinced of the opposing viewpoint.

What drove the original post was a frustration of Windows Phone getting slammed left and right and mostly because of the fact that IE isn’t WebKit and many mobile web developers take the easy path and make sure their stuff runs good on WebKit. This is very understandable since WebKit probably accounts for over 90 percent of mobile web traffic. This being the reality, it’s frustrating to see sites like The Verge give negative reviews to Windows Phone because of the fact that IE doesn’t render the non-standard CSS on their site properly.

It seemed like the obvious solution to this is if Microsoft was to adopt WebKit and contribute back to it to make it better, and overall WebKit’s implementation of HTML5 would get better. The main opposing viewpoints were that by Microsoft adopting WebKit there wouldn’t be a strong opposing implementation of HTML5 to keep WebKit honest and work harder to properly support the standard, and since the IE rendering engine, Trident, is so core to Windows 8 Store apps and other apps via the web browser control, it would be very hard to swap it out.

So back to my original frustration about Windows Phone and having a default non-WebKit browser. This is a real issue and I feel now that I recommended the wrong solution. The better solution is to add the capability to Windows Phone 8 to choose an alternative default browser. This would leave it open to the browser providers such as Google, Mozilla, Opera, etc. to provide a better option on the platform. Specifying a different default browser is something you can’t do on the iPhone, and Windows Phone could easily turn it into some positive publicity. After all, Windows 8 lets you pick your default browser, so why not enable this in Windows Phone.

So in conclusion, I’m not afraid to be wrong, and I’m wrong pretty often, but it’s great when it leads to a discussion where a better solution becomes clear. In this case I believe the real solution is for Windows Phone 8 to allow you to pick your default browser.

Source code for this sample: http://www.billreiss.com/wp-content/uploads/2013/01/TestJsonWebAsync.zip

The application landscape of today often consists of applications on various different platforms accessing a common set of web services. By far the most common technique for doing this, since it’s well supported on pretty much every platform, is to use REST and JSON. If recommending a service layer to a customer these days, I’ll almost always recommend REST and JSON, with JSON being the more important part of the equation. It gives you the flexibility to decide later if you want to support other client side platforms and to be ready for any future platforms that may arise.

Now with fairly little effort you can code up an HttpWebRequest and do JSON serialization and deserialization using the built in .NET classes, but you have to deal with callbacks and probably more code than is necessary to handle the JSON serialization and deserialization. Also if you have to call multiple services in sequence, the nesting of the different calls and async callbacks gets nasty really fast. With the advent of the new async and await keywords in C#, using HttpWebRequest with callbacks seems so antiquated. In this article I’ll provide a sample of how to easily call JSON based web services using the async and await pattern. This sample is for Windows 8 Store apps, but it would also work with Windows Phone 8.

Setting Up

To follow along you’ll need Windows 8 and Visual Studio 2012. We’ll do File->New Project and select C#->Windows Store->Blank App(XAML). Name it TestJsonWebAsync.

image

Now we’ll add new project to the solution, of type Class Library (Windows Store Apps) and name it JsonWebAsync. This will be a class library you can reuse from your Windows 8 apps. You could potentially use a Portable Class Library (PCL) assembly, but there are currently problems with the Windows Phone 8 designer in Visual Studio and PCL, so if you want to target both platforms you’ll currently need 2 separate projects anyway, and just add all of the same files to the other project.

image 

In the TestJsonWebAsync project, add a reference to the JsonWebAsync project so that we can call it from there.

image

In the JsonWebAsync project, add a class named JsonWebClient. This will contain the wrapper methods we’ll create to call JSON based services.

First let’s create a method that returns the result string, and in this case we won’t care what the format is. Actually we’ll create two methods, one that takes an HttpWebRequest object so that you can specify other options on the request like custom headers or authentication, and another that just takes a URL. Add the following methods to the JsonWebClient class, and make sure you make the class public:

public class JsonWebClient
{
    public async Task<System.IO.TextReader> DoRequestAsync(WebRequest req)
    {
        var task = Task.Factory.FromAsync((cb, o) => ((HttpWebRequest)o).BeginGetResponse(cb, o), res => ((HttpWebRequest)res.AsyncState).EndGetResponse(res), req);
        var result = await task;
        var resp = result;
        var stream = resp.GetResponseStream();
        var sr = new System.IO.StreamReader(stream);
        return sr;
    }

    public async Task<System.IO.TextReader> DoRequestAsync(string url)
    {
        HttpWebRequest req = HttpWebRequest.CreateHttp(url);
        req.AllowReadStreamBuffering = true;
        var tr = await DoRequestAsync(req);
        return tr;
    }
}

Now these methods allow us to await on the request and returns a TextReader that we can use to read the result. This is an improvement over the HttpWebRequest as-is because we don’t have to worry about callbacks, etc. We can add code to our test app to see what comes back from these methods.

For this test we’ll retrieve the JSON string for the Microsoft page on Facebook. First in MainPage.xaml, inside the Grid element, add the following:

<StackPanel>
    <Button Content="Get JSON string from Microsoft's Facebook page" x:Name="buttonStringGet" Click="buttonStringGet_Click_1"/>
    <TextBlock x:Name="resultText" Style="{StaticResource BodyTextStyle}" TextWrapping="Wrap"/>
</StackPanel>

Then we need to code up the click event in MainPage.xaml.cs:

private async void buttonStringGet_Click_1(object sender, RoutedEventArgs e)
{
    JsonWebAsync.JsonWebClient client = new JsonWebAsync.JsonWebClient();
    var resp = await client.DoRequestAsync("http://graph.facebook.com/microsoft");
    string result = resp.ReadToEnd();
    resultText.Text = result;
}

It’s a neat little trick that for most events in Windows 8 Store apps, you can just add the async keyword and it will then be an async method. This allows you to then await inside of the method, since methods have to be tagged async for you to use the await keyword.

If we run this and click the button, it looks like this:

image

However it’s not quite where we want it to be, what we want is to get the data back as a strongly typed object so that it’s easier to deal with.

Now you can get away with using the built in .NET JSON support but I really love Json.NET, an open source library by NewtonSoft. You can serialize and deserialize JSON easily with one line of code. You can go to CodePlex and download the latest assemblies and add the references to your project, but it’s even easier with NuGet.

In Solution Explorer if you right click on the project node for JsonWebAsync you can choose Manage NuGet Packages. Json.NET will probably be on the first page because it’s really popular but if not you can enter JSON in the search box. Select Json.NET and click Install.

image

If you’re not familiar with NuGet, it will add all of the assemblies you need, and any supporting assemblies if necessary (and get the correct versions!), so after selecting this you should be able to use Json.NET in this class library. Do the same thing for our TestJsonWebAsync project, since for our next test we’ll want to access Json.NET in the test app.

Let’s say you want to be able to just retrieve JSON content and get property values based on the name of the property. This allows you to not have to define a proxy object in the client side code to get at deserialized JSON data. It’s very similar to how you would deal with JSON in JavaScript.

To kick off the test, we’ll add another Button to the StackPanel under the first one in MainPage.xaml:

<Button Content="Get JObject from Microsoft's Facebook page" x:Name="buttonJObjectGet" Click="buttonJObjectGet_Click_1"/>

Then for the event handler, we’ll do the following:

    private async void buttonJObjectGet_Click_1(object sender, RoutedEventArgs e)
    {
        JsonWebAsync.JsonWebClient client = new JsonWebAsync.JsonWebClient();
        var resp = await client.DoRequestJsonAsync("http://graph.facebook.com/microsoft");
        string result = "about property value is: " + resp["about"];
        resultText.Text = result;
    }

When we click on the second button, the JSON response is parsed into a JObject (provided by Json.NET to allow easy name/value pair access) and we set the result to the about property.

image

This is a really good step in the right direction, but if you’re an experienced .NET developer this whole name/value pair thing probably rubs you a little the wrong way. So let’s see how we can return a strongly typed object. These methods are very similar to the previous methods, but in this case we’ll call the generic version of DeserializeObject and add a type specifier to the method call:

    public async Task<T> DoRequestJsonAsync<T>(WebRequest req)
    {
        var ret = await DoRequestAsync(req);
        var response = await ret.ReadToEndAsync();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response);
    }

    public async Task<T> DoRequestJsonAsync<T>(string uri)
    {
        var ret = await DoRequestAsync(uri);
        var response = await ret.ReadToEndAsync();
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response);
    }

Now in the test app, we’ll need another button. Add it after the previous one.

    <Button Content="Get Strongly typed object from Microsoft's Facebook page" x:Name="buttonTypedObjectGet" Click="buttonTypedObjectGet_Click_1"/>

Since this is going to return a strongly typed object, we need to define one in our test program. We could go field by field in the JSON object and create corresponding fields, but thankfully there are a few apps and services that can help us out. If you “google it with bing” and search for “generate c# from json” you’ll see a bunch of options but let’s use the free online web version at http://json2csharp.com/

On this site enter the URL to our service, http://graph.facebook.com/microsoft and it’ll look something like this:

image

In the TestJsonWebAsync project, let’s add a new class called FacebookPageResponse. In the json2csharp page, click the copy button and then Ctrl-C. Delete the FacebookPageResponse class definition in the FacebookPageResponse.cs file and then replace it with the contents of the clipboard. Rename RootObject to FacebookPageResponse. Now this object can be used when deserializing a JSON object.

Here is the button event handler you need to add to MainPage.xaml.cs:

    private async void buttonTypedObjectGet_Click_1(object sender, RoutedEventArgs e)
    {
        JsonWebAsync.JsonWebClient client = new JsonWebAsync.JsonWebClient();
        var resp = await client.DoRequestJsonAsync<FacebookPageResponse>("http://graph.facebook.com/microsoft");
        string result = "about property value is: " + resp.about;
        resultText.Text = result;            
    }

Notice that it’s almost identical to the previous version but now we specify the object type on the method call and access the property directly instead of getting it by name. Here is how it looks when executed:

image

Up until this point we’ve dealt with simple string URLs in our tests. This isn’t always the case because many times you have to provide authentication, specify a different REST verb, or specify other headers. In these cases you can use the method overload that accepts an HttpWebRequest instead of a URL. To test this, the official web site for .NET User Groups in Florida, http://fladotnet.com, provides a JSON interface but to use it you need to specify a content type. In the test app let’s add yet another button.

    <Button Content="Get JArray from Florida.net" x:Name="buttonJObjectFloridaGet" Click="buttonJObjectFloridaGet_Click_1"/>

Then for the event handler:

    private async void buttonJObjectFloridaGet_Click_1(object sender, RoutedEventArgs e)
    {
        JsonWebAsync.JsonWebClient client = new JsonWebAsync.JsonWebClient();
        HttpWebRequest req = HttpWebRequest.CreateHttp("http://www.fladotnet.com/FlaNetData/api/flnetmeetings");
        req.ContentType = "application/json";
        var resp = await client.DoRequestJsonAsync<Newtonsoft.Json.Linq.JArray>(req);
        string result = "first description is: " + resp[0]["Description"];
        resultText.Text = result;
    }

In this case the result is an array of JSON objects, so we can call the generic DoRequestJsonAsync method and specify a type of JArray and get the result to deserialize properly. Then we get the first entry and show its Description property. We could have also generated a strong type and serialized into it as we did in the previous example.

image

I hope this has been useful and you can see how powerful and simple mixing HttpWebRequest with await and async can be.

Source code for this sample: http://www.billreiss.com/wp-content/uploads/2013/01/TestJsonWebAsync.zip

UPDATE: I was wrong and I now feel I recommended the incorrect solution to the problem. After hearing back from many people more knowledgeable that I am, I think this is a better solution: http://www.billreiss.com/follow-up-to-webkit-for-ie-hint-i-was-wrong/

With all of the hype about HTML 5, it sounded like we were on the way to web development nirvana where as long as you coded to the HTML 5 spec, things would “just work”. This is a great idea and it would be true except for the fact that developers are not coding to the HTML 5 spec, they are making sure that their stuff works great with WebKit based browsers. You can’t blame them since Safari and Chrome use WebKit, and therefore a huge majority of their mobile users are on WebKit. The W3C sees the danger of this and is very concerned that WebKit could become the defacto standard.

Internet Explorer has made great strides, and they can claim that in some tests they beat out WebKit in support for standards, or that they have better performance in some areas (like with a virtual fishbowl). According to html5test.com, IE10 is still lagging in HTML5 standards support but it’s definitely getting closer.

I end up asking myself why Microsoft spends so much effort supporting a browser that still can’t become a clear leader in HTML 5 support. Microsoft’s insistence on continuing with a non-WebKit based browser, no matter what the supposed benefits are, is negatively impacting their users.

When it comes down to it, what does Microsoft gain from IE? I’m really not clear about this, and I’ve asked many other people inside and outside Microsoft about this, and I still have no idea. Even if there was a clear advantage, wouldn’t that advantage still be around if they built a version of IE on top of WebKit?

VHS beat BetaMax, even though BetaMax was considered by most to be the better technology. This happened again with HD-DVD and Blu-Ray. Microsoft was on the losing side of that battle, and now rumors are that the next XBox will have Blu-Ray. At this point it really doesn’t matter who has the superior technology, so even if Microsoft feels IE is technically superior, it’s too late.