WCF Step by Step Tutorial

1. Basics of WCF
2. Download – Source Code
3. Download WCF Tutorial – PDF document

Basics of WCF

Definition of WCF 

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF we can build secure, reliable, transacted solutions that integrate across platforms.

WCF is a unified framework which provides :

1. NET Remoting 2.Distributed Transactions 3.Message Queues and 4.Web Services into a single service-oriented programming model for distributed computing.

WCF interoperate between WCF-based applications and any other processes that communicate via SOAP (Simple Object Access Protocol) messages.

Features of WCF

  1. Service Orientation
  2. Interoperability
  3. Multiple Message Patterns
  4. Service Metadata
  5. Data Contracts
  6. Security
  7. Multiple Transports and Encodings
  8. Reliable and Queued Messages
  9. Durable Messages
  10. Transactions
  11. AJAX and REST Support
  12. Extensibility
To know more about features of WCF see: http://msdn.microsoft.com/en-us/library/ms733103.aspx

Terms of WCF
A WCF service is exposed to the outside world as a collection of endpoints.
1. Endpoint: Endpoint is a construct at which messages are sent or received (or both). Endpoint comprises of ABC’s       
What are ABC’s of WCF ? 
A. Address - Address is a location that defines where messages can be sent
B. Binding - Binding is a specification of the communication mechanism (a binding) that described how messages should be sent
C. Contract - Contract is a definition for a set of messages that can be sent or received (or both) at that location (a service contract) that describes what message can be sent.

2. Service: A construct that exposes one or more endpoints, with each endpoint exposing one or more service operations.

3. Contracts: A contract is a agreement between two or more parties for common understanding and it is a is a platform-neutral and standard way of describing what the service does. In WCF, all services expose contracts.

Types of Contracts:
1) Operation Contract: An operation contract defines the parameters and return type of an operation.

[OperationContract]
double Add(double i, double j);

2) Service Contract: Ties together multiple related operations contracts into a single functional unit.

[ServiceContract] //System.ServiceModel
public interface IMath
{
    [OperationContract]
    double Add(double i, double j);
    [OperationContract]
    double Sub(double i, double j);
    [OperationContract]
    Complex AddComplexNo(Complex i, Complex j);
    [OperationContract]
    Complex SubComplexNo(Complex i, Complex j);
}

3) Data Contract: The descriptions in metadata of the data types that a service uses.

// Use a data contract
[DataContract] //using System.Runtime.Serialization
public class Complex
{
    private int real;
    private int imaginary;

    [DataMember]
    public int Real { get; set; }

    [DataMember]
    public int Imaginary { get; set; }
}

WCF Step by Step Tutorial

 

This is the Basic WCF Tutorial ‘wcfMathSerLib’ will be created in a step by step approach. This ‘wcfMathSerLib’ will be tested by ‘ConsoleMathClient’ and with ‘WCF Test Client’

Steps for creating wcfMathSerLib

1. Open Visual Studio 2010 and File->NewProject
2.select WCF in ‘Recent Templates’
3.select ‘WCF Service Library’
4.Give Name as wcfMathServiceLibrary
5.Click OK

Image(1)

2. Delete IService1.cs and Service1.cs

Image(2)

3. Add IMath.cs and MathService.cs and add the code listed below

Image(3)

IMath.cs


using System.Runtime.Serialization;
using System.ServiceModel;

namespace WcfMathServLib
{
    [ServiceContract] //System.ServiceModel
    public interface IMath
    {
        [OperationContract]
        double Add(double i, double j);
        [OperationContract]
        double Sub(double i, double j);
        [OperationContract]
        Complex AddComplexNo(Complex i, Complex j);
        [OperationContract]
        Complex SubComplexNo(Complex i, Complex j);
    }

    // Use a data contract
    [DataContract] //using System.Runtime.Serialization
    public class Complex
    {
        private int real;
        private int imaginary;

        [DataMember]
        public int Real { get; set; }

        [DataMember]
        public int Imaginary { get; set; }
    }
}

MathService.cs

    namespace WcfMathServLib
    {
        public class MathService : IMath
        {

            public double Add(double i, double j)
            {
                return (i + j);
            }

            public double Sub(double i, double j)
            {
                return (i - j);
            }

            public Complex AddComplexNo(Complex i, Complex j)
            {
                Complex result = new Complex();
                result.Real = i.Real + j.Real;
                result.Imaginary = i.Imaginary + j.Imaginary;
                return result;
            }

            public Complex SubComplexNo(Complex i, Complex j)
            {
                Complex result = new Complex();
                result.Real = i.Real - j.Real;
                result.Imaginary = i.Imaginary - j.Imaginary;
                return result;
            }
        }
    }
    

4.Modify the App.config file as shown

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.web>
    <compilation debug="true" />
  </system.web>

  <system.serviceModel>
    <services>
      <service name="WcfMathServLib.MathService">

        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8732/Design_Time_Addresses/WcfMathServLib/MathService/" />
          </baseAddresses>
        </host>

        <!-- Service Endpoints -->
        <endpoint address ="" binding="wsHttpBinding" contract="WcfMathServLib.IMath">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>

        <!-- Metadata Endpoints -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>

      <serviceBehaviors>
        <behavior>
           <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>

</configuration>


Result Using WCF Test Client

1. Run the WcfMathServLib project you will get the ‘WCF Test Client’
2. Select each method say ‘AddComplexNo’ Give the values in ‘Request’
3. Click on Invoke button
4. See the results in “Response”

Image(4)

Steps for creating ConsoleMathClient

1. Open Visual Studio 2010 and File->NewProject
2. select Visual C#->Windows in ‘Installed Templates’
3. select ‘Console Application’
4. Give Name as ConsoleMathClient
5. Click OK

image

2. Go to ‘Solution Explorer’ Right click on ConsoleMathClient -> Select ‘Add Service
Reference’ the below dialog will be displayed
1. Click on Discover button
2. Give namespace as ‘MathServiceReference’ and click OK

image

The service reference will be added now modify the program.cs as shown below.

Program.cs

using System;
using ConsoleMathClient.MathServiceReference;

namespace ConsoleMathClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press <Enter> to run the client....");
            Console.ReadLine();

            MathClient math = new MathClient();
            Console.WriteLine("Add of 3 and 2 = {0}", math.Add(3, 2));
            Console.WriteLine("Sub of 3 and 2 = {0}", math.Sub(3, 2));

            Complex no1 = new Complex();
            no1.Real = 3;
            no1.Imaginary = 3;

            Complex no2 = new Complex();
            no2.Real = 2;
            no2.Imaginary = 2;

            Complex result = new Complex();
            result = math.AddComplexNo(no1, no2);
            Console.WriteLine("Add of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);

            result = math.SubComplexNo(no1, no2);
            Console.WriteLine("Sub of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);

            Console.ReadLine();
        }
    }
}

Result

Compile and Run the project to see the Result

image

112 thoughts on “WCF Step by Step Tutorial

  1. Pingback: WCF Step by Step Tutorial « TNV Balaji …

  2. Pingback: Basics of WCF «

  3. I had to enter the url when adding the service reference. Just clicking on the “Discover” button without the url found nothing even though the service was running.
    I also don’t understand where the definition for MathClient comes from. How does the system know to create a name like MathClient?

  4. You are a legend !
    I have never seen it this simple , and everything works as expected . oh and thank you Daniel for “MathClient is from
    using ConsoleMathClient.MathServiceReference;”

  5. I still don’t understand where ‘MathClient’ comes from. If I want to change this name ( to ‘MonkeyClient’ or something like that) then what do I have to do ?

    Thanks

    • The “Add Service Reference” adds a proxy class. The name is determined by taking the service contract name, getting rid of the ‘I’ prefix and adding the “Client” suffix. The proxy class allows you to talk to the service without having to create a channel factory, which requires more code. To see the code, click “View all files” in Solution Explorer.

  6. Hi, Thanks for this awesome tutorial.
    Am just starting with wcf for a project, and being an intern, it’s doubly hard for me. You have simplified my task tremendously, and this tutorial explains the concepts with much clarity.
    Just one problem that I had: I had to add the Console Project to the same solution, otherwise it would not work!

    Maybe it’s unique to my case, nevertheless, Absolutely Awesome Work! :)

  7. Thank you for the explanation. But I had a problem when I test with ConsoleMathClient: when I entered the address and I click “Discover”, the following message:
    ——————————————-
    “There was an error downloading ‘http://localhost:8732/Design_Time_Addresses/wcfMathServiceLibrary/MathService/’.
    Unable to connect to the remote server
    No connection could be made because the target machine actively refused it 127.0.0.1:8732
    Metadata contains a reference that cannot be resolved: ‘http://localhost:8732/Design_Time_Addresses/wcfMathServiceLibrary/MathService/’.
    There was no endpoint listening at http://localhost:8732/Design_Time_Addresses/wcfMathServiceLibrary/MathService/ that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
    Unable to connect to the remote server
    No connection could be made because the target machine actively refused it 127.0.0.1:8732
    Si le service est défini dans la solution actuelle, essayez de générer la solution et d’ajouter de nouveau la référence du service.”
    ——————————————————
    Can you help me please? and tell me if I must integrate the service in the solution of test

    • I got the same error message while adding service reference to the console application.
      Anyone knows how to resolve it?

    • I resolved it. The issue was that while adding a service reference, you need to run the service first so that your console application can find it and then you may add it.

      • How can I run the service? If I start it in VS 2010, I can’t switch projects while the WCF Test Client runs?

  8. Really a good article for starter with sample code. From the trace comments above I could able to recognize that MathClient object created is from the proxy class. But I would like to know if for every reference, the proxy class name is determined by taking the service contract name, getting rid of the ‘I’ prefix and adding the “Client” suffix.

    Thanks once again

  9. I got the following error:
    The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService. Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract.

    Any ideas?

  10. Balaji,

    Excellent tutorial. I was just curious… say if the client using the WCF service is using UNIX (or some non-windows) platform, how would it access the proxy class ? From your example, the proxy class seems to be generated in a dot net language. I am sure I am missing something here. Can you please fill in my gap ?

    Thanks in advance,
    Asif

  11. Hello There. I discovered your blog the usage of msn. This is an extremely smartly written article. I’ll make sure to bookmark it and return to learn more of your useful info. Thanks for the post. I’ll certainly return.

  12. This is a great example,
    but perhaps I’m missing some basics, because to add the ServiceReference, I had to open two VS windows, one loaded with wcfMathServiceLibrary project, another with ConsoleMathClient, and run wcfMathServiceLibrary project.
    Now, did I miss any step that was not mention here? Did I need to add something to IIS?
    I tried to do similar example from MSDN, and same problem was there – I had to open two projects and run my host in one, in order to find the service.
    Am I missing anything?
    I appreciate any light on this,

    vadim

  13. System.InvalidOperationException: The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService. Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract.

    Where am I wrong actually

  14. my Math Client program unable to connect to service available in local machine! it nothing being available after clicking on Discover. Can you plz help.

  15. Thank you Balaji… Helped a lot in understanding WCF….. I encountered some problem in meta data exchange…. Changed the binding type of service endpoint from wshttpbinding to httpBinding… That worked….. Also gave the service behavior name and specified that behavior in service name tag. This helped in overcoming the ImetadataExchange interface related error while running the service.. Thank you…

  16. Hello,
    I have got the following message when i am trying to run this above code that you have mention.
    Target Assembly Contains no assembly types. You may need to adjust the Code Access Security policy of the assembly.

  17. I tried this tutorial on VS2008 and got this error message:
    The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService.
    Any idea why?

  18. Without Running state for WCF Service, Is there any possible way we can call and run that service in our project?? Also knows about how to link wcf service to IIS so that whenever system start, WCF Service will start also and we can used it in our project without running webservice with another instance??

  19. The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService.

  20. For all the people who have issues with MathClient, here is the solution.
    I had the same issue.
    if you cannot get the service on the first window typing(copying) on the address bar, you will have the issue. so, get the URL from the test client (something like http://localhost:8732/Design_Time_Addresses/WcfMathServLib/MathService/), Note, if there is anything after MathService/ delete that(mex or something). Then click on Go button and you will be good.
    MathClient is actually a partial class.
    you can see that if you show all files and open Reference.cs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s