Click here to Skip to main content
15,168,422 members
Articles / Desktop Programming / Windows Forms
Posted 14 May 2007


66 bookmarked

A Quick and Dirty WCF Service and Client (Using WCF and Winforms)

Rate me:
Please Sign up or sign in to vote.
4.91/5 (27 votes)
14 May 20077 min read
An example of how to use Windows Communication Foundation services.


This is a complete walk-through of creating a self-hosted WCF Service and Client. You will need .NET 3.0 and Visual Studio 2005 in order to get this to work.

Example WCF Service

Getting Started

Open Visual Studio 2005 and create a new WCF Service Library project. This project type is listed under NET Framework 3.0. This will create a project and a C# file (Class1.cs). The C# file contains a service stub that we will modify.

Modifying the Service

First we will change the data contract class near the bottom of the page. It starts off looking like this:

public class DataContract1
    string firstName;
    string lastName;

    public string FirstName
        get { return firstName; }
        set { firstName = value; }
    public string LastName
        get { return lastName; }
        set { lastName = value; }

All we are going to do is change the class name. Change the class name to "Patient" now.

Data Contract definition

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, in order to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) in order to be exchanged. (Microsoft)

Next we need to change the service contract interface.

Service Contract definition

Service contracts express valid message exchange patterns between two parties. The party that initiates communication is called the initiator. The other party is called the service. Service contracts specify one or more operation contracts. An operation contract represents an individual message exchange or a correlated request/reply message exchange. (Don Box)

The service contract's name is fine, but let's change the methods marked with the [OperationContract] attribute to Get and Set methods for our Patient class (data contract).

public interface IService1
    Patient GetPatient(Int32 index);

    void SetPatient(Int32 index, Patient patient);

The index parameter to the above methods will be used to access a single Patient in an array of Patients. This will become obvious after we modify the IService1 implementation class next. Replace the service1 class with the following code:

public class PatientService : IService1
    Patient[] pat = null;

    public PatientService()
        pat = new Patient[3];

        pat[0] = new Patient();
        pat[0].FirstName = "Bob";
        pat[0].LastName = "Chandler";

        pat[1] = new Patient();
        pat[1].FirstName = "Joe";
        pat[1].LastName = "Klink";

        pat[2] = new Patient();
        pat[2].FirstName = "Sally";
        pat[2].LastName = "Wilson";

    public Patient GetPatient(Int32 index)
        if (index <= pat.GetUpperBound(0) && index > -1)
            return pat[index];
            return new Patient();

    public void SetPatient(Int32 index, Patient patient)
        if (index <= pat.GetUpperBound(0) && index > -1)
            pat[index] = patient;

The ServiceBehavior attribute, IncludeExceptionDetailInFaults=true, will give us more detailed error information while debugging if we mess something up. Without this we get a generic FaultException that tells us nothing about the real error.

The constructor of our PatientService class creates and fills our Patient array.
The GetPatient method returns the Patient object at index.
The SetPatient method sets the Patient object at index to the Patient object passed in via the second parameter.

Now we should have a working service but we need a host for our service to reside in.

The Service Host

Right-click on the service project and go to Properties. Change the Output Type from Class Library to Windows Application.

Close the properties Window and right-click the project again and this time choose Add, New Item, choose Windows Form and click the Add button.

In the form Designer add a single button and double-click the newly added button. This will add a click event handler and move you to the code window.

Add a using System.ServiceModel; up at the top. This will allow us to host our service.

Then, right above the Form1 constructor, add 2 new class variables.

bool serviceStarted = false;
ServiceHost myServiceHost = null;
Now back to the button1_Click event handler code. Make the code listed below your method body.
if (serviceStarted)
    serviceStarted = false;
    button1.Text = "Start Service";
    Uri baseAddress = new Uri("net.tcp://localhost:2202/PatientService");

    NetTcpBinding binding = new NetTcpBinding();

    myServiceHost = new ServiceHost(typeof(PatientService), baseAddress);
    myServiceHost.AddServiceEndpoint(typeof(IService1), binding, baseAddress);


    serviceStarted = true;
    button1.Text = "Stop Service";

What this bit of code does is startup a host for our service if its not started already, or closes the host if it is started.

To host or start a service you have to know your ABC's. Not the alphabet, but the service's Address, Binding, and Contract.

In this case, we pretty much make up an address. We'll use TCP binding (method of communication) so the first part of the address (URI) is set to net.tcp. The next part of the address is the machine name or IP and port number. Localhost just means your machine and the port number (2202) was just arbitrary. You will need to make sure its a valid and open port before just choosing any number. The last part of the address is just our service name.

The binding is TCP so we need to make a NetTcpBinding object.

Our contract is IService1, the name of our service contract interface.

We create a new ServiceHost object which takes a "singletonInstance" type and our Address as parameters. The "singletonInstance" is our contract's implementation class, PatientService.

Next we add an Endpoint to the host we just created. This takes our ABC's as parameters, but in reverse order for some reason.

The host is Opened or Closed to allow clients access or not respectively.

We need to add a main entry point to our host application so at the bottom, right below the class but inside the namespace brackets, add the following code.

static class Program
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
        Application.Run(new Form1());

Go ahead back to the form designer and change the text on the button to "Start Service".

You can build and run this application if you want to now. You have now finished a self-hosted service, but we need a client to consume the service.

Example Client

Right-click on the solution and click Add, New Project, Windows, and choose Windows Application.

Add 3 label controls, 3 textboxes, and 2 buttons to the new Form.

  • Change label1's text property to "Index:"
  • Change label2's text property to "First Name:"
  • Change label3's text property to "Last Name:"
  • Change button1's text property to "Get Patient"
  • Change button2's text property to "Set Patient"
  • Line up textBox1 and button1 to label1
  • Line up textBox2 and button2 to label2
  • Finally, line up textBox3 to label3

The end product should look like this:

Screenshot - Image1.jpg

Now double-click a blank part of the form to add a Load event handler for the form. Then double-click both of the buttons to add click event handlers for each.

We need to add 2 references to the client project. Select the Project menu item and click Add Reference. Under the .NET tab, find and select System.ServiceModel and click OK. Add another reference, this time choose the Projects tab and select your service that you made earlier.

Back in Form1.cs, add using System.ServiceModel; and using YourService; (replace YourService with the name of your service) to the list of other usings.

Now we're ready to access our service. Add a class variable right above the constructor called IService1 patientSvc and set it to null. Like in our host application we have to use our ABC's to setup an Endpoint to our service. In the Form1_Load event handler, add the following code:

EndpointAddress address = new EndpointAddress
            (new Uri("net.tcp://localhost:2202/PatientService"));
NetTcpBinding binding = new NetTcpBinding();
ChannelFactory<iservice1 /><IService1> factory = 
            new ChannelFactory<iservice1 /><IService1>(binding, address);
patientSvc = factory.CreateChannel();</iservice1 /></iservice1 />

This code creates a new IService1 object in the form of our PatientService class, again using the service contract's ABC's. Microsoft defines a ChannelFactory as... A factory that creates channels of different types that are used by clients to send messages to variously configured service endpoints. So now we have a PatientService (IService1) object, which is all we need to know at this point.

Put the following code into the button click handlers:

private void button1_Click(object sender, EventArgs e)
    Patient patient = patientSvc.GetPatient(Convert.ToInt32(textBox1.Text));

    if (patient != null)
        textBox2.Text = patient.FirstName;
        textBox3.Text = patient.LastName;

private void button2_Click(object sender, EventArgs e)
    Patient patient = new Patient();
    patient.FirstName = textBox2.Text;
    patient.LastName = textBox3.Text;

    patientSvc.SetPatient(Convert.ToInt32(textBox1.Text), patient);

When button1 is clicked, it takes the index entered in textBox1, converts it to an Int32, and passes it to our GetPatient method in our PatientService. What returns is a full-fledged Patient object if the index is valid (null otherwise). This is the same Patient object that we defined in our DataContract class in our service. We then fill the other 2 textboxes with the first and last names.

When button2 is clicked, we create a new Patient object, fill its 2 properties with values from our textboxes and then set the Patient at index in our PatientService to this new Patient.


That's it! We now have a working self-hosted WCF service and client. Right-click on the solution and choose Set Startup Projects, then choose Multiple Startup Projects. Set the Action on both projects to Start, then click OK. Now debug the solution and the service host and the client will both be running. Make sure to click the Start Service button before attempting to click any buttons on the client.


  • May 14, 2007: Version 1.0 uploaded
  • May 17th, 2007: Fixed article mistake in client ChannelFactory settings


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Jason Henderson
Software Developer (Senior)
United States United States
I have been a professional developer since 1996. I live in the middle of no where in Illinois, USA. I am married and have four children.

Comments and Discussions

QuestionBefore I go down the primrose path. Pin
stixoffire23-Apr-15 10:45
Memberstixoffire23-Apr-15 10:45 
AnswerRe: Before I go down the primrose path. Pin
Jason Henderson23-Apr-15 11:04
MemberJason Henderson23-Apr-15 11:04 
GeneralRe: Before I go down the primrose path. Pin
stixoffire23-Apr-15 18:42
Memberstixoffire23-Apr-15 18:42 
QuestionWhen try to connect with service, I have an error Error: Cannot obtain Metadata from net.tcp://localhost:2202/PatientService Pin
kbaranowski3-Oct-14 0:48
Memberkbaranowski3-Oct-14 0:48 
AnswerRe: When try to connect with service, I have an error Error: Cannot obtain Metadata from net.tcp://localhost:2202/PatientService Pin
Jason Henderson6-Oct-14 17:34
MemberJason Henderson6-Oct-14 17:34 
Questionsame data access by every client Pin
Hasan Habib Surzo11-Sep-13 7:42
MemberHasan Habib Surzo11-Sep-13 7:42 
AnswerRe: same data access by every client Pin
Jason Henderson11-Sep-13 8:58
MemberJason Henderson11-Sep-13 8:58 
Questiongood start point Pin
FabianSilva28-Mar-13 14:43
MemberFabianSilva28-Mar-13 14:43 
Questionconstructor with parameter Pin
sameer pokhrel23-Apr-12 2:56
Membersameer pokhrel23-Apr-12 2:56 
AnswerRe: constructor with parameter Pin
Jason Henderson23-Apr-12 4:56
MemberJason Henderson23-Apr-12 4:56 
GeneralMy vote of 3 Pin
gowrisankarvgs30-Jun-11 1:01
Membergowrisankarvgs30-Jun-11 1:01 
Generalgreat Pin
littlechiru25-Oct-10 19:10
Memberlittlechiru25-Oct-10 19:10 
GeneralRe: great Pin
Jason Henderson26-Oct-10 4:13
MemberJason Henderson26-Oct-10 4:13 
GeneralRe: great Pin
littlechiru26-Oct-10 6:48
Memberlittlechiru26-Oct-10 6:48 
GeneralMy vote of 5 Pin
FrankJAR5-Oct-10 11:38
MemberFrankJAR5-Oct-10 11:38 
QuestionHow to use in WEB Pin
kramcbe7-Apr-10 6:20
Memberkramcbe7-Apr-10 6:20 
GeneralWCF Snippet Pin
William Hooper11-Jan-10 13:02
MemberWilliam Hooper11-Jan-10 13:02 
QuestionHow about Callbacks Pin
hamid_m27-Oct-09 11:52
Memberhamid_m27-Oct-09 11:52 
AnswerRe: How about Callbacks Pin
Jason Henderson27-Oct-09 13:14
MemberJason Henderson27-Oct-09 13:14 
GeneralRe: How about Callbacks Pin
hamid_m27-Oct-09 22:29
Memberhamid_m27-Oct-09 22:29 
GeneralRe: How about Callbacks Pin
Jason Henderson28-Oct-09 5:08
MemberJason Henderson28-Oct-09 5:08 
GeneralRe: How about Callbacks Pin
hamid_m28-Oct-09 5:37
Memberhamid_m28-Oct-09 5:37 
GeneralThank you Pin
Y Kasan29-Oct-08 15:05
MemberY Kasan29-Oct-08 15:05 
GeneralThanks Pin
arbel kfir1-Apr-08 23:00
Memberarbel kfir1-Apr-08 23:00 
GeneralClient apps in .NET 1.1 Pin
hulinning5-Nov-07 2:58
Memberhulinning5-Nov-07 2:58 
I would like to know if possbile a .NET client application can communicate with WCF service.

Thanks a lot

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.