Windows Communication Foundation & Wpf

  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Windows Communication Foundation & Wpf as PDF for free.

More details

  • Words: 14,941
  • Pages: 55
What Is Windows Communication Foundation? The global acceptance of Web services, which includes standard protocols for application-toapplication 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. WCF simplifies development of connected applications through a new service-oriented programming model. WCF supports many styles of distributed application development by providing a layered architecture. At its base, the WCF channel architecture provides asynchronous, untyped messagepassing primitives. Built on top of this base are protocol facilities for secure, reliable, transacted data exchange and broad choice of transport and encoding options. 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.



An existing reservation application built on a J2EE server running on a non-Windows system. Due to a recent merger with another car rental firm, this existing system must be able to access the new application’s logic to provide customers of the merged firms with a unified experience.



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.

Addressing the Problem The foundation for new Windows-based applications is the .NET Framework. Accordingly, WCF is implemented primarily as a set of classes on top of the .NET Framework CLR. Because it extends their familiar environment, WCF enables developers who create object-oriented applications using the .NET Framework today to also build service-oriented applications in a familiar way.

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:



Unification of existing .NET Framework communication technologies.



Support for cross-vendor interoperability, including reliability, security, and transactions.



Explicit service orientation.

Unification of Microsoft Distributed Computing Technologies In the absence of WCF, the development team that implements the rental car application would need to choose the right distributed technology from the multiple choices offered by the .NET Framework. Yet given the diverse requirements of this application, no single technology would fit the requirements. Instead, the application would probably use multiple existing .NET Framework technologies, such as the following:



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.



Microsoft Message Queuing (MSMQ). Used to communicate with Windows-based partner applications that require guaranteed data delivery as well as decoupling of workloads and application lifetimes. The durable messaging that Message Queuing provides is typically the best solution for intermittently connected applications.

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-andtext 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. Interoperability with Other Web Services Platforms Enterprises today typically have systems and applications that they purchased from a range of suppliers. In the rental car application, for instance, communication is required with various other software applications written in various languages and running on various operating systems. Because WCF’s fundamental communication mechanism is SOAP-based Web services, WCF-based applications can communicate with other software running in a variety of contexts. An application built on WCF can interact with all of the following:



WCF-based applications running in a different process on the same Windows machine.



WCF-based applications running on another Windows machine.



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. Grouped by function, those specifications cover:



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.



Security: WS-Security, WS-SecureConversation, WS-Trust, and WS-Federation all define additions to SOAP messages for providing authentication, data integrity, data privacy, and other security features.



Reliability: WS-Reliable Messaging defines additions to the SOAP header that allow reliable end-to-end communication, even when one or more Web services intermediaries must be traversed.



Transactions: Built on WS-Coordination, WS-Atomic Transaction allows coordinating twophase commit transactions in the context of Web services conversations.

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. Interoperability with Microsoft Technologies Many Microsoft customers have made significant investments in the .NET Framework technologies that WCF includes. Protecting those investments was a fundamental goal of WCF’s designers. Installing WCF does not break existing technology, so there is no requirement that organizations change existing applications to use it. A clear upgrade path is provided, however, and wherever possible, WCF interoperates with those earlier technologies. 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-WCFbased 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.

Interoperability with Other XML Protocols The future of the Internet is not predictable and the technologies used today may evolve or be replaced. Today, a popular trend in building Web-centric applications (called by many "Web 2.0"), is an application model based on communication using only simple XML formats that are not SOAPbased and exclusively rely on HTTP as a transport and as an application protocol. For example, the Representational State Transfer (REST) architectural style has no notion of user-defined operations for dealing with data. Instead, application state is associated with HTTP URLs and HTTP methods

(such as PUT, POST, DELETE, and GET). This approach is in contrast to the creation of user-defined procedures or functions that most developers are familiar with in an enterprise environment. However, the REST approach is of value in scenarios where services must function as the back end of Web 2.0 applications. 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 nonXML 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.

Fundamental Windows Communication Foundation Concepts This document provides a high-level view of the Windows Communication Foundation (WCF) architecture. It is intended to explain key concepts and how they fit together. For a tutorial on creating the simplest version of a WCF service and client, see Getting Started Tutorial. To learn WCF programming, see Basic WCF Programming.

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. Messaging and Endpoints WCF is based on the notion of message-based communication, and anything that can be modeled as a message (for example, an HTTP request or an MSMQ message) can be represented in a uniform way in the programming model. This enables a unified API across different transport mechanisms. 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.



