Using WCF Service in Windows Phone 8.1 - CodeProject

:

Introduction

From the previous post, you know how to write and configure the WCF Service to be used on mobile applications. If you do not know how to use WCF Service, let's review this article...

In this article, we will learn the last part about how to use WCF Service in Windows Phone 8.1.

Previously on Windows Phone 7, Windows Phone 8, Windows 8.1 the way to use WCF Service is relatively easy, you only need Add Service Reference then call generated functions that are defined in the WCF Service at code-behind. But in Windows Phone 8.1, everything seems a little bit strange because there will be two different ways to build applications for Windows Phone that use Silverlight core or Windows Runtime core. Now we'll take a detailed look at how to use WCF Service in Windows Phone 8.1: example source code is reused from the previous post which is a WCF service that has two functions GetMessage and PostMessage.

Using the Code

I) Using WCF Service on Windows Phone 8.1 Silverlight

First we will talk about how to use WCF Service in Windows Phone 8.1 Silverlight app. This approach can be applied on Windows Phone 7, Windows Phone 8, Windows 8.1 App or Desktop App (WinForms), Web App (ASP.NET, ASP.NET MVC ...) too.

Step 1

In the solution (created in previous article), we added blank Windows Phone 8.1 Silverlight app named WCFRESTDemo as shown below:

Step 2

Ctrl-F5 to run the WCF Service, the purpose of this step is to run WCF Service and we can find it by Add Service Reference in the next step.

Step 3

Right-click on References and select Add Service Reference. Then click Discover to find the service in the Solution. I'll see WCFRestDemo service, name it as WCFDemo and click OK.

Step 4

After 3 steps above, we have finished preparing WCF Service to use. Next, we need to design the interface of Windows Phone application to call the functions in this service. WCF Service only has two simple functions, so we will design UI to have two buttons and rename App name and Page name on MainPage.xaml like below:

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel"

            Grid.Row="0"

            Margin="12,17,0,28">
    <TextBlock Text="Tungnt.net WP8.1 Siverlight App"

               Style="{StaticResource PhoneTextNormalStyle}"

               Margin="12,0" />
    <TextBlock Text="WCF Demo"

               Margin="9,-7,0,0"

               Style="{StaticResource PhoneTextTitle1Style}" />
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel"

      Grid.Row="1"

      Margin="12,0,12,0">
    <StackPanel Orientation="Vertical">
        <Button Name="btnGetMessage"

                Content="GetMessage"

                HorizontalAlignment="Stretch"

                VerticalAlignment="Top"

                />
        <Button Name="btnPostMessage"

                Content="PostMessage"

                HorizontalAlignment="Stretch"

                VerticalAlignment="Top"

                />
    </StackPanel>
</Grid>

Step 5

On Designer, double-click two buttons to add click event handler. Then from these handlers, we call GetMessage and PostMessage functions of WCF Service like this:

<Grid x:Name="ContentPanel"

      Grid.Row="1"

      Margin="12,0,12,0">
    <StackPanel Orientation="Vertical">
        <Button Name="btnGetMessage"

                Content="GetMessage"

                HorizontalAlignment="Stretch"

                VerticalAlignment="Top"

                Click="btnGetMessage_Click" />
        <Button Name="btnPostMessage"

                Content="PostMessage"

                HorizontalAlignment="Stretch"

                VerticalAlignment="Top"

                Click="btnPostMessage_Click" />
    </StackPanel>
</Grid>
private void btnGetMessage_Click(object sender, RoutedEventArgs e)
{
    WCFRestDemoClient client = new WCFRestDemoClient();
    client.GetMessageCompleted += client_GetMessageCompleted;
    client.GetMessageAsync();
}

void client_GetMessageCompleted(object sender, GetMessageCompletedEventArgs e)
{
    if (e.Error == null)
    {
        MessageBox.Show(e.Result);
    }
}

private void btnPostMessage_Click(object sender, RoutedEventArgs e)
{
    WCFRestDemoClient client = new WCFRestDemoClient();
    client.PostMessageCompleted += client_PostMessageCompleted;
    client.PostMessageAsync("Nguyen Thanh Tung");
}

void client_PostMessageCompleted(object sender, PostMessageCompletedEventArgs e)
{
    if (e.Error == null)
    {
        MessageBox.Show(e.Result);
    }
}

At this point, everything has completed, right-click Windows Phone Project and choose Set as Startup, then press F5 to enjoy the fruits.

Click on the button GetMessage we will see a CommunicationException instead of message returned from WCF Service.

This exception occurs because in the previous post, we have only one Endpoint configuration for WCFRestDemo service that returns JSON (use webHttpBinding binding) so it’s not valid here. We need to add another Endpoint use basicHttpBinding binding to return data as SOAP/XML to use in this case. Open web.config file in the project Tungnt.NET.WCFRestDemo and edit as below:

<service name="Tungnt.NET.WCFRestDemo.WCFRestDemo">
  <endpoint name ="RESTEndPoint" contract ="Tungnt.NET.WCFRestDemo.IWCFRestDemo"

