Thursday, 20 December 2012

Connecting to a WCF RESTful service from a Windows 8 Store App: Part 2 Connecting to the WCF Service

Part 2 of this mini blog series which is simple example of how to connect a Windows 8 store app to a WCF RESTful service. In Part 1 I went and created a very simple WCF RESTful service that had one simple GET method that returned an object.

In the first Part I created a solution with 2 projects in it one a WCF Service Application and the other was a Windows 8 Store App. I decided to start with a blank XAML app and first things first I stuck in a quick bit of mark up to create a very simple user interface.


One thing I have included here is a nifty little thing I found which you now have to do compared to writing XAML for WPF. The highlighted line that sets the horizontal and vertical alignment on the control. This is because compared to the likes of WPF grid layout controls the content within them isn't set to fill the entire row or column by default. It auto sizes to the size of its content. However I prefer my grid controls to do the resize of its child controls for me if the window size changes and therefore this is why I have set them to stretch.

Anyway I digress once this is in place I created a button event that would do the call to the WCF RESTful service to get my data and then place it into a readonly TextBox

private void btnCall_Click(object sender, RoutedEventArgs e)
{
    CallService();
}

public async void CallService()
{
    HttpClient client = new HttpClient();
    string url = "http://localhost:59000/Goat/1";
    HttpResponseMessage response = await client.GetAsync(url);
    txtResponse.Text = await response.Content.ReadAsStringAsync();
}
The button calls another method that will do all the work to get JSON data back and place it into the TextBox. In the past I would have created a HttpWebRequest and set the headers and then created a HttpWebResponse for the response or use I would use the WebClient, however this isn't avalible for Windows RT so I had to use the new HttpClient object. In this very basic example all I do is create a HttpClient object I have the url for my service which is running on localhost as its in the same solution. I have however set the service to always run on port 59000.

The next thing that is happening is the client object fires the GetAsync method passing it the URL. The reason it is a GetAsync is because we are using the GET HTTP verb as that's what the WCF RESTful service created in part 1 is expecting. Now to use this method you require the async/await keywords and there is an good post that best describes these here

Now this is a simple example which is just showing the basics. Once I have had more time to play with this I may post a Part 3 to this blog which could contain other HTTP Verbs, Authentication and also look into what the method returns and doing more with the response.

Useful Links:
Part 1
Source Code

No comments:

Post a Comment