Message Transmission Optimization Mechanism (MTOM) encoding, which is an interoperable way for efficiently sending unstructured binary data to and from a service.



Binary encoding for efficient transfer.

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 endpoint exposed by the application and that corresponds to a service contract implemented by the application. infrastructure endpoint An endpoint that is exposed by the infrastructure to facilitate functionality that is needed or provided by the service that does not relate to a service contract. For example, a service might have an infrastructure endpoint that provides metadata information. address 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 A binding defines how an endpoint communicates to the world. It is constructed of a set of components called binding elements that "stack" one on top of the other to create the communication infrastructure. At the very least, a binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint. For more information, see Configuring Services. binding element A binding element represents a particular piece of the binding, such as a transport, an encoding, an implementation of an infrastructure-level protocol (such as WSReliableMessaging), or any other component of the communication stack. behaviors A behavior is a component that controls various run-time aspects of a service, an endpoint, a particular operation, or a client. Behaviors are grouped according to scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations. For example, one service behavior is throttling, which specifies how a service reacts when an excess of messages threaten to overwhelm its handling capabilities. An endpoint behavior, on the other hand, controls only aspects relevant to endpoints, such as how and where to find a security credential. system-provided bindings WCF includes a number of system-provided bindings. These are collections of binding elements that are optimized for specific scenarios. For example, the WSHttpBinding is designed for interoperability with services that implement various WS-* specifications. These predefined bindings save time by presenting only those options that can be correctly applied to the specific scenario. If a predefined binding does not meet your requirements, you can create your own custom binding. configuration versus coding Control of an application can be done either through coding, through configuration, or through a combination of both. Configuration has the advantage of allowing someone other than the developer (for example, a network administrator) to set client and service parameters after the code is written and without having to recompile. Configuration not only enables you to set values like endpoint addresses, but also allows further control by enabling you to add endpoints, bindings, and behaviors. Coding allows the developer to retain strict control over all components of the service or client, and any settings done through the configuration can be inspected and if needed overridden by the code. service operation A service operation is a procedure defined in a service's code that implements the functionality for an operation. This operation is exposed to clients as methods on a WCF client. The method may return a value, and may take an optional number of arguments, or take no arguments, and return no response. For example, an operation that functions as a simple "Hello" can be used as a notification of a client's presence and to begin a series of operations. service contract 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 A channel is a concrete implementation of a binding element. The binding represents the configuration, and the channel is the implementation associated with that configuration. Therefore, there is a channel associated with each binding element. Channels stack on top of each other to create the concrete implementation of the binding: the channel stack. WCF client A WCF client is a client-application construct that exposes the service operations as methods (in the .NET Framework programming language of your choice, such as Visual Basic or Visual C#). Any application can host a WCF client, including an application that hosts a service. Therefore, it is possible to create a service that includes WCF clients of other services. A WCF client can be automatically generated by using the ServiceModel Metadata Utility Tool (Svcutil.exe) and pointing it at a running service that publishes metadata. 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 in WCF includes confidentiality (encryption of messages to prevent eavesdropping), integrity (the means for detection of tampering with the message), authentication (the means for validation of servers and clients), and authorization (the control of access to resources). These functions are provided by either leveraging existing security mechanisms, such as TLS over HTTP (also known as HTTPS), or by implementing one or more of the various WS-* security specifications. transport security mode 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

Contracts and Descriptions Contracts define various aspects of the message system. The data contract describes every parameter that makes up every message that a service can create or consume. The message parameters are defined by XML Schema definition language (XSD) documents, enabling any system that understands XML to process the documents. The message contract defines specific message

parts using SOAP protocols, and allows finer-grained control over parts of the message, when interoperability demands such precision. The service contract specifies the actual method signatures of the service, and is distributed as an interface in one of the supported programming languages, such as Visual Basic or Visual C#. 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. WSSecurity 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. Hosting and Activation In its final form, a service is a program. Like other programs, a service must be run in an executable. This is known as a self-hosted service.

Services can also be hosted, or run in an executable managed by an external agent, such as IIS or Windows Activation Service (WAS). WAS enables WCF applications to be activated automatically when deployed on a computer running WAS. Services can also be manually run as executables (.exe files). A service can also be run automatically as a Windows service. COM+ components can also be hosted as WCF services.

How to: Define a Windows Communication Foundation Service Contract This is the first of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorialtopic. 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.

To create a Windows Communication Foundation contract with an interface

1.

Open Visual Studio 2008 as an administrator by right-clicking the program in the Start menu and selecting Run as administrator.

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.

3.

Change the default Service namespace to Microsoft.ServiceModel.Samples.

4.

Add a reference to System.ServiceModel.dll to the project:

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.

5.

Add a using statement (Imports in Visual Basic) for the System.ServiceModel namespace.

C#

using System.ServiceModel;

6.

Define a new interface called ICalculator and apply the ServiceContractAttribute attribute to the interface with a Namespace value of "http://Microsoft.ServiceModel.Samples". Specifying the namespace explicitly is a best practice because it prevents the default namespace value from being added to the contract name.

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")] 9. public interface ICalculator

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] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2);

