Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: silverlight

What I’ve Been Up To Lately

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

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

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

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

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

WP7 for iPhone and Android Developers – Introduction to C#

I’ve started a new series of articles over on Silverlightshow.net. In this series of articles I guide the reader through some of the most important aspects of Windows Phone 7 development, with an eye toward helping readers map their existing iOS and Android knowledge to C#, WP7, and Silverlight.

The first of these articles has just been published here. Head on over and give it a read, I hope you enjoy it.

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.

Microsoft KittyHawk – More Proof MS Just Doesn’t Get It

I was flipping through my usual onslaught of tech feed this morning when I came across this article from Mary Jo Foley.

The long and short of this article is that Microsoft is apparently working on a new tool to make it easier for people (non-developers) to build .NET applications. The inspiration for this tool comes from the good old days of FoxPro/Visual FoxPro development and other “app builder” tools that let people drag and drop various types of features that wrapped (mostly) hidden code underneath bound GUI controls and let Excel Users build apps.

Here’s a quote from her article, which is actually quoting her source on the subject:

“KittyHawk is targeting the corporate guy with some Excel/Access savvy,” said one of my tipsters, who asked for anonymity. “It is a drag and drop, template-driven, visual designer….It’s not code-based, but you can write code if you want to.”

No. In the name of all that is good and decent and sane on this planet… NO. I can say with reasonable certainty that there is less than 6 degrees of separation between any developer and the nightmarish contrail flaming behind the zealous efforts of some corporate guy with Excel savvy. A tool that allows these people to do more damage is absolutely unwarranted.

Remember Microsoft Access? Remember when the corporate guys would grab Access so that they could harmlessly store some business information that pertained to their daily workflow? Remember, that was nice and before the apocalypse. Then, invariably, each one of these people started putting more and more mission-critical stuff into that DB and then they put GUIs on it. Then, because this was such a useful tool, they shared the app. This shared app then grew and grew until it became self-ware and literally devoured the entire office. Finally, as this story always ends the same way, someone from IT was tasked with converting this Access DB/Excel sheet/pile of sticky notes into a legitimate, supportable, maintainable application. It is a tale as old as time, and has no Disney ending where the prince and princess live happily ever after.

All joking aside, I think there’s a serious gap here between reality and the scenario Microsoft is attempting to enable. There is a huge gap between the type of things needed to support a corporate guy and their Excel spreadsheet and the type of things needed to build a real-world application that plays nicely on a corporate intranet. Giving non-developers a tool like this to build business applications and expect them to perform and behave and stay functional the same way that an app built by a real developer would is myopic at best. This is just my opinion, but it’s an opinion burned into my brain from having seen tools like this cause insane amounts of damage, lost time, and lost money.

Here’s to hoping nobody lets any of their corporate guys use KittyHawk.

Microsoft Releases Silverlight for Symbian

Microsoft today announced that they will be releasing Silverlight for Symbian. For those who don’t know, Symbian is another mobile operating system that runs on devices and smart phones that compete with Apple’s iPhone, Microsoft’s Windows Phone (and upcoming Windows Phone 7), and Android devices among others.

According to various websites, including Nokia, Silverlight will be running on the S60 5th edition phones, including the Nokia 5800 XpressMusic, Nokia N97 and Nokia N97 Mini.

What does this mean for developers? If you’re a Silverlight developer, this is fantastic news. This is yet another suite of mobile hardware against which you can target mobile application development. Because it’s Silverlight, the difference in programming paradigm and available tools between the various platforms (web, WP7, Symbian) will be minimal.

I have not personally downloaded the new Silverlight for Symbian development tools, but it sounds pretty awesome if you ask me. If you’re already doing your best to create clear separation of concerns in your applications and you don’t have any layer bleed and you have re-usable, core C# libraries that all of your Silverlight GUIs use, then you should be able to quickly and easily build a Symbian front-end for your Silverlight application.