Chapter 22
Windows Communication Foundation

Wrox.com Code Downloads for this Chapter

The wrox.com code downloads for this chapter are found at www.wrox.com/go/beginningvisualc#2015programming on the Download Code tab. The code is in the Chapter 22 download and individually named according to the names throughout the chapter.

In recent years, as use of the Internet has become more ubiquitous, there has been a rapid increase in web services. A web service is like a website that is used by a computer instead of a person. For example, instead of browsing to a website about your favorite TV program, you might instead use a desktop application that pulled in the same information via a web service. The advantage here is that the same web service might be used by all sorts of applications, and, indeed, by websites. Also, you can write your own application or website that uses third-party web services. Perhaps you might combine information about your favorite TV program with a mapping service to show filming locations.

The .NET Framework has supported web services for some time now. However, in the more recent versions of the framework, web services have been combined with another technology, called remoting, to create Windows Communication Foundation (WCF), which is a generic infrastructure for communication between applications.

Remoting makes it possible to create instances of objects in one process and use them from another process — even if the object is created on a computer other than the one that is using it. However, remoting on its own is limited, and isn't the easiest thing for a beginner programmer to learn.

WCF takes concepts such as services and platform-independent SOAP messaging from web services, and combines these with concepts such as host server applications and advanced binding capabilities from remoting. The result is a technology you can think of as a superset that includes both web services and remoting, but that is much more powerful than web services and much easier to use than remoting. Using WCF, you can move from simple applications to applications that use a service-oriented architecture (SOA). SOA means that you decentralize processing and make use of distributed processing by connecting to services and data as you need them across local networks and the Internet.

This chapter walks you through how to create and consume WCF services from your application code. But just as importantly, it also covers the principles behind WCF, so you understand why things work the way they do.

What Is WCF?

WCF is a technology that enables you to create services that you can access from other applications across process, machine, and network boundaries. You can use these services to share functionality across multiple applications, to expose data sources, or to abstract complicated processes.

The functionality that WCF services offer is encapsulated as individual methods that are exposed by the service. Each method — or, in WCF terminology, each operation — has an endpoint that you exchange data with in order to use it. This data exchange can be defined by one or more protocols, depending on the network that you use to connect to the service and your specific requirements.

In WCF, an endpoint can have multiple bindings, each of which specifies a means of communication. Bindings can also specify additional information, such as which security requirements must be met to communicate with the endpoint. A binding might require username and password authentication or a Windows user account token, for example. When you connect to an endpoint, the protocol that the binding uses affects the address that you use, as you will see shortly.

Once you have connected to an endpoint, you can communicate with it by using Simple Object Access Protocol (SOAP) messages. The form of the messages that you use depends on the operation you are using and the data structures that are required to send messages to (and receive messages from) that operation. WCF uses contracts to specify all of this. You can discover contracts through metadata exchange with a service. One commonly used format for service discovery is the Web Service Description Language (WSDL), which was originally used for web services, although WCF services can also be described in other ways.

When you have identified a service and endpoint that you want to use, and after you know which binding you use and which contracts to adhere to, you can communicate with a WCF service as easily as with an object that you have defined locally. Communications with WCF services can be simple, one-way transactions, request/response messages, or full-duplex communications that can be initiated from either end of the communication channel. You can also use message payload optimization techniques, such as Message Transmission Optimization Mechanism (MTOM), to package data if required.

The WCF service itself might be running in one of a number of different processes on the computer where it is hosted. Unlike web services, which always run in IIS, you can choose a host process that is appropriate to your situation. You can use IIS to host WCF services, but you can also use Windows services or executables. If you are using TCP to communicate with a WCF service over a local network, there is no need even to have IIS installed on the PC that is hosting the service.

The WCF framework has been designed to enable you to customize nearly everything you have read about in this section. However, this is an advanced subject and you will only be using the techniques provided by default in .NET 4.5 in this chapter.

Now that you have covered the basics about WCF services, you will look in more detail at these concepts in the following sections.

WCF Concepts

This section describes the following aspects of WCF:

  • WCF communication protocols
  • Addresses, endpoints, and bindings
  • Contracts
  • Message patterns
  • Behaviors
  • Hosting

WCF Communication Protocols

As described earlier, you can communicate with WCF services through a variety of transport protocols. In fact, five are defined in the .NET 4.5 Framework:

  • HTTP — Enables you to communicate with WCF services from anywhere, including across the Internet. You can use HTTP communications to create WCF web services.
  • TCP — Enables you to communicate with WCF services on your local network or across the Internet if you configure your firewall appropriately. TCP is more efficient than HTTP and has more capabilities, but it can be more complicated to configure.
  • UDP — User Datagram Protocol is similar to TCP in that it enables communications via the local network or Internet, but it's implemented in a subtly different way. One of the consequences of this implementation is that a service can broadcast messages to multiple clients simultaneously.
  • Named pipe — Enables you to communicate with WCF services that are on the same machine as the calling code, but reside in a separate process.
  • MSMQ — Microsoft Message Queuing is a queuing technology that enables messages sent by an application to be routed through a queue to arrive at a destination. MSMQ is a reliable messaging technology that ensures that a message sent to a queue will reach that queue. MSMQ is also inherently asynchronous, so a queued message will be processed only when messages ahead of it in the queue have been processed and a processing service is available.

These protocols often enable you to establish secure connections. For example, you can use the HTTPS protocol to establish an SSL connection across the Internet. TCP offers extensive possibilities for security in a local network by using the Windows security framework. UDP doesn't support security.

In order to connect to a WCF service, you must know where it is. In practice, this means knowing the address of an endpoint.

Addresses, Endpoints, and Bindings

The type of address you use for a service depends on the protocol that you are using. Service addresses are formatted for the three protocols described in this chapter (MSMQ is not covered) as follows:

  • HTTP — Addresses for the HTTP protocol are URLs of the familiar form http://<server>:<port>/<service>. For SSL connections, you can also use https://<server>:<port>/<service>. If you are hosting a service in IIS, <service> will be a file with a .svc extension. IIS addresses will probably include more subdirectories than this example — that is, more sections separated by / characters before the .svc file.
  • TCP — Addresses for TCP are of the form net.tcp://<server>:<port>/<service>.
  • UDP — Addresses for UDP are of the form soap.udp://<server>:<port>/<service>. Certain <server> values are required for multicast communications, but this is beyond the scope of this chapter.
  • Named pipe — Addresses for named pipe connections are similar but have no port number. They are of the form net.pipe://<server>/<service>.

The address for a service is a base address that you can use to create addresses for endpoints representing operations. For example, you might have an operation at net.tcp://<server>:<port>/<service>/operation1.

For example, imagine you create a WCF service with a single operation that has bindings for all three of the protocols listed here. You might use the following base addresses:

http://www.mydomain.com/services/amazingservices/mygreatservice.svc
net.tcp://myhugeserver:8080/mygreatservice
net.pipe://localhost/mygreatservice

You could then use the following addresses for operations:

http://www.mydomain.com/services/amazingservices/mygreatservice.svc/greatop
net.tcp://myhugeserver:8080/mygreatservice/greatop
net.pipe://localhost/mygreatservice/greatop

Since .NET 4, it has been possible to use default endpoints for operations, without having to explicitly configure them. This simplifies configuration, especially in situations where you want to use standard endpoint addresses, as in the preceding examples.

Bindings, as mentioned earlier, specify more than just the transport protocol that will be used by an operation. You can also use them to specify the security requirements for communication over the transport protocol, transactional capabilities of the endpoint, message encoding, and much more.

Because bindings offer such a great degree of flexibility, the .NET Framework provides some predefined bindings that you can use. You can also use these bindings as starting points, tweaking them to obtain exactly the type of binding you want — up to a point. The predefined bindings have certain capabilities to which you must adhere. Each binding type is represented by a class in the System.ServiceModel namespace. Table 22.1 lists the most commonly used bindings along with some basic information about them.

Table 22.1 Binding Types

Binding Description
BasicHttpBinding The simplest HTTP binding, and the default binding used by web services. It has limited security capabilities and no transactional support.
WSHttpBinding A more advanced form of HTTP binding that is capable of using all the additional functionality that was introduced in WSE.
WSDualHttpBinding Extends WSHttpBinding capabilities to include duplex communication capabilities. With duplex communication, the server can initiate communications with the client in addition to ordinary message exchange.
WSFederationHttpBinding Extends WSHttpBinding capabilities to include federation capabilities. Federation enables third parties to implement single sign-on and other proprietary security measures. This is an advanced topic not covered in this chapter.
NetTcpBinding Used for TCP communications, and enables you to configure security, transactions, and so on.
NetNamedPipeBinding Used for named pipe communications, and enables you to configure security, transactions, and so on.
NetMsmqBinding Used with MSMQ, which is not covered in this chapter.
NetPeerTcpBinding Used for peer-to-peer binding, which is not covered in this chapter.
WebHttpBinding Used for web services that use HTTP requests instead of SOAP messages.
UdpBinding Allows binding to the UDP protocol.

Many of the binding classes have similar properties that you can use for additional configuration. For example, they have properties that you can use to configure timeout values. You'll learn more about this when you look at code later in this chapter.

Since .NET 4, endpoints have default bindings that vary according to the protocol used. These defaults are shown in Table 22.2.

Table 22.2 NET Default Bindings

Protocol Default Binding
HTTP BasicHttpBinding
TCP NetTcpBinding
UDP UdpBinding
Named pipe NetNamedPipeBinding
MSMQ NetMsmqBinding

Contracts

Contracts define how WCF services can be used. Several types of contract can be defined:

  • Service contract — Contains general information about a service and the operations exposed by a service. This includes, for example, the namespace used by service. Services have unique namespaces that are used when defining the schema for SOAP messages in order to avoid possible conflicts with other services.
  • Operation contract — Defines how an operation is used. This includes the parameter and return types for an operation method along with additional information, such as whether a method will return a response message.
  • Message contract — Enables you to customize how information is formatted inside SOAP messages — for example, whether data should be included in the SOAP header or SOAP message body. This can be useful when creating a WCF service that must integrate with legacy systems.
  • Fault contract — Defines faults that an operation can return. When you use .NET clients, faults result in exceptions that you can catch and deal with in the normal way.
  • Data contract — If you use complex types, such as user-defined structs and objects, as parameters or return types for operations, then you must define data contracts for these types. Data contracts define the types in terms of the data that they expose through properties.

You typically add contracts to service classes and methods by using attributes, as you will see later in this chapter.

Message Patterns

In the previous section, you saw that an operation contract can define whether an operation returns a value. You've also read about duplex communications that are made possible by the WSDualHttpBinding binding. These are both forms of message patterns, of which there are three types:

  • Request/response messaging — The “ordinary” way of exchanging messages, whereby every message sent to a service results in a response being sent back to the client. This doesn't necessarily mean that the client waits for a response, as you can call operations asynchronously in the usual way.
  • One-way, or simplex, messaging — Messages are sent from the client to the WCF operation, but no response is sent.
  • Two-way, or duplex, messaging — A more advanced scheme whereby the client effectively acts as a server as well as a client, and the server as a client as well as a server. Once set up, duplex messaging enables both the client and the server to send messages to each other, which might not have responses.

You'll see how these message patterns are used in practice later in this chapter.

Behaviors

Behaviors are a way to apply additional configuration that is not directly exposed to a client to services and operations. By adding a behavior to a service, you can control how it is instantiated and used by its hosting process, how it participates in transactions, how multithreading issues are dealt with in the service, and so on. Operation behaviors can control whether impersonation is used in the operation execution, how the individual operation affects transactions, and more.

Since .NET 4, you can specify default behaviors at various levels, so that you don't have to specify every aspect of every behavior for every service and operation. Instead, you can provide defaults and override settings where necessary, which reduces the amount of configuration required.

Hosting

In the introduction to this chapter, you learned that WCF services can be hosted in several different processes. These possibilities are as follows:

  • Web server — IIS-hosted WCF services are the closest thing to web services that WCF offers. However, you can use advanced functionality and security features in WCF services that are much more difficult to implement in web services. You can also integrate with IIS features such as IIS security.
  • Executable — You can host a WCF service in any application type that you can create in .NET, such as console applications, Windows Forms applications, and WPF applications.
  • Windows service — You can host a WCF service in a Windows service, which means that you can use the useful features that Windows services provide. This includes automatic startup and fault recovery.
  • Windows Activation Service (WAS) — Designed specifically to host WCF services, WAS is basically a simple version of IIS that you can use where IIS is not available.

Two of the options in the preceding list — IIS and WAS — provide useful features for WCF services such as activation, process recycling, and object pooling. If you use either of the other two hosting options, the WCF service is said to be self-hosted. You will occasionally self-host services for testing purposes, but there can be very good reasons for creating self-hosted production-grade services. For example, you could be in a situation where you're not allowed to install a web server on the computer on which your service should run. This might be the case if the service runs on a domain controller or if the local policy of your organization simply prohibits running IIS. In this case you can host the service in a Windows service and it will work every bit as well as it would otherwise.

WCF Programming

Now that you have covered all the basics, it is time to get started with some code. In this section you'll start by looking as a simple web server–hosted WCF service and a console application client. After looking at the structure of the code created, you'll learn about the basic structure of WCF services and client applications. Then you will look at some key topics in a bit more detail:

  • Defining WCF service contracts
  • Self-hosted WCF services

The WCF Test Client

In the previous Try It Out, you created both a service and a client in order to look at how the basic WCF architecture works and how configuration of WCF services is achieved. In practice, though, the client application you want to use might be complex, and it can be tricky to test services properly.

To ease the development of WCF services, Visual Studio provides a test tool you can use to ensure that your WCF operations work correctly. This tool is automatically configured to work with your WCF service projects, so if you run your project the tool will appear. All you need to do is ensure that the service you want to test (that is, the .svc file) is set to be the startup page for the WCF service project. Alternatively, you can run the test client as a standalone application. You can find the test client on 64-bit operating systems at C:Program Files (x86)Microsoft Visual Studio 14.0Common7IDEWcfTestClient.exe.

If you are using a 32-bit operating system, the path is the same except the root folder is Program Files.

The tool enables you to invoke service operations and inspect the service in some other ways. The following Try It Out illustrates this.

Defining WCF Service Contracts

The previous examples showed how the WCF infrastructure makes it easy for you to define contracts for WCF services with a combination of classes, interfaces, and attributes. This section takes a deeper look at this technique.

Data Contracts

To define a data contract for a service, you apply the DataContractAttribute attribute to a class definition. This attribute is found in the System.Runtime.Serialization namespace. You can configure this attribute with the properties shown in Table 22.3.

Table 22.3 DataContractAttribute Properties

Property Description
Name Names the data contract with a different name than the one you use for the class definition. This name will be used in SOAP messages and client-side data objects that are defined from service metadata.
Namespace Defines the namespace that the data contract uses in SOAP messages.
IsReference Affects the way that objects are serialized. If this is set to true, then an object instance is serialized only once even if it is referenced several times, which can be important is some situations. The default is false.

The Name and Namespace properties are useful when you need interoperability with existing SOAP message formats (as are the similarly named properties for other contracts), but otherwise you will probably not require them.

Each class member that is part of a data contract must use the DataMemberAttribute attribute, which is also found in the System.Runtime.Serialization namespace. Table 22.4 lists this attribute's properties.

Table 22.4 DataMemberAttribute Properties

Property Description
Name Specifies the name of the data member when serialized (the default is the member name).
IsRequired Specifies whether the member must be present in a SOAP message.
Order An int value specifying the order of serializing or deserializing the member, which might be required if one member must be present before another can be understood. Lower Order members are processed first.
EmitDefaultValue Set this to false to prevent members from being included in SOAP messages if their value is the default value for the member.

Service Contracts

Service contracts are defined by applying the System.ServiceModel.ServiceContractAttribute attribute to an interface definition. You can customize the service contract with the properties shown in Table 22.5.

Table 22.5 ServiceContractAttribute Properties

Property Description
Name Specifies the name of the service contract as defined in the <portType> element in WSDL.
Namespace Defines the namespace of the service contract used by the <portType> element in WSDL.
ConfigurationName The name of the service contract as used in the configuration file.
HasProtectionLevel Determines whether messages used by the service have explicitly defined protection levels. Protection levels enable you to sign, or sign and encrypt, messages.
ProtectionLevel The protection level to use for message protection.
SessionMode Determines whether sessions are enabled for messages. If you use sessions, then you can ensure that messages sent to different endpoints of a service are correlated — that is, they use the same service instance and so can share state, and so on.
CallbackContract For duplex messaging the client exposes a contract as well as the service. This is because, as discussed earlier, the client in duplex communications also acts as a server. This property enables you to specify which contract the client uses.

Operation Contracts

Within interfaces that define service contracts, you define members as operations by applying the System.ServiceModel.OperationContractAttribute attribute. This attribute has the properties described in Table 22.6.

Table 22.6 OperationContractAttribute Properties

Property Description
Name Specifies the name of the service operation. The default is the member name.
IsOneWay Specifies whether the operation returns a response. If you set this to true, then clients won't wait for the operation to complete before continuing.
AsyncPattern If set to true, the operation is implemented as two methods that you can use to call the operation asynchronously: Begin<methodName>() and End<methodName>().
HasProtectionLevel See the previous section.
ProtectionLevel See the previous section.
IsInitiating If sessions are used, then this property determines whether calling this operation can start a new session.
IsTerminating If sessions are used, then this property determines whether calling this operation terminates the current session.
Action If you are using addressing (an advanced capability of WCF services), then an operation has an associated action name, which you can specify with this property.
ReplyAction As with Action, but specifies the action name for the operation response.

Message Contracts

The earlier example didn't use message contract specifications. If you use these, then you do so by defining a class that represents the message and applying the MessageContractAttribute attribute to the class. You then apply MessageBodyMemberAttribute, MessageHeaderAttribute, or MessageHeaderArrayAttribute attributes to members of this class. All these attributes are in the System.ServiceModel namespace. You are unlikely to want to do this unless you need a very high degree of control over the SOAP messages used by WCF services, so details are not provided here.

Fault Contracts

If you have a particular exception type — for example, a custom exception — that you want to make available to client applications, then you can apply the System.ServiceModel.FaultContractAttribute attribute to the operation that might generate this exception.

Self-Hosted WCF Services

So far in this chapter you have seen WCF services that are hosted in web servers. This enables you to communicate across the Internet, but for local network communications it is not the most efficient way of doing things. For one thing, you need a web server on the computer that hosts the service. In addition, the architecture of your applications might be such that having an independent WCF service isn't desirable.

Instead, you might want to use a self-hosted WCF service. A self-hosted WCF service exists in a process that you create, rather than in the process of a specially made hosting application such as a web server. This means, for example, that you can use a console application or Windows application to host your service.

To self-host a WCF service, you use the System.ServiceModel.ServiceHost class. You instantiate this class with either the type of the service you want to host or an instance of the service class. You can configure a service host through properties or methods, or (and this is the clever part) through a configuration file. In fact, host processes, such as web servers, use a ServiceHost instance to do their hosting. The difference when self-hosting is that you interact with this class directly. However, the configuration you place in the <system.serviceModel> section of the app.config file for your host application uses exactly the same syntax as the configuration sections you've already seen in this chapter.

You can expose a self-hosted service through any protocol that you like, although typically you will use TCP or named pipe binding in this type of application. Services accessed through HTTP are more likely to live inside web server processes, because you get the additional functionality that web servers offer, such as security and other features.

If you want to host a service called MyService, you could use code such as the following to create an instance of ServiceHost:

ServiceHost host = new ServiceHost(typeof(MyService));

If you want to host an instance of MyService called myServiceObject, you could code as follows to create an instance of ServiceHost:

MyService myServiceObject = new MyService();
ServiceHost host = new ServiceHost(myServiceObject);

After creating a ServiceHost instance you can configure the service and its endpoints and binding through properties. Alternatively, if you put your configuration in a .config file, the ServiceHost instance will be configured automatically.

To start hosting a service once you have a configured ServiceHost instance, you use the ServiceHost.Open() method. Similarly, you stop hosting the service through the ServiceHost.Close() method. When you first start hosting a TCP-bound service, you might, if you have it enabled, receive a warning from the Windows Firewall service, as it will block the TCP port by default. You must open the TCP port for the service to begin listening on the port.

In the following Try it Out you use self-hosting techniques to expose some functionality of a WPF application through a WCF service.

image What You Learned in this Chapter

Topic Key Concepts
WCF fundamentals WCF provides a framework for creating and communicating with remote services. It combines elements of the web service and remoting architectures along with new technologies to achieve this.
Communication protocols You can communicate with a WCF service by any one of several protocols, including HTTP and TCP. This means that you can use services that are local to your client application, or that are separated by machine or network boundaries. To do this, you access a specific endpoint for the service through a binding corresponding to the protocol and features that you require. You can control these features, such as using session state or exposing metadata, through behaviors. .NET 4.5 includes many default settings to make it very easy to define a simple service.
Communication payload Typically, calls to responses from WCF services are encoded as SOAP messages. However, there are alternatives, such as plain HTTP messages, and you can define your own payload types from scratch if you need to.
Hosting WCF services might be hosted in IIS or in a Windows service, or they can be self-hosted. Using a host such as IIS enables you to make use of the host's built-in capabilities, including security and application pooling. Self-hosting is more flexible, but it can require more configuration and coding.
Contracts You define the interface between a WCF service and client code through contracts. Services themselves, along with any operations they expose, are defined with service and operation contracts. Data types are defined with data contracts. Further customization of communications is achieved with message and fault contracts.
Client applications Client applications communicate with WCF services by means of a proxy class. Proxy classes implement the service contract interface for the service, and any calls to operation methods of this interface are redirected to the service. You can generate a proxy by using the Add Service Reference tool, or you can create one programmatically through channel factory methods. In order for communications to succeed, the client must be configured to match the service configuration.
..................Content has been hidden....................

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