Friday 25 March 2011

WCF tutorial part 01

In this tutorial I would like to tell you a bit about WCF. WCF stands for Windows Communication Foundation and it's a part of .NET since 3.0 version. It allows us to both create and consume services.
We can communicate through HTTP, TCP, PIPES, PEER Network and MSMQ. It can be hosted in several modes:
  • Self hosting
  • Windows Service
  • IIS
  • WAS
All communication within WCF occurs through enpoints. Each endpoint can be described using ABC's:
  • A - Address - specifies where the endpoint can be found
  • B - Binding - specifies how a client can communicate with the endpoint
  • C - Contract - specifies which operations are available for the endpoint.
In this tutorial we will communicate through HTTP and service will be self-hosted (standalone .exe file).
We will use WSHttpBinding for endpoint.

Creating host
Let's begin with creating new project - Console application
Add new class file  IService.cs instead of a defined class we will write interface definition
interface IService
{
 string GetTime();
 string Greet(string name);
} 
Add another class called Service.cs implementing IService interface
class Service : IService
{
 public string GetTime()
 {
  return DateTime.Now.ToShortTimeString();
 }
 public string Greet(string name)
 {
  return "Hello " + name;
 }
}
Add reference to System.ServiceModel to project:

Add “using System.ServiceModel;” statement to IService.cs and mark our interface with attributes:

[ServiceContract]
interface IService
{
[OperationContract]
string GetTime();
[OperationContract]
string Greet(string name);
}
 
Create host with this lines:

Uri baseAddress = new Uri("http://localhost:8000/Service");
ServiceHost serviceHost = new ServiceHost(typeof(Service), baseAddress);

Add “using System.ServiceModel;” statement

Create first endpoint
serviceHost.AddServiceEndpoint(typeof(IService),new WSHttpBinding(),"Service");
As I mentioned before, an endpoint must consist of address, binding and contract, here we are specifing these three as following:
Address - "Service"
Binding - WSHttpBinding
Contract - IService

Create service metadata (so our service can be discovered):
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(smb);

Start host
serviceHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <enter> to terminate service.");
Console.ReadLine();
serviceHost.Close();


Whole file:
class Host
{
 static void Main(string[] args)
 {
  Uri baseAddress = new Uri("http://localhost:8000/Service");
  ServiceHost serviceHost = new ServiceHost(typeof(Service), baseAddress);
  try
  {
   serviceHost.AddServiceEndpoint(
   typeof(IService),
   new WSHttpBinding(),
   "Service");

   ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
   smb.HttpGetEnabled = true;
   serviceHost.Description.Behaviors.Add(smb);

   serviceHost.Open();
   Console.WriteLine("The service is ready.");
   Console.WriteLine("Press <enter> to terminate service.");
   Console.ReadLine();

   serviceHost.Close();
  }
  catch (CommunicationException)
  {
   if (serviceHost != null)
   {
    serviceHost.Abort();
   }
  }
  catch (Exception)
  {
   if (serviceHost != null)
   {
    serviceHost.Abort();
   }
   throw;
  }
 }
}

Creating client
Add new project Console Application Client
Right click on the solution and choose "Set Startup Projects...", in the new windows choose "Current selection"
Start your host by clicking inside Host project and press CTRL + F5. If everything have been done correctly you should get window saying:

Now rightclick on your client project and choose "Add Service Reference", inside the window as an address type an address of our endpoint ("http://localhost:8000/service") and cllick Go. Our service should be discovered.
Set Namespace to "ServiceReference" (as shown on the picture above) and click OK.
App.config file will be generated, reference to “System.ServiceModel” also will be added automatically.

We can start connecting to our host:
ServiceReference.ServiceClient client = new ServiceReference.ServiceClient();
Console.WriteLine(client.GetTime());
Console.WriteLine(client.Greet("anonymous"));
client.Close();

Click on Client project, and press CTRL+F5, if everything was done ok console window should open (last message is in polish)

One final note, inside app.config file in endpoint section there will be added line specifying identity:
<client>
    <endpoint address="http://localhost:8000/Service/Service" binding="wsHttpBinding"
        bindingConfiguration="WSHttpBinding_IService" contract="ServiceReference.IService"
        name="WSHttpBinding_IService">
        <identity>
            <userPrincipalName value="tomaszo@abcd.pl" />
        </identity>
    </endpoint>
</client>
If you have errors running client, remove the following line:
<identity>
    <userPrincipalName value="tomaszo@abcd.pl" />
</identity>
You can download whole project from here:
http://sites.google.com/site/terespl/files/WCFTutorialpart01.zip

No comments:

Post a Comment