Example The following code example shows a basic interface that defines a service contract. C#

using System; // Step 5: Add the using statement for the System.ServiceModel namespace using System.ServiceModel;

namespace Microsoft.ServiceModel.Samples { // Step 6: Define a service contract. [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] public interface ICalculator { // Step7: Create the method declaration for the contract. [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); } } 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.

How to: Implement a Windows Communication Foundation Service Contract This is the second of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six tasks, see the Getting Started Tutorial topic. 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 userdefined ICalculator interface. The code used for this task is provided in the example following the procedure.

To implement a WCF service contract

1.

Create a new class called CalculatorService in the same file where you defined the ICalculator interface. The CalculatorService implements theICalculator interface. C#

public class CalculatorService : ICalculator

2.

Implement each method defined in the ICalculator interface within the CalculatorService class. C#

public double Add(double n1, double n2) { double result = n1 + n2; Console.WriteLine("Received Add({0},{1})", n1, n2); // Code added to write output to the console window. Console.WriteLine("Return: {0}", result); return result; }

public double Subtract(double n1, double n2) { double result = n1 - n2; Console.WriteLine("Received Subtract({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; }

public double Multiply(double n1, double n2) { double result = n1 * n2; Console.WriteLine("Received Multiply({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; }

public double Divide(double n1, double n2) { double result = n1 / n2; Console.WriteLine("Received Divide({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); 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 { // Define a service contract. [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] public interface ICalculator { [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); }

// Step 1: Create service class that implements the service contract. public class CalculatorService : ICalculator { // Step 2: Implement functionality for the service operations. public double Add(double n1, double n2) { double result = n1 + n2; Console.WriteLine("Received Add({0},{1})", n1, n2); // Code added to write output to the console window. Console.WriteLine("Return: {0}", result); return result; }

public double Subtract(double n1, double n2) { double result = n1 - n2; Console.WriteLine("Received Subtract({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; }

public double Multiply(double n1, double n2) { double result = n1 * n2; Console.WriteLine("Received Multiply({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; }

public double Divide(double n1, double n2) { double result = n1 / n2; Console.WriteLine("Received Divide({0},{1})", n1, n2);

Console.WriteLine("Return: {0}", 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. If you are using a command-line compiler, you must reference the System.ServiceModel assembly.

How to: Host and Run a Basic Windows Communication Foundation Service This is the third of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorialtopic. This topic describes how to run a basic Windows Communication Foundation (WCF) service. This procedure consists of the following steps:



Create a base address for the service.



Create a service host for the service.



Enable metadata exchange.



Open the service host.

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.

To configure a base address for the service

1.

Create a Uri instance for the base address of the service. This URI specifies the HTTP scheme, your local machine, port number 8000, and the path ServiceModelSample/Service to the service that was specified for the namespace of the service in the service contract. C#

Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

To host the service

1.

Import the System.ServiceModel.Description namespace. This line of code should be placed at the top of the Program.cs/Program.vb file with the rest of the using or imports statements.

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#

ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

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#

ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); 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("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine();

// Close the ServiceHostBase to shutdown the service. selfHost.Close();

To verify the service is working 1.

Run the service.exe from inside Visual Studio. When running on Windows Vista, the service must be run with administrator privileges. Because Visual Studio was run with Administrator privileges, service.exe is also run with Administrator privileges. You can also start a new command prompt running it with Administrator privileges and run service.exe within it.

2.

Open Internet Explorer and browse to the service's debug page at http://localhost:8000/ServiceModelSamples/Service.

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. Be sure to reference System.ServiceModel.dll when compiling the code. C#

using System; using System.ServiceModel; using System.ServiceModel.Description;

namespace Microsoft.ServiceModel.Samples { // Define a service contract. [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] public interface ICalculator

{ [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); }

// Service class that implements the service contract. // Added code to write output to the console window. public class CalculatorService : ICalculator { public double Add(double n1, double n2) { double result = n1 + n2; Console.WriteLine("Received Add({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; }

public double Subtract(double n1, double n2) { double result = n1 - n2; Console.WriteLine("Received Subtract({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; }

public double Multiply(double n1, double n2) { double result = n1 * n2;

Console.WriteLine("Received Multiply({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; }

public double Divide(double n1, double n2) { double result = n1 / n2; Console.WriteLine("Received Divide({0},{1})", n1, n2); Console.WriteLine("Return: {0}", result); return result; } } class Program { static void Main(string[] args) {

// Step 1 of the address configuration procedure: Create a URI to serve as the base address. Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");

// Step 2 of the hosting procedure: Create ServiceHost ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

try {

// Step 3 of the hosting procedure: Add a service endpoint. selfHost.AddServiceEndpoint( typeof(ICalculator), new WSHttpBinding(), "CalculatorService");

// Step 4 of the hosting procedure: Enable metadata exchange. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb);

// Step 5 of the hosting procedure: Start (and then stop) the service. selfHost.Open(); Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine();

// Close the ServiceHostBase to shutdown the service. selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("An exception occurred: {0}", ce.Message); 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.

How to: Create a Windows Communication Foundation Client

This is the fourth of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorialtopic. 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.

To create a Windows Communication Foundation client 1.

Create a new project within the current solution for the client in by doing the following steps:

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. 2.

Click OK.

Add a reference to the System.ServiceModel.dll for the project:

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.

3.

Add a using statement (Imports in Visual Basic) for the System.ServiceModel namespace in the generated Program.cs or Program.vb file. 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]

svcutil.exe /language:vb /out:generatedProxy.vb /config:app.config http://localhost:8000/ServiceModelSamples/service [C#]

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service 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#

//-----------------------------------------------------------------------------//

//

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

//

the code is regenerated.

//
//------------------------------------------------------------------------------

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace="http://Microsoft.ServiceModel.S amples", ConfigurationName="ICalculator")] public interface ICalculator {

[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa mples/ICalculator/Add", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/AddResponse")] double Add(double n1, double n2);

[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa mples/ICalculator/Subtract", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/SubtractResponse")] double Subtract(double n1, double n2);

[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa mples/ICalculator/Multiply", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/MultiplyResponse")] double Multiply(double n1, double n2);

[System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.ServiceModel.Sa mples/ICalculator/Divide", ReplyAction="http://Microsoft.ServiceModel.Samples/ICalculator/DivideResponse")] double Divide(double n1, double n2); }

[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 partial class CalculatorClient : System.ServiceModel.ClientBase, ICalculator {

public CalculatorClient() { }

public CalculatorClient(string endpointConfigurationName) : base(endpointConfigurationName) { }

public CalculatorClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { }

public CalculatorClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { }

public CalculatorClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { }

public double Add(double n1, double n2) { return base.Channel.Add(n1, n2); }

public double Subtract(double n1, double n2) { return base.Channel.Subtract(n1, n2); }

public double Multiply(double n1, double n2) { return base.Channel.Multiply(n1, n2); }

public double Divide(double n1, double n2) { return base.Channel.Divide(n1, 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.

How to: Configure a Basic Windows Communication Foundation Client This is the fifth of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorialtopic. 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. Rightclick 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.

3. 4. 5. 6. 7.

<system.serviceModel> <wsHttpBinding>

8.



9.



10.



11.



12.



13. 14.

<endpoint 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.



20.



21.
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 The endpoint element specifies that the Microsoft.ServiceModel.Samples.ICalculator contract is used for the communication, which is configured with the system-provided WsHttpBinding. This binding specifies HTTP as the transport, interoperable security, and other configuration details.

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.

<system.serviceModel> <wsHttpBinding>
useDefaultWebProxy="true" allowCookies="false"> <security mode="Message"> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
<endpoint address="http://localhost:8000/ServiceModelSamples/Service/CalculatorService" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator" contract="ICalculator" name="WSHttpBinding_ICalculator"> <userPrincipalName value="[email protected]" />

Now the client has been configured. Proceed to How to: Use a Windows Communication Foundation Client. For troubleshooting information, seeTroubleshooting the Getting Started Tutorial.

How to: Use a Windows Communication Foundation Client This is the sixth of six tasks required to create a basic Windows Communication Foundation (WCF) service and a client that can call the service. For an overview of all six of the tasks, see the Getting Started Tutorialtopic. 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.

To use a Windows Communication Foundation client

1.

Create an EndpointAddress instance for the base address of the service you are going to call and then create an WCF Client object. C#

//Step 1: Create an endpoint address and an instance of the WCF Client. CalculatorClient client = new CalculatorClient();

2.

Call the client operations from within the Client. C#

// Step 2: Call the service operations. // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = client.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

// Call the Subtract service operation.

value1 = 145.00D; value2 = 76.54D; result = client.Subtract(value1, value2); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

// Call the Multiply service operation. value1 = 9.00D; value2 = 81.25D; result = client.Multiply(value1, value2); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

// Call the Divide service operation. value1 = 22.00D; value2 = 7.00D; result = client.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

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.WriteLine("Press <ENTER> to terminate client."); 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 { static void Main() { //Step 1: Create an endpoint address and an instance of the WCF Client. CalculatorClient client = new CalculatorClient();

// Step 2: Call the service operations. // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = client.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

// Call the Subtract service operation. value1 = 145.00D; value2 = 76.54D; result = client.Subtract(value1, value2); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

// Call the Multiply service operation. value1 = 9.00D; value2 = 81.25D;

result = client.Multiply(value1, value2); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

// Call the Divide service operation. value1 = 22.00D; value2 = 7.00D; result = client.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

//Step 3: Closing the client gracefully closes the connection and cleans up resources. client.Close();

Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); 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

Troubleshooting the Getting Started Tutorial This topic lists the most common problems encountered when working through the Getting Started Tutorial and how to resolve them.

Problem: I am unable to find the project files on my hard drive. Solution: Visual Studio saves project files in c:\users\<user name\Documents\Visual Studio 2005\Projects in Windows Vista and c:\Documents and Settings\<user name>\My Documents\Visual Studio 2005\Projects in earlier versions of Windows. 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: Unable to find the app.config file generated by Svcutil.exe. 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: Unhandled Exception: System.ServiceModel.EndpointNotFoundException: Could not connect to http://localhost:8000/ServiceModelSamples/Service/CalculatorService. TCP error code 10061: No connection could be made because the target machine actively refused it. Solution: This error occurs if you run the client application without running the service.

How to: Host a WCF Service in IIS This topic outlines the basic steps required to create a Windows Communication Foundation (WCF) service that is hosted in Internet information Services (IIS). A WCF service that runs in the IIS environment takes full advantage of IIS features, such as process recycling, idle shutdown, process health monitoring, and message-based activation. This hosting option requires that IIS be properly configured, but it does not require that any hosting code be written as part of the application. You can use IIS hosting only with an HTTP transport. For the source copy of this example, see IIS Hosting Using Inline Code.

To create a service hosted by IIS 1.

Confirm that IIS is installed and running on your computer.

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.

<%@ServiceHost language=c# Debug="true" Service="Microsoft.ServiceModel.Samples.CalculatorService"%> 4.

Create an App_Code subdirectory within the application directory.

5.

Create a code file in the App_Code subdirectory.

6.

Define the service contract for the type of service in the code file. C#

[ServiceContract] public interface ICalculator

{ [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); }

7.

Implement the service contract in a service class in the code file. C#

public class CalculatorService : ICalculator { public double Add(double n1, double n2) { return n1 + n2; } public double Subtract(double n1, double n2) { return n1 - n2; } public double Multiply(double n1, double n2) { return n1 * n2; } public double Divide(double n1, double 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

<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" />





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] public interface ICalculator { [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); }

public class CalculatorService : ICalculator {

public double Add(double n1, double n2) { return n1 + n2; } public double Subtract(double n1, double n2) { return n1 - n2; } public double Multiply(double n1, double n2) { return n1 * n2; } public double Divide(double n1, double n2) { return n1 / n2; } }

WCF Client Overview This section describes what client applications do, how to configure, create, and use a Windows Communication Foundation (WCF) client, and how to secure client applications.

Using WCF Client Objects A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps: 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.



Configuring and securing clients.



Creating callback objects for duplex services.



Calling services asynchronously.



Calling services using client channels.

Obtain the Service Contract, Bindings, and Addresses In WCF, services and clients model contracts using managed attributes, interfaces, and methods. To connect to a service in a client application, you need to obtain the type information for the service contract. Typically, you do this by using the ServiceModel Metadata Utility Tool (Svcutil.exe), which downloads metadata from the service, converts it to a managed source code file in the language of your choice, and creates a client application configuration file that you can use to configure your WCF client object. For example, if you are going to create an WCF client object to invoke a MyCalculatorService, and you know that the metadata for that service is published athttp://computerName/MyCalculatorService/Service.svc?wsdl, then the following code example shows how to use Svcutil.exe to obtain a ClientCode.vb file that contains the service contract in managed code.

svcutil /language:vb /out:ClientCode.vb /config:app.config http://computerName/MyCalculatorService/Service.svc?wsdl You can either compile this contract code into the client application or into another assembly that the client application can then use to create an WCF client object. You can use the configuration file to configure the client object to properly connect to the service . For an example of this process, see How to: Create a Windows Communication Foundation Client. For more complete information about contracts, see Contracts.

Create a WCF Client Object A WCF client is a local object that represents a WCF service in a form that the client can use to communicate with the remote service. WCF client types implement the target service contract, so when you create one and configure it, you can then use the client object directly to invoke service operations. The WCF run time converts the method calls into messages, sends them to the service, listens for the reply, and returns those values to the WCF client object as return values or out or ref parameters. You can also use WCF client channel objects to connect with and use services. For details, see Client Architecture. Creating a New WCF Object To illustrate the use of a ClientBase class, assume the following simple service contract has been generated from a service application. 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" )] public interface ISampleService { [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" )] string SampleMethod(string msg); } 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 partial class SampleServiceClient : System.ServiceModel.ClientBase, ISampleService {

public SampleServiceClient() { }

public SampleServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { }

public SampleServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { }

public SampleServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress)

: base(endpointConfigurationName, remoteAddress) { }

public SampleServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public string SampleMethod(string msg) { 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. Contracts, Bindings, and Addresses Before you can create a WCF client object, you must configure the client object. Specifically, it must have a serviceendpoint to use. An endpoint is the combination of a service contract, a binding, and an address. (For more information about endpoints, see Endpoints: Addresses, Bindings, and Contracts.) Typically, this information is located in the <endpoint> element in a client application configuration file, such as the one the Svcutil.exe tool generates, and is loaded automatically when you create your client object. Both WCF client types also have overloads that enable you to programmatically specify this information. For example, a generated configuration file for an ISampleService used in the preceding examples contains the following endpoint information. Xml

<system.serviceModel> <wsHttpBinding>
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"> <security mode="Message"> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
<endpoint address="http://localhost:8080/SampleService" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISampleService" contract="ISampleService" name="WSHttpBinding_ISampleService">
This configuration file specifies a target endpoint in the 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.) For example, if you have the following service contract: C#

namespace Microsoft.ServiceModel.Samples { using System; using System.ServiceModel;

[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] public interface ICalculator { [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); } } Visual Basic

Namespace Microsoft.ServiceModel.Samples

Imports System Imports System.ServiceModel

<ServiceContract(Namespace:= _ "http://Microsoft.ServiceModel.Samples")> _

Public Interface ICalculator _ Function Add(n1 As Double, n2 As Double) As Double _ Function Subtract(n1 As Double, n2 As Double) As Double _ Function Multiply(n1 As Double, n2 As Double) As Double _ Function Divide(n1 As Double, n2 As Double) As Double 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(); } catch (TimeoutException timeout) { // Handle the timeout exception. wcfClient.Abort(); } catch (CommunicationException commException) { // Handle the communication exception. 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.

Configuring and Securing Clients Configuring a client starts with the required loading of target endpoint information for the client or channel object, usually from a configuration file, although you can also load this information programmatically using the client constructors and properties. However, additional configuration steps are required to enable certain client behavior and for many security scenarios. 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 runtime behaviors. For more information about how to configure a custom client behavior, see Configuring Client Behaviors.

Creating Callback Objects for Duplex Services Duplex services specify a callback contract that the client application must implement in order to provide a callback object for the service to call according to the requirements of the contract. Although callback objects are not full services (for example, you cannot initiate a channel with a callback object), for the purposes of implementation and configuration they can be thought of as a kind of service. Clients of duplex services must:



Implement a callback contract class.



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.



Invoke operations and handle operation callbacks.

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(); EndpointAddress endptadr = new EndpointAddress("http://localhost:12000/DuplexTestUsingCode/Server"); dualBinding.ClientBaseAddress = new Uri("http://localhost:8000/DuplexTestUsingCode/Client/");

The following code shows how to do this in a configuration file C#

<endpoint name ="ServerEndpoint" address="http://localhost:12000/DuplexUsingConfig/Server" bindingConfiguration="WSDualHttpBinding_IDuplex" binding="wsDualHttpBinding" contract="IDuplex" /> <wsDualHttpBinding>

Calling Services Asynchronously How operations are called is entirely up to the client developer. This is because the messages that make up an operation can be mapped to either synchronous or asynchronous methods when expressed in managed code. Therefore, if you want to build a client that calls operations asynchronously, you can use Svcutil.exe to generate asynchronous client code using the /async option. For more information, see How to: Call WCF Service Operations Asynchronously.

Calling Services Using WCF Client Channels WCF client types extend ClientBase, which itself derives from System.ServiceModel.IClientChannel interface to expose the underlying channel system. You can invoke services by using the target service contract with theSystem.ServiceModel.ChannelFactory class. For details, see Client Architecture.

Windows Workflow Foundation Overview Windows Workflow Foundation is a framework that enables users to create system or human workflows in their applications written for Windows Vista, Windows XP, and the Windows Server 2003 operating systems. It consists of a namespace, an in-process workflow engine, and designers for Visual Studio 2005. Windows Workflow Foundation can be used to solve simple scenarios, such as showing UI controls based on user input, or complex scenarios encountered by large enterprises, such as order processing and inventory control. Windows Workflow Foundation comes with a programming model, a rehostable and customizable workflow engine, and tools for quickly building workflow-enabled applications on Windows. Scenarios that Windows Workflow Foundation addresses include:



Enabling workflow within line-of-business applications.



User-interface page flows.



Document-centric workflows.



Human workflows.



Composite workflows for service-oriented applications.



Business rule-driven workflows.



Workflows for systems management.

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.

Workflow Runtime Engine Every running workflow instance is created and maintained by an in-process runtime engine that is commonly referred to as the workflow runtime engine. There can be several workflow runtime engines within an application domain, and each instance of the runtime engine can support multiple workflow instances running concurrently.

When a workflow model is compiled, it can be executed inside any Windows process including console applications, forms-based applications, Windows Services, ASP.NET Web sites, and Web services. Because a workflow is hosted in process, a workflow can easily communicate with its host application. 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.

Local Communication and Correlation Overview Host processes can communicate with workflows by exchanging data through custom local communication services. These local communication services implement user-defined interfaces that define methods and events that will be passed between the workflow and the host process. 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.

Workflow Changes Overview Windows Workflow Foundation enables you to dynamically update your workflow instance and declarative rules during run time. Before activities are scheduled for execution, you can change expected behaviors, flow control, and so on. This ability enables you to modify business processing logic without having to recompile and restart your workflow.

Rules and Conditions Overview Windows Workflow Foundation can implement business logic as either rules or conditions. Conditions are used by IfElseBranchActivity, ConditionedActivityGroup, WhileActivity, and ReplicatorActivity activities to control activity execution. Conditions can be expressed as declarative, or defined in code. Declarative conditions are created as code DOM statements in the rules' XML file. Code-based conditions reference a method in the workflow's code file that returns its result through the Result property. 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.

Fault Handling Overview Exceptions that occur in activities are handled asynchronously by the workflow runtime engine in a process called fault handling. Exceptions are scheduled in a queue to be handled later. If the exception type matches the one that is handled by a particular FaultHandlerActivity activity, that activity will handle the exception. If the exception cannot be handled, it is bubbled up through parent activities until it ultimately causes the termination of the workflow instance.

Workflow Markup Overview Workflow markup, which is based on extensible Application Markup Language (XAML), enables developers and designers to model business logic declaratively and separate it from lower-level implementation details that are modeled by code-beside files. Because workflows can be modeled declaratively, it is possible to activate a workflow by directly loading a workflow markup file into the workflow runtime engine at run time.

WWF: http://msdn.microsoft.com/en-us/library/ms735927.aspx

Related Documents