Click here to Skip to main content
Click here to Skip to main content

Calling WCF Service Across a Network

, 14 May 2011
Rate this:
Please Sign up or sign in to vote.
This article describes how you can call WCF service from a remote machine

Introduction

This article focuses on how you can utilize WCF Service across a network. Invoking WCF Service on the same machine is pretty straightforward but when you want to access it over a network, things get complex and you need to follow certain steps to make it happen.

In this demo, I’ll also show you how you can transfer large data across a network. I’ll not dive into much depth of issues such as security and data transfer.

The goal of this article is to let the reader have a basic understanding of steps required to invoke WCF service dataprocessing large across a network. (Consider images, files, etc. as large data).

Beginning

Two machines are required, one for deploying WCF Service and another acting as a Client. Don’t forget to run Visual Studio in Administrator mode since WCF Service’s deployment requires administrator privileges.

First Step – Deploying WCF Service

If you don’t know anything about WCF, I strongly recommend you to refer to MSDN documentation on WCF Service.

Create a new WCF Service Application project.

All WCF service code is located in IService1.cs file. The service interface provides three methods. I’m using Byte in order to show that this example can also work for images.

namespace WcfService
{
  [ServiceContract]
  public interface IService1
  {
    [OperationContract]
    void setValue(Byte bval);

    [OperationContract]
    Byte getValue(int index);

    [OperationContract]
    int lengthOfVal();
  }
}

Service1.cs class inherits IService1 interface and provides the associated functionality of the methods declared in IService1 interface. It also contains static data member that is list of bytes.

namespace WcfService
{
  [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
  public class Service1 : IService1
  {
    static List<Byte> byteList = new List<Byte>();

    public void setValue(Byte bval)
    {
      byteList.Add(bval);
    }

    public Byte getValue(int index)
    {
      return byteList[index];
    }

    public int lengthOfVal()
    {
      return byteList.Count;
    }
  }
}

As you can see, I’ve used AddressFilterMode that is used to route incoming messages to the correct endpoint. This is generally used if you encounter the following error:

The message with To 'http://……./Service1.svc' cannot be processed at the receiver, 
due to an AddressFilter mismatch at the EndpointDispatcher. 
Check that the sender and receiver's EndpointAddresses agree. 

Web.config file is the main settings and configuration file for WCF Service Application. As you can see, I’ve used <service> tag which specifies WcfService application that has <endpoint> tag required to form a connection point to the service.

I’ve used basicHttpBinding instead of wsHttpBinding just for demo purposes. Basichttpbinding provides fewer security options than wsHttpBinding and is not recommended. For more understanding on bindings in WCF, refer to MSDN.

The <baseAddress> tag specifies the location of the WCF Service. Use IP address of the machine you want to deploy this service on in place of localhost. The <behaviors> tag is also required that describes the <serviceBehavior>.

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="WcfService.Service1" behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="basicHttpBinding" contract="WcfService.IService1"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://{Enter IP Address}/WcfService/Service1.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>

Make sure IIS is installed on your system. If not, go to Programs, Turn Windows features on or off and then select IIS to install all the features of IIS. Also make sure you select Microsoft .NET Framework that is in Turn Windows features on or off for enabling HTTP features.

Still, IIS is not completely installed and if you try to deploy any service using IIS, it will not succeed and will show the following error:

For this, run command prompt as an administrator. Go to C:\Windows\Microsoft.NET\Framework64\v4.0\ (v4.0 or whichever is installed on your machine) and run command “aspnet_regiis.exe –i”. This will successfully install ASP.NET and you are ready for deploying your service now.

Now right click your project and go to Properties and click on Web. Select “Use Local IIS Web Server” and click on Create Virtual Directory Button.

Now try to run the project and see if browser opens showing you the WCF Service deployed and ready for use by Client. Turn off Firewall on machine the service is deployed on (not recommended though, just for this demo purpose, so use other type of bindings).

Second Step – Invoking WCF Service through Remote Client

You can deploy multiple clients and use them to access WCF Service. However, this is concerned with Threading and Synchronization issue as in general scenario multiple clients access same service functionality.

Here, I’m using two clients that access get and set functionality respectively and both are deployed on the same machine.

Create a new C# Console application. Right click the project and click on add service reference. In Address text box, enter the WcfService address. (eg. http://{IP Address}/WcfService/Service1.svc?wsdl). This will add app.config file in the client project.

Two files are required for generating proxies. Service utility tool is used to generate these proxies. This is usually located in C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin. Run the following command to generate the proxy files:

Svcutil.exe http://{IP Address}/WcfService/Service1.svc?wsdl 

This will create two files, Service1.cs and output.config. Copy the contents of output.config file in app.config file and add Service1.cs file in the client project. Now your client is ready for communicating with the web service.

WcfClient project is used to set the data members of WcfService.

namespace WcfClient
{
    class Program
    {
        static void Main(string[] args)
        {            
            Service1Client client = new Service1Client();
            client.Open();
            for (long i = 0; i < 20000; ++i)
            {
                client.setValue((Byte)i);
            }
            client.Close();
            Console.WriteLine("Press Enter");
            Console.Read();
        }
    }
}

Create a client and use setter method to set the list of bytes data member on Service. Here I’m transferring 20 KB of data to Service. General PNG images are around 200 KB. You can transfer byte by byte to service and thus can transfer the whole file to Server.

Run the project till it transfers data completely to Service.

Now, create another client by selecting New C# Console Application in the same project. WcfClientRead is used to access the data on service. Add the same two proxy files in this project as in WcfClient.

namespace WcfClientRead
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1Client client = new Service1Client();
            int length = client.lengthOfVal();
            for (int i = 0; i < length; ++i)
            {
                Console.WriteLine(client.getValue(i));
            }
            client.Close();
            Console.WriteLine("Press Enter");
            Console.Read();
        }
    }
}

This will print the values of the list of bytes data member on console.

Conclusion

Thus you saw how remote clients can access WCF Service across the network. The basic stuff to keep in mind is using the correct binding, service behavior in Web.config file and making sure IIS is properly installed on machine.

History

  • 14th May, 2011: Initial post

License

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

About the Author

Priyank Kabaria
Student
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmember$andesh M Patil4-Sep-13 3:58 
QuestionCannot get data persistence with WCF test client. PinmemberBlueBanana23-Feb-13 10:56 
This is a very helpful example. One thing I can't figure out is why when I run the service in the WCF test client of Visual Studio 2012 it works perfectly but when I write something similar myself the data doesn't persist.
 
In the example given the Service1 class maintains a static list of bytes. If you run the test client and test the setValue method a few times then you can use the getValue method and get back the bytes you stored earlier.
 
My program does much the same but maintains a static dictionary. When I run the test client on this then I can add as many items to the dictionary as I like but can never retrieve them. The dictionary is always empty at the point any of the methods are called. It is as if you are staring afresh with a new instance of the class every time a method is tested. However, the methods of my class do work. I have stepped through them and they are manipulating the dictionary correctly.
 
Is there a setting somewhere that turns on persistence? My web.config file looks very much like the example given.
GeneralMy vote of 1 PinmemberMahesh Reddy Yenugu14-May-12 21:33 
GeneralRe: My vote of 1 Pinmembervictorbos2-Jun-13 3:47 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 14 May 2011
Article Copyright 2011 by Priyank Kabaria
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid