I’ve finished adding a level sharing service to maze-escape. Since working out how to do it was not so easy, I thought I’d share my experiences.
It should be fairly simple, upload levels as xml documents using a http post request, and to get them just download that xml document as a string and parse it. Only one problem: How do you make a http post request in XNA on WP7? It’s definitely possible for silverlight apps to access the internet, but what about XNA?
Turns out it is not only possible, but also quite simple. However, finding out how to implement it was not so easy due to the differences between the .Net framework for Windows and for Windows Phone 7.
So, to execute the HTTP requests, I am using the WebClient
class which is in the System.Net
namespace.
But before you can send an object in a POST request, first you need it as a string. To do that it needs to be serialized as XML. To do this in XNA a reference needs to be added to your project for System.Xml.Serialization as it is not there by default, then the code is as follows:
XmlSerializer serialiser = new XmlSerializer(typeof(MyLevelObject));
StringWriter sw = new StringWriter();
serialiser.Serialize(sw, myLevel);
Simple right? Now that you have your object as a string you can upload it like so:
Uri httpPost = new Uri(@"http://www.somewebsite.com"); WebClient webClient1 = new WebClient(); //Let the webserver know it needs to accept a post request webClient1.Headers["Content-Type"] = "application/x-www-form-urlencoded"; webClient1.UploadStringAsync(upload, "levelName=ALevelName" + "&data=" + sw.ToString()); //Add the event handler for when the upload is complete webClient1.UploadStringCompleted += new UploadStringCompletedEventHandler(web_UploadStringCompleted);
The final thing to do is get the response of the web server once the request has finished. Heres the code for the method thats called once the request is complete:
void web_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) { try { //HTTP request complete. //Store the returned html page in a string. string result = e.Result; } catch (WebException) { //Something went wrong //Get the error message. string errMsg = e.Error.Message; } }
And that’s the basics of a level sharing service for an XNA game. Downloading levels can be achieved in a similar way, and of course for both uploading and downloading there is backend php / database stuff that need to be done, but I’ll leave that to you.