How To: Building a WCF Service and consumer

How To: Building a WCF Service and consumer

Do you see service everywhere? Alright I admit that may not be an original. However, with Windows Communication Foundation and the .NET Framework 3.0 you can.WCF is the unified programming model for building service oriented applications. It is designed to simplify the creation of connected applications through a new service oriented programming model. WCF supports a variety of distributed application development by providing a layered architecture.  The base of WCF provides the asynchronous message passing primitives. The higher level services layered on top of this base include secure and reliable messaging exchange, a typed programming model including serialization facilities, queued and transacted messaging exchange, integration with other programming models like MSMQ, COM+ and ASP.NET Web Services, Web Service Enhancements and others. Technically, WCF is implemented as a set of classes that in the .NET Framework 3.0 The main namespace for working with WCF is the System.ServiceModel. This namespace contains the classes, enumerations and interfaces necessary to build WCF services and client applications.

A Windows Communication Foundation service is provided by defining one or more Windows Communication Foundation endpoints.  An endpoint is defined by an address, a binding and a service contract.  The address defines where the service is located.  The binding specifies how to communicate with the service.  The service contract defines the operations that the service can perform.  WCF services must be hosted within a process to become active. The hosting environment is responsible to create and control the context and lifetime of the service. WCF services are designed to run in any Windows process that supports managed code. This programming model is designed to remain consistent and is considered independent of the runtime environment that is used to deploy the service. The benefit is that this makes the code for your service look very much the same whatever hosting option is selected.

Typically hosting options range from running inside a console or Windows Form application to server environments running within a worker process managed by IIS, or the Windows Process Activation Service (WAS). WCF allows developers to choose the hosting environment that meet the needs of their application as opposed to requiring the use of a specific transport or technology.

In this article we will build a simple WCF service that is exposed by one Windows Form application and consumed by a second Windows Form application. The first part of this article we build the server component hosted in a Windows Form application. The exposed service takes a value and returns an appended string. In the second part of the article we create the Windows form application that connects to the server and then passes and retrieves the server value.

Building the Server

Use the following steps to build a WCF Service that is hosted in a Windows Form

1.       Create a new Windows Form Project called WinHost. This server project will host the exposed service.

2.       Set a reference to the System.ServiceModel  namespace.

 

3.       Add the following code to a class file named ClsService.vb.

Imports System

Imports System.ServiceModel

 

<ServiceContract()> _

Public Interface IClsService

    <OperationContract()> _

Function ReturnHello(ByVal YourName As String) As String

End Interface

 

Public Class ClsService

    Implements IClsService

 

    Public Function ReturnHello(ByVal YourName As String) As String Implements IClsService.ReturnHello

        Return "Hello: " + YourName

    End Function

 

End Class

 

Public Class MyServiceHost

    Friend Shared myServiceHost As ServiceHost = Nothing

    Friend Shared Sub StartService()

        ' Consider putting the baseAddress in the configuration system

        ' and getting it here with AppSettings

        Dim baseAddress As Uri = New Uri("https://localhost:8080/WinHost/NameService")

 

        ' Instantiate a new ServiceHOst

        myServiceHost = New ServiceHost(GetType(WinHost.ClsService), baseAddress)

 

 

        myServiceHost.Open()

    End Sub

 

    Friend Shared Sub StopService()

        ' Call StopService from your application's shutdown logic (i.e. dispose)

        If myServiceHost.State <> CommunicationState.Closed Then

            myServiceHost.Close()

        End If

    End Sub

End Class

 

This class holds the infrastructure for the service. Part of the real beauty of WCF is how this can be so concisely placed into a single class. Often referred to as the ServiceHost class this creates the necessary programming infrastructure to expose a service endpoint as the way to communicate with the service. The [ServiceContract] attribute indicates that this class is exposed as a service and the attribute [OperationContract] indicates that the ReturnHello function will be exposed as a method on that service.

4.       Add a new application configuration file. This will hold the configuration definitions for the service. It also is used to define the runtime attributes for the service. One of the nice features of WCF is that because this is stored in a configuration file outside of the running code you can change this on the fly as a way of affecting your service.

5.       Add the following XML configuration data at the end of the end of the configuration file. This configuration section contains all the Windows Communication Foundation (WCF) ServiceModel configuration elements.

<system.serviceModel>

<services>

<service name="WinHost.ClsService" behaviorConfiguration="MyServiceTypeBehaviors" >

                  <!-- Add the following endpoint. -->

                  <!-- Note: your service must have an http base address to add this endpoint. -->

                  <endpoint contract="WinHost.IClsService" binding="mexHttpBinding" address="mex" />

                  </service>

            </services>

            <behaviors>

                  <serviceBehaviors>

                        <behavior name="MyServiceTypeBehaviors" >

                              <!-- Add the following element to your service behavior configuration. -->

                              <serviceMetadata httpGetEnabled="true" />

                        </behavior>

                        <behavior name="returnFaults" >

                              <serviceDebug includeExceptionDetailInFaults="true" />

                        </behavior>

                  </serviceBehaviors>

            </behaviors>

      </system.serviceModel>

 

WCF services are defined in the services section of the configuration file. An assembly can contain any number of services. Each service has its own service configuration section. Each service exposes one or more endpoints defined in an endpoint element. Each endpoint has its own address and binding. All bindings used within the configuration file must be defined in the scope of the file.  This section and its content define the service contract, behavior and endpoints of the particular service.

6.       One the main form of the project. Add two buttons and a label box. These will be used to turn on and off the service as well as provide  visual feedback as to whether the service is currently available.

7.       Add the following code to the form. This is the actual code that is used to turn on and off the service.

Public Class Form1

 

    Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click

        ' start the service

        MyServiceHost.StartService()

        LblStatus.Text = "ON"

    End Sub

 

    Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click

        ' stop the service

        MyServiceHost.StopService()

        LblStatus.Text = "OFF"

    End Sub

End Class

 

Once this is done you have created the WCF service. In order to test this you can use the URL that was identified within the application (https://localhost:8080/WinHost/NameService). This example uses HTTP as the transport. Because of this we can see a sample pagemuch  like the ASMX page for Web Services that can be used to validate the service is running.

 

 

Building the Client

Once the service component is built we can create a consumer application. In this case we will create another Windows Form application that can connect and retrieve data from the Windows Form server application.

1.       Create a new Windows Form application called WinClient.

2.       Using the svcutil utility within Visual Studio we can automatically generate the service files needed to connect to the service we have created in the first part of this article. The command line ServiceModel Metadata Utility tool is used to generate service model code based on the published metadata documents from the server. This utility can be accessed through the Visual Studio command prompt

3.       Within the command prompt enter the following command to generate these files.

 

svcutil  /language:vb https://localhost:808/Winhost/nameservice

NOTE: Make sure to use the “/language:vb” switch. This will generate the service model code in VB.

4.       By default these files are generated in the “C:\Program Files\Microsoft Visual Studio 8\VC directory.

 

5.       Once the service model files are generated they need to be added to the current client application. When adding them to the current client application - rename “output.config” to app.config. Once these two files are added to the current solution the file explorer should look like the following.

 

Note: I usually copy these files into the current application directory and then rename them using File Explorer. After renaming add them to the current application using the Add – Existing item option.

6.       The only thing remaining is to actually place the following code in the client Windows Form application. This is the code that connects to the service using the generated service model file for this application and retrieves the data. Place the following code in a button behind the main form.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim client As ClsServiceClient = New ClsServiceClient

        ' Use the 'client' variable to call operations on the service.

        MsgBox(client.ReturnHello("Thom"))

        ' Always close the client.

        client.Close()

    End Sub

 

First make sure that the server application is running. You can then start up the client application and click the button to retrieve the data

WCF has a wide variety of concepts and techniques to understand. This article was meant to provide a brief introduction and an easy to follow sample on building a service using a Windows Form application. In other posts we will start to dive deeper into the various components and technologies around WCF. You can download all the code demonstrated for this article from here.

<<Download the sample code>>