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)

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

Wednesday, 19 December 2012

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

Part 2: Creating the Windows 8 App Now Up

This is part 1 of a simple blog to give you guys a heads up on the best way to connect a Windows 8 store app to a WCF RESTful service. I had some problems trying to get this working for a project I am on at work so thought I would share. All the source code for this project is available from my GitHub here.

This project was designed to be a quick a simple example to help others that maybe having the same problem. I started but firstly creating a Windows 8 Store application (we will look at this in more detail in part 2). If you haven't already you will need to ensure that you have a developer licence which is really easy to set up, if you don't have one Visual Studio will ask you to sign in when trying to create this application type. Some help with acquiring a developer licence.

Once I had the solution created I then went and added an additional project of WCF Service Application.In the past when I have done this I have used a specific project type for WCF RESTful service template that you can add to Visual Studio, but for this example I didn't have that to hand.

By choosing this template I had to do some more work to get it working the way I wanted. First things first I added a Global.asax top the service project and this is because I wanted to take advantage of the routing in ASP.NET and also because I have done  previous WCF RESTful services this way and I like the way it works. I then added a new route to the route table in the Global.asax.

        private void RegisterRoutes()
            RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Service1)));

Note: When adding this you may need to add a reference to System.ServiceModel.Activation to allow for the new Service Route.

The next thing I did was to update the config file to include the bindings, endpoints and behaviorConfigurations. Below is a small snippet of the config service endpoint for the full config check the solution.


The final thing on the service I did was implement the Service and operation contract. For this example I created an additional layer that generated 3 Goat objects that I would then be able to return from the service depending on the id passed.

Service Contract:
public interface IService1
    [WebGet (UriTemplate="Goat/{id}", ResponseFormat= WebMessageFormat.Json)]
    Goat GetGoatForId(string id);

Important things to note in the above code:
  • The use of WebGet on the method signature this is to specify the HTTP verb used for this method.
  • The URI template. This specifies the url you can use to access this method.
  • Note the type of the parameter in the signature. its string and this is because everything with URI's are string. however the id type of the object is an int, so we simple parse the id in the service method.
public class Service1 : IService1
    GoatService goatService = new GoatService();

    public Goat GetGoatForId(string id)
        return goatService.GetGoatFromID(int.Parse(id));    

A quick test in the browser to make sure that it is working with the URI template highlighted.

There we go a Simple WCF RESTful service ready and waiting for our Windows 8 Store app to consume, which I will follow up in Part 2 in the next few days.  

Quick Blog: Code Syntax Highlighting in blogs

Just found this little gem of a post

Following the quick steps in here got everything working quickly and I can now provide useful code snippets instead of screenshots. For Example:

// Start of Code.

for (int i = 0; i < 10; i++)
    Console.Writeline("Value of i: " + i);

// End Of Code.