Introduction
I'll talk today about new Technology called WCF, i.e. “Windows Communication Foundation”. Before going into detail, let’s define our problem. We have multiple programs (server and clients) which need communication in order to accomplish their target.
For example, if we need to make a chatting system, we can implement it in the client server way. The server will be responsible for taking requests from the chat clients (such as login request, send message request, logout request, … ) and clients will be considered a thin client because most of the operations are done in the server. This is a popular example in which we need a communication framework.
Another example is in making programs that need heavy processing. We recommend putting a server application on a powerful machine and any simple client application on a simple machine, e.g. a laptop. A small PC can connect to the server and make use of it.
This was just an introduction by illustrating in what situations we need this technology. Let’s see what the current possibilities are, i.e. the technologies we have to make it.
Background
The most popular technologies are: COM, COM+, CORBA and WCF. COM and COM+ are implemented using C++ language but it’s considered very difficult due to using pointers which are considered to be difficult for many developers. For CORBA, it’s implemented in Java, I used it and I think it’s easy and has an important feature which is cross platform. I'll try to post an article of how to use it later.
Using the Code
I'll take you through a small application (client and server) implemented by WCF and C#. The purpose of this application is to simulate a very small bank system as follows:
The server will have to provide these functionalities:
AddAccount
RemoveAccount
GetAccounts
The client will be responsible for calling the previous functionalities from the server. So here are our steps.
Server Side
Create a new Console Application in C# language and add System.ServiceModel.dll to its references by navigating to this path “c:\windows\Microsoft.Net\Framework\v3.0\Windows Communication Foundation” and select system.servicemodel.dll.
Create our contract: The contract is an interface that contains the functionalities that the server will implement some day . We can define it as follows: add a new class to your application and paste this code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace BankServer
{
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface IBank
{
[OperationContract]
int AddAccount(string clientName, int clientAge);
[OperationContract]
bool RemoveAccount(int accountNumber);
[OperationContract]
List<String> GetAccounts();
}
}
Create our data model i.e., Account
class. Add a new class, call it Account
and paste this code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankServer
{
class Account
{
private int _id = 0;
private string _name = "";
private int _age = 0;
public Account(int id, string name, int age)
{
_id = id;
_name = name;
_age = age;
}
public string ClientName
{
get { return _name; }
set { _name = value; }
}
public int ClientAge
{
get { return _age; }
set { _age = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
public override string ToString()
{
return String.Format("ID:{0} Name:{1} Age:{2}",
_id.ToString(), _name, _age.ToString());
}
public override bool Equals(object obj)
{
Account temp = (Account)obj;
return this.ID.Equals(temp.ID);
}
}
}
Implement the Contract: Create a new class called bank
and put this code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankServer
{
class Bank :IBank
{
private List<Account> _accounts = new List<Account>();
private int _idGenerator = 0;
public int AddAccount(string clientName, int clientAge)
{
_idGenerator++;
Account acc = new Account(_idGenerator, clientName, clientAge);
_accounts.Add(acc);
return _idGenerator;
}
public bool RemoveAccount(int accountNumber)
{
Account acc = new Account(accountNumber, "", 0);
return _accounts.Remove(acc);
}
public List<string> GetAccounts()
{
List<string> accLst = new List<string>();
foreach (Account acc in _accounts)
{
accLst.Add(acc.ToString());
}
return accLst;
}
}
}
Configure the server: this will specify an address for our service and start it. Copy and paste this code in program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace BankServer
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri
("http://localhost:8000/ServiceModelSamples/Services");
ServiceHost selfHost = new ServiceHost(typeof(Bank), baseAddress);
try
{
selfHost.AddServiceEndpoint(typeof(IBank),
new WSHttpBinding(), "BankService");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
selfHost.Open();
Console.WriteLine("Our Bank Service is Open now");
Console.WriteLine("Press <ENTER> to close it");
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
}
catch (CommunicationException cs)
{
Console.WriteLine("Exception:{0}", cs.Message);
selfHost.Abort();
}
}
}
}
Client Side
Create your client: right click on your solution and create a new project. Call it MyBankClient
and its type is console C# application and don't forget to add System.ServiceModel.dll. You can find it in the recent tab.
Generate a proxy class in your client that you will use to deal with the bankservice:
Use our bank service. Paste this code in your program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace MyBankClient
{
class Program
{
static void Main(string[] args)
{
EndpointAddress epAddress = new EndpointAddress
("http://localhost:8000/ServiceModelSamples/Services/BankService");
BankClient client = new BankClient(new WSHttpBinding(), epAddress);
Console.WriteLine("Adding John , 20 years");
client.AddAccount("John", 20);
Console.WriteLine("Adding Peter , 21 years");
client.AddAccount("Peter", 21);
Console.WriteLine("Adding Andrew , 25 years");
client.AddAccount("Andrew", 25);
DisplayAccounts(client.GetAccounts());
Console.WriteLine("Removing John");
client.RemoveAccount(1);
DisplayAccounts(client.GetAccounts());
client.Close();
Console.WriteLine();
Console.WriteLine("Press <Enter> to close");
Console.ReadLine();
}
private static void DisplayAccounts(string[] accounts)
{
Console.WriteLine();
Console.WriteLine("Current Accounts:");
foreach (string acc in accounts)
{
Console.WriteLine(acc);
}
Console.WriteLine();
}
}
}
Run the server, then the client, and check the result.
Congratulations, you've created a working WCF application.
Points of Interest
WCF gives you great facility in making communication between applications. You can use it in more complex applications. Use MSDN as it is a great help.
History
- 20th July, 2008: Initial post