Sunday, November 28, 2010

Consume REST service on Windows Phone 7

 

Windows Phone 7 (WP7) was out last month. It is a successor to Microsoft’s Mobile platform but completely different from Windows Mobile 6.5 or earlier version. That means no backward compatibility. The programming use Silverlight. For the detailed architecture overview of WP7, there is a great reference here: ecn.channel9.msdn.com/o9/te/NorthAmerica/2010/pptx/WPH313.pptx

The service is the same as the last post (Oct. 25).

Here is the code on the WP7(everything in Silverlight is synchronized):

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (txtSearch.Text != "")
            {
                string url = "http://localhost:8000/Users/Eric";
                WebClient proxy = new WebClient();
                proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);
                proxy.OpenReadAsync(new Uri(url));
            }
        }

        void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
            User foundUser = ser.ReadObject(e.Result) as User;
            if (null != foundUser)
            {
                txtUser.Text = foundUser.Name;          
            }
        }

These two namespaces need to be included for Json serialization:


using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

Monday, October 25, 2010

Why I choose REST over SOAP

REST is an architectural style when providing a service which focuses on resources. It is modeled after world wide web which is one of the greatest invention in the 21st century due to its scalability and ease of use. It is stateless means no client context being stored on the server between requests. SOAP is an XML/RPC based protocol. The biggest difference is scalability and complexity. Take a look of these two facts:
– 85% clients prefer Amazon RESTful API
– Google recently announced it would no longer support its SOAP/WSDL API
Because of the uniformity of REST, it is much easier to scale. WS-* (called WS splat) standards associated with SOAP based web services are EXTREMELY complicated. REST plus JSON (can use XML) encoding gave people an efficient and consistent way to provide and consume web services.
WCF in .NET 3.5 already support REST. .NET 4.0 provides more support via REST Starter Kit server components. Client component in starter kit didn’t make its way to .NET 4.0 but is available through a separate DLL.
Here is a simple REST service implemented in .NET 4.0:

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet(UriTemplate = "Users/{id}", ResponseFormat = WebMessageFormat.Json)]
        User GetUser(string id);
        [OperationContract]
        [WebInvoke(Method="POST", UriTemplate = "Users", ResponseFormat = WebMessageFormat.Json)]
        User PostUser(User user);
    }
    public class Service : IService
    {
        public User GetUser(string id)
        {
            return new User { ID = id, Name = "Demo User" };
        }
        public User PostUser(User user)
        {
            return new User { ID = user.ID, Name = "Hello, " + user.Name };
        }
    }
    [DataContract(Namespace = "")]
    public class User
    {
        [DataMember]
        public string ID { get; set; }
        [DataMember]
        public string Name { get; set; }
    }

The client sample is built on .NET 4.0 with the REST starter kit used on the client side (using Microsoft.Http):

            string baseUri = "http://localhost:8000/Users";
            string uri1 = baseUri + "/2";
            var client = new HttpClient();
            var user = new User() {ID="2", Name="Foo"};
            var content = HttpContentExtensions.CreateJsonDataContract<User>(user);
            HttpResponseMessage response = client.Post(new Uri(baseUri),content);
            using (content = response.Content as HttpContent)
            {
                string result = content.ReadAsString();
            }
            response = client.Get(new Uri(baseUri+"\\2"));
            using (content = response.Content as HttpContent)
            {
                string result = content.ReadAsString();
            }

REST service is based on HTTP stand and doesn’t have its own “standard,” that means it doesn’t have its own “flavor.” This has both pros and cons: the main pro is that it is not vendor dependent, as long as http is supported, it can be consumed as we can see in the client samples. The con is that since no proxy is generated, coding can be a little more than RPC/SOAP style when using a proxy. But this can be solved by using customized or vendor provided client REST support tools (e.g. Microsoft.Http and Microsoft.Http.Extensions).

Reference:

[1] http://www.iks.inf.ethz.ch/education/ss07/ws_soa/slides/SOAPvsREST_ETH.pdf

[2] http://msdn.microsoft.com/en-us/netframework/cc950529.aspx