Make sure you've installed .NET Framework 3.0 Redistributable Package and Microsoft® Windows® Software Development Kit for Windows Vista™ and .NET Framework 3.0 Runtime Components before you try out the sample.
Introduction
WCF is the .NET 3.0 way of communicating between objects across machines. It is based on WSDL. WCF service requires a couple of things to be done right before it starts working for you. The following points describe in the briefest of brief terms all the technical Jargons.
Before delving into the dirty work, let us look at the basics. I'll keep them as straight and simple as possible.
Basics of WCF
The popular ABC's
This is now becoming popular way to understand how WCF works. A is the address, B the binding and C the contract.
- Address is where you communicate. This is not the same as the location you deploy your service, but the URL that will be used internally to map your requests and responses.
- Binding is how you communicate. There are several default ones like BasicHttp, TCP, NamedPipes, MSMQ and several others. This is the protocol that the server and client understands while communicating.
- Contract is what you communicate. Refer the next section for details on contracts.
Contracts
There are two types of contracts:
- Service Contracts: It is the API the service consumer invokes on your service. It's the method signature that will go into the WSDL.
- Data Contracts: It is your data that would travel from the service consumer and the service. It's the data structure. This can be found in the schema of your service.
There is something else called Message Contract, which is basically a way to communicate using messages instead of strictly typed structures. There are several situations where you want to use this, but is out of the context for this article.
Hosting
There are three ways in which you can host your service.
- Self hosting: The service will be hosting itself and listens to the client requests and responds
- IIS hosting: By far the most popular one so far. IIS will host your service (Just like your ASMX service)
- WAS hosting: This is only for Windows Vista and offers several advantages over the other methods and is out of the scope of this article.
Now that you have basic information on WCF, let's build one.
Developing the first app
The first thing you'd want to do is to have your service ready so that the client can start using it.
Developing the Service
Create your data contract by defining your data structures.
[DataContract]
public class Request
{
string name;
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
[DataContract]
public class Response
{
string message;
[DataMember]
public string Message
{
get { return message; }
set { message = value; }
}
}
We basically wrote two classes but specified DataContract
and DataMember
attributes which make them special for WCF.
Now, let us create a service contract by defining the API signature.
[ServiceContract]
public interface ISampleService
{
[OperationContract]
Response GetMessage ( Request request );
[OperationContract]
String SayHello();
}
In the above code, I've defined two service contracts, one using data contracts and other using native data structure (string
). That's it, it's simple.
Now that we have the structures ready, we'll go and build our service.
[ServiceBehavior]
public class Service: ISampleService
{
[OperationBehavior]
public Response GetMessage ( Request request )
{
Response response = new Response();
if ( null == request )
response.Message = "Error!";
else
response.Message = "Hello, " + request.Name;
return response;
}
[OperationBehavior]
public string SayHello()
{
return "Hello, World!";
}
}
Again, we are not doing anything different here. Just added the ServiceBehavior
attribute to the service
class and inherited from ServiceContract
interface
. In fact, adding ServiceBehavior
attribute is optional. All you have to do is derive your service
class from the service contract.
Now that we have developed the service, we should host it so that the consumers can start using it. I'll show you how to host it in IIS as I feel this is the most common one.
To host the service in IIS, we need two things. A Config file and a Service host file (.svc)
Config file is where we define our ABC's and svc file is where we define our service and will be the point of contact for our consumers.
//web.config file excerpts
<system.serviceModel>
<services>
<service name="SampleService.Service"
behaviorConfiguration="SampleServiceBehavior">
<endpoint address="" binding="basicHttpBinding"
contract="SampleService.ISampleService"/>
<endpoint contract="IMetadataExchange"
binding="mexHttpBinding" address="mex"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SampleServiceBehavior">
<serviceDebug includeExceptionDetailInFaults ="true"/>
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
//svc file excerpts
<% @ServiceHost Language=C# Service="SampleService.Service" %>
You'll have to add reference, the service assembly.
The service behavior in the Config file basically instructs the runtime to include the metadata when querying using the HttpGet
protocol.
Now, we are done with our service. Just open the svc file in the browser to see if everything looks fine. You should see the file browse using the IIS or the VS Web Server.
Developing the Client
We'll now focus on how to develop a client for this service.
We now need to create a proxy to communicate with the service. Having Visual Studio here helps, if not we can use the svcutil.exe to generate a proxy.
I wrote the proxy myself as this gives me freedom to reduce the unnecessary things svcutil puts in. I'll skip the proxy as this is very much similar to the servicecontract
, datacontract
and the service stubs.
VS automatically generates a Config file, which looks like:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISampleService"
closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false"
hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288"
maxReceivedMessageSize="65536" messageEncoding="Text"
textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32"
maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName"
algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address=http://localhost:4161/ServiceHost/Service.svc
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ISampleService"
contract="SampleService.ISampleService"
name="BasicHttpBinding_ISampleService" />
</client>
</system.serviceModel>
</configuration>
This basically specifies the timeouts, the content length and other essentials and explanation of those elements is out of the scope of this article.
Points of interest here is the endpoint element and its attributes. The address here refers to the svc file we created and hosted and the binding should be same as the server binding. If you want to specify multiple bindings, you can do so. But the server should be ready for that first. Finally, the contract is specifying the code to be executed at the server.
The client application is as easy as using the API exposed by the proxy and looks like:
static void Main( string[] args )
{
Request request = new Request();
request.Name = "Sidhu";
SampleServiceClient service = new SampleServiceClien
( "BasicHttpBinding_ISampleService" );
Console.WriteLine( service.SayHello() );
Response response = service.GetMessage( request );
Console.Write( response.Message );
Console.ReadKey();
}
Only thing to consider here is that the endpoint name should be same as in the Config file.
Summary
Execute the program and look at the screen for Hello, World!
So much for a simple program, but worth a start as the potential is enormous.
Please leave feedback/suggestions/comments on this article. If you want the working solution with this code, drop a mail with the subject line "Source code: First WCF sample". This will help me in filtering and replying promptly.