binding ="webHttpBinding" address ="rest" behaviorConfiguration ="restBehavior"/>
  <endpoint name ="SOAPEndPoint" contract ="Tungnt.NET.WCFRestDemo.IWCFRestDemo"

binding ="basicHttpBinding" address =""/>
</service>

The last step is to right-click WCFDemo Service Reference and update the service.

Finally F5 to run and now everything works like a charm.

Very simple and easy to implement, isn’t it?

II) Using WCF Service on Windows Phone 8.1 App Store/Universal App

We have just connected and used the WCF Service from Windows Phone 8.1 Silverlight app, everything is easy to implement because Visual Studio supports all for you. But with Windows Phone 8.1 App Store/Universal App with core Windows Runtime, things become more complicated because it no longer supports using the Add Service Reference and directly calls the WCF function again. We have to build and call WCF REST Service manually by the construction of HTTP GET/POST messages.

This approach is relatively new to those who have long been using the Add Service Reference method above. In my opinion, it seems that Microsoft has not completed this API yet because Windows 8.1 still supports Add Service Reference method but Windows Phone 8.1 does not. Everything might change when Windows 10 released but now the only way is to use the method mentioned above. Let's get started.

Step 1

Add another Windows Phone 8.1 App Store project to the WCFRESTDemo solution as shown below:

Step 2

Design the application interface similar to Windows Phone Silverlight apps, but change the App name to "App Store Tungnt.net WP8.1".

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel"

            Grid.Row="0"

            Margin="12,17,0,28">
    <TextBlock Text="Tungnt.net WP8.1 Store App"

               Style="{StaticResource TitleTextBlockStyle}"

               Margin="12,0" />
    <TextBlock Text="WCF Demo"

               Margin="9,-7,0,0"

               Style="{StaticResource HeaderTextBlockStyle}" />
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel"

      Grid.Row="1"

      Margin="12,0,12,0">
    <StackPanel Orientation="Vertical">
        <Button Name="btnGetMessage"

                Content="GetMessage"

                HorizontalAlignment="Stretch"

                VerticalAlignment="Top"

                Click="btnGetMessage_Click" />
        <Button Name="btnPostMessage"

                Content="PostMessage"

                HorizontalAlignment="Stretch"

                VerticalAlignment="Top"

                Click="btnPostMessage_Click" />
    </StackPanel>
</Grid>

Step 3

Similarly, we handle two buttons click event handler to call the WCF Service function. We will use HttpClient, HttpRequestMessage and HttpResponseMessage classes (in System.Net.Http namespace) to send and receive data by REST.

I will create a common function to call WCF REST Service named WCFRESTServiceCall.
Note: URI is the URL of WCFRestDemo service + function name like PostMessage or GetMessage.

private async void btnGetMessage_Click(object sender, RoutedEventArgs e)
{
    string result = await WCFRESTServiceCall("GET", "GetMessage");
    var dialog = new MessageDialog(result);
    await dialog.ShowAsync();
}

private async void btnPostMessage_Click(object sender, RoutedEventArgs e)
{
    string result = await WCFRESTServiceCall("POST", "PostMessage","\"Nguyen Thanh Tung\"");
    var dialog = new MessageDialog(result);
    await dialog.ShowAsync();
}

/// <summary>
/// Utility function to get/post WCFRESTService
/// </summary>
/// <param name="methodRequestType">RequestType:GET/POST</param>
/// <param name="methodName">WCFREST Method Name To GET/POST</param>
/// <param name="bodyParam">Parameter of POST Method (Need serialize to JSON before passed in)</param>
/// <returns>Created by tungnt.net - 1/2015</returns>
private async Task<string> WCFRESTServiceCall(string methodRequestType, string methodName, string bodyParam = "")
{
    string ServiceURI = "http://localhost:34826/WCFRestDemo.svc/rest/" + methodName;
    HttpClient httpClient = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage(methodRequestType == "GET" ? HttpMethod.Get : HttpMethod.Post, ServiceURI);
    if (!string.IsNullOrEmpty(bodyParam))
    {
        request.Content = new StringContent(bodyParam, Encoding.UTF8, "application/json");
    }
    HttpResponseMessage response = await httpClient.SendAsync(request);
    string returnString = await response.Content.ReadAsStringAsync();
    return returnString;
}

We've built Windows Phone 8.1 application to WCF REST Service, please F5 to run the test and everything works fine.

 

Points of Interest

In this article, we explored how to use WCF Service on Windows Phone application. Step by step, we know how to use WCF Service on two types of applications: Windows Phone 8.1 Silverlight and Windows Phone 8.1 App Store. Each way has pros and cons so you should consider using them in your application as per your requirements.

  • Add Service Reference easy to implement but it cannot be used for Windows Phone 8.1 App Store and performance is not good as using WCF REST Service returns JSON
  • Create GET/POST message and use HttpClient, HttpRequestMessage, HttpResponseMessage to call WCF Service is harder to implement and you need to write more code but support on Windows Phone 8.1 App Store and better performance by using JSON

Hopefully, this article will be helpful to you when building Windows Phone applications to use cloud server to store data.

If you have any questions or experiences, please share in the comments section below.

History

  • 1st April, 2015: Initial version