Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: webservices

Accessing Neo4j from Play Framework 2.1 with Web Service Futures

As you may have noticed, I’ve recently been doing a little bit of talking about Neo4j and graph databases. A database on its own is a fantastic thing, but it doesn’t do anybody much good if the information contained within stays there, or if you can’t put information into it from some application. In my own proof of concept, I wanted to see how easy it would be to access Neo4j from my favorite web application framework, Play.

Turns out it was a little annoying because I started looking for frameworks to talk to Neo4j. First I looked at AnormCypher, which is a library that provides an “anorm-like” API access to Cypher. I couldn’t use this one because it failed with multiple runtime errors when I attempted to bring it into my Play application. Next, I tried another Cypher wrapper that I found on github and that one failed miserably, too – it had a conflict between the version of a JSON parser it was using versus the one that my Play application was using.

Then I figured, why even bother? It’s just a REST API. So, I decided to try accessing Neo4j using nothing but Play framework’s own Web services API, which is basically the WS object. This turned out to be stupidly easy and, when I figured out future chaining in combination with that WS API, amazing stuff started to happen. You know, like, productivity.

First, I created a teeny little wrapper around the Neo4j REST API URL, I just called it NeoService:

class NeoService(rootUrl: String) {
    def this() = this("http://default/neo/URL/location/db/data")

    val stdHeaders = Seq( ("Accept", "application/json"), ("Content-Type", "application/json") )

    def executeCypher(query: String, params: JsObject) : Future[Response] = {
        WS.url(rootUrl + "/cypher".withHeaders(stdHeaders:_*).post(Json.obj(
            "query" -> query,
            "params" -> params
            ))
       )
    }

    // Convert a Future[Response] into a Future[Int]!
    def findNodeIdByKindAndName(kind:String, name:String) : Future[Option[Int]] = {
        val cypher = """
          START n=node:node_auto_index(kind={theKind})
          WHERE n.name = {theName}
          RETURN id(n) as id
       """.stripMargin
        val params = Json.obj( "theName" -> name, "theKind" -> kind )
        for (r <- executeCyper(cypher, params)) yield {
            val theData = (r.json \ "data").as[JsArray]
            if (theData.value.size == 0)
               None
            else
               // Json: "data" : [ [ ### ] ]
               Some(theData.value(0).as[JsArray].value(0).as[Int])
        }
    }
}

So, in this little tiny class I’ve got a function that I can use to execute Cypher queries and because I know that I have an auto-index’d node property called kind and I have another property called name, I can attempt to find a node’s ID based on the kind and name properties using a Cypher query. Instead of finding them synchronously, I can just convert my Future[Response]  into a Future[Option[Int]] where the Option[Int] is the result of looking through the Neo4j database for that data. I’ve just converted a future with a future, and being able to do so is pretty freaking awesome.

Not only can I do that, but I can chain these method calls from other code, like this:

val neo = new utils.NeoService()
for (nodeId <- neo.findNodeIdByKindAndName("zombie", "bob"))
    for (zombieId <- otherObject.tweakZombie(zombieId))
        yield {
           zombieId.map { id => println("I got a zombie!") }.getOrElse { println("Zombie doesn't exist!") }
        }

In the code here, tweakZombie can be written to be aware of the Option[] so that if it’s empty, it doesn’t tweak anything, allowing me to chain call after call after call and not worry about slapping a crapload of if statements in there – a judicious use of map, and for, and options and futures gives me a ridiculous amount of power.

All of this is made possible by the fact that the Play Framework Web Services API is based on Futures. I was originally skeptical of futures because the old code I had seen before was more confusing than single-threaded, synchronous programming. With the new Futures syntax and well-coded libraries like the Play WS object, you can do ridiculous things in a very small number of lines of code.

Building a RESTful Service with Grizzly, Jersey, and Glassfish

I realize that my typical blog post of late usually revolves around creating something with iOS or building an application for Mac OS X or wondering what the hell is up with the Windows 8 identity crisis. If you’ve been following my blog posts for a while, you’ll know that there was a very long period of time where I was convinced that there was no easier way to create a RESTful service than with the WCF Web Api which is now a basic, included part of the latest version of the .NET Framework.

