The World’s Leading Microsoft .NET Magazine
   
 
The .NET Addict's Blog

My Top Tags

                                                           

My RSS Feeds








I heart FeedBurner

Latest Diggs - Programming

Computers Blogs - Blog Top Sites

Site Hits

Total: 4,889,478
since: 19 Jan 2005

Consuming an ASP.NET MVC POX Service from Cocoa

posted Mon 30 Jun 08

After giving up in my initial attempt to consume a WSDL service from the Mac, I decided to try out for myself what it would be like to consume a simple POX service (which is really nothing more than reading an XML document from disk or from an NSURL location). Turns out its really, really easy. 

The code is nearly line-for-line copied from Hillegass' book. What this means is that the sample uses the table view column identifier to store the XPath required to pull that column from an XML Node. This highlights exactly everything that I hate about books and code samples found online - sure, simple 'hello world' apps illustrate the syntax but they don't illustrate good patterns and practices. If you are learning from Hillegass' book, please take the time to convert his sample from using XPath column identifiers to using actual model objects that are loosely coupled from the underlying data source. Please, for the love of all that is decent about Cocoa.

Friends don't let friends code tightly coupled.

Here's the code that gets executed in response to pushing a fetch button in the demo app:

- (IBAction)fetchFoodStars:(id)sender
{
    [progress startAnimation:nil];

    NSString *urlString = @"http://testbox:9000/SampleData.mvc";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                             cachePolicy:NSURLRequestReturnCacheDataElseLoad
                        timeoutInterval:30];

    NSData *urlData;
    NSURLResponse *response;
    NSError *error;

    urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                    returningResponse:&response
                                                error:&error];
    if (!urlData)
    {
        NSAlert *alert = [NSAlert alertWithError:error];
        [alert runModal];
        return;
    }   

[doc release];
   doc = [[NSXMLDocument alloc] initWithData:urlData options:0 error:&error];

    if (!doc) {
        NSAlert *alert = [NSAlert alertWithError:error];
        [alert runModal];
        return;
    }   
    NSLog(@"Doc = %@", doc);
    [itemNodes release];

    itemNodes = [[doc nodesForXPath:@"//FoodNetworkStar" error:&error] retain];
    [tableView reloadData];
    [progress stopAnimation:nil];
}

Basically what this code is doing is opening a URL that's pointing at the location of my ASP.NET MVC application which has a controller that knows it should be dealing in POX and not HTML (turns out that is scary easy, as will be detailed in the next post). 

Then this code converts the XML document retrieved into an array of XML nodes. The app controller acts as the data source for the table view, using the identifier value of each table view column as a key to retrieving the XPath that will retrieve the value for that column. For example, the 'name' column has an identifier of '@name', which tells the controller to get the value for the name column from the @name XPath (the name attribute on the current XML node).

Below you can see the results after pushing the fetch button. The table view took care of the binding and the call to reloadData on the tableview updated the values.

This is dead simple stuff. As I mentioned before, you do NOT want to be putting XPath in the column identifiers for your table views - that's tightly coupled HACKing. What you should be doing is converting the XML from your service into instances of your local data model (which is datasource-agnostic, isn't it???) and then your table view's data source will access the local data model objects instead of raw XML nodes. Once you get into trying to allow the user to interactively edit data that came from a web service, you'll thank me for recommending the local data model conversion.

In the next post, I'll show you the source code to the ASP.NET MVC application and the controller that I used as a POX service host. You'll be surprised that it was quicker and easier to implement the POX controller in ASP.NET MVC than it would've been in Ruby on Rails!

tags:                  

links: digg this    del.icio.us    technorati    reddit

AddThis Social Bookmark Button




1. Denis Ahrens left...
Tue 01 Jul 08 6:35 am

I tried to use WSDL Service some days ago and it went really fine until I noticed that it is not available on the iPhone (but you can use it on the Simulator). So what was your problem with WSDL Service?


2. MrScrith left...
Tue 01 Jul 08 9:27 am

POX.... wasn't familiar with that term so I googled it... first thing that comes up were images of bodies covered in boils and sores... thanks a lot.. :P


3. james Gregurich left...
Tue 01 Jul 08 12:33 pm

Having to use MS tools is like having a pox...so, the name is appropriate. :)


4. Erik D. left...
Sat 05 Jul 08 2:28 am

A while again, when people wanted to say "not SOAP" they used REST, which didn't make much sense, so people started saying "Plain Old XML" ie. POX. http://en.wikipedia.org/wiki/Plain_Old_XML


5. jack left...
Wed 24 Dec 08 9:04 am

would this code work from iphone?


6. Kevin Hoffman left...
Wed 24 Dec 08 12:07 pm

To consume the service from the phone, if you stuck completely to the NSURL stuff and consuming it as raw XML and you don't use WSDL or anything else, then you should be good to go. Web Services Core isn't on the phone, so you need to stay at the low level.


7. Richard Walsh left...
Thu 11 Feb 10 11:12 pm

I have been working with this example as well as the original example from BigNerdRanch, but it seems I cannot for the life of me to get this methodolgy to work. I am trying to parse an element from the xml, ie <row name="John" location="Canada"></row>, using the @name on the identifier, but still nothing comes accross on the tableview.

Any help/advice would be greatly appreciated.


8. Kevin Hoffman left...
Fri 12 Feb 10 8:40 am

When parsing XML using SAX (push parsing), the events you get are different for attributes than for elements. I had similar troubles and just modified the XML output of my service to use nested elements instead of attributes... but I'm lazy like that :)


9. C#Ghost left...
Mon 22 Feb 10 8:20 pm :: http://vtd-xml.sf.net

You may want to look at vtd-xml, it claims to be the best performing XML parser/indexer/xpath engine available

http://vtd-xml.sf.net


Tag Related Posts

Html.JqGrid - Cleaning up your jqGrid Code

Tue 22 Dec 09 8:46 P GMT-05
tags:              

Would you like to touch my mono?

Mon 23 Nov 09 2:59 P GMT-05

How to Build your First Azure-Powered MVC App

Tue 29 Sep 09 2:16 P GMT-05
tags:        

ViewState is the Froo-It of the Dev-Il

Wed 23 Sep 09 3:09 P GMT-05
tags:      

Fix for Minor Bug in ASP.NET MVC New Project Template

Mon 04 May 09 2:48 A GMT-05
tags:      

Building RESTful Java Web Services with JAX-RS

Mon 23 Feb 09 8:42 P GMT-05
tags:                    

Know thine Enemy: RESTful Web Services in ... Java!

Sun 11 Jan 09 2:08 P GMT-05
tags:                    

Smart, Deep Property Notifications in CLINQ v2.0

Tue 07 Oct 08 1:15 P GMT-05
tags:          

Microsoft's Lofty Direction

Sun 05 Oct 08 2:30 P GMT-05

Apple drops the iPhone NDA for Released Software

Wed 01 Oct 08 3:54 P GMT-05
tags:          

Cappuccino, Objective-J, and You

Wed 10 Sep 08 6:14 P GMT-05

Enterprise Web Services Manifesto - Wire Formats

Tue 02 Sep 08 1:43 P GMT-05
tags:                

So I'm in the LA Times ;)

Wed 27 Aug 08 2:51 P GMT-05
tags:                  

MobileMe vs. Live Mesh Throwdown - Round 1

Wed 16 Jul 08 10:33 A GMT-05

Building Model Classes in C# and Cocoa

Sun 15 Jun 08 3:13 P GMT-05
tags:            

NYC SharePoint Developer Needed

Mon 12 May 08 12:09 P GMT-05

One Framework to Rule them All

Mon 25 Feb 08 6:49 P GMT-05

Scott Guthrie Updates the ASP.NET MVC Roadmap

Wed 13 Feb 08 3:49 P GMT-05
tags:    

Volta is to Ajax what Tums is to my Stomach

Wed 30 Jan 08 4:11 P GMT-05

LINQ to REST - A much better name for Astoria

Tue 11 Dec 07 1:23 P GMT-05
tags:        

ASP.NET 3.5 Extensions Preview Released

Mon 10 Dec 07 2:10 P GMT-05

Leopard Code Sample : Sprinkling in some Bonjour

Tue 27 Nov 07 2:32 P GMT-05
tags:        

Leopard Sample: A Bound NSCollectionView

Mon 29 Oct 07 1:41 A GMT-05

Leopard is out - let the code samples begin!

Fri 26 Oct 07 10:09 A GMT-05
tags: