Using WCF Service in Windows Phone 8.1

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

In the previous article you learned how to write and configure the WCF Service to be used on mobile applications. If you do not know how to use a WCF Service then let's review this article:

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

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

Step 1: In the solution (created in the previous article) we added a 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 a 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, named it is WCFDemo and click OK.





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


  1. <!--TitlePanel contains the name of the application and page title-->  
  2. <StackPanel x:Name="TitlePanel"  
  3.             Grid.Row="0"  
  4.             Margin="12,17,0,28">  
  5.     <TextBlock Text="Tungnt.net WP8.1 Siverlight App"  
  6.                Style="{StaticResource PhoneTextNormalStyle}"  
  7.                Margin="12,0" />  
  8.     <TextBlock Text="WCF Demo"  
  9.                Margin="9,-7,0,0"  
  10.                Style="{StaticResource PhoneTextTitle1Style}" />  
  11. </StackPanel>  
  12. <!--ContentPanel - place additional content here-->  
  13. <Grid x:Name="ContentPanel"  
  14.       Grid.Row="1"  
  15.       Margin="12,0,12,0">  
  16.     <StackPanel Orientation="Vertical">  
  17.         <Button Name="btnGetMessage"  
  18.                 Content="GetMessage"  
  19.                 HorizontalAlignment="Stretch"  
  20.                 VerticalAlignment="Top"  
  21.                 />  
  22.         <Button Name="btnPostMessage"  
  23.                 Content="PostMessage"  
  24.                 HorizontalAlignment="Stretch"  
  25.                 VerticalAlignment="Top"  
  26.                 />  
  27.     </StackPanel>  
  28. </Grid>  
Step 5: On the Designer double-click the two buttons to add a click event handler. Then from these handlers we call the GetMessage and PostMessage functions of the WCF Service like this:
  1. <Grid x:Name="ContentPanel"  
  2.       Grid.Row="1"  
  3.       Margin="12,0,12,0">  
  4.     <StackPanel Orientation="Vertical">  
  5.         <Button Name="btnGetMessage"  
  6.                 Content="GetMessage"  
  7.                 HorizontalAlignment="Stretch"  
  8.                 VerticalAlignment="Top"  
  9.                 Click="btnGetMessage_Click" />  
  10.         <Button Name="btnPostMessage"  
  11.                 Content="PostMessage"  
  12.                 HorizontalAlignment="Stretch"  
  13.                 VerticalAlignment="Top"  
  14.                 Click="btnPostMessage_Click" />  
  15.     </StackPanel>  
  16. </Grid>  
  1. private void btnGetMessage_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.     WCFRestDemoClient client = new WCFRestDemoClient();  
  4.     client.GetMessageCompleted += client_GetMessageCompleted;  
  5.     client.GetMessageAsync();  
  6. }  
  7.   
  8. void client_GetMessageCompleted(object sender, GetMessageCompletedEventArgs e)  
  9. {  
  10.     if (e.Error == null)  
  11.     {  
  12.         MessageBox.Show(e.Result);  
  13.     }  
  14. }  
  15.   
  16. private void btnPostMessage_Click(object sender, RoutedEventArgs e)  
  17. {  
  18.     WCFRestDemoClient client = new WCFRestDemoClient();  
  19.     client.PostMessageCompleted += client_PostMessageCompleted;  
  20.     client.PostMessageAsync("Nguyen Thanh Tung");  
  21. }  
  22.   
  23. void client_PostMessageCompleted(object sender, PostMessageCompletedEventArgs e)  
  24. {  
  25.     if (e.Error == null)  
  26.     {  
  27.         MessageBox.Show(e.Result);  
  28.     }  
  29. }  
At this point everything has completed, right-click the 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 a message returned from WCF Service as in the following:
 

 
This exception occurs because in the previous article we have only one Endpoint configuration for the WCFRestDemo service returns JSON (use webHttpBinding binding) so it's not valid here. We need to add another Endpoint that uses a basicHttpBinding binding to return data as SOAP/XML to use in this case. Open the web.config file in the project Tungnt.NET.WCFRestDemo and edit as in the following:
  1. <Service name = "Tungnt.NET.WCFRestDemo.WCFRestDemo">  
  2.         <Endpoint name = "RESTEndPoint" contract = "Tungnt.NET.WCFRestDemo.IWCFRestDemo" binding = "webHttpBinding" address = "rest" beha                           viorConfiguration = "restBehavior" />  
  3.         <Endpoint name = "SOAPEndPoint" contract = "Tungnt.NET.WCFRestDemo.IWCFRestDemo" binding = "basicHttpBinding" address = "" />  
  4. </ Service>  
The last step is to right-click WCFDemo Service Reference and update the service.



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





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

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 need to build and call the 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 itn seems that Microsoft has not completed this API yet because Windows 8.1 still supports the Add Service Reference method but Windows Phone 8.1 does not. Everything might change when Windows 10 release but for now the only way we have is using the method said 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".


  1. <!--TitlePanel contains the name of the application and page title-->  
  2. <StackPanel x:Name="TitlePanel"  
  3.             Grid.Row="0"  
  4.             Margin="12,17,0,28">  
  5.     <TextBlock Text="Tungnt.net WP8.1 Store App"  
  6.                Style="{StaticResource TitleTextBlockStyle}"  
  7.                Margin="12,0" />  
  8.     <TextBlock Text="WCF Demo"  
  9.                Margin="9,-7,0,0"  
  10.                Style="{StaticResource HeaderTextBlockStyle}" />  
  11. </StackPanel>  
  12.   
  13. <!--ContentPanel - place additional content here-->  
  14. <Grid x:Name="ContentPanel"  
  15.       Grid.Row="1"  
  16.       Margin="12,0,12,0">  
  17.     <StackPanel Orientation="Vertical">  
  18.         <Button Name="btnGetMessage"  
  19.                 Content="GetMessage"  
  20.                 HorizontalAlignment="Stretch"  
  21.                 VerticalAlignment="Top"  
  22.                 Click="btnGetMessage_Click" />  
  23.         <Button Name="btnPostMessage"  
  24.                 Content="PostMessage"  
  25.                 HorizontalAlignment="Stretch"  
  26.                 VerticalAlignment="Top"  
  27.                 Click="btnPostMessage_Click" />  
  28.     </StackPanel>  
  29. </Grid>  
Step 3: Similarly we handle two button's click event handler to call the WCF Service function. We will use the HttpClient, HttpRequestMessage and HttpResponseMessage classes (in the System.Net.Http namespace) to send and receive data by REST.

I will create a common function to call the WCF REST Service named WCFRESTServiceCall. Note: URI is the URL of WCFRestDemo service + function name like PostMessage or GetMessage.
  1.  private async void btnGetMessage_Click(object sender, RoutedEventArgs e)   
  2. {  
  3.     string result = await WCFRESTServiceCall("GET", "GetMessage");  
  4.     var dialog = new MessageDialog(result);  
  5.     await dialog.ShowAsync();  
  6. }  
  7.   
  8. private async void btnPostMessage_Click(object sender, RoutedEventArgs e)   
  9. {  
  10.     string result = await WCFRESTServiceCall("POST", "PostMessage", "\"Nguyen Thanh Tung\"");  
  11.     var dialog = new MessageDialog(result);  
  12.     await dialog.ShowAsync();  
  13. }  
  14.   
  15. /// <summary>  
  16. /// Utility function to get/post WCFRESTService  
  17. /// </summary>  
  18. /// <param name="methodRequestType">RequestType:GET/POST</param>  
  19. /// <param name="methodName">WCFREST Method Name To GET/POST</param>  
  20. /// <param name="bodyParam">Parameter of POST Method (Need serialize to JSON before passed in)</param>  
  21. /// <returns>Created by tungnt.net - 1/2015</returns>  
  22. private async Task < string > WCFRESTServiceCall(string methodRequestType, string methodName, string bodyParam = "")   
  23. {  
  24.     string ServiceURI = "http://localhost:34826/WCFRestDemo.svc/rest/" + methodName;  
  25.     HttpClient httpClient = new HttpClient();  
  26.     HttpRequestMessage request = new HttpRequestMessage(methodRequestType == "GET" ? HttpMethod.Get : HttpMethod.Post, ServiceURI);  
  27.     if (!string.IsNullOrEmpty(bodyParam))   
  28.     {  
  29.         request.Content = new StringContent(bodyParam, Encoding.UTF8, "application/json");  
  30.     }  
  31.     HttpResponseMessage response = await httpClient.SendAsync(request);  
  32.     string returnString = await response.Content.ReadAsStringAsync();  
  33.     return returnString;  
  34. }  
We've built a Windows Phone 8.1 application to WCF REST Service, please press F5 to run the test and everything will work fine.





Conclusion

In this article we explored how to use a WCF Service in a Windows Phone application. This article showed step-by-step how to use a WCF Service in 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 for your fit.
  • Add Service Reference is easy to implement but it cannot be used for Windows Phone 8.1 App Store and performance not good as using WCF REST Service returns JSON.
  • Create GET/POST message and use HttpClient, HttpRequestMessage and HttpResponseMessage to call a WCF Service is harder to implement and you need to write more code but has support by the Windows Phone 8.1 App Store and better performance using JSON.
Hopefully this article has helped you when building Windows Phone applications to use a cloud server to store data.

If you have any questions or experience then please share in the comments below the article and if you find it useful, please share it with your friends.

Happy coding. Stay tuned.

P.S.: You can download the example source code here: WCFRESTDemoFinal