次の方法で共有


Connect Windows Phone 7 Apps to Wordpress using XMLRPC

post-xmlrpc

Download Code Samples

This post was originally published on my main blog: https://kevinashley.com

This is Part 1 of my Windows Phone connectivity series. Check out Part 2 on how to connect to Wordpress using JSON.

Many of us use Wordpress: it's an excellent platform for bloggers. Every time I start a new Web project, before deciding to build it from scratch, I try to consider Wordpress or other CMS to save time and effort. Wordpress plugins fills many gaps, including eCommerce, Membership, CMS and hundreds of other use cases. If you are used to building everything from scratch, you probably smell danger in this lego mentality. Well, it makes sense, considering that 60% of software projects fail on time and on the budget. The paradigm of “standing on the shoulders of the giants” suddenly makes sense in the risky business of building software!

As a Windows Phone app developer you probably wonder how can you connect your Windows Phone 7 app to your Wordpress blog? Wordpress' standard built-in mechanism is XMLRPC. If you care to read my next post I'll show you how you can use another popular mechanism: JSON to communicate with your favorite blog engine.

Which one is better? JSON currently requires a plugin to be installed for Wordpress. XMLRPC is built in. The choice is really what’s easier to you to work with in your Windows Phone application, and whether you want to install additional plugins.

Goals

In this project we’ll explore Windows Phone 7 connectivity with Wordpress using XMLRPC. We’ll build an app that retrieves a list of posts from Wordpress and shows them on our Windows Phone app.

Creating a Windows Phone 7 Project

We’ll create a Windows Phone 7 Panorama project. Panorama control is really cool Smile It started as an open source project on CodePlex and are now shipped as part of the Windows Phone Developer Tools. In Visual Studio, create a new Windows Phone Panorama Application.

image

Panorama control takes advantage of MVVM (Model-View-View-Model) pattern. If you haven’t heard of it, this wiki is a good starting point, but this pattern is great solid foundation for separating business logic from the presentation. Trust me, when you hit a few thousand lines, you will need a pattern like this, or you may get lost in the woods (code).

After building our template project, we’ll see something like this in the emulator. As you can see, our template loads sample items into our Panorama control. All this magic happens in the MainViewModel.cs file in the LoadData() method.

Using XMLRPC Library with Windows Phone 7

imageTake a look at XML-RPC.NET project by Charles Cook. This is a truly amazing and rich library that does fantastic job for integrating XMLRPC with .NET. The library supports both synchronous and asynchronous modes, mapping of XMLRPC method and struct member names to .NET compatible names,  code generation of type-safe client proxies , Silverlight and Windows Phone 7 , ASP.NET Web Services which support both XML-RPC and SOAP, client support for asynchronous calls , client support for various XML encodings and XML indentation styles (some other XML-RPC server implementations only accept certain indentation styles) , built-in support for XML-RPC Introspection API on server , dynamic generation of documentation page at URL of XML-RPC end-point and much much more!

Magical stuff! We’ll go to downloads, and let’s take a work in progress version (v 3.0.0+). At the time I’m writing this I recommend using version 3.0.0.241 or higher. Unzip this library and add a reference to CookComputing.XmlRpcPhone.dll to your project in Visual Studio. This assembly is a build of Charles Cook’s XML-RPC.NET library for Windows Phone.

After adding

 using CookComputing.XmlRpc;

your app can start using XML-RPC.NET classes.

Using MVVM classes to load posts from Wordpress

Our goal is to pull recent Wordpress posts into our Windows Phone 7 app and display them as items of our Panorama control. Panorama control template project automatically generates all Model-View-View-Model (MVVM) classes we need. Before we proceed further, let’s add another separate class to our project. We’ll call it WordpressWrapper. Remember to replace the url of your blog, username and password of your Wordpress user:

 using System.Reflection;
using CookComputing.XmlRpc;

[XmlRpcUrl(WordpressWrapper.BlogUrl)]
public class WordpressWrapper : XmlRpcClientProtocol
{
    public const string BlogUrl = "https://MYWORDPRESSURL/xmlrpc.php";

    [XmlRpcBegin("metaWeblog.getRecentPosts")]
    public IAsyncResult BeginGetRecentPosts(int blogid, string username, string password, int numposts, AsyncCallback acb)
    {
        return this.BeginInvoke(MethodBase.GetCurrentMethod(), new object[] { 0, username, password, numposts }, acb, null);
    }

    [XmlRpcEnd]
    public XmlRpcStruct[] EndGetRecentPosts(IAsyncResult iasr)
    {
        XmlRpcStruct[] ret = (XmlRpcStruct[])this.EndInvoke(iasr);
        return ret;
    }
}

Take a look at MainViewModel.cs, this class has a method called LoadData which simply inserts some sample data into the Panorama control. We’ll replace that with a call to our WordpressWrapper class as follows (remember to replace your user credentials in the below snippet):

 public void LoadData()
{
    WordpressWrapper proxy = new WordpressWrapper();
    proxy.BeginGetRecentPosts(0, "USER", "PASSWORD", 20, asr =>
    {
         ((App)App.Current).RootFrame.Dispatcher.BeginInvoke(delegate()
        {
            try
            {
                var posts = proxy.EndGetRecentPosts(asr);
                foreach (var post in posts)
                {
                    this.Items.Add(new ItemViewModel() { LineOne = (string)post["title"] });
                }

            }
            catch (Exception ex)
            {
                // Handle exception here
            }
        });
    });

    this.IsDataLoaded = true;
}

Compile your app and run it, et voila!

image

How Does It Work?

Let’s go back to our WordpressWrapper class.  Notice metaWeblog.getRecentPosts method supplied in the XmlRpcBegin attibute. You can supply any method that Wordpress supports. In fact Wordpress supports several XMLRPC APIs: Blogger API, metaWeblog API, and the Movable Type API. In our case we used metaWeblog API, but you can use any methods from the above APIs by simply adding more wrapper methods, just as I did with metaWeblog.getRecentPosts . Our method call returns a list of posts, and we need to provide a username for the blog, password and the number of posts to be retrieved.

 [XmlRpcBegin("metaWeblog.getRecentPosts")]
public IAsyncResult BeginGetRecentPosts(int blogid, string username, string password, int numposts, AsyncCallback acb)
{
    return this.BeginInvoke(MethodBase.GetCurrentMethod(), new object[] { 0, username, password, numposts }, acb, null);
}

We want to be a good non-blocking app, so I’m using asynchronous call pattern to make it work.

 [XmlRpcEnd]
public XmlRpcStruct[] EndGetRecentPosts(IAsyncResult iasr)
{
    XmlRpcStruct[] ret = (XmlRpcStruct[])this.EndInvoke(iasr);
    return ret;
}

When the method returns, I expect XmlRpcStruct to give me the result. XML-RPC.NET library provides an enhanced type mapping, which is beyond the scope of this essay, but I encourage you to check the documentation for some examples.

In our next post in this series I’ll show you how to do similar things using JSON.

Download Code Samples

Comments

  • Anonymous
    October 04, 2011
    Thanks