I have seen other ways to create RESTful services and one of my favorites was doing so using the Play! Framework, Scala, and Akka. That was a crapload of fun and anytime you can have fun being productive you know it’s a good thing.

Recently I had to wrap a RESTful service around some pre-existing Java libraries and I was shocked to find out how easily I could create a self-launching JAR that embeds its own web server and all the plumbing necessary to host the service, e.g. java -jar myservice.jar. All I needed was Maven and to declare some dependencies on Grizzly and Jersey.

To start with, you just create a driver class, e.g. something that hosts your main() method that will do the work required to launch the web server and discover your RESTful resources.


// Create and fire up an HTTP server
ResourceConfig rc = new PackagesResourceConfig("com.kotancode.samples");
HttpServer server = GrizzlyServerFactory.createHttpServer("http://localhost:9999", rc);

Once you have created your HTTP server, all you need to do is create classes in the com.kotancode.samples (the same  package name we specified in the ResourceConfig class) that will serve as your RESTful resources. So, to create a RESTful resource that returns a list of all of the zombies within a given area code you can just create a resource class (imagine that, calling a resource a resource … which hardly any RESTful frameworks actually do!):


// Zombies Resource
// imports removed for brevity

@Path("/zombies")
public class ZombieResource {

    @GET
    @Produces("application/json")
    @Path("nearby/{zipcode}")
    public String getZombiesNearby(
        @PathParam("zipcode") String zipCode
    ) {

       // Do calculations
       // Get object, convert to JSON string.
       return zombiesNearbyJsonString;
    }
}

In this simple class, we’re saying that the root of the zombie resource is the path /zombies. The method getZombiesNearby() will be triggered whenever someone issues a GET at the template nearby/{zipcode}. The cool part of this is that the paths are inherited, so even though this method’s path is nearby/{zipcode}, it gets the root path from the resource, e.g. http://(server root)/(resource root)/(method path) or /zombies/nearby/{zipcode}.

So the moral of this story, kids, is that there is no one best technology for everything and any developer who introduces themselves with an adjective or a qualifier, e.g. “a .NET developer” or “an iPhone developer” may be suffering from technology myopia. If you keep a closed mind, then you’ll never see all the awesome things the (code) world has to offer. If I limited my thinking to being “a .NET developer” or “an iOS developer” or “a Ruby Developer”, I would miss a metric crap-ton of really good stuff.

p.s. If you want to get this working with Maven, then just add the following dependencies to your POM file and then if you want, drop in a <build> section to uberjar it so everything you need is contained in a single JAR file – no WAR files, no XML configuration files, no Spring, no clutter.

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-server</artifactId>
  <version>1.16</version>
</dependency>
<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-grizzly2</artifactId>
  <version>1.16</version>
</dependency>

Struggling for Elegant Simplicity in the Enterprise

As you know, the theme of this blog is kotan (枯淡), the Japanese word for the concept of the elegance one finds within simplicity. This is what I strive for every day in my code, my architecture, my designs, and in general, my life.

We often start out with the best of intentions and then, at some point down the road, we take a step back from what we’re doing and we think, “What the hell is going on here?” We started out trying to solve what looked like a relatively simple problem and things have escalated and exploded into a mountain of code, plumbing, infrastructure, and a potential maintenance nightmare.

Take a simple facade problem. Your company has a suite of services that provide functionality within your organization. You’ve actually done a great job at making these services isolated, durable, idempotent, and you’re proud of the work you’ve done. No data access is allowed that doesn’t route through these services. Now your company wants to expose some of this functionality to external customers.

This should be a fairly simple architectural problem to solve, right? You figure you can expose a thin facade layer of services on the outside of your organization which then just make calls against your internal services. Great, fire up the IDE and start coding. The first bump in the road – you can’t expose your internal service contracts to external customers because that forces them to be coupled with your internal versioning scheme. If you add fields that are only useful within your organization, you can’t drop that field as optional into your public schema.

