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

Writing your first WCF Service

, 28 Apr 2007
Rate this:
Please Sign up or sign in to vote.
This article helps in writing the first WCF Service

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:

  1. Service Contracts: It is the API the service consumer invokes on your service. It's the method signature that will go into the WSDL.
  2. 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.

  1. Self hosting: The service will be hosting itself and listens to the client requests and responds
  2. IIS hosting: By far the most popular one so far. IIS will host your service (Just like your ASMX service)
  3. 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.

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

Share

About the Author

Sidhartha Gundavarapu
Microsoft
India India
I'm working as a Consultant at Microsoft Global Services and like to spend my spare time investigating new stuff and write articles about the ones that are less discussed about. Please feel free to send your comments/suggestions/corrections on any of my work.

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberviragdesai15-Nov-12 18:47 
QuestionSource code: First WCF sample" PinmemberHarocool16-Jan-12 19:48 
GeneralMy vote of 5 Pinmemberbemimi9-Oct-10 22:52 
QuestionWhere are refrences in Framework 4? PinmemberDr TJ29-Sep-10 19:50 
AnswerRe: Where are refrences in Framework 4? PinprofessionalKevin Strong13-Nov-13 5:31 
GeneralGood article for a beginer like me. Pinmembervibhuti_a20-Jul-10 20:58 
GeneralRe: Good article for a beginer like me. PinmemberHarocool16-Jan-12 21:54 
QuestionHow to create SampleServiceProxy.cs file in Writing your first WCF Service? PinmemberPradip.Kumar.Meta14-Jul-10 1:50 
How to create SampleServiceProxy.cs file in Writing your first WCF Service?
QuestionNetwork supported? PinmemberMember 232129314-Sep-09 0:12 
QuestionHow to change localhost to IP address Pinmembersubho1008-May-08 1:14 
AnswerRe: How to change localhost to IP address PinmemberSidhartha Gundavarapu8-May-08 18:13 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141015.1 | Last Updated 28 Apr 2007
Article Copyright 2007 by Sidhartha Gundavarapu
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid