Click here to Skip to main content
15,886,799 members
Articles / Programming Languages / C# 4.0
Article

Consuming WCF Service from Windows 7 Phone Application

Rate me:
Please Sign up or sign in to vote.
3.63/5 (7 votes)
16 May 2011CPOL3 min read 69.1K   2.5K   7   5
This article describes how you can consume WCF service from Windows 7 Phone Application

Introduction

This article focuses on how you can consume WCF Service from Windows Phone Application.

First Step – Writing a WCF Service

Run Visual Studio in Administrator mode and create New WCF Service Application.

IWin7MobileService.cs defines the interface of the WCF Service.

C#
namespace WcfServiceForWinMobile
{
  [ServiceContract]
  public interface IWin7MobileService
  {
    [OperationContract]
    void setString(string _str);

    [OperationContract]
    string getString();
  }
}

It has two methods which are essentially getter and setter methods.

Image 1

Win7MobileService.svc.cs is an implementation of the interface. The class contains a static data member and the implementation of the methods of the interface.

C#
namespace WcfServiceForWinMobile
{
  [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
  public class Win7MobileService : IWin7MobileService
  {
    static string str;

    public string getString()
    {
      return str;
    }

    public void setString(string _str)
    {
      str = _str;
    }
  }
}

Image 2

Web.config file defines essentially the <service> and <serviceBehaviors>. Make a note of the attributes of <service> and of <endpoint> tag.

XML
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <bindings />
    <client />
    <services>
      <service name="WcfServiceForWinMobile.Win7MobileService"
      behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="basicHttpBinding"
        contract="WcfServiceForWinMobile.IWin7MobileService"/>
        <endpoint address="mex" binding="mexHttpBinding"
        contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress=
		"http://192.168.1.3/WcfServiceForWinMobile/Win7MobileService.svc"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <directoryBrowse enabled="true"/>
  </system.webServer>
  <system.web>
    <compilation debug="true"/>
  </system.web>
</configuration>

Image 3

In your implementation, modify the <baseAddresses> tag with the IP address of the machine you write/deploy WCF Service on.

XML
<baseAddresses>
  <add baseAddress="http://{IP Address}/WcfServiceForWinMobile/Win7MobileService.svc"/>
</baseAddresses>

Second Step – Deploying WCF Service

I generally use IIS to deploy WCF Service, so you can consume WCF Service across a network. If you don’t have IIS installed on your system, I suggest you read “First Step: Deploying WCF Service” of my article http://www.codeproject.com/KB/webservices/WCFServiceAcrossNetwork.aspx.

In order to deploy WCF Service on your machine, right click the WCF Service Application project and go to Properties -> Web. Select “Use Local IIS Web Server” and click on Create Virtual Directory button. Now, if you want to check if the web service is deployed correctly or not, type http://localhost/WcfServiceForWinMobile/ in the browser and it should show you the following:

Image 4

Third Step – Consuming WCF Service using Windows 7 Phone Application

The mobile Client is similar to other desktop based clients consuming WCF Service. The notable difference here is that all WCF Service calls from Silverlight application are routed through asynchronous communications.

Create a new Windows Phone Application. Here, we will not modify manually any XAML code but will make use of toolbox for controls. As shown below, I’ve made use of TextBlock, TextBox and Button controls from toolbox.

Image 5

In order to consume deployed WCF Service, right click the project and select Add Service Reference. Enter the address of the WCF Service (i.e. http://{IP Address}/wcfserviceforwinmobile/win7mobileservice.svc?wsdl).

Image 6

This will create ServiceReferences.ClientConfig file in the project. Now you can utilize WCF Service in your Client application.

The following is the MainPage.xaml.cs code:

C#
namespace Win7SampleApp
{
  public partial class MainPage : PhoneApplicationPage
  {
    // Constructor
    public MainPage()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
      ServiceReference1.Win7MobileServiceClient client =
      	new ServiceReference1.Win7MobileServiceClient();

      if (nameTextBox.Text.Length != 0)
      {
        client.setStringAsync(nameTextBox.Text);
        client.getStringAsync();
        client.getStringCompleted+=new EventHandler
        <ServiceReference1.getStringCompletedEventArgs>(client_getStringCompleted);
      }
    }

    private void client_getStringCompleted
    (object sender, ServiceReference1.getStringCompletedEventArgs e)
    {
      nameTextBlock.Text = e.Result;
    }
  }
}

Image 7

As you can see in the code, on button click, we are creating a proxy object of the service. The getString() and setString() contract in the generated proxy is implemented with asynchronous methods. The asynchronous method getStringAsync() and an event client_getStringCompleted are raised when the operation has completed.

The event handler sets the textblock value which is essentially the response from WCF Service.

Now run the application and on button click you should see something similar to the following:

Image 8

Conclusion

This article demo-ed how you can create a WCF Service Application and deploy using IIS server. I used two different machines acting essentially as client and server for this demo and would suggest you try out the same.

History

  • 16th May, 2011: Initial post

License

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


Written By
Student
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Yoda0124-Jun-12 5:57
Yoda0124-Jun-12 5:57 
QuestionConfig Pin
ltl999912-Apr-12 16:08
ltl999912-Apr-12 16:08 
SuggestionThanks Pin
Fiachra Bonner11-Feb-12 9:28
Fiachra Bonner11-Feb-12 9:28 
GeneralMy vote of 3 Pin
eugene.smykov17-Jan-12 1:28
eugene.smykov17-Jan-12 1:28 
GeneralMy vote of 1 Pin
Selvin16-May-11 14:37
Selvin16-May-11 14:37 

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.