Sunday, 17 February 2008

WCF: First Steps

WCF is basically a way of allowing applications to communicate. I know that's a very broad description but that is pretty much what the technology allows - the communication method (the bits that actually go down the line) is up to you (http/tcp/Named pipes - or even custom), the message you send is up to you to - normally XML is used... but that is your call, and finally the way the "conversation" takes place is up to you, be it full duplex (like talking on a phone), half duplex (like a walkie-talkie) or One way (like sending a letter).

Getting Started

So lets get started with the first hello world message!

Firstly lets get the plumbing in place. Fire up visual studio and create a console project called client. Now if you are using vista you need to start visual studio again but this time it must run as an administrator (right click on the icon and click run as administrator) - if you are using XP then you can just run it normally. Again create a console project but this time call it server.

Now for both projects add a reference to System.ServiceModel (right click on references, then click add reference

addref

Then select System.ServiceModel and click ok:

servicemodel

And now for simplicity add a "Using System.ServiceModel;" to the top of both your client app and the server app.

Now we are ready to start coding!

Contract

As with Webservices we need to define what is actually going to be transferred. The contract should not change (but there are certain exceptions such as adding method but Ill cover that later).

A WCF contract is simply an interface with a few attributes added. For this simple example we are going to return a message sent to us, so the contract is going to be:-

    [ServiceContract]
interface IHelloWorldObject
{
[OperationContract]
string ReturnMessage(string strMessage);
}

Note how we have decorated the interface with a Service Contract and the method with the Operation Contract.

This interface must be copied to both the client and server app (yes a bit manual for now... but we will get to WSDL soon!)

The Implementation

So now we have our contract we must implement it! Nothing to complicated so Ill just copy my implementation - feel free to vary it, as long as you implement this interface the sample code below will still work!

    class HelloWorldObject : IHelloWorldObject
{
public HelloWorldObject()
{
Console.WriteLine("Object Created");
}
public string ReturnMessage(string strMessage)
{
Console.WriteLine("Message Received: " + strMessage);
return "Return: " + strMessage;
}
}

This code is just for the server.

The host (& the bindings)

The host orchestrates the calls to everything but its the bindings that specify how data flows. The default bindings are:-

But then you always have the option of implementing your own custom binding!

(If you want to know more about these bindings then take a look here http://msdn2.microsoft.com/en-us/library/ms731092.aspx)

For this sample we will start using the basic http binding as its perhaps the easiest.

static void Main(string[] args)
{
Console.WriteLine("Server Started");
ServiceHost oHost = new ServiceHost(typeof(HelloWorldObject));
BasicHttpBinding oHTTP = new BasicHttpBinding();
oHost.AddServiceEndpoint("Server.IHelloWorldObject", oHTTP, "http://localhost/HelloWorld");
oHost.Open();
Console.WriteLine("Server Listening...");
Console.ReadLine();
}

Lets walk through this a little. WCF makes a lot of use of reflection to create the object above (HellowWorldObject) so all we do is pass into the service host method the type so it can instantiate it as and when a call comes in.

The binding part is pretty simple - just the default implementation.

Then we add the binding as an endpoint to the host. The method AddServiceEndpoint accepts a string stating the contract this endpoint implements (HelloWorldObject must implement this contract to!), a referance to the binding and finally the address it will listen to - in this sample we will just listen to "http://localhost/HelloWorld"

Then all we do is open the connection. When you run this application you may see this error if you didnt start the server application as an administrator (under Vista):-


HTTP could not register URL http://+/HelloWorld/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).


Simply close the project and restart it running as an administrator.

The Client

The client makes use of a channel factory - and again this code is pretty straight forward:-

static void Main(string[] args)
{
BasicHttpBinding oHTTPBinding = new BasicHttpBinding();
ChannelFactory<IHelloWorldObject> oChannel = new ChannelFactory<IHelloWorldObject>(oHTTPBinding);
IHelloWorldObject oHi = oChannel.CreateChannel(new EndpointAddress("http://localhost/HelloWorld"));

string strMessage = "Hello World";
Console.WriteLine("Sending Message: " + strMessage);
string strResponse = oHi.ReturnMessage(strMessage);
Console.WriteLine("Message Received: " + strResponse);
Console.ReadLine();
}

Again we add the Basic http binding (both client and server have to "talk" the same language).

The channel factory is a generic object which uses the interface so it knows what the contract is. We then create an instance of the interface by calling createchannel and passing in the endpoint we are going to listen to.

Then all we do is call the return message method - and that's it!

The Results

Capture

And if we run the client again we get the following from the server:-

Capture2

Nothing too surprising there except perhaps the fact that the object is create twice. Ill cover how to stop this and manage session in a later tutorial.

The End

Ok that is a very simple look at WCF. I'm hoping this will be the start of a series looking and some more complicated examples but we will see how many people are interested in this first!

You can grab the code form here if you want to download it http://www.box.net/shared/vf0z8er4o8

No comments: