At your service (part I) – WCF tutorial in VB

Introduction


In this post I’m going to do a tutorial on Windows Communication Foundation, WCF. This tutorial is divided in 4 steps:


  1. Defining the WCF data and service contracts.
  2. Implementing the WCF service contract.
  3. Creating the service-host application.
  4. Create a client application that uses the service.

So without further ado, let’s get busy.


Here is where we are getting busy


We’re going to implement our WCF server as a simple console application so start Visual Studio and create a new Console project. But for now we just leave the Sub Main() empty, since we implement the server in step 3. We also need to add a couple of references, first of all we need to add a reference to the System.ServiceModel.dll, right click on the project node in the Solution Explorer and click Add>Reference and scroll down the list until you find it. We also need to add a reference to the System.Runtime.Serialization.dll, so repeat the earlier step to add that as well.


Before we start with the WCF specific details we’re going to create a Data Access Layer (a DAL) which our service will work against to retrieve data. For the purpose of this article I’ve made a very simple class that can return a list of persons, or a single person. This could be customer information or an employment roll or whatever. In this sample I’ve hardcoded a list of persons, in a real word application you would retrieve this data from a database.


Public Class DataAccess
  Private Shared _list As List(Of Person)
  Private Shared Function GetPersonList() As List(Of Person)
    If _list Is Nothing Then
      _list = New List(Of Person)
      With _list
        .Add(New Person(1, "Homer", "Simpson"))
        .Add(New Person(2, "Marge", "Simpson"))
        .Add(New Person(3, "Bart", "Simpson"))
        .Add(New Person(4, "Lisa", "Simpson"))
        .Add(New Person(5, "Maggie", "Simpson"))
      End With
    End If
    Return _list
  End Function

  Public Shared Function GetPerson(ByVal id As Integer) As Person
    Return (From p In GetPersonList() Where p.ID = id).FirstOrDefault
  End Function

  Public Shared Function GetPersons() As List(Of Person)
    Return GetPersonList()
  End Function
End Class

As you can see the methods returns either a List(Of Person) or a single Person object. We will create the Person class in the next step.


Defining the WCF data and service contracts


We need to create a data contract for each object a WCF service can return, we also need to mark each property that is returned as a DataMember. We do that by adding attributes to our class and its members. Add a new class to the project, make sure you import the System.ServiceModel and the System.Runtime.Serialization namespaces, that we added a reference to earlier, and add the following code to the class.


Imports System.ServiceModel
Imports System.Runtime.Serialization


<DataContract()> _
Public Class Person
  Private _id As Integer
  <DataMember()> _
  Public Property ID() As Integer
    Get
      Return _id
    End Get
    Set(ByVal value As Integer)
      _id = value
    End Set
  End Property

  Private _firstName As String
  <DataMember()> _
  Public Property FirstName() As String
    Get
      Return _firstName
    End Get
    Set(ByVal value As String)
      _firstName = value
    End Set
  End Property

  Private _lastName As String
  <DataMember()> _
  Public Property LastName() As String
    Get
      Return _lastName
    End Get
    Set(ByVal value As String)
      _lastName = value
    End Set
  End Property

  Public Sub New(ByVal id As Integer, ByVal firstName As String, ByVal lastName As String)
    _id = id
    _firstName = firstName
    _lastName = lastName
  End Sub
End Class


The next step is to create the service contract for our WCF service. This contract defines what kind of operations our service provides and are defined as interfaces.


<ServiceContract(Namespace:="http://demo.wcf.samples")> _
Public Interface IPerson
  <OperationContract()> _
  Function GetPerson(ByVal id As Integer) As Person
  <OperationContract()> _
  Function GetPersons() As List(Of Person)
End Interface

Notice that the interface is decorated with a ServiceContractAttribute, I also changed its namespace, specifying the namespace is a best practice to prevent the default namespace of “http://tempuri.org” being used. Each operation that our service provides must be marked with the OperationContractAttribute, which you can see that I used on the two methods.


OK, now we have our contracts set up so we now need to implement them which we do next.


Implementing the WCF service contract


Since the contract and the service interface have already been designed, creating the service is straightforward and only requires that the interface is implemented.


Public Class PersonService
  Implements IPerson

  Public Function GetPerson(ByVal id As Integer) As Person _
Implements IPerson.GetPerson Return DataAccess.GetPerson(id) End Function Public Function GetPersons() As List(Of Person) _
Implements IPerson.GetPersons Return DataAccess.GetPersons() End Function End Class

As you can see I simply call the methods in the DataAccess class, that we defined in the introduction, in the implementation of the two methods.


That’s it. Our service is all done. But to be able to use it from a client application later we need to create a service-host application, which will host our service objects. That will be our actual server application and we’ll start creating that next.


Creating the service-host application


As I mentioned in the introduction, we will implement our service-host as a simple console application. So open the module with the Sub Main() definition and import the System.ServiceModel and the System.ServiceModel.Description namespaces. The latter of the namespaces is needed to describe the behavior of the metadata. In our case we will allow a client to get the data via a HTTP GET request.


The first thing we need to do is to configure a base address for the service. We do that by creating a new URI that specifies the address, port number, and the path of our service. We can use any IP port number that is usually not occupied, in this example I will use port 8240.


Dim uri = New Uri("http://localhost:8240/demo/wcf/samples")

As the path of the service I picked the same as I did for the namespace of the service contract we created earlier (which was “http://demo.wcf.samples”).


Next we need to create a ServiceHost reference, to which we must pass the type that implements our service contract and the base address that we just specified.


Dim host As New ServiceHost(GetType(PersonService), uri)


Now that we have our ServiceHost object we need to add an endpoint that exposes the service. To do this, you must specify the type of the contract the endpoint is exposing, a binding, and the address of the endpoint. The contract is our interface, and in this demo we will be using the WSHTTPBinding as the binding, and for the address we simply use the string “PersonService”.


A WCF service can use almost any kind of binding, you can use http binding, tcp binding and so on.


We will also need to enable Metadata exchange, to do that we add a service metadata behavior, as I already mentioned we will allow a client to get data from the service via a HTTP GET request. When this is done all we have to do is to open our host and wait for client requests.


Try
  host.AddServiceEndpoint(GetType(IPerson), New WSHttpBinding, "PersonService")
  Dim behavior As New ServiceMetadataBehavior()
  behavior.HttpGetEnabled = True
  host.Description.Behaviors.Add(behavior)

  host.Open()
  Console.WriteLine("The service has been started.")
  Console.WriteLine("Press the ENTER key to terminate service.")
  Console.WriteLine()
  Console.ReadLine()
  host.Close()
Catch ex As CommunicationException
  Console.WriteLine("Error: {0}", ex.Message)
  host.Abort()
End Try


You can now run the application. Not much will happen though, a console window will be created and the message that the service is started is shown. What we need to do now is to create a client application that can use the service. We’ll do that in the next section.


Create a client application that uses the service


Start by launching a new instance of Visual Studio, and create a new Console Application project. Add a reference to the System.ServiceModel.dll.


The first thing we need to do is to get the meta data of the service, and create the proxy code. You can use the SvcUtil.exe command line tool to do so, but there is an easier way. We can let Visual Studio do this for us by adding a Service Reference. To do this we first must make sure our service is running. So switch back to the previous instance of Visual Studio and start the project. Now switch back to this instance of Visual Studio and right click on the project node in the Solution Explorer and select “Add Service Reference” in the context menu. In the dialog that pops up we type in the URI we specified for our service endpoint in the previous section (http://localhost:8240/demo/wcf/samples) and click on the Go button. You should get the result you can see in the image below.


image


Click on the OK button and wait a few seconds while Visual Studio creates the proxy code for you.


Our proxy client will get the name PersonClient() which we need to create an instance of to be able to call the methods our service exposes.


Public Sub Main()
  Dim client As New ServiceReference1.PersonClient()
  Dim pers As ServiceReference1.Person = client.GetPerson(1)
  If Not pers Is Nothing Then
    Console.WriteLine("Person with ID=1 is {0} {1}", _
                      pers.FirstName, pers.LastName)
  End If
  Console.WriteLine("Person list")
      
  For Each p In client.GetPersons()
    Console.WriteLine("{0}: {1} {2}", _
                      p.ID, p.FirstName, p.LastName)
  Next
  Console.ReadLine()
End Sub


Make sure the service is running before running this code.


Conclusion


That’s all the steps that is needed to create a simple WCF service. It does require more code than an ASP.Net Web Service, in which you basically slap a WebMethodAttribute() to a method and your done, but I like the fact that WCF services encourage developers to use the contract-first principles. Next time, in part 2 of this “At your Service” series, I will do a comparison of an ASP.Net Web Service contra a WCF Service. Until then:


Have fun!

5 thoughts on “At your service (part I) – WCF tutorial in VB”

  1. I know this has been here a while, but I wanted to let you know I worked through this tutorial today, and it has given me a glimmer of understanding about WCF, something I just started learning. Thank you for your work. I am off to find At your service (part II)!

  2. thank you very much..this was way easier to work with than the MSDN stuff…you’re great…will see if there’s more tutorials…

  3. Thank you very much, I spent one entire day trying to make WCF work from the microsoft tutorials.

    Yours is way much better

    Thanks again

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>