Chapter 39. Creating and Consuming WCF Services

During the last several years, many technologies were developed for distributed applications that communicate over networks. The idea is that client applications can exchange information with a service via a network protocol such as Hypertext Transport Protocol (HTTP) or Transmission Control Protocol (TCP), just to mention some. Among these technologies there are SOAP (an XML-based information exchange system), Microsoft Messaging Queue (a message-based system), the well-known web services, and the .NET Remoting (which connects applications based on the .NET Framework). Although powerful, all these technologies have one limitation: Two or more applications can connect only if all of them rely on the same technology. Just for clarification, an application based on MSMQ cannot communicate with another one based on SOAP. To avoid this limitation, Microsoft created the Windows Communication Foundation (WCF) technology that was first introduced with the .NET Framework 3.0. It is a unified programming model for distributed applications. With WCF, developers can write code for exchanging data and information between services and clients without worrying about how data is transmitted because this is the job of the .NET Framework. WCF is another large technology, and covering every single aspect would require an entire book; therefore, in this chapter you learn about implementing, configuring, hosting, and consuming WCF services with Visual Basic 2012.

Introducing Windows Communication Foundation

WCF is a technology that enables data and information exchange between services and clients through messages. The service exposes information through the network and is nothing but a .NET assembly. Then the client receives that information and can send back other information or data. In this section, you learn how data exchange between the service and clients works before creating your first WCF service. This is important because you need to know some fundamentals about WCF infrastructure before putting your hands on the code. If you ever developed .NET Web Services (.asmx), you’ll notice several similarities with WCF, at least in the implementation. However, several things under the hood make WCF more powerful. Moreover, although web services are obviously still allowed and supported in .NET Framework 4.5, WCF is the main technology for data exchange through networks and is intended to be a replacement of web services, even though WCF provides fully integrated support with client and web applications, such as WPF and Silverlight.


WCF 4.5

Windows Communication Foundation in .NET Framework 4.5 is also known as WCF 4.5, although this is actually the fourth version. There are some improvements in the new version of WCF, and a lot of work has been done to simplify the way services are developed and maintained. We, however, focus on them only when required, preferring to illustrate how you implement and consume services. For further information about what’s new in WCF 4.5, read the MSDN Library at: http://msdn.microsoft.com/en-us/library/dd456789(v=vs.110).aspx.


Understanding Endpoints

A WCF service is a .NET assembly (in the form of dll) relying on the System.ServiceModel namespace and exposing objects and members like any other class library. Thus, client applications can invoke members and use objects exposed by services. Behind the scenes, this happens through message exchanges. Client and services exchange messages through endpoints. An endpoint is the place where client and service meet and is where both applications exchange their information, so it can be considered like a communication port. Each WCF service offers at least one endpoint; multiple endpoints serve as communication ports for different data types (for example, .NET objects and messages). But every endpoint needs to be configured with some other information to be a functional place for meeting the needs of service and clients. The configuration is provided by the Address, Binding, and Contract as explained in the next section.

Address, Binding, Contract: The ABC of WCF

When a client application attempts to reach a service, it needs to know some information for finding the service and for data exchange. The service exposes such information via the ABC, which represents the Address, Binding, and Contract properties in the service. The Address is the physical URI where the service is running. For example, on the local machine the Address could be http://localhost/MyService.svc or http://www.something.com/MyService.svc if the service is running on the Internet. The Binding property is a complex object and is responsible for

• Establishing how service and clients communicate (with a Behavior object)

• Establishing which protocol and credentials must be used within the communication

• Handling data transmission to the target (via a Channel object), converting data into an acceptable format, and transmitting data via the specified protocol (such as HTTP, HTTPS, and so on)

The Contract is probably the most significant item in the ABC. It establishes what data can be exchanged and which .NET objects/members are exposed by the service and that the client must accept; this is defined as platform-independent because clients will just accept the contract without worrying about the code that implemented objects on the server side. If you think of classic managed class libraries, when you add a reference to a class library, you want to use its members, but in most cases you will not worry about the code that implemented those members. With WCF, it is the same thing. For code, a contract is a .NET interface that defines public members available from the service to clients. Such an interface is then implemented by a class that actually makes members available to the external world. All these concepts will be explained in code. There are different contract types in WCF, but the most important are summarized in Table 39.1.

Table 39.1. WCF Contracts

Image

As you see in the next section, contracts are applied with special .NET attributes. The good news about the ABC is that all information is typically stored inside the configuration file and therefore can be edited with any text editor by system and network administrators, too, without the need of recompiling the source code. This makes services administration simpler. At this point, you are ready to create your first WCF service with Visual Basic 2012.

Implementing WCF Services

Visual Studio 2012 offers some project templates for creating WCF projects. Table 39.2 lists them all.

Table 39.2. WCF Project Templates

Image

This book covers the WCF Service Application template, which is useful because it provides service self-hosting. A WCF service cannot be run or consumed as a standalone and must be hosted inside a .NET application. Host applications can be of several types: Console applications, Internet Information Services (including the Express edition), and ASP.NET Development Server are all valid host applications. The WCF Service Application template provides hosting inside the Internet Information Services (IIS) Express development server, which is something new in Visual Studio 2012. IIS Express is a lightweight version of the famous IIS web server and is typically used on development machines for testing purposes. In Visual Studio 2012, IIS Express is the default setting for WCF 4.5, but you can still use the ASP.NET Development Server (see Figure 39.6 to locate the host selection). Select the File, New Project command, and in the New Project dialog box, select the WCF Service Application template, as shown in Figure 39.1. Name the new project BookService and then click OK.

Image

Figure 39.1. Creating a new WCF project.

The goal of the example is to offer a way for validating books’ information, such as ISBN code, title, and author. The service exposes a Book class representing a single book and a method named ValidateBook that provides the validation logic. Before writing custom code, you should take a look at the autogenerated code to understand what WCF needs. Visual Studio 2012 generated a web project visible in Solution Explorer. The new project contains the following files:

• IService1.vb, which defines the contract interface

• Service1.svc.vb (nested into Service1.svc as a code-behind file), which defines the class that implements the contract

• Service1.svc, which is the actual service that exposes data and that is to be consumed by clients

• Web.config, which provides definitions for the ABC


Note on the Web.config File

Starting with the .NET Framework 4.0 and Visual Studio 2010, the Web.config file no longer contains a WCF metadata definition in case you use the default settings because they are considered as implicit. This is important with regard to the current example. If you decide to implement custom settings instead, the Web.config stores the metadata definition. Because configuration files in client applications reflect Web.config files from services, later in this chapter you see the client-side metadata definition mapping the implicit metadata of the current sample service.


Let’s take a look at the IService1.vb file, which is reported in Listing 39.1 and that defines a couple of contracts.

Listing 39.1. Autogenerated Contracts


' NOTE: You can use the "Rename" command on the "Refactor" menu
' to change the interface name "IService1" in both code and
' config file together.
<ServiceContract()>
Public Interface IService1

    <OperationContract()>
    Function GetData(ByVal value As Integer) As String

    <OperationContract()>
    Function GetDataUsingDataContract(ByVal composite As  _
                                      CompositeType) As CompositeType

    ' TODO: Add your service operations here

End Interface

' Use a data contract as illustrated in the sample below
' to add composite types to service operations.
<DataContract()>
Public Class CompositeType

    <DataMember()>
    Public Property BoolValue() As Boolean

    <DataMember()>
    Public Property StringValue() As String
End Class


The IService1 interface is decorated with the ServiceContract attribute, meaning that it establishes which members the service defines and makes available to the public. The interface defines two methods, both decorated with the OperationContract attribute. This attribute makes methods visible to the external world and consumable by clients. You need to remember that, in WCF, marking a method as Public is not sufficient to make it available to clients; it needs to be marked as OperationContract to be visible. Methods exposed by WCF services are also known as service operations, and this definition will be recalled in the next chapter with regard to WCF Data Services. Notice how the GetDataUsingDataContract method receives an argument of type CompositeType. This type is a custom class declared as DataContract, so the WCF service can exchange data of this type. Members from this class also need to be marked as DataMember to be visible to the external world. As for service operations, marking a member as Public is not sufficient; you need to decorate members with the DataMember attribute. The Service1 class shows an example of implementing the contract and the logic for service operations. Listing 39.2 shows the autogenerated sample code.

Listing 39.2. Autogenerated Contracts Implementation


' NOTE: You can use the "Rename" command on the "Refactor" menu to
' change the class name "Service1" in code, svc and config file together.
Public Class Service1
    Implements IService1

    Public Sub New()
    End Sub

    Public Function GetData(ByVal value As Integer) As String _
                    Implements IService1.GetData
        Return String.Format("You entered: {0}", value)
    End Function

    Public Function GetDataUsingDataContract(ByVal composite As CompositeType) As  _
                    CompositeType Implements IService1.GetDataUsingDataContract
        If composite Is Nothing Then
            Throw New ArgumentNullException("composite")
        End If
        If composite.BoolValue Then
            composite.StringValue &= "Suffix"
        End If
        Return composite
    End Function
End Class


The class implements the contract interface and provides logic for service operations working like any other .NET class. The content of the .svc file is discussed later; for now let’s make some edits to the code replacing the autogenerated one with custom implementation.

Implementing Custom Logic for the WCF Service

Rename the IService1.vb file to IBookService.vb; then switch to the code editor. Right-click the IService1 identifier and select Rename. Next, provide the new IBookService identifier and click OK. Visual Studio will prompt for confirmation and will rename the instances in code as well. This is important to update all references inside the project to the interface, including references inside the .svc file. Now delete the code for the CompositeType class and replace the entire code with the one shown in Listing 39.3.

Listing 39.3. Implementing Custom Contracts


<ServiceContract()>
Public Interface IBookService

    <OperationContract()>
    Function ValidateBook(ByVal bookToValidate As Book) As String

End Interface

<DataContract()>
Public Class Book

    <DataMember()>
    Public Property Title As String

    <DataMember()>
    Public Property ISBN As String

    <DataMember()>
    Public Property Author As String

    <DataMember()>
    Public Property DatePublished As Date?
End Class


The IBookService contract defines a ValidateBook method that will be invoked for validating a book. A single book is represented by the Book class, which exposes four self-explanatory properties. Now switch to the Service1 class and, following the steps described before, rename the Service1 identifier into BookService. Then replace the autogenerated code with the one shown in Listing 39.4.

Listing 39.4. Implementing the Service Logic


Imports System.Text.RegularExpressions
Public Class BookService
    Implements IBookService

    Private Const isbnPattern As String = _
    "ISBN(?:-13)?:?x20*(?=.{17}$)97(?:8|9)([ -])d{1,5}1d{1,7}1d{1,6}1d$"

    Public Function ValidateBook(ByVal bookToValidate As Book) As _
                    String Implements IBookService.ValidateBook

        Dim isValidIsbn As Boolean = Regex.IsMatch(String.Concat("ISBN-13: ",
                                                   bookToValidate.ISBN),
                                                   isbnPattern)

        If isValidIsbn = False Then
            Return "Invalid ISBN"
        End If

        Dim isValidAuthor As Boolean = String.IsNullOrEmpty(bookToValidate.Author)
        If isValidAuthor = True Then
            Return "Author not specified"
        End If

        Dim isValidTitle As Boolean = String.IsNullOrEmpty(bookToValidate.Title)
        If isValidTitle = True Then
            Return "Title not specified"
        End If

        If bookToValidate.DatePublished Is Nothing Then
            Return "Book data is valid but date published was not specified"
        End If

        Return "Valid book"
    End Function
End Class


The code for the ValidateBook method is simple. It uses a regular expression for checking whether the ISBN code is valid and then checks for valid properties in the Book class instance that must be validated.


Note on the Regular Expression Pattern

The regular expression pattern for checking ISBNs is from the RegExLibrary website at the following address: http://regexlib.com/REDetails.aspx?regexp_id=1748. A lot of patterns for validating ISBNs are available; the one used in this book is just an example. You can replace it with a different one.


Now right-click the BookService.svc file in Solution Explorer, and select View in Browser. In a few seconds, the WCF service will be hosted by the ASP.NET Development Server and will run inside the web browser, as demonstrated in Figure 39.2.

Image

Figure 39.2. The WCF service has been hosted by the ASP.NET Development Server and is now running.

This test is required to ensure that the service works correctly. Notice how information is provided on how consuming the service is. The web page shows information explaining that you should invoke the SvcUtil.exe command-line tool pointing to the wdsl metadata of the service.


What is WSDL?

Web-service Definition Language (WSDL) is a standard format and is an XML representation of how a web service works (including WCF services), describing document information and procedure information, including endpoints and messages. WSDL explains how a service must work—for example, how information has to be transmitted, which protocol must be used, and how it interacts in scenarios such as REST and SOAP. Such information is known as service metadata and in WCF it plays an important role.


SvcUtil is described in the next section. Click the link available near SvcUtil.exe. By doing so, you access metadata offered by the WCF service, including contracts and members, as reported in Figure 39.3.

Image

Figure 39.3. Exploring the service’s metadata.

Client applications invoke service members passing through the service metadata. The next section explains how you invoke service members through a proxy class, but before going into that, let’s take a look at the BookService.svc file.


Exposing Generics in WCF

Because WCF services metadata are exposed via WSDL, some issues with generics are not supported by this. I suggest you read this blog post by MVP Jeff Barnes that provides explanations and workarounds: http://bit.ly/4CzGv3. Another suggestion is to investigate how WCF Data Services work for exposing entities (see Chapter 40, “Implementing and Consuming WCF Data Services,” for information about Data Services).


Right-click this file and select View Markup. The XHTML code for this file is the following:

<%@ ServiceHost Language="VB" Debug="true"
    Service="BookService.BookService" CodeBehind="BookService.svc.vb" %>

This file defines the service entry point. It states that the BookService class is the service entry point because it defines the real logic that implements the contract. There is some other information such as the programming language used and the code-behind the file, but the Service tag is absolutely the most important. After this overview of the service implementation, it’s time to consume the service from a client application.


Exposing Entity Data Models and LINQ to SQL Classes

WCF services are also used to expose Entity Data Models (EDM) and LINQ to SQL classes via serialization. Entities and their members in EDMs are marked by default with the DataContract and DataMember attributes, respectively. LINQ to SQL classes, on the other hand, have to be enabled for serialization by setting the Serialization Mode property of the DataContext class as Unidirectional and then marking entities with DataContract. In Chapter 40 you learn about WCF Data Services, which provide an easy implementation of WCF services by exposing data models without the need of making such customizations manually. Thus, you should create custom WCF services for exposing data models only when you need to handle special scenarios that require implementing different business logic than the one offered by Data Services.


Consuming WCF Services

Clients can easily consume WCF services by adding a service reference directly from Visual Studio 2012. In the next example, you create a simple Console client application for validating ISBNs by invoking objects from the WCF service implemented in the previous section.

Creating the Client and Adding a Service Reference

Add a new Console project to the current solution and name it BookClient. The first step you have to accomplish is adding a service reference to the WCF service. Right-click the new project name in Solution Explorer and select Add Service Reference. This brings up the Add Service Reference dialog box, where you need to enter the full web address of your service. If the service you want to add a reference to is available in the current solution, as in the current example, click Discover. The service appears in the dialog box, as shown in Figure 39.4.

Image

Figure 39.4. The Add Service Reference dialog box enables you to add a reference to a WCF service.

Click the service name on the left to enable the development server to correctly host the service and discover its members. At this point, the dialog box lists available contracts (IBookService in this case) and their members. Replace the Namespace identifier with BookServiceReference.

Understanding the Proxy Class

The WCF service is exposed through the network via a WSDL. To consume objects and data exposed by the WSDL, the client needs a proxy class that is responsible for translating WSDL information into managed code that you can reuse. This is accomplished via a command-line tool named SvcUtil.exe, which is part of the .NET Framework. Fortunately, you do not need to run SvcUtil manually because Visual Studio will do the work for you. When you click OK from the Add Service Reference dialog box, Visual Studio invokes SvcUtil and generates a proxy class. In Solution Explorer, a new folder named Service references appears. This folder contains all service references and, for the current example, stores a new item named BookServiceReference. This new item provides all the metadata information required to consume the service and especially the proxy class. Click the Show All Files button in Solution Explorer and expand the Reference.svcmap file; then double-click the Reference.vb file. This code file exposes the BookServiceReference namespace to provide client-side code for accessing members exposed from the service. This namespace exposes client-side implementations of the Book class and the IBookService interface. The most important class exposed by the namespace is named BookServiceClient and is the actual proxy class, which inherits from System.ServiceModel.ClientBase and is responsible for connecting to the service and closing the connection. It is also responsible for exposing service members such as the ValidateBook that was implemented on the service side. The namespace also exposes the IBookServiceChannel interface that inherits from IClientChannel, which provides members for the request/reply infrastructure required by WCF services. You instantiate the proxy class to establish a connection with the WCF service, and you interact with the proxy class for accessing members from the service, as explained in the next section.

Invoking Members from the Service

To invoke service members, you need to create an instance of the proxy class, which in our example is named BookClient.BookServiceReference.BookServiceClient. Creating an instance of the class can establish a connection to the WCF service and give you access to public members. Continuing with the previous example, the client application could have an instance of the Book class and invoke the ValidateBook method for checking whether the Book instance is correct according to our needs. The code in Listing 39.5 shows how to accomplish this.

Listing 39.5. Instantiating the Proxy Class and Invoking Service Members


Imports BookClient.BookServiceReference

Module Module1

    Sub Main()
        'Creates an instance of the proxy class
        'and automatically establishes a connection
        'to the service
        Dim client As New BookServiceClient

        'A new book
        'Note that the RegEx pattern requires to write the ISBN in the form
        'provided below, so like: 000-0-0000-0000-0 including the minus
        'character
        Dim myBook As New Book
        With myBook
            .Author = "Alessandro Del Sole"
            .Title = "Visual Studio LightSwitch Unleashed"
            .ISBN = "978-0-6723-3553-2"
            .DatePublished = Date.Today
        End With

        'Invokes the ValidateBook method from
        'the service
        Console.WriteLine(client.ValidateBook(myBook))
        Console.WriteLine("Done")
        Console.ReadLine()
        client.Close()

    End Sub
End Module


In the client you can invoke all public members from the service, where public means functions decorated with the OperationContract attribute and data classes decorated with the DataContract attribute. Running the code in Listing 39.5 produces the result shown in Figure 39.5, but you can try to change the ISBN code to check how the application works with different values.

Image

Figure 39.5. The client application validated a book.

Remember to close the connection to the service invoking the Close method on the proxy class. This ensures that the service will be shut down.

Understanding the Configuration File

When you add a proxy class to your WCF service, Visual Studio also updates the configuration file to provide information on how to reach and interact with the service. The most important information is stored in the System.ServiceModel section of the app.config file. Listing 39.6 shows the most interesting excerpt.

Listing 39.6. Configuration Settings for the Client


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IBookService" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:18315/BookService.svc"
                      binding="basicHttpBinding"
                      bindingConfiguration="BasicHttpBinding_IBookService"
                      contract="BookServiceReference.IBookService"
                      name="BasicHttpBinding_IBookService" />
        </client>
    </system.serviceModel>
</configuration>


The app.config file maps the related nodes in the Web.config file from the service. This is important to remember in case you want to implement a custom configuration different from the default one. The bindings node defines how data and information are transferred. The basicHttpBinding binding is the simplest way and uses HTTP and Text or XML as the encoding format. WCF offers lots of other bindings specific for particular needs, such as secured communications or peer-to-peer applications. Table 39.3 summarizes built-in bindings.

Table 39.3. WCF Built-In Bindings

Image

WCF Simplification in .NET 4.5

Several simplification features in .NET 4.5 are specific for WCF. Among them, Visual Studio 2012 simplifies the generated app.config file for clients when you add a service reference. Such a simplification avoids the explicit specification of binding property values if they have the default value, making the XML code simpler. For example, a binding has the openTimeOut and closeTimeOut properties that, until Visual Studio 2010, were explicitly added to the binding with a value of 00:01:00 seconds. Because this is their default value, in Visual Studio 2012 they are no longer added explicitly in code and the runtime assumes they already have a value of 00:01:00. You will instead specify explicitly a binding property value only if such a property has a value different from the default one. This is the reason Listing 39.6 shows a simplified configuration file (if you purchased the previous edition of this book, you can easily check this out).


In addition to built-in bindings, WCF enables defining custom bindings, but this is beyond the scope of this chapter.


Implementing Secure Bindings on Both Service and Clients

The current code example uses, on both the service side and client side, the basicHttpBinding, which is the simplest binding available. Using a different binding depends on the particular scenario you need to work on. Because of this, look at the official MSDN documentation related to built-in bindings, which also provides examples and explanations on when each binding should be used. The documentation is located at the following address: http://msdn.microsoft.com/en-us/library/ms730879(v=vs.110).aspx.


You can also customize timeouts by specifying the closeTimeout, openTimeout, sendTimeout, and receiveTimeOut properties; you could change the maximum size for data exchange by setting maxBufferSize and maxReceivedMessageSize. These two are important because you might be required to increase the default size in case your application transfers large amounts of data. Now take a look at the client node. This defines the endpoint’s ABC, such as the address pointing to the physical URI of the service, the binding transport protocol, and the contract interface (BookServiceReference.IBookService). Notice that when moving the service to production, the address URI must be replaced with the Internet/intranet address of your service. This can be accomplished by replacing the address item in the configuration file without the need of rebuilding the application.

Handling Exceptions in WCF

WCF applications can throw communication exceptions that both services and clients need to handle. Typically, the most common exception in the WCF development is the System.ServiceModel.FaultException; it offers a generic, strongly typed flavor and a nongeneric one. The exception needs to first be handled in the WCF service, but the nongeneric implementation is less useful than the generic one because it provides less detailed information. Because of this, we now consider how to handle the FaultException(Of T). Replace the ValidateBook method definition in the IBookService interface as follows:

<OperationContract()> <FaultContract(GetType(Book))>
Function ValidateBook(ByVal bookToValidate As Book) As String

The FaultContract attribute receives the type that might encounter processing errors during the invocation of the service operation. This can enable the FaultException to throw detailed SOAP information for that type. To accomplish this, replace the ValidateBook method implementation in the BookService class with the following:

Public Function ValidateBook(ByVal bookToValidate As Book) As _
                String Implements IBookService.ValidateBook

    Try
        Dim isValidIsbn As Boolean = Regex.IsMatch(String.
                                     Concat("ISBN-13: ",
                                     bookToValidate.ISBN), isbnPattern)

        If isValidIsbn = False Then
            Return "Invalid ISBN"
        End If

        Dim isValidAuthor As Boolean = _
            String.IsNullOrEmpty(bookToValidate.Author)
        If isValidAuthor = True Then
            Return "Author not specified"
        End If

        Dim isValidTitle As Boolean = _
            String.IsNullOrEmpty(bookToValidate.Title)
        If isValidTitle = True Then
            Return "Title not specified"
        End If

        If bookToValidate.DatePublished Is Nothing Then
            Return _
            "Book data is valid but date published was not specified"
        End If

        Return "Valid book"

    Catch ex As FaultException(Of Book)
        Throw New FaultException(Of Book)(bookToValidate,
                                          ex.Reason, ex.Code)
    Catch ex As Exception
        Throw
    End Try
End Function

The intercepted FaultException is rethrown to the caller specifying the instance of the Book class that caused the error, a Reason property that contains a SOAP description of the problem, and a Code property that returns a machine-readable identifier used for understanding the problem. With these pieces of information, client applications can understand what the problem was during the communication.

Hosting WCF Services in Internet Information Services

Host applications for WCF services can be of various kinds. Besides the IIS Express or the ASP.NET Development Server, you can host services inside managed applications, Windows services, and Internet Information Services as well. In most cases, you will need to deploy to IIS so we will cover this scenario. To host your WCF service in IIS on your development machine, follow these steps:

1. Restart Visual Studio 2012 under administrator privileges.

2. Go to the My Project designer for the WCF service project and select the Web tab.

3. Check the Use Local IIS Web Server option, but uncheck the Use IIS Express option and specify, if required, a different directory; then rerun the WCF service (see Figure 39.6).

Image

Figure 39.6. Setting IIS as the deployment web server.

Visual Studio will request your permission for creating and configuring a virtual directory on IIS, so you just need to accept it. When this is done, remember to replace the endpoint address in the client application configuration file with the new service URI. To host a WCF service on a nondevelopment machine, you need to create a directory under the Default Website and link the physical folder to the folder where the .svc file is placed together with the compiled dll service. You do this via the Internet Information Services Manager administrative tools available in the Windows operating system.

Configuring Services with the Configuration Editor

WCF services enable high-level customizations over their configuration. This task can be complex if you consider that there are hundreds of options that you should translate into XML. Fortunately, the .NET Framework offers a graphical tool called WCF Service Configuration Editor that you can also launch from the Tools menu in Visual Studio. In this section, you see how this tool can be used to enable tracing for WCF services. Tracing is useful because it lets you record into log file (with .svclog extension) events occurring during the WCF service running time. When launched, open the Web.config file for your service. When ready, click the Diagnostics folder on the left and then click the Enable Tracing command under the Tracing title on the right (see Figure 39.7).

Image

Figure 39.7. Enabling tracing for WCF services.

By default, tracing records messages classified at least as warnings. To modify this behavior, click the Trace Level link. If you click the ServiceModelTraceListener link, you can also specify additional information to be tracked, such as the process ID, the call stack, and the Thread ID. To view the log of recorded information, you need to run the Service Trace Viewer tool located in the C:Program Files (x86)Microsoft SDKsWindowsv8.0AinNETFX 4.0 Tools folder on 64-bit machines (or C:Program FilesMicrosoft SDKsWindowsv8.0AinNETFX 4.0 Tools on 32-bit systems). When the tool is running, open the .svclog file, which usually resides in the service folder. Figure 39.8 shows an example of log analysis. The tool provides tons of information about every event occurring at the service level and is helpful if you encounter any problems.

Image

Figure 39.8. The Service Trace Viewer tool in action.

Summary

Windows Communication Foundation is a unified programming model for distributed applications that share information across networks. In this chapter, you got an introductory overview and then learned the basics about metadata. You learned that WCF services expose endpoints to be accessible from clients and that each endpoint exposes the ABC (Address-Binding-Contract). The contract is a .NET interface (marked with the ServiceContract attribute) that establishes service operations that can be consumed by clients. Services expose information and data through a class that implements the contract, which is the main entry point in the service. WCF services can also expose objects marked with the DataContract attribute and that represent data that services and clients can exchange. Next, you found out how to consume WCF services from clients by adding service references and creating proxy classes to access service members. The last part of this chapter provided an overview of exceptions handling and configurations with specific tools such as the Configuration Editor and the Service Trace Viewer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.212.102