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

WCF Basic Client/Server

By , 18 Jun 2006
 

Introduction

This article shows how to build a client/server application using Windows Communication Foundation (WCF) which is a part of .NET 3.0 (WinFX). WCF makes life easier for developers to build connected applications.

Most of the applications now require to support the SOA architecture. This means that the application should provide a service interface to be exposed to other applications, these interfaces can be exposed using many technologies, i.e. ASP.NET, XML Web Services, COM+ and MSMQ and so on. Each technology is completely different from the other technologies and requires special knowledge of how to code it.

Now WCF makes life better, developers will use WCF to expose service interfaces using any technology. WCF has the same set of functions and attributes that will be used for all technologies (bindings) which will abstract more implementation details and will improve productivity.

Background

The developer should simply identify three major points before starting work with WCF: Address, Binding and Contract (ABC).

The address specifies the location of the service which will be exposed like http://myserver/myservice. Clients will use this address to communicate with the service.

The contract specifies the interface between the client and server, it's simply a class interface with some attributes.

The binding specifies how the two parties will communicate in terms of transport and encoding and protocols.

Using the code

First of all we will developer the contract, which is a simple interface class (ICustomers) containing two functions (GetRandomCustomerName,GetSCustomersCount).
In order to declare that the interface is a contract "ServiceContract" attribute is used. We will also use the "OperationContract" attribute for each operation that we want to expose in the contract.

[ServiceContract]
public interface ICustomers
{
    [OperationContract]
    string GetRandomCustomerName();
    [OperationContract]
    int GetCustomersCount();
}

Second we will develop the Server. The server should implement the contract simply by implementing the ICustomers interface as the following code:

public class Customers : ICustomers
{
    #region ICustomers Members

    public string GetRandomCustomerName()
    {
        return "Random Name";
    }

    public int GetCustomersCount()
    {
        return 100;
    }

    #endregion
}

After this, we will develop the core server side code which starts the server:

static void Main(string[] args)
{
    using (ServiceHost host = new ServiceHost(typeof(Customers)))
    {
        host.Open();
        Console.WriteLine("Server Started");
        Console.ReadLine();
        host.Close();
    }
}

Now the server is configured to run using the ICustomers Contract, but we didn't specify the Address or the Binding. It's a good practice to add them in a config file outside the source code so we can modify them later.

The App.Config file contains the Address and Binding as follows:

<?xml version="1.0" encoding="utf-8" ?>
<CONFIGURATION>
    <SYSTEM.SERVICEMODEL>
        <SERVICES>
            <SERVICE name="Server.Customers">
                <ENDPOINT contract="CustomersInterface.ICustomers" 
            binding="netTcpBinding" 
            address="net.tcp://localhost:5555/Customers" />
            </SERVICE>
        </SERVICES>
    </SYSTEM.SERVICEMODEL>
</CONFIGURATION>

This file can be generated using the SvcConfigEditor.exe tool under "\Program Files\Microsoft SDKs\Windows\v1.0\Bin"

Now we are done, the server is completed and we can start building the client. The client will call the two methods of the contract in its main function as following:

 static void Main(string[] args)
{
    using (ChannelFactory<ICUSTOMERS> customersFactory =
                new ChannelFactory<ICUSTOMERS>("MyClient"))
    {
        ICustomers customersProxy = customersFactory.CreateChannel();
        string name = customersProxy.GetRandomCustomerName();
        int count = customersProxy.GetCustomersCount();
        Console.WriteLine(name);
        Console.WriteLine(count);
    }
}

Now we can generate the App.config of the client in the same way that we generated the server with the SvcConfigEditor.exe to get the following file:

<?xml version="1.0" encoding="utf-8" ?>
<CONFIGURATION>
    <SYSTEM.SERVICEMODEL>
        <CLIENT>
            <ENDPOINT name="MyClient" 
        contract="CustomersInterface.ICustomers" 
        binding="netTcpBinding" 
        address="net.tcp://localhost:5555/Customers" />
        </CLIENT>
    </SYSTEM.SERVICEMODEL>
</CONFIGURATION>         

License

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

Ehab El-Gindy
Web Developer
Egypt Egypt
Member
My name is Ehab El-Gindy,working as teaching assistant in the faculty of computers and information, Helwan University, Egypt.
 
Holding MCAD, MCT and Microsoft Goto Trainer for Vista and WinFX (.Net 3.0)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhow to programmatically add HTTP binding?membervhrao21 Mar '13 - 13:32 
When I run a WCF service from vs.net 2012 express, it creates default test client that runs at http://localhost:50421/Service1.svc.test. Modified code by adding a end point with uri href="http://localhost:8006/Service1.svc
Then tried adding the new service in the test client, the program stalls never comes back. Tried the new service from browser, nothing happens.
However a When I invoke exposed methods on port 50421 they don't work either. Basically I do not want the test port 50421. I want it override it programmatically to run at port 8006, expose the two methods and test it. How can I do this?
Here is the code. Can you please help?
 
public class Service1 : IService1
{
public Service1()
{
Uri baseAddress = new Uri("http://localhost:8006/Service1.svc");

using (ServiceHost svcHost = new ServiceHost(typeof(Service1), baseAddress))

{
try
{
// Check to see if the service host already has a ServiceMetadataBehavior
ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find();
// If not, add one
if (smb == null)
smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
// svcHost.Description.Behaviors.Add(smb);
// Add MEX endpoint
svcHost.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexHttpBinding(),
"mex"
);
// Add application endpoint
svcHost.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "");
// Open the service host to accept incoming calls
svcHost.Open();
 
// The service can now be accessed.
Console.WriteLine("The service is ready.");
Console.WriteLine("Press to terminate service.");
Console.WriteLine();
Console.ReadLine();
 
// Close the ServiceHostBase to shutdown the service.
svcHost.Close();
}
catch (CommunicationException commProblem)
{
Console.WriteLine("There was a communication problem. " + commProblem.Message);
Console.Read();
}
}
}
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
 
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
Questionmy vote is 5memberanharal7 Dec '12 - 22:51 
Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
QuestionGreat Job!memberub_prabhakant1 Mar '12 - 6:19 
Thanks for a simple and yet powerful demo of WCF. Frequently, people put lots of fluffy code around simple concepts and that confuses the main issue. Your example is to the point. Please keep it up, and post similarly intuitive findings that you make.
 
Well done!
Question3Tier, WCFmemberMember 232129329 Sep '09 - 23:09 
hi,
 
Assume i am creating a project in 3 Tier and WCF pattern.
Hence my project will be more than 1 class and how it is going to look like?
can config file addressing more than 1 class?
 
by member 2321293(CSTan)
AnswerRe: 3Tier, WCFmemberEhab El-Gindy30 Sep '09 - 2:14 
Hi there,
I am afraid that your question is too general, would you please elaborate more and give me more details. I think it's a good idea to illustrate your question by an example.
Regards,
 
Ehab El-Gindy

GeneralThank You!membermerlin98126 Sep '08 - 10:05 
I've been looking everywhere for a very simple to use WCF example. Your article is exactly what I needed. Thanks a million. Five from me.
 


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
LINQ Exchange - Learn about LINQ and Lambda Expressions
Mentally Jumbled - Geek Blog
 
Joke of the Day and Random Jokes - ReallyFunnyQuickJokes.com
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

GeneralNew to WCFmemberblackkongu2 Apr '08 - 19:34 
Hi
Im Very New to WCF,Can u Give me some basic examples with WCF
Generala request from an unknown useradminSean Ewington1 Jun '07 - 9:00 
"Please Correct the part of the CS code regarding the Client Side code, Also the XML of the server side configuration I couldn't configure them correctly"
- unknown user
GeneralNow can make the above aplicationmemberhussain.patel6 Oct '06 - 9:37 
Yes you can Create the above application but with some minor changes .
With due respect to the code written by Ehab El-Gindy and that also months before the actual release of WinFx.
 
If you are having VS2005 you can download the latest Redistruable components of Microsoft .NET Framework 3.0 for Visual Studio 2005 frm the article I have submitted.
 

 


QuestionCan not make WCF applicationmemberMyLoveDataBase25 Jun '06 - 6:03 
Hello Ehab;
I have VS 2005 + WinFX SDK (1.1 Gb) I have installed them but I can not build any WinFX application, simply I can not notice any changes after installing WinFX sdk, please provide me with more information how to build application with WinFX

 
Thank you,
Ramy Mahrous
http://ramymahrous.blogspot.com/
AnswerRe: Can not make WCF applicationmemberEhab El-Gindy25 Jun '06 - 7:16 
Hi Ramy,
Simply add reference to System.ServiceModel.dll
and use "System.ServiceModel" namespace.

 
Ehab El-Gindy
http://hobzy.blogspot.com
AnswerRe: Can not make WCF applicationmemberjswoofer13 Nov '06 - 3:45 
You might check out the article series here :
http://bloggingabout.net/blogs/dennis/archive/2006/10/18/WCF-Part-0-_3A00_-Introduction.aspx[^]
 
It's not completed yet, but it explains what's writter here for the RTM version of WCF.
 
And if you can't reference System.ServiceModel you need to install the WCF extensions. You don't need the SDK!

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 18 Jun 2006
Article Copyright 2006 by Ehab El-Gindy
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid