Creating a WCF Client Part 2: What do I do with the generated class and config file?


After overcoming the self-signed certificate issue from Part 1, I had a a C# class and a .config file. This article explains how to create a simple WCF client using the files generated by svcutil.

 

Notes:

 

Here are the steps I used to create a simple WCF Client Application:

  1. Start a new .NET Console application (Can be adapted for WinForms)
  2. Right click on the References folder in the Solutoin Explorer sidebar and add the following:
    1. System.ServiceModel
    2. System.Runtime.Serialization
  3. Right-click on the Project Name in the Solution Explorer sidebar and select Add -> Existing Item...
  4. Add both the ServiceName.cs and the output.config file
  5. Double click on the ServiceName.cs file to find out its namespace
  6. Open the Program.cs file and add a 'using' line for the namespace from step 4
  7. Now the fun begins- you can instantiate a client!

For example, if the svcutil generated code has a connection class named SomeServiceClient you could use the following code to instantiate an object, open and close it:

// Instantiates a client object
SomeServiceClient client = new SomeServiceClient(); 

// Opens the client object
client.Open(); 

//
// Between the open & close, you would use any methods made available in the class.
// For example, if the client provided a method named ReturnDataTable which
// Returns a data table, you could do something like this: 

DataTable results = client.ReturnDataTable(); 

// Closes the client object
client.Close();

 

I would recommend setting a break-point on the line where you run client.Open(), then stepping through the code to get a feel for how your client is behaving. If the code doesn't quite behave how you expect, see the notes referenced below for some possible help

The next article will cover how to add multiple Service bindings and endpoints to your WCF client via the app.config file.

A couple of considerations:

1. If you are connecting to a web service which uses a Self-signed Certificate, you will need to disable the SSL Certificate validation if the certificate is not trusted. One way of doing this is to:

  • Add System.Net to your project ( using System.Net; )
  • Add this line in your code before you open your client:

    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };

    WARNING: This line of code will always return 'True' When performing a certificate check. Code like this is not suitable in a production environment where you need trusted communication. For our purposes here it helps us in our testing environment.

2. You may need to rename the output.config file to app.config. I had to do this to get my simple client to compile and run