Beruflich Dokumente
Kultur Dokumente
The global acceptance of Web services, which includes standard protocols for application-to-
application communication, has changed software development. For example, the functions that
Web services now provide include security, distributed transaction coordination, and reliable
communication. The benefits of the changes in Web services should be reflected in the tools and
technologies that developers use. Windows Communication Foundation (WCF) is designed to offer a
manageable approach to distributed computing, broad interoperability, and direct support for service
orientation.
The typed programming model (called the service model) is designed to ease the development of
distributed applications and to provide developers with expertise in ASP.NET Web services, .NET
Framework remoting, and Enterprise Services, and who are coming to WCF with a familiar
development experience. The service model features a straightforward mapping of Web services
concepts to those of the .NET Framework common language runtime (CLR), including flexible and
extensible mapping of messages to service implementations in languages such as Visual C# or
Visual Basic. It includes serialization facilities that enable loose coupling and versioning, and it
provides integration and interoperability with existing .NET Framework distributed systems
technologies such as Message Queuing (MSMQ), COM+, ASP.NET Web services, Web Services
Enhancements (WSE), and a number of other functions.
Problem Example
The following example illustrates some of the problems that WCF addresses. A car rental company
decides to create a new application for reserving cars. The creators of this rental car reservation
application know that the business logic it implements must be accessible by other software running
both inside and outside their company. Accordingly, they decide to build it in a service-oriented
style, with the application’s logic exposed to other software through a well-defined set of services.
To implement these services, and thus communicate with other software, the new application will
use WCF.
Over its lifetime, the rental car reservation application will likely be accessed by a range of other
applications. When it is designed, however, the architects of the rental car reservation application
know that its business logic will be accessed, as shown in the preceding figure, by three other kinds
of software:
• A call center client application running on the Windows desktops that are used by
employees in the organization’s call center. Created specifically for the new reservations
system, this application will also be built using the Microsoft .NET Framework and WCF. This
application is not truly distinct from the new rental car reservation application, because its
only purpose is to act as a client for the new system. From a service-oriented perspective,
it is just another client for the reservation system’s business logic.
• Partner applications running on a variety of platforms, each located within a company that
has a business arrangement with the car rental firm. Partners might include travel agencies,
airlines, and others that have a business requirement to make car rental reservations.
The diverse communication requirements for the new rental car reservation application are not
simple. For interactions with the call center client application, for instance, performance is
important, while interoperability is straightforward, because both are built on the .NET Framework.
For communication with the existing J2EE-based reservation application and with the diverse
partner applications, however, interoperability becomes the highest goal. The security requirements
are also quite different, varying across local Windows-based applications, a J2EE-based application
running on another operating system, and a variety of partner applications coming in across the
Internet. Even transactional requirements might vary, with only the internal applications being
allowed to make transactional requests. How can these diverse business and technical requirements
be met without exposing the creators of the new application to unmanageable complexity?
WCF is designed for this diverse but realistic scenario and is the default technology for Windows
applications that expose and access services. This topic provides an introduction to WCF, examining
what it provides and showing how it is used. Throughout this introduction, the scenario just
described will serve as an example. The goal is to make clear what WCF is, show what problems it
solves, and illustrate how it solves those problems.
The figure shows a view of a WCF client and service. The two interact using SOAP, the WCF native
message representation, so even though the figure shows both parties built on WCF, this is not
required. WCF is built on .NET Framework 2.0.
As the scenario described earlier suggests, WCF addresses a range of challenges for communicating
applications. Three things stand out, however, as the most important aspects of WCF:
• ASP.NET Web services (ASMX). An option for communicating with the J2EE-based existing
reservation application and with the partner applications across the Internet. Given that
basic Web services are supported today on most platforms, this was the most direct way to
achieve cross-vendor interoperability before the release of WCF.
• .NET Framework remoting. An option for communication with the call center application,
because both are built on the .NET Framework. Remoting is designed expressly for tightly
coupled .NET-to-.NET communication, so it offers a seamless and straightforward
development experience for applications in the local network.
• Enterprise Services. Used by the rental car reservation application for managing object
lifetimes and defining distributed transactions. These functions could be useful in
communicating and integrating with any of the other applications in this scenario, but
Enterprise Services supports only a limited set of communication options.
• WSE. Could be used along with ASMX to communicate with the J2EE-based reservation
application and with the partner applications. Because it implements more recently defined
Web services agreements, known collectively as the WS-* specifications, WSE allows for
more flexible Web services security, as long as all applications involved support compatible
versions of these new specifications.
Built on .NET Framework, the rental car reservation application must use more than one of these
communication technologies to meet its requirements. Although this is technically possible, the
resulting application would be complex to implement and challenging to maintain.
With WCF, the solution is much easier to implement. As the figure shows, WCF can be used for all
the situations previously described. Accordingly, the rental car reservation application can use this
single technology for all of its application-to-application communication. The following shows how
WCF addresses each of these requirements:
• Because WCF can communicate using Web services, interoperability with other platforms
that also support SOAP, such as the leading J2EE-based application servers, is
straightforward.
• You can also configure and extend WCF to communicate with Web services using messages
not based on SOAP, for example, simple XML formats like RSS.
• Performance is of paramount concern for most businesses. WCF is developed with the goal
of being one of the fastest distributed application platform developed by Microsoft. For a
high-level performance comparison between WCF and other Microsoft .NET distributed
communication technologies, see http://go.microsoft.com/fwlink/?LinkId=94274.
• To allow optimal performance when both parties in a communication are built on WCF, the
wire encoding used in this case is an optimized binary version of an XML Information Set.
Messages still conform to the data structure of a SOAP message, but their encoding uses a
binary representation of that data structure rather than the standard angle-brackets-and-
text format of the XML 1.0 text encoding. Using this option makes sense for communicating
with the call center client application, because it is also built on WCF, and performance is an
important concern.
• Managing object lifetimes, defining distributed transactions, and other aspects of Enterprise
Services are now provided by WCF. They are available to any WCF-based application, which
means that the rental car reservation application can use them with any of the other
applications it communicates with.
• Because it supports a large set of the WS-* specifications, WCF helps provide reliability,
security, and transactions when communicating with any platform that also supports these
specifications.
• The WCF option for queued messaging, built on Message Queuing, allows applications to
use persistent queuing without using another set of application programming interfaces.
The result of this unification is greater functionality and significantly reduced complexity.
Interoperability with Applications Built on Other Technologies
While WCF introduces a new development environment for distributed applications, it is designed to
interoperate well with the non-WCF applications. There are two important aspects to WCF
interoperability: interoperability with other platforms, and interoperability with the Microsoft
technologies that preceded WCF. The following section describes both.
• Applications built on other technologies, such as J2EE application servers, that support
standard Web services. These applications can be running on Windows machines or on
machines running other operating systems.
To allow more than just basic communication, WCF implements Web services technologies defined
by the WS-* specifications. All of these specifications were originally defined by Microsoft, IBM, and
other vendors working together. As the specifications become stable, ownership often passes to
standards bodies, such as the World Wide Web Consortium (W3C) or the Organization for the
Advancement of Structured Information Standards (OASIS). These specifications address several
areas, including basic messaging, security, reliability, transactions, and working with a service’s
metadata. For more information, see Interoperability and Integration. For more information about
advanced Web services specifications, see http://go.microsoft.com/fwlink/?LinkId=86603.
• Messaging: SOAP is the foundation for Web services and defines a basic envelope that
contains header and a body sections. WS-Addressing defines additions to the SOAP header
for addressing SOAP messages, which frees SOAP from relying on the underlying transport
protocol, such as HTTP, to carry addressing information. Message Transmission Optimization
Mechanism (MTOM) defines an optimized transmission format for SOAP messages with large
binary data contents based on the XML-binary Optimized Packaging (XOP) specification.
• Metadata: The Web Services Description Language (WSDL) defines a standard language for
specifying services and various aspects of how those services can be used. WS-Policy allows
specification of more dynamic aspects of a service’s behavior that cannot be expressed in
WSDL, such as a preferred security option. WS-MetadataExchange allows a client to directly
request descriptive information about a service, such as its WSDL and its policies, using
SOAP.
The rental car reservation application would likely use several of these more advanced technologies.
For example, WS-Addressing is essential whenever SOAP is used over a transport mechanism other
than HTTP, which might be the case for communication with the .NET Framework-based call center
client application. WCF relies on WS-Policy and WS-Metadata Exchange to discover whether the
system it is communicating with is also using WCF and for other things. Reliable communication is
essential for most situations, so it is likely that WS-Reliable Messaging would be used to interact
with many of the other applications in this scenario. Similarly, you might also use WS-Security and
the related specifications for securing the communication with one or more of the applications,
because all would require some kind of protection against unauthorized access or message
modification and interception. For the applications that require transaction integration with the
rental car reservation system, WS-Atomic Transaction would be essential. Finally, MTOM could be
used whenever an optimized wire format for binary data is necessary (for instance for pictures of
fleet examples), and both sides of the communication supported this option.
The key point is that WCF implements interoperable Web services complete with cross-platform
security, reliability, transactions, and other services. To provide maximum throughput, WCF-to-WCF
communication can be significantly optimized, but all other communication uses standard Web
services protocols. In fact, it is possible for a single application to expose its services to both kinds
of clients.
For example, both WCF and ASMX use SOAP, so WCF-based applications can directly interoperate
with those built on ASMX. Existing Enterprise Services applications can also be wrapped with WCF
interfaces, allowing them to interoperate with applications built on WCF. And because persistent
queuing in WCF relies on MSMQ, WCF-based applications can interoperate directly with non-WCF-
based applications built using native MSMQ interfaces. In the rental car reservations application,
software built using any of these earlier technologies could directly connect to and use the new
system’s WCF-based services.
Interoperability is not always possible, however. For example, even though WSE 1.0 and WSE 2.0
implement some of the same WS-* specifications as WCF, these earlier technologies implement
earlier versions of the specifications. Version 3.0 of WSE does allow interoperability with WCF, but
earlier versions do not. For more information about interoperability, seeMigrating WSE 3.0 Web
Services to WCF.
REST is just one example of an evolving Web 2.0 technology. In this environment of experimental
programming models and ongoing reinterpretation and refinement of standards, flexibility is
required to cope with unforeseeable changes. WCF is flexible. For example, while WCF uses SOAP as
an underlying structure, it is not bound to using SOAP for wire communication. In fact, WCF can be
configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be
extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-
XML formats, such as JavaScript Object Notation (JSON). This flexibility ensures that code written
today will be valid in the future, even if protocols change or are replaced. Therefore, WCF was
designed for the present and the future.
WCF Fundamentals
Windows Communication Foundation (WCF) is a runtime and a set of APIs for creating systems that
send messages between services and clients. The same infrastructure and APIs are used to create
applications that communicate with other applications on the same computer system or on a system
that resides in another company and is accessed over the Internet.
The model distinguishes between clients, which are applications that initiate communication,
and services, which are applications that wait for clients to communicate with them and respond to
that communication. A single application can act as both a client and a service.
Messages are sent between endpoints. Endpoints are places where messages are sent or received
(or both), and they define all the information required for the message exchange. A service exposes
one or more application endpoints (as well as zero or more infrastructure endpoints), and the client
generates an endpoint that is compatible with one of the service's endpoints.
An endpoint describes in a standard-based way where messages should be sent, how they should
be sent, and what the messages should look like. A service can expose this information as metadata
that clients can process to generate appropriate WCF clients and communication stacks.
Communication Protocols
One required element of the communication stack is the transport protocol. Messages can be sent
over intranets and the Internet using common transports, such as HTTP and TCP. Other transports
are included that support communication with Microsoft Message Queuing (MSMQ) applications and
nodes on a Peer Networking mesh. More transport mechanisms can be added using the built-in
extension points of WCF.
Another required element in the communication stack is the encoding that specifies how any given
message is formatted. WCF provides the following encodings:
• Text encoding, an interoperable encoding.
More encoding mechanisms (for example, a compression encoding) can be added using the built-in
extension points of WCF.
Message Patterns
WCF supports several messaging patterns, including request-reply, one-way, and duplex
communication. Different transports support different messaging patterns, and thus affect the types
of interactions that they support. The WCF APIs and runtime also help you to send messages
securely and reliably.
WCF Terms
Other concepts and terms used in the WCF documentation include the following.
message
A message is a self-contained unit of data that may consist of several parts, including a
body and headers.
service
A service is a construct that exposes one or more endpoints, with each endpoint exposing
one or more service operations.
endpoint
An endpoint is a construct at which messages are sent or received (or both). It comprises a
location (an address) that defines where messages can be sent, a specification of the
communication mechanism (a binding) that described how messages should be sent, and a
definition for a set of messages that can be sent or received (or both) at that location (a
service contract) that describes what message can be sent.
An WCF service is exposed to the world as a collection of endpoints.
application endpoint
An address specifies the location where messages are received. It is specified as a Uniform
Resource Identifier (URI). The URI schema part names the transport mechanism to use to
reach the address, such as HTTP and TCP. The hierarchical part of the URI contains a unique
location whose format is dependent on the transport mechanism.
The endpoint address enables you to create unique endpoint addresses for each endpoint in
a service, or under certain conditions share an address across endpoints. The following
example shows an address using the HTTPS protocol with a non-default port:
HTTPS://cohowinery:8005/ServiceModelSamples/CalculatorService
binding
The service contract ties together multiple related operations into a single functional unit.
The contract can define service-level settings, such as the namespace of the service, a
corresponding callback contract, and other such settings. In most cases, the contract is
defined by creating an interface in the programming language of your choice and applying
the ServiceContractAttribute attribute to the interface. The actual service code results by
implementing the interface.
operation contract
An operation contract defines the parameters and return type of an operation. When
creating an interface that defines the service contract, you signify an operation contract by
applying the OperationContractAttribute attribute to each method definition that is part of
the contract. The operations can be modeled as taking a single message and returning a
single message, or as taking a set of types and returning a type. In the latter case, the
system will determine the format for the messages that need to be exchanged for that
operation.
message contract
A message contract describes the format of a message. For example, it declares whether
message elements should go in headers versus the body, what level of security should be
applied to what elements of the message, and so on.
fault contract
A fault contract can be associated with a service operation to denote errors that can be
returned to the caller. An operation can have zero or more faults associated with it. These
errors are SOAP faults that are modeled as exceptions in the programming model.
data contract
The data types a service uses must be described in metadata to enable others to
interoperate with the service. The descriptions of the data types are known as the data
contract, and the types can be used in any part of a message, for example, as parameters
or return types. If the service is using only simple types, there is no need to explicitly use
data contracts.
hosting
A service must be hosted in some process. A host is an application that controls the lifetime
of the service. Services can be self-hosted or managed by an existing hosting process.
self-hosted service
A self-hosted service is one that runs within a process application that the developer
created. The developer controls its lifetime, sets the properties of the service, opens the
service (which sets it into a listening mode), and closes the service.
hosting process
A hosting process is an application that is designed to host services. These include Internet
Information Services (IIS), Windows Activation Services (WAS), and Windows Services. In
these hosted scenarios, the host controls the lifetime of the service. For example, using IIS
you can set up a virtual directory that contains the service assembly and configuration file.
When a message is received, IIS starts the service and controls its lifetime.
instancing
A service has an instancing model. There are three instancing models: "single," in which a
single CLR object services all the clients; "per call," in which a new CLR object is created to
handle each client call; and "per session," in which a set of CLR objects are created, one for
each separate session. The choice of an instancing model depends on the application
requirements and the expected usage pattern of the service.
client application
A client application is a program that exchanges messages with one or more endpoints. The
client application begins by creating an instance of a WCF client and calling methods of the
WCF client. It is important to note that a single application can be both a client and a
service.
channel
metadata
The metadata of a service describes the characteristics of the service that an external entity
needs to understand to communicate with the service. Metadata can be consumed by
the ServiceModel Metadata Utility Tool (Svcutil.exe) to generate a WCF client and
accompanying configuration that a client application can use to interact with the service.
The metadata exposed by the service includes XML schema documents, which define the
data contract of the service, and WSDL documents, which describe the methods of the
service.
When enabled, metadata for the service is automatically generated by WCF by inspecting
the service and its endpoints. To publish metadata from a service, you must explicitly
enable the metadata behavior.
security
Security can be provided by one of three modes: transport mode, message security mode,
and transport with message credential mode. The transport security mode specifies that
confidentiality, integrity, and authentication are provided by the transport layer mechanisms
(such as HTTPS). When using a transport like HTTPS, this mode has the advantage of being
efficient in its performance, and well understood because of its prevalence on the Internet.
The disadvantage is that this kind of security is applied separately on each hop in the
communication path, making the communication susceptible to a "man in the middle"
attack.
message security mode
Message security mode specifies that security is provided by implementing one or more of
the security specifications, such as the specification named "Web Services Security: SOAP
Message Security" (available at http://go.microsoft.com/fwlink/?LinkId=94684). Each
message contains the necessary mechanisms to provide security during its transit, and to
enable the receivers to detect tampering and to decrypt the messages. In this sense, the
security is encapsulated within every message, providing end-to-end security across
multiple hops. Because security information becomes part of the message, it is also possible
to include multiple kinds of credentials with the message (these are referred to as claims).
This approach also has the advantage of enabling the message to travel securely over any
transport, including multiple transports between its origin and destination. The
disadvantage of this approach is the complexity of the cryptographic mechanisms
employed, resulting in performance implications.
transport with message credential security mode
This mode uses the transport layer to provide confidentiality, authentication, and integrity
of the messages, while each of the messages can contain multiple credentials (claims)
required by the receivers of the message.
WS-*
Shorthand for the growing set of Web Service (WS) specifications, such as WS-Security,
WS-ReliableMessaging, and so on, that are implemented in WCF.
Windows Communication Foundation Architecture
The following graphic illustrates the major layers of the Windows Communication Foundation (WCF)
architecture.
WCF Architecture
Policies and bindings stipulate the conditions required to communicate with a service. For example,
the binding must (at a minimum) specify the transport used (for example, HTTP or TCP), and an
encoding. Policies include security requirements and other conditions that must be met to
communicate with a service.
Service Runtime
The service runtime layer contains the behaviors that occur only during the actual operation of the
service, that is, the runtime behaviors of the service. Throttling controls how many messages are
processed, which can be varied if the demand for the service grows to a preset limit. An error
behavior specifies what occurs when an internal error occurs on the service, for example, by
controlling what information is communicated to the client. (Too much information can give a
malicious user an advantage in mounting an attack.) Metadata behavior governs how and whether
metadata is made available to the outside world. Instance behavior specifies how many instances of
the service can be run (for example, a singleton specifies only one instance to process all
messages). Transaction behavior enables the rollback of transacted operations if a failure occurs.
Dispatch behavior is the control of how a message is processed by the WCF infrastructure.
Extensibility enables customization of runtime processes. For example, message inspection is the
facility to inspect parts of a message, and parameter filtering enables preset actions to occur based
on filters acting on message headers.
Messaging
The messaging layer is composed of channels. A channel is a component that processes a message
in some way, for example, by authenticating a message. A set of channels is also known as
a channel stack. Channels operate on messages and message headers. This is different from the
service runtime layer, which is primarily concerned about processing the contents of message
bodies.
There are two types of channels: transport channels and protocol channels.
Transport channels read and write messages from the network (or some other communication point
with the outside world). Some transports use an encoder to convert messages (which are
represented as XML Infosets) to and from the byte stream representation used by the network.
Examples of transports are HTTP, named pipes, TCP, and MSMQ. Examples of encodings are XML
and optimized binary.
Protocol channels implement message processing protocols, often by reading or writing additional
headers to the message. Examples of such protocols include WS-Security and WS-Reliability.
The messaging layer illustrates the possible formats and exchange patterns of the data. WS-
Security is an implementation of the WS-Security specification enabling security at the message
layer. The WS-Reliable Messaging channel enables the guarantee of message delivery. The encoders
present a variety of encodings that can be used to suit the needs of the message. The HTTP channel
specifies that the HyperText Transport Protocol is used for message delivery. The TCP channel
similarly specifies the TCP protocol. The Transaction Flow channel governs transacted message
patterns. The Named Pipe channel enables interprocess communication. The MSMQ channel enables
interoperation with MSMQ applications.
When creating a basic WCF service, the first task is to define a contract. The contract specifies what
operations the service supports. An operation can be thought of as a Web service method. Contracts
are created by defining a C++, C#, or VB interface. Each method in the interface corresponds to a
specific service operation. Each interface must have the ServiceContractAttribute applied to it and
each operation must have the OperationContractAttribute applied to it. If a method within an
interface that has the ServiceContractAttribute does not have the OperationContractAttribute,
that method is not exposed.
The code used for this task is provided in the example following the procedure.
2. Create a new console application project. In the New Project dialog, select Visual
Basic or Visual C#, and choose the Console Application template, and name it Service.
Use the default Location.
a. In the Solution Explorer, right-click the References folder under the project
folder and choose Add Reference.
b. Click the Browse tab in the Add Reference dialog and navigate
to c:\Windows\Microsoft.Net\Framework\v3.0\Windows Communication
Foundation and select System.ServiceModel.dll and click OK.
Note:
When using a command-line compiler (for example, Csc.exe or Vbc.exe), you must also provide
the path to the assemblies. By default, on a computer running Windows Vista for example, the
path is: Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation.
using System.ServiceModel;
Note:
When using attributes to annotate an interface or class, you can drop the "Attribute" part from
the attribute name. SoServiceContractAttribute becomes [ServiceContract]
7. C#
8. [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
10. Declare a method for each of the operations the ICalculator contract exposes (add,
subtract, multiply, and divide) within the interface and apply
the OperationContractAttribute attribute to each method that you want to expose as
part of the public WCF contract.
C#
[OperationContract]
[OperationContract]
[OperationContract]
[OperationContract]
Example
The following code example shows a basic interface that defines a service contract.
C#
using System;
using System.ServiceModel;
namespace Microsoft.ServiceModel.Samples
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
[OperationContract]
[OperationContract]
[OperationContract]
[OperationContract]
Now the interface is created. Build the project to ensure there are no compilation errors and then
proceed to How to: Implement a Windows Communication Foundation Service Contract to
implement the interface. For troubleshooting information see Troubleshooting the Getting Started
Tutorial.
Creating a WCF service requires that you first create the contract, which is defined using an
interface. For more information about creating the interface, see How to: Define a Windows
Communication Foundation Service Contract. The next step, shown in this example, is to implement
the interface. This involves creating a class called CalculatorService that implements the user-
defined ICalculator interface. The code used for this task is provided in the example following the
procedure.
C#
public class CalculatorService : ICalculator
C#
return result;
return result;
return result;
}
public double Divide(double n1, double n2)
return result;
Note:
The write output code has been added to make testing convenient.
Example
The following code example shows both the interface that defines the contract and the
implementation of the interface.
C#
using System;
using System.ServiceModel;
namespace Microsoft.ServiceModel.Samples
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
[OperationContract]
[OperationContract]
[OperationContract]
[OperationContract]
}
// Step 1: Create service class that implements the service contract.
return result;
return result;
return result;
return result;
Now the service contract is created and implemented. Build the solution to ensure there are no
compilation errors and then proceed to How to: Host and Run a Basic Windows Communication
Foundation Service to run the service. For troubleshooting information, see Troubleshooting the
Getting Started Tutorial.
This topic describes how to run a basic Windows Communication Foundation (WCF) service. This
procedure consists of the following steps:
A complete listing of the code written in this task is provided in the example following the
procedure. Add the following code into the Main() method defined in the Program class. This
class was generated when you created the Service solution.
C#
using System.ServiceModel.Description;
2. Create a new ServiceHost instance to host the service. You must specify the type that
implements the service contract and the base address. For this sample the base address
is http://localhost:8000/ServiceModelSamples/Service and CalculatorS
ervice is the type that implements the service contract.
C#
3. Add a try-catch statement that catches a CommunicationException and add the code in the
next three steps to the try block. The catch clause should display an error message and
then call selfHost.Abort().
4. Add an endpoint that exposes the service. To do this, you must specify the contract that the
endpoint is exposing, a binding, and the address for the endpoint. For this sample,
specify ICalculator as the contract, WSHttpBinding as the binding,
and CalculatorService as the address. Notice here the endpoint address is a relative
address. The full address for the endpoint is the combination of the base address and the
endpoint address. In this case the full address
is http://localhost:8000/ServiceModelSamples/Service/CalculatorServ
ice.
C#
selfHost.AddServiceEndpoint(
typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
5. Enable Metadata Exchange. To do this, add a service metadata behavior. First create
a ServiceMetadataBehavior instance, set theHttpGetEnabled property to true, and then add
the new behavior to the service. For more information about security issues when
publishing metadata, see Security Considerations with Metadata.
C#
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
6. Open the ServiceHost and wait for incoming messages. When the user presses the ENTER
key, close the ServiceHost.
C#
selfHost.Open();
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
Example
The following example includes the service contract and implementation from previous steps in the
tutorial and hosts the service in a console application. Compile the following into an executable
named Service.exe.
C#
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Microsoft.ServiceModel.Samples
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
[OperationContract]
[OperationContract]
[OperationContract]
[OperationContract]
return result;
return result;
return result;
return result;
class Program
// Step 1 of the address configuration procedure: Create a URI to serve as the base
address.
try
selfHost.AddServiceEndpoint(
typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
// Step 4 of the hosting procedure: Enable metadata exchange.
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Step 5 of the hosting procedure: Start (and then stop) the service.
selfHost.Open();
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
selfHost.Abort();
Note:
Services such as this one require permission to register HTTP addresses on the machine for
listening. Administrator accounts have this permission, but non-administrator accounts must be
granted permission for HTTP namespaces. For more information about how to configure
namespace reservations, see Configuring HTTP and HTTPS. When running under Visual Studio,
the service.exe must be run with administrator privileges.
Now the service is running. Proceed to How to: Create a Windows Communication Foundation
Client. For troubleshooting information, seeTroubleshooting the Getting Started Tutorial.
This topic describes how to retrieve metadata from a WCF service and use it to create a WCF proxy
that can access the service. This task is completed by using the ServiceModel Metadata Utility Tool
(Svcutil.exe)provided by WCF. This tool obtains the metadata from the service and generates a
managed source code file for a proxy in the language you have chosen. In addition to creating the
client proxy, the tool also creates the configuration file for the client that enables the client
application to connect to the service at one of its endpoints.
The client application uses the generated proxy to create an WCF client object. This procedure is
described in How to: Use a Windows Communication Foundation Client.
The code for the client generated by this task is provided in the example following the procedure.
a. In Solution Explorer (on the upper right) within the same solution that contains
the service, right-click the current solution (not the project), and select Add, and
then New Project.
b. In the Add New Project dialog, select Visual Basic or Visual C#, and choose
the Console Application template, and name itClient. Use the default Location.
c. Click OK.
a. Right-click the References folder under the Client project in the Solution
Explorer and select Add Reference.
b. Select the Recent tab and select System.ServiceModel.dll from the list box and
click OK. Because you already added a reference to this assembly in the first step
of this tutorial, it is now listed in the Recent tab. If you do not see it in
the Recent tab, select theBrowse tab and navigate to
C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation
and select the assembly from there.
Note:
When using a command-line compiler (for example, Csc.exe or Vbc.exe), you must also provide
the path to the assemblies. By default, on a computer running Windows Vista for example, the
path is: Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation.
C#
using System.ServiceModel;
4. Start the service created in the previous steps. For more information, see How to: Host and
Run a Basic Windows Communication Foundation Service.
5. Run the Service Model Metadata Utility Tool (SvcUtil.exe) with the appropriate switches to
create the client code and a configuration file by doing the following steps:
a. Start a Windows SDK console session by selecting CMD Shell under the Microsoft
Windows SDK entry in the Start menu.
b. Navigate to the directory where you want to place the client code. If you created
the client project using the default, the directory is C:\Users\<user
name>\Documents\Visual Studio 2005\Projects\Service\Client.
c. Use the command-line tool Service Model Metadata Utility Tool (SvcUtil.exe) with
the appropriate switches to create the client code. The following example generates
a code file and a configuration file for the service.
[Visual Basic]
[C#]
By default, the client proxy code is generated in a file named after the service (in
this case, for example, CalculatorService.cs or CalculatorService.vb where the
extension is appropriate to the programming language: .vb for Visual Basic or .cs
for C#). The /outswitch changes the name of the client proxy file to
generatedProxy.cs. The /config switch changes the name of the client
configuration file from the default output.config to app.config. Note that both of
these files get generated in the C:\Users\<user name>\Documents\Visual Studio
2005\Projects\Service\Client directory.
6. Add the generated proxy to the client project in Visual Studio, right-click the client project
in Solution Explorer and select Add and thenExisting Item. Select
the generatedProxy.cs file generated in the preceding step.
Example
This example shows the client code generated by the Service Model Metadata Utility Tool
(Svcutil.exe).
C#
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1366
//
// Changes to this file may cause incorrect behavior and will be lost if
// </auto-generated>
//------------------------------------------------------------------------------
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://Microsoft.ServiceModel.S
amples", ConfigurationName="ICalculator")]
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa
mples/ICalculator/Add",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse")]
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa
mples/ICalculator/Subtract",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResponse")]
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa
mples/ICalculator/Multiply",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResponse")]
[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa
mples/ICalculator/Divide",
ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideResponse")]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface ICalculatorChannel : ICalculator, System.ServiceModel.IClientChannel
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public CalculatorClient()
base(endpointConfigurationName)
base(endpointConfigurationName, remoteAddress)
base(endpointConfigurationName, remoteAddress)
base(binding, remoteAddress)
}
public double Add(double n1, double n2)
Now you have created a Windows Communication Foundation (WCF) client. Proceed to How to:
Configure a Basic Windows Communication Foundation Client to configure the client. For
troubleshooting information, see Troubleshooting the Getting Started Tutorial.
This topic adds the client configuration file that was generated using the Service Model Metadata
Utility (Svcutil.exe) to the client project and explains the contents of the client configuration
elements. Configuring the client consists of specifying the endpoint that the client uses to access the
service. An endpoint has an address, a binding and a contract, and each of these must be specified
in the process of configuring the client.
The content of the configuration files generated for the client is provided in the example after the
procedure.
To configure a Windows Communication Foundation client
1. Add the App.config configuration file generated in the previous How to: Create a Windows
Communication Foundation Client procedure to the client project in Visual Studio. Right-
click the client project in Solution Explorer, select Add and then Existing Item. Next
select the App.config configuration file from the C:\Users\<user name>\Documents\Visual
Studio 2005\Projects\Service\Client directory. (This is named the App.config file because
you used the /config:app.config switch when generating this with Svcutil.exe tool.)
Click OK. By default. the Add Existing Item dialog box filters out all files with a .config
extension. To see these files select All Files (*.*) from the drop-down list box in the lower
right corner of the Add Existing Item dialog box.
2. Open the generated configuration file. Svcutil.exe generates values for every setting on the
binding. The following example is a view of the generated configuration file. Under
the <system.serviceModel> section, find the <endpoint> element. The following
configuration file is a simplified version of the file generated.
4. <configuration>
5. <system.serviceModel>
6. <bindings>
7. <wsHttpBinding>
8. <binding name="WSHttpBinding_ICalculator">
9. </binding>
10. </wsHttpBinding>
11. </bindings>
12. <client>
13. <endpoint
14. address="http://localhost:8000/ServiceModelSamples/Service/Calcula
torService"
15. binding="wsHttpBinding"
16. bindingConfiguration="WSHttpBinding_ICalculator"
17. contract="Microsoft.ServiceModel.Samples.ICalculator"
18. name="WSHttpBinding_ICalculator">
19. </endpoint>
20. </client>
21. </system.serviceModel>
</configuration>
This example configures the endpoint that the client uses to access the service that is
located at the following address: http://localhost:8000/ServiceModelSamples/service
22. For more information about how to use the generated client with this configuration,
see How to: Use a Windows Communication Foundation Client.
Example
The example shows the content of the configuration files generated for the client.
Once a Windows Communication Foundation (WCF) proxy has been created and configured, a client
instance can be created and the client application can be compiled and used to communicate with
the WCF service. This topic describes procedures for creating and using a WCF client. This procedure
does three things: creates a WCF client, calls the service operations from the generated proxy, and
closes the client once the operation call is completed.
The code discussed in the procedure is also provided in the example following the procedure. The
code in this task should be placed in the Main() method of the generated Program class in the
client project.
C#
C#
value2 = 76.54D;
value1 = 9.00D;
value2 = 81.25D;
value1 = 22.00D;
value2 = 7.00D;
3. Call Close on the WCF client and wait until the user presses the enter key to terminate the
application.
C#
//Step 3: Closing the client gracefully closes the connection and cleans up resources.
client.Close();
Console.WriteLine();
Console.ReadLine();
Example
The following example shows you how to create a WCF client, how to call the operations of the
client, and how to close the client once the operation call is completed.
Compile the generated WCF client and the following code example into an executable named
Client.exe. Be sure to referenceSystem.ServiceModel when compiling the code.
C#
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
namespace ServiceModelSamples
class Client
value1 = 145.00D;
value2 = 76.54D;
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
value1 = 22.00D;
value2 = 7.00D;
//Step 3: Closing the client gracefully closes the connection and cleans up resources.
client.Close();
Console.WriteLine();
Console.ReadLine();
Ensure the service is running before attempting to use the client. For more information, see How to:
Host and Run a Basic Windows Communication Foundation Service.
To launch the client, start a Windows SDK console session by selecting CMD Shell under
the Microsoft Windows SDK entry in the Start menu. Navigate to the C:\Users\<user
name>\Documents\Visual Studio 2005\Projects\Service\Client\bin\Debug directory, and
type client and press ENTER. The operation requests and responses appear in the client console
window as follows.
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Press <ENTER> to terminate client.
If you see this output, you have successfully completed the tutorial. T
Solution:
Problem:
The following error occurs when you attempt to run the service application: HTTP could not register
URL http://+:8000/ServiceModelSamples/Service/. Your process does not have access rights to this
namespace (see Configuring HTTP and HTTPS for details.
Solution:
The process that hosts a WCF service must be run with administrative privileges. If you are running
the service from inside Visual Studio 2008 you must run Visual Studio 2008 as an Administrator. To
do so click Start, right-click Visual Studio 2008 and select Run As Administrator. If you are
running the service from a command-line prompt you must start the command line prompt as an
administrator in a similar fashion. Click Start, right click Command Prompt and select Run As
Administrator.
Problem:
The following error occurs when you attempt to use the Svcutil.exe tool: 'svcutil' is not recognized
as an internal or external command, operable program or batch file.
Solution:
Svcutil.exe must be in the system path. The easiest solution is to use the Visual Studio 2005
Command Prompt. Click Start, select All Programs,Visual Studio 2008, Visual Studio Tools,
and Visual Studio 2008 Command Prompt. This command prompt sets the system path to the
correct locations for all tools shipped as part of Visual Studio 2008.
Problem:
Solution:
The Add Existing Item dialog only displays files with the following extensions by default: .cs,
.resx, .settings, .xsd, .wsdl. You can specify that you want to see all file types by selecting All Files
(*.*) in the drop down list box in the lower right corner of the Add Existing Item dialog box.
Problem:
The following syntax error occurs during compilation of the client application: 'CalculatorClient' does
not contain a definition for '<method name>' and no extension method '<method name>' accepting
a first argument of type 'CalculatorClient' could be found (are you missing a using directive or an
assembly reference?)
Solution:
Only those methods that are marked with the ServiceOperationAttribute are exposed to the
outside world. If you omitted theServiceOperationAttribute attribute from one of the methods in
the ICalculator interface you get this error message when compiling a client application that makes
a call to the operation missing the attribute.
Problem:
The following error occurs during compilation of the client application: The type or namespace name
'CalculatorClient' could not be found (are you missing a using directive or an assembly reference?)
Solution:
You get this error if you do not add the proxy.cs or proxy.vb file to your client project.
Problem:
Solution:
This error occurs if you run the client application without running the service.
For the source copy of this example, see IIS Hosting Using Inline Code.
2. Create a new folder for your application files, ensure that ASP.NET has access to the
contents of the folder, and use the IIS management tool to create a new IIS application
that is physically located in this application directory.
3. Create a new file named "service file" with an .svc extension in the application. Edit this file
by adding the appropriate @ServiceHost directive information for the service. For example,
the service file contents for the CalculatorService samples contain the following
information.
6. Define the service contract for the type of service in the code file.
C#
[ServiceContract]
[OperationContract]
[OperationContract]
[OperationContract]
[OperationContract]
C#
return n1 + n2;
return n1 - n2;
return n1 * n2;
return n1 / n2;
8. Create a file named "Web.config" in the application directory. To run the service, the
Web.config file must be located in the same directory as the service file.
9. Add the appropriate configuration code into the file. At runtime, the WCF infrastructure uses
the information to construct an endpoint that client applications can communicate with. For
the CalculatorService sample, the configuration code is in the following example.
Xml
<configuration>
<system.serviceModel>
<services>
<service name="Microsoft.ServiceModel.Samples.CalculatorService">
<endpoint address=""
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</configuration>
Example
The following code shows the contents of the code file with the contract and its implementation
within the namespace specified by the directive in the Service.svc file.
C#
using System;
using System.ServiceModel;
namespace Samples
[ServiceContract]
[OperationContract]
[OperationContract]
[OperationContract]
[OperationContract]
{
public double Add(double n1, double n2)
return n1 + n2;
return n1 - n2;
return n1 * n2;
return n1 / n2;
1. Obtain the service contract, bindings, and address information for a service endpoint.
2. Create a WCF client using that information.
3. Call operations.
4. Close the WCF client object.
The following sections discuss these steps and provide brief introductions to the following issues:
• Handling errors.
For an example of this process, see How to: Create a Windows Communication Foundation Client.
For more complete information about contracts, see Contracts.
You can also use WCF client channel objects to connect with and use services. For details, see Client
Architecture.
Note:
If you are using Visual Studio to create your WCF client, objects are loaded automatically into
the object browser when you add a service reference to your project.
C#
[System.ServiceModel.ServiceContractAttribute(
Namespace = "http://microsoft.wcf.documentation"
)]
[System.ServiceModel.OperationContractAttribute(
Action = "http://microsoft.wcf.documentation/ISampleService/SampleMethod",
ReplyAction =
"http://microsoft.wcf.documentation/ISampleService/SampleMethodResponse"
)]
[System.ServiceModel.FaultContractAttribute(
typeof(microsoft.wcf.documentation.SampleFault),
Action =
"http://microsoft.wcf.documentation/ISampleService/SampleMethodSampleFaultFault"
)]
If you are not using Visual Studio, examine the generated contract code to find the type that
extends ClientBase and the service contract interface ISampleService. In this case, that type
looks like the following code:
C#
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public SampleServiceClient()
base(endpointConfigurationName)
base(endpointConfigurationName, remoteAddress)
base(endpointConfigurationName, remoteAddress)
base(binding, remoteAddress)
return base.Channel.SampleMethod(msg);
This class can be created as a local object using one of the constructors, configured, and then used
to connect to a service of the type ISampleService.
It is recommended that you create your WCF client object first, and then use it and close it inside a
single try/catch block. You should not use the using statement (Using in Visual Basic) because it
may mask exceptions in certain failure modes. For more information, see the following sections as
well as Avoiding Problems with the Using Statement.
For example, a generated configuration file for an ISampleService used in the preceding
examples contains the following endpoint information.
Xml
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ISampleService"
closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:01:00"
sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8"
useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192"
maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="None"
proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows"
negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8080/SampleService"
binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_ISampleService"
contract="ISampleService"
name="WSHttpBinding_ISampleService">
</endpoint>
</client>
</system.serviceModel>
</configuration>
This configuration file specifies a target endpoint in the <client> element. For more information
about using multiple target endpoints, see
the System.ServiceModel.ClientBase.#ctor(System.String) or
theSystem.ServiceModel.ChannelFactory.#ctor(System.String) constructors.
Calling Operations
Once you have a client object created and configured, create a try/catch block, call operations in the
same way that you would if the object were local, and close the WCF client object. When the client
application calls the first operation, WCF automatically opens the underlying channel, and the
underlying channel is closed when the object is recycled. (Alternatively, you can also explicitly open
and close the channel prior to or subsequent to calling other operations.)
C#
namespace Microsoft.ServiceModel.Samples
using System;
using System.ServiceModel;
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
[OperationContract]
[OperationContract]
[OperationContract]
[OperationContract]
Visual Basic
Namespace Microsoft.ServiceModel.Samples
Imports System
Imports System.ServiceModel
<ServiceContract(Namespace:= _
"http://Microsoft.ServiceModel.Samples")> _
Public Interface ICalculator
<OperationContract> _
<OperationContract> _
<OperationContract> _
<OperationContract> _
End Interface
You can call operations by creating a WCF client object and calling its methods, as the following
code example demonstrates. Note that the opening, calling, and closing of the WCF client object
occurs within a single try/catch block. For more information, see Accessing Services Using a
Client and Avoiding Problems with the Using Statement.
C#
CalculatorClient wcfClient = new CalculatorClient();
try
Console.WriteLine(wcfClient.Add(4, 6));
wcfClient.Close();
wcfClient.Abort();
wcfClient.Abort();
Handling Errors
Exceptions can occur in a client application when opening the underlying client channel (whether
explicitly or automatically by calling an operation), using the client or channel object to call
operations, or when closing the underlying client channel. It is recommended at a minimum that
applications expect to handle
possibleSystem.TimeoutException and System.ServiceModel.CommunicationException exceptions in
addition to anySystem.ServiceModel.FaultException objects thrown as a result of SOAP faults
returned by operations. SOAP faults specified in the operation contract are raised to client
applications as a System.ServiceModel.FaultException where the type parameter is the detail type of
the SOAP fault. For more information about handling error conditions in a client application,
see Sending and Receiving Faults. For a complete sample the shows how to handle errors in a client,
see Expected Exceptions.
For example, security requirements for service contracts are declared in the service contract
interface, and if Svcutil.exe created a configuration file, that file usually contains a binding that is
capable of supporting the security requirements of the service. In some cases, however, more
security configuration may be required, such as configuring client credentials. For complete
information about the configuration of security for WCF clients, seeSecuring Clients.
In addition, some custom modifications can be enabled in client applications, such as custom run-
time behaviors. For more information about how to configure a custom client behavior,
see Configuring Client Behaviors.
• Create an instance of the callback contract implementation class and use it to create
theSystem.ServiceModel.InstanceContext object that you pass to the WCF client
constructor.
Duplex WCF client objects function like their nonduplex counterparts, with the exception that they
expose the functionality necessary to support callbacks, including the configuration of the callback
service.
For example, you can control various aspects of callback object runtime behavior by using
properties of theSystem.ServiceModel.CallbackBehaviorAttribute attribute on the callback class.
Another example is the use of theSystem.ServiceModel.Description.CallbackDebugBehavior class to
enable the return of exception information to services that call the callback object. For more
information, see Duplex Services. For a complete sample, see Service Contract: Duplex.
On Windows XP computers running Internet Information Services (IIS) 5.1, duplex clients must
specify a client base address using the System.ServiceModel.WSDualHttpBinding class or an
exception is thrown. The following code example shows how to do this in code.
C#
WSDualHttpBinding dualBinding = new WSDualHttpBinding();
dualBinding.ClientBaseAddress = new
Uri("http://localhost:8000/DuplexTestUsingCode/Client/");
C#
<client>
<endpoint
name ="ServerEndpoint"
address="http://localhost:12000/DuplexUsingConfig/Server"
bindingConfiguration="WSDualHttpBinding_IDuplex"
binding="wsDualHttpBinding"
contract="IDuplex"
/>
</client>
<bindings>
<wsDualHttpBinding>
<binding
name="WSDualHttpBinding_IDuplex"
clientBaseAddress="http://localhost:8000/myClient/"
/>
</wsDualHttpBinding>
</bindings>
• Document-centric workflows.
• Human workflows.
Windows Workflow Foundation provides a consistent and familiar development experience with other
.NET Framework 3.0 technologies, such as Windows Communication Foundation and Windows
Presentation Foundation. The Windows Workflow Foundation API provides full support for Visual
Basic .NET and C#, a specialized workflow compiler, debugging within a workflow, a graphical
workflow designer, and developing your workflow completely in code or in markup. Windows
Workflow Foundation also provides an extensible model and designer to build custom activities that
encapsulate workflow functionality for end users or for reuse across multiple projects.
The concepts in this section are inherent to Windows Workflow Foundation. They are briefly
described here to provide a basic understanding. The Programming Guide section of this SDK
provides implementation details and a deeper level of knowledge.
Workflows Overview
A workflow is a set of elemental units called activities that are stored as a model that describes a
real-world process. Workflows provide a way of describing the order of execution and dependent
relationships between pieces of short- or long-running work. This work passes through the model
from start to finish, and activities might be executed by people or by system functions.
The following illustration shows how workflows, activities, and the workflow runtime engine are all
hosted in process with a host application.
Activities Overview
Activities are the elemental unit of a workflow. They are added to a workflow programmatically in a
manner similar to adding XML DOM child nodes to a root node. When all the activities in a given
flow path are finished running, the workflow instance is completed.
An activity can perform a single action, such as writing a value to a database, or it can be a
composite activity and consist of a set of activities. Activities have two types of behavior: runtime
and design time. The runtime behavior specifies the actions upon execution. The design-time
behavior controls the appearance of the activity and its interaction while being displayed within the
designer.
Windows Workflow Foundation contains a library of standard activities and provides the mechanisms
for you to create your own. This enables extensibility and reusability between workflows.
Services Overview
The workflow runtime engine uses many services when a workflow instance runs. Windows
Workflow Foundation provides default implementations of the runtime services that meet the needs
of many types of applications, such as a persistence service, which stores the execution details of a
workflow instance in a SQL database. These service components are pluggable, which allows
applications to provide these services in ways that are unique to their execution environment. Other
types of services used by the runtime engine include scheduling services, transaction services, and
tracking services.
Custom services can be created to extend the Windows Workflow Foundation platform by deriving
from the base service classes. An example of this would be a persistence service that uses an XML
file instead of a database for storage.
Compensation Overview
Compensation is the act of undoing any actions that were performed by a successfully completed
compensatable activity because of an exception that occurred elsewhere in a workflow.
Host processes can also interact with a specific activity in a specific workflow instance by using a
unique ID that is passed between the host process and the workflow as an event argument. This is
known ascorrelation.
Persistence Overview
Windows Workflow Foundation simplifies the process of creating stateful, long-running, persistent
workflow applications. The workflow runtime engine manages workflow execution and enables
workflows to remain active for long periods of time and survive application restarts. This durability is
a key tenet of Windows Workflow Foundation. It means that workflows can be unloaded from
memory while awaiting input and serialized into a persistent store, such as a SQL database or XML
file. Whenever the input is received, the workflow runtime engine loads the workflow state
information back into memory and continues execution of the workflow.
Windows Workflow Foundation provides the SqlWorkflowPersistenceService that integrates well with
Microsoft SQL Server 2005 Express, SQL Server 2000 or later, or SQL Server 2000 Desktop Engine
(MSDE) to persist workflow information easily and efficiently. You can also create your own
persistence service to store workflow state information any way you want by deriving from
the WorkflowPersistenceService base class.
Tracking Overview
Tracking is the ability to specify and capture information about workflow instances and store that
information as the instances execute. Windows Workflow Foundation provides
the SqlTrackingService, which is a tracking service that uses a SQL database to store the collected
tracking information. You can also write your own tracking service to collect and store this
information in any format that your application requires.
When a new workflow is created, the tracking service requests a tracking channel to be associated
with that workflow. All of the tracking information from the workflow is then sent to this tracking
channel.
The tracking service can track three types of events: Workflow instance events, Activity events, and
User events. You can configure the type and amount of information that your service wants to
receive for a particular workflow instance or type of workflow by providing a tracking profile.
The tracking framework also provides the ability to extract information about activities or the
workflow during an event. If a specific property or field in your activity or workflow needs to be
tracked, you can provide this information in the extracts section of the tracking profile, and that
information will be extracted during the specified event.
Serialization Overview
Workflows, activities, and rules can be serialized and deserialized. This enables you to persist them,
use them in workflow markup files, and view their properties, fields, and events in a workflow
designer.
Windows Workflow Foundation provides default serialization capabilities for standard activities, or
you can create your own for custom activities. For example, with a custom activity serializer, you
can decide which members are serialized and how they are serialized. This determines if those
members are visible or hidden in a workflow designer.
Rules, like conditions, are expressed as code DOM statements, and are collected in the rules XML
file. Rules include a condition statement and collections of actions that are performed based on the
result of the condition. Rules are collected into rule sets, which support both simple sequential
execution of rules, and sophisticated forward-chaining of rules. Rule sets are executed by
the PolicyActivityactivity.
A key advantage of defining your logic with rules and declarative conditions is that they can be
modified at run time by doing dynamic updates using workflow changes. In addition, rules let you
separate your business logic from a workflow in order to share those rules with other workflows.
Finally, defining business logic in rules allows for advanced tools, such as dependency visualization
and impact analysis tools, to be built on top of the object model.
WWF: http://msdn.microsoft.com/en-us/library/ms735927.aspx