How to start with creating WCF services and test using WCFTestClient.exe

This article will give you an introduction to Windows communication foundation services and teach you how to create a WCF service library with basic WCF service example. And this will also tell you how to test WCF services using WCFTestClient.

Introduction to WCF services

With WCF services you can do all which you could do with ASMX web services, .Net remoting, use MSMQ for Message queuing, COM+ applications. Functionality of any combination of these technologies can be by using WCF services. WCF gives you several advantages over these technologies.

  1. You are not limited to use only one protocol. It allows you to with multiple protocols like HTTP, HTTPs, TCP/IP, and other network protocols. You can have the flexibility to switch protocols very easily.
  2. You can host your WCF service in multiple ways like in IIS, Windows Activation Service, Windows service, Console/Windows application, or self-hosting.
  3. It gives you the ability to provide more secure and reliable services.
  4. You can also send request, response messages using SOAP, REST.

How to create a Windows Communication Foundation Service:

Creating WCF service follow the below steps.

  1. Open visual studio – Click from menu File –> New -> Project
  2. Choose C#->WCF from the Installed template.
  3. Select the WCF service library.
  4. Now we will add our new product service by adding ServiceContract. Add new interface to the project by right clicking project in solution explorer – select Add- New Item- Interface. Name the interface as “IProducts”. Add using statement using System.ServiceModel to IProducts.
  5. Mark the interface as ServiceContracts.
                
    namespace NorthwindServices
    {
        [ServiceContract]
        public interface IProducts
        {
    
        }
    }
            
  6. Add methods to interface. In WCF the method which is accessible by thee client is called as OperationContract. Now you can add the OperationContracts for product interface.

                
    [ServiceContract] 
    public interface IProducts
    {   
        [OperationContract]
        public string GetProductName(int productID);
    
        [OperationContract]
        public int GetProductQty(int productID);
    
        [OperationContract]
        public string GetCategoryName(int productID);
    }
            
  7. Add a service class where you can write your operation logic. Add a new class to the project. Name it as ProductService. Inherit the service contract IProducts.

                
    public class ProductService : IProducts
    {
        public string GetProductName(int productID)
        {
            throw new NotImplementedException();
        }
    
        public int GetProductQty(int productID)
        {
            throw new NotImplementedException();
        }
    
        public string GetCategoryName(int productID)
        {
            throw new NotImplementedException();
        }
    }
            
  8. For this tutorial, we will use XML file as our datasource. Add a new XML file with name products.xml to C drive. Add the below data to file.

                
    <?xml version="1.0" standalone="yes"?>
    <DocumentElement>
      <Products>
        <productID>1</productID>
        <productname>Chai</productname>
        <categoryID>1</categoryID>
        <UnitsInStock>39</UnitsInStock>
        <CategoryName>Beverages</CategoryName>
      </Products>
      <Products>
        <productID>2</productID>
        <productname>Chang</productname>
        <categoryID>1</categoryID>
        <UnitsInStock>17</UnitsInStock>
        <CategoryName>Beverages</CategoryName>
      </Products>
      <Products>
        <productID>3</productID>
        <productname>Aniseed Syrup</productname>
        <categoryID>2</categoryID>
        <UnitsInStock>13</UnitsInStock>
        <CategoryName>Condiments</CategoryName>
      </Products>  
    </DocumentElement>
                            
            
  9. Add your method logic and return details. Basically you will implement the service contract here. Your complete service class would look like this.

                
    using System.Linq;
    using System.Xml.Linq;
    
    namespace NorthwindServices
    {
    public class ProductService : IProducts
    {
        public string GetProductName(int productID)
        {
            XDocument doc = XDocument.Load("C:\\products.xml");
    
            string productName =
                (from result in doc.Descendants("DocumentElement")
                .Descendants("Products")
                where result.Element("productID").Value 
                    == productID.ToString()  
                select result.Element("productname").Value)
                .FirstOrDefault<string>();
    
            return productName;
        } 
    
        public int GetProductQty(int productID)
        {
            XDocument doc = XDocument.Load("C:\\products.xml");
            int ProductQty = 0;
    
            string strProductQty = 
                (from result in doc.Descendants("DocumentElement")
                .Descendants("Products")
                where result.Element("productID").Value == productID.ToString()
                select result.Element("UnitsInStock").Value)
                .FirstOrDefault<string>();
    
            int.TryParse(strProductQty, out ProductQty); 
    
            return ProductQty;
        }
    
        public string GetCategoryName(int productID)
        {
            XDocument doc = XDocument.Load("C:\\products.xml");
    
            string categoryName = 
                (from result in doc.Descendants("DocumentElement")
                    .Descendants("Products")
                    where result.Element("productID").Value == productID.ToString()
                    select result.Element("CategoryName").Value)
                    .FirstOrDefault<string>();
    
            return categoryName;
        }
    }
    }
            
  10. Endpoint

    Using endpoint clients can communicate with service. The Endpoint is an access point for clients to service functionality. Endpoint contains Address, Bindings Contract which is commonly called Endpoints ABC.

    • Address

      Endpoint Address provides information about its location.

    • Binding

      Endpoint Binding specifies what kind of protocols should be used to communicate to clients.

    • Contract

      Endpoint Contracts gives details about what agreement needed between service and client means what operations are available for the client.

    Create an Endpoint for ProductService. Open App.config of service and locate <system.serviceModel><services>. Remove default endpoint for NorthwindServices.Service1 and add below <service> tag under <system.serviceModel><services>

                
    <service name="NorthwindServices.ProductService">
        <host>    
            <baseAddresses>
                <add baseAddress = "http://localhost:8732/Design_Time_Addresses
                    /NorthwindServices/ProductService/" />
            </baseAddresses>
        </host>
        <endpoint address ="" binding="wsHttpBinding" 
                            contract="NorthwindServices.IProducts">
            <identity>
                <dns value="localhost"/>
            </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" 
                    contract="IMetadataExchange"/>
    </service>
                            
        
  11. Testing WCF Service with WCFTestClient

    WCFTestClient is a simple GUI tool to test your WCF service. You can provide values to input parameters of service operations, invoke it, and see the response values. You can find the WCF Test Client (WcfTestClient.exe) at C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\

    For testing our ProductService run the application from the visual studio by pressing F5 and you will see the WCFTestClient with available operations.

    WCF Test Client

    Double click on any operation, provide value for the input parameter and click invoke. You will see the response in Response block.

    WCF Test Client with Operation Contracts

With this your service is ready for hosting WCF service in IIS or in hosting in Windows service.

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


  • geeksarray user
    08/05/2015 12:48 AM Ashu

    If I want to pass class object as parameter ..how would you do?

  • geeksarray user
    08/11/2015 01:33 AM Laxmikant

    you can use faultcontract with DataContract for more details see https://geeksarray.com/blog/handling-wcf-service-exceptions-using-fault-contracts

  • geeksarray user
    08/11/2015 01:34 AM Laxmikant

    sorry previous one was for FaultContract to handle exception for DataContract see below article https://geeksarray.com/blog/wcf-datacontract-with-enum-example

  • geeksarray user
    08/07/2016 03:07 PM Alan

    Excellent. Please add that the WCFTestClient (in Visual Studio 2015) will automatically run from the debugger (F5) only when the wcf service library is marked as the Startup project when there are multiple projects in the solution. Great tutorial.

  • geeksarray user
    12/28/2016 03:40 AM Kumar

    there is one more extra step that we need to do, attach the bindingConfiguration & behaviourConfiguration to endPoint in the app.config / web.config Thanks Kumar Vaddadi 9849230576

Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee