Click here to Skip to main content
15,878,852 members
Articles / Web Development / HTML
Tip/Trick

Using WCF Service in Windows Phone 8.1

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
3 Apr 2015CPOL5 min read 72.1K   549   5   12
This article will guide you how to using WCF service in Windows Phone.

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:

Image 1

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.

Image 2

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.

Image 3

Image 4

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:

Image 5

HTML
<!--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:

HTML
<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>
C#
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.

Image 6

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

Image 7

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:

HTML
<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.

Image 8

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

Image 9

Image 10

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:

Image 11

Step 2

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

Image 12

HTML
<!--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.

HTML
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.

Image 13 

Image 14

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
This article was originally posted at http://tungnt.net/using-wcf-service-in-windows-phone-8-1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect MISA JSC
Vietnam Vietnam
I'm a chief software architect at MISA JSC a software vendor from Ha Noi, Viet Nam, mostly working with Microsoft technologies, especially is Silverlight, Entity Framework, ASP.NET and more. I hold a BS degree in Computer Science obtained from VietNam National University, Ha Noi.
My hobbies are playing Badminton and listen to music in free time.

If you like my article, please visit my blog for more: http://tungnt.net

Comments and Discussions

 
QuestionError Pin
Member 102594031-Apr-16 7:22
Member 102594031-Apr-16 7:22 
AnswerRe: Error Pin
tungnt18510-Apr-16 9:02
tungnt18510-Apr-16 9:02 
QuestionGreat tutorial but how do i pass parameters do a php webservice Pin
Member 1050351424-Aug-15 6:59
Member 1050351424-Aug-15 6:59 
AnswerRe: Great tutorial but how do i pass parameters do a php webservice Pin
tungnt18525-Aug-15 15:53
tungnt18525-Aug-15 15:53 
QuestionThanks for the article!!! question though.. Pin
roger_2731-May-15 16:49
roger_2731-May-15 16:49 
AnswerRe: Thanks for the article!!! question though.. Pin
tungnt18531-May-15 20:37
tungnt18531-May-15 20:37 
GeneralRe: Thanks for the article!!! question though.. Pin
roger_271-Jun-15 19:03
roger_271-Jun-15 19:03 
GeneralRe: Thanks for the article!!! question though.. Pin
tungnt1851-Jun-15 22:00
tungnt1851-Jun-15 22:00 
Questionusing a Portable Class Library Pin
Arjan van dam20-Apr-15 18:52
Arjan van dam20-Apr-15 18:52 
AnswerRe: using a Portable Class Library Pin
tungnt18522-Apr-15 8:20
tungnt18522-Apr-15 8:20 
Hi Arjan,

A PCL project is usable in Windows Phone and Service project too.
I think your problem is the portable library selected profile does not match the target platform chosen for the service project that references it. Please try to check and change target of PCL as this link: https://msdn.microsoft.com/en-us/library/gg597391(v=vs.110).aspx[^]

Regards
Nguyen Thanh Tung
Questionhave you consider to post this as a tip? Pin
Nelek6-Apr-15 8:46
protectorNelek6-Apr-15 8:46 
AnswerRe: have you consider to post this as a tip? Pin
tungnt1857-Apr-15 22:41
tungnt1857-Apr-15 22:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.