So now you’ve got public schemas and internal (often referred to as canonical) schemas. Great. No big deal. Let’s just create some plumbing that maps the external messaging schema to the internal messaging schema. Now you need to come up with some of the things that most larger SOA implementations need like a service registry, you need logging, security, and so on. Worse yet, your infrastructure might be doing a bunch of context switching, changing between message-oriented and POxO (POCO for C#, POJO for Java, etc) oriented. Now you might have complicated code generation processes happening in order to make sure that your code objects always line up nicely with your schema-based messages … and so on. Recognize this pattern? 90% of our lines of code are not spent in support of business functionality, but rather are spent in ceremony. If you were to walk up to this system and look for the code that does actual work that advances company business processes, you’d probably see relatively few lines of code. The real problem is when you ask a developer to build a new service in the above scenario, they will spend the same ratio of time as we see in the code – 90% of their time coding ceremony and 10% of their time coding real, valuable, logic. This is neither simple nor elegant.

The point of this blog post isn’t to talk about SOA facades and message-passing architectures, that was just an example of how things can rapidly go from simple to incredibly complicated in a matter of hours. The point of this blog post is to shatter the idea that your code has an excuse to be bloated, complicated, difficult to read, and difficult to maintain simply because it’s enterprise code.

The next time you sit down and start hammering out code in advance of your newest, shiniest architecture, ask yourself whether you’re spending the majority of your time writing useful lines of code, or writing ceremony.

Here are some rules that I live by when implementing large-scale systems:

  • If you think you’re wasting your time, you probably are.
  • If you think it looks to complicated, it probably is.
  • If you’re the only one who can work on it because maintenance requires too much context, you’re doing it wrong.
  • If you think there might be an easier way to do it, there probably is.
  • If you’re writing code for a feature you don’t know if anyone’s going to use, stop. (premature optimization)

There’s no shame in buying a commercial product or utilizing open source libraries so that you can focus on writing code in service of your company’s core competency and leave the ceremony to someone else.

To summarize – enterprise, back-end code has notoriously been big, bloated, complicated, hard to read, and nearly impossible to maintain. Stop the insanity! Enterprise code can be just as beautiful, elegant, easy to read, and easy to maintain as any other type of code – you just need to be vigilant and ruthless. If an architecture doesn’t let you write elegant, simple code (even if you’re the architect!), you need to cut your losses, put it out of its misery, and move on*.

* = We all have to make exceptions to accommodate budget, timelines, and alien-abducted-pod-bosses-from-Mars. Choose your battles wisely.

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.

Consuming YouTube Feeds from Windows Phone 7

In my previous two blog posts, I talked about the mechanics of talking to simple Web Services on the web using the WebClient class and how you can parse that information. You can find those posts here and here. In this blog post, I’m going to create a class that you can use in your apps to consume feeds of published YouTube videos.

Basically I want to create a YouTubeManager class that I can just call a method on to go grab and parse a YouTube feed. I want to have the ability to extend this class in the future so that it can be used asynchronously in the background, so I’m going to use WebClient‘s DownloadStringAsync() method.

Here’s the code for my YouTubeManager class: (note that this is preliminary – the current design here doesn’t let you fetch more than one YouTube feed simultaneously):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;

namespace ExclaimComputing.ClientBranding.YouTube
{
 public static class YouTubeManager
 {
   private static Action<YouTubeVideoInfo[]> videoHandler;
   private static Action<Exception, object> videoFailHandler;

   public static void GetYouTubeFeed(
     string userName, Action<YouTubeVideoInfo[]> handler,
     Action<Exception,object> failHandler)
   {
   videoHandler = handler;
   videoFailHandler = failHandler;
   WebClient wc = new WebClient();
   wc.DownloadStringCompleted +=
     new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
   wc.DownloadStringAsync(
    new Uri("http://gdata.youtube.com/feeds/api/users/" +
    userName + "/uploads"));
   }

   static void wc_DownloadStringCompleted(object sender,
     DownloadStringCompletedEventArgs e)
   {
   if (e.Error != null)
   {
     videoFailHandler(e.Error, e.UserState);
   }
   else
   {
     Debug.WriteLine(e.Result);

     StringReader sr = new StringReader(e.Result);
     var reader = XmlReader.Create(sr);
     var document = XDocument.Load(reader);

     XNamespace atom = "http://www.w3.org/2005/Atom";
     var entries =
      from entry in document.Descendants(atom + "entry")
      let postedDate =
        DateTime.Parse(entry.Element(atom + "published").Value)
      orderby postedDate descending
      select new YouTubeVideoInfo()
      {
        PostedDate =
          DateTime.Parse(entry.Element(atom + "published").Value),
        Description = entry.Element(atom + "content").Value,
        Title = entry.Element(atom + "title").Value
      };

    videoHandler(entries.ToArray());
   }
   }
  }
}

Now that the manager (plumbing) code is taken care of, we can write our ViewModel class. An instance of our ViewModel class is to what the WP7 GUI will be bound. The following is a quick and dirty ViewModel class that invokes the manager to retrieve some videos:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;

namespace ExclaimComputing.ClientBranding.YouTube
{
 public class YouTubeViewModel : INotifyPropertyChanged
 {
 public YouTubeViewModel()
 {
   this.Items = new ObservableCollection<YouTubeVideoInfo>();

   YouTubeManager.GetYouTubeFeed(
     "????",
     //success handler
     videos =>
     {
       foreach (YouTubeVideoInfo videoInfo in videos)
       {
         this.Items.Add(videoInfo);
       }
     },
     // fail handler
     (exc, userState) =>
     {
       Debug.WriteLine(exc.ToString());
     }
   );
  }

  public ObservableCollection<YouTubeVideoInfo> Items { get; private set; }

  public event PropertyChangedEventHandler PropertyChanged;
  private void NotifyPropertyChanged(String propertyName)
  {
     PropertyChangedEventHandler handler = PropertyChanged;
     if (null != handler)
     {
       handler(this, new PropertyChangedEventArgs(propertyName));
     }
   }
 }
}

The NotifyPropertyChanged pattern is implemented in this view model out of habit – while I might start out just binding to the observable collection, past experience tells me that at some point I’m going to need to put a property on this thing. I have a code snippet for implementing INotifyPropertyChanged so it’s not that big of a deal.

In the preceding code, the “????” string should be replaced with the the username of the YouTube user whose uploads you want to obtain in this query.

A funny thing to note about the asynchronous wrapping pattern I’m using in my call to GetYouTubeFeed. It was inspired by how the new iOS4 SDK integrates blocks into many of the new API calls – allowing the developer to specify blocks of code to be executed at the completion of an asynchronous request. The beauty of this pattern is that even though what’s happening is asynchronous, I can still see all of the possible outcomes of this asynchronous request in the same area of the code. This makes my code easier to read and maintain and actually a lot easier to write.

Armed with the code from this blog post, it should be ridiculously easy now to integrate the consumption of YouTube video feeds into your WP7 application. Enjoy!

Accessing Web Services from Windows Phone 7, Part II – Parsing XML

In my previous blog post, I talked about the ways you can get data over HTTP from web services on WP7 and Silverlight. In this post, I’m going to talk about what you can do with that data once you have it.

If we had access to the full desktop or server versions of .NET 4.0, we’d be able to use classes like the XmlDocument or we’d be able to use facilities like XML serialization, which lets us work backwards from an XML string and hydrate a fully functional object graph from that. Unfortunately, neither of these facilities are available to us on WP7.

However, XDocument and LINQ to XML are available and, as you’ll see, you don’t need anything else. XDocument, which provides a fluent-style API over an XML DOM (Document Object Model), when paired with LINQ to XML, is incredibly powerful. Not just powerful, but it is also expressive and super tight. By that I mean you can rip apart an XML document into an array of ViewModel POCOs in just a few lines of code.

In the following code sample, I’m fabricating an XML document that contains a couple of stock quotes. Imagine that instead of me mocking it up, this XML document came from a live web service that provides stock quotes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;

namespace WindowsPhoneApplication1
{
 public class StockQuote
 {
   public string Symbol { get; set; }
   public decimal Price { get; set; }
   public DateTime QuoteTime { get; set; }
 }

 public partial class MainPage : PhoneApplicationPage
 {
   // Constructor
   public MainPage()
   {
     InitializeComponent();

     // pretend this came from a web service
     string xmlData =
     @"<ServiceReply>
       <StockQuote symbol='IBM' price='32.50' quotetime='01/01/2010 12:21:00'/>
       <StockQuote symbol='MSFT' price='21.20' quotetime='01/01/2010 12:20:30' />
      </ServiceReply>
     ";

   XDocument dataDoc = XDocument.Load(new StringReader(xmlData));

   var quotes = from quote in dataDoc.Descendants("StockQuote")
     let stamp = DateTime.Parse(quote.Attribute("quotetime").Value)
     orderby stamp ascending
     select new StockQuote
     {
       Symbol = quote.Attribute("symbol").Value,
       Price = decimal.Parse(quote.Attribute("price").Value)
     };

   foreach (StockQuote stockQuote in quotes)
   {
     Debug.WriteLine(stockQuote.Symbol + " : " + stockQuote.Price);
   }
 }
 }
}

Pay special attention to lines 43 through 50. What I’m doing here in what amounts to a single line of code is ripping open the XML, storing the important bits on POCO instances and while I’m at it, I’m specifying that I want the results sorted by a timestamp, from oldest to newest. When you run this code, you’ll notice that the output is the reverse of the document order of the original XML string.

Lines 43 through 50 truly exemplify Kotan – they are elegant in their simplicity. The code is readable, self-documenting, and it takes care of a massive amount of ceremony and grunt work that would otherwise clutter up your code. Then, when you think that the collection you just got from a web service can be merged into an ObservableCollection<StockQuote> to which your GUI is bound, things start looking pretty awesome.

So fear not – at first glance it may look like WP7 and Silverlight are hamstrung and hindered but take one look at XDocument and LINQ to XML and you’ll realize that you’ve still got an incredible amount of power and simplicity available.

Accessing Web Services from Windows Phone 7

I’ve said many times before that the Windows Phone 7 learning curve is actually pretty small assuming you already know Silverlight. One of the hardest things to get used to with Silverlight is remembering which pieces of the .NET Framework are not available to developers from Silverlight and WP7.

One area that is significantly limited from it’s larger desktop counterpart is networking. For obvious reasons, the number of ways in which Silverlight can initiate outbound network connections is capped, including the fact that developers do not have access to the WebRequest class.

In Silverlight and Windows Phone 7 development, there are only to ways to access web services: Using WCF or using the System.Net.WebClient class. There are a plethora of resources available on the web for both of these methods, including probably nearly a dozen different books on WCF programming.

Assuming you aren’t using WCF to talk to a back-end web service, then you’re probably going to want to consume data over regular HTTP. To do this, you use the WebClient class. Some of us remember the good old early days of .NET programming when the use of this class was commonplace.

Here’s some code that downloads the contents of a web page as a string and prints that string to the debug log and it does it all asynchronously:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Diagnostics;

namespace WindowsPhoneApplication1
{
 public partial class MainPage : PhoneApplicationPage
 {
 // Constructor
 public MainPage()
 {
 InitializeComponent();

 WebClient wc = new WebClient();
 wc.DownloadStringAsync(
    new Uri("http://my.serviceapp.com/my/webservice"));
 wc.DownloadStringCompleted +=
    new DownloadStringCompletedEventHandler(
      wc_DownloadStringCompleted);
 }

 void wc_DownloadStringCompleted(object sender,
    DownloadStringCompletedEventArgs e)
 {
     Debug.WriteLine("Web service says: " + e.Result);
 }
 }
}

Finally, the main methods we need to be concerned with on the WebClient class are:

  • UploadData and UploadDataAsync – This is what you’ll use to POST or PUT data to a RESTful (or less-than-RESTful depending on which API you’re talking to…) web service.
  • UploadString and UploadStringAsync – Rather than sending byte arrays, this lets you push a simple string. This comes in very handy if you’re talking XML over the wire.
  • DownloadData and DownloadDataAsync – Downloads (GET) data from a web URL.
  • DownloadString and DownloadStringAsync – Downloads data from a web URL and that data is returned to the developer as a simple string. Again, this is a really handy shortcut for talking XML to remote endpoints.

There are also a bunch of useful properties, including properties like Credentials that help you authenticate against web services and you can access the HTTP headers (many public web services make use of this facility) using the Headers property.

Stay tuned, this is just the first post of many in some WP7 posts that I’ve had lying around for a while and needed to get out of my system. Long story short: armed with System.Net.WebClient you can talk HTTP to any web service in the cloud. In subsequent posts, I’ll show some more techniques for dealing with things like XML, RSS, etc.

Check out Part 2 of this series, where I discuss parsing XML on WP7.