1
2
Building distributed applications In today’s world, implementing distributed systems that provide business value in a reliable fashion presents many challenges. We take many features for granted when developing Non distributed systems that can become issues when working with disparate distributed systems. Although some of these challenges are obvious (such as a loss of connectivity leading to data being lost or corrupted), for other aspects such as tightly coupled systems the dependencies between the various components of a system make it cost prohibitive to make changes as needed to meet the demands of the business. As developers, we’ve been building distributed applications for years now. But however, it’s never been as easy as it should be, or could be. •Though the ability to build distributed applications has certainly changed over the past few years, it hasn’t necessarily gotten any easier. In fact, additional capabilities and options for building distributed applications have brought with them additional complexity! Security is critical for applications, but often complicated to implement. Standards-based interoperability needs to be taken into account for communication across heterogeneous systems. The different programming models with different capabilities that are focused on different application scenarios: Web services, distributed objects, and message queuing and COM+ all helped address development needs, but again, they’ve added more complexity to developers lives. It mandates a programmer to learn different programming paradigms , tools and technologies and often contain functionality and features that don’t compose (combine) well with one another. Business processes quite often are supported by systems that are running on different platforms and technologies both within and outside the organization. Service-Oriented Architecture(SOA) is a mechanism that enables organizations to facilitate communication between the systems running on multiple platforms by using services that expose business functionality. SOA allows each individual service to be modified independently of other services to help respond to the ever-evolving market conditions of a business (Need to design applications for flexibility in the face of change.) So what is SOA? Business processes quite often are supported by systems that are running on different technologies and platforms within an outside the organization. SOA is a mechanism that enables the organization to facilitate communication between the systems running on the different platforms. Service-oriented architecture (SOA) is a collection of services. Service-oriented architecture (SOA) is a flexible set of design principles used during the phases of systems development and integration in computing. A system based on SOA architecture will provide a loosely-coupled suite of services that can be used within multiple separate systems from several business domains. SOA also generally provides a way for consumers of services, such as web-based applications, to be aware of available SOA-based services. For example, several disparate departments within a company may develop and deploy SOA services in different implementation languages; their respective clients will benefit from a well understood, well defined interface to access them. XML is commonly used for interfacing with SOA services, though this is not required.SOA defines how to integrate widely disparate applications for a Web-based environment and uses multiple implementation platforms. Rather than defining an API, SOA defines the interface in terms of protocols and functionality. An endpoint is the entry point for such a SOA implementation. Service-orientation requires loose coupling of services with operating systems, and other technologies that underlie applications. SOA separates functions into distinct units, or services, which developers make accessible over a network in order to allow users to combine and reuse them in the production of applications. These services and their corresponding consumers communicate with each other by passing data in a well-defined, shared format, or by coordinating an activity between two or more services. So what is a Service? A service is a unit of functionality exposed to the world. The services can be local or remote, developed by multiple parties using any technology, versioned independently, and even execute on different timelines. The client of a service is merely the party consuming its functionality. Clients and services interact by sending and receiving messages. Messages may transfer directly from client to service or via an intermediary. For more Details Refer to linked SOA document Solution………………………..! It was these types of development challenges in building distributed applications that drove the WCF product design goals. WCF takes the service-oriented concepts of message passing, schema, contract, and policy, and implicitly applies it to all of the services we build. As such, WCF provides developers with the first true service-oriented programming model. WCF addresses SOA concepts to promote WCF as a practical SOA implementation from Microsoft.
3
Why WCF Service? •SOA : WCF is a Microsoft's platform for creating service oriented applications. It is the programming model built from the ground up to provide explicit service oriented application and ready –to-face business orientation. It is not a technology but a architecture style or design concept. Service-oriented architecture (SOA) is the reliance on services to send and receive data. Service Oriented architecture is a collection of services. It is an architectural style that uses a set of services to achieve desired business functionality. The services have the general advantage of being loosely-coupled instead of hard-coded from one application to another. •Interoperability: WCF implements modern industry standards for Web service interoperability. •Loosely coupled: A loosely-coupled relationship implies that any client created on any platform can connect to any service as long as the essential contracts are met. Service Metadata: WCF supports publishing service metadata using formats specified in industry standards such as WSDL, XML Schema and WS-Policy. Service metadata provides information about how to interact with the service endpoint. This metadata can be used by tools, such as Svcutil.exe, can automatically generate client code for accessing the service. Windows Communication Foundation (WCF) provides a rich infrastructure for exporting, publishing, retrieving, and importing service metadata. WCF services use metadata to describe how to interact with the service's endpoints Metadata can be published over HTTP and HTTPS or using the Web Service Metadata Exchange standard. •Multiple Transports and Encodings Messages can be sent on any of several built-in transport protocols and encodings. The most common protocol and encoding is to send text encoded SOAP messages using is the Hypertext Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively, WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages can be encoded as text or using an optimized binary format. Binary data can be sent efficiently using the MTOM(Message transmission Optimization Mechanism) standard. MTOM- is used for sending unstructured binary data . If none of the provided transports or encodings suit application needs developers can develop custom transport or encoding. •Security WCF is a distributed programming platform based on SOAP messages. Using WCF, you can create applications that function as both services and service clients, creating and processing messages from an unlimited number of other services and clients. In such a distributed application, messages can flow from node to node, through firewalls, onto the Internet, and through numerous SOAP intermediaries(multiple points in the network). This introduces a variety of message security threats. Windows Communication Foundation (WCF) is a SOAP message-based distributed programming platform, and securing messages between clients and services is a vital aspect of secured communication to protect data. WCF provides a versatile and interoperable platform for exchanging secure messages based upon both the existing security infrastructure and the recognized security standards for SOAP messages. WCF uses familiar concepts to built secure, distributed applications like HTTPS, Windows integrated security, or user names and passwords to authenticate users. WCF not only integrates with existing security infrastructures, but also extends distributed security beyond Windows-only domains by using secure SOAP messages. Consider WCF an implementation of existing security mechanisms with the major advantage of using SOAP as the protocol in addition to existing protocols. For example, credentials that identify a client or a service, such as user name and password or use X.509 certificates. Using any one of these methods messages are exchanged securely. Messages can be encrypted to protect privacy and client of the service are authenticated before being allowed to receive messages. Key security features include: • Auditing: Effective auditing and logging is the key to non-repudiation. Non-repudiation guarantees that a user cannot deny performing an operation or initiating a transaction. • Authentication: Authentication allows you to confidently identify the clients of your service. These might be end users, other services, processes, or computers. WCF supports mutual authentication, which identifies both the client and the service or both, to help in preventing man-in-the-middle attacks. • Authorization Authorization determines what system resources and operations can be accessed by the authenticated user. This allows you to grant specific application and resource permissions for authenticated users. • Confidentiality Confidentiality, also referred to as privacy, is the process of making sure that data remains private and confidential, and that it cannot be viewed by unauthorized users. Encryption is frequently used to enforce confidentiality. Privacy is a key concern, particularly for data / messages passed across networks. • Integrity Integrity is the guarantee that data is protected from accidental or deliberate modification. Like privacy, integrity is a key concern, particularly for data / messages passed across networks. Integrity for data in transit is typically provided by using hashing techniques and message authentication codes. •Unified Programming Model The distributed systems technologies before the birth of WCF were .NET Remoting, Web Services, Web Service Enhancements (WSE), MSMQ, and Enterprise Services/COM+. WCF unifies all these into one programming model and developers no longer have to make an exclusive explicit choice for one of these technologies. Therefore, WCF offers a single programming model that unifies the features of .NET Remoting, MSMQ, Enterprise Services, Web Services and Web Service Enhancements. You can create a WCF Service that can be 1) Exposed as a legacy .asmx based service. 2) Run as NT Service 3) Hosted as Enterprise Service Component 4) That can read and write to Message queues of O.S. 5) A service that can behave like a remote for cross process communication behind the fire wall.
4
Role of WCF .asmx based services –Web Service : A .NET web service is a remote web component whose method can be invoked remotely over a wired protocol. It is programmable application logic accessible via standard Web protocols. They are based on internet standards like •XML-Extensible Markup language : Web service emit XML Messages, •SOAP-Simple Object Access protocol: Protocol for communication. SOAP uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data. • WSDL-Web Service description language : XML description of the web service . •UDDI -Universal , Description , Discovery and Integration: Registry for the web services and •HTTP-Hyper text Transfer Protocol: Protocol for transfer. Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to location of the service and understand how to send and receive SOAP messages (HTTP and XML). •Microsoft .NET Enterprise Services : COM provides one way to write component-based applications. It is well known that the plumbing work required to write COM components is significant and repetitive. COM+ is not so much about a new version of COM; rather, COM+ provides a services infrastructure for components. Microsoft COM+ provides a strong foundation to build component-based enterprise applications by using Microsoft Component Object Model (COM) objects. Microsoft .NET Enterprise Services is a feature that is included in the Microsoft .NET Framework. With .NET Enterprise Services, the .NET objects can take advantage of COM+ features like Some of these services include, transactions, object pooling ,role-based security, object pooling, just-in-time activation . Additionally, .NET Enterprise Services includes some new features for .NET components that are not available to COM components. The process to develop Enterprise Services components (or serviced components) is similar to the process that you use to develop COM+ components. COM+ features are available to both processes, and these features work the same for both processes. The .NET Framework provides a managed class into COM+ called Enterprise Services (ES) within the System.EnterpriseServices namespace. This class offers ways to programmatically make use of these services in a more simplified fashion than in the past. WS-* (pronounced as WS specification) : Web Services are used for consuming business logic across platforms. The core web service architecture formulates the way to define the web service and how the web service message are formatted. There are a variety of specifications associated with web services. These Web service specifications are occasionally referred to collectively as "WS-*". These specifications are in varying degrees of maturity and are maintained or supported by various standards bodies and entities. The web service can be consumed across platform in an interoperable manner. As the business requirements that drive web services became more and more complex, the developers required additional capabilities like reliable messaging , security etc . Were not addressed by web services. The industry leaders like Microsoft and IBM came together to provide these in a standardized form called as WS-* suite of protocols. These specifications address several different areas, including basic messaging, security, reliability, transactions, and working with a service’s metadata.By default, WCF services speak standard WS-* protocols when sending and receiving messages for maximum interoperability. These features include: Interoperable security(WS-Security), reliable messaging(WS-Reliability), and transaction support are provided through WS-* implementations. Reliable messaging guarantees “in order” and “exactly once” delivery. Transaction support enables reliable execution or rollback of multi-step operations(WS-Transactions). Thus to support features beyond just the basic communication, WCF implements Web services enhancements defined by the WS-* specifications. •Message Queuing: MSMQ is a set of objects that allow you to perform queue messaging in windows. Message Queuing is a message infrastructure and a development platform for creating distributed, loosely-coupled messaging applications for the Microsoft Windows operating system. Message Queuing applications can use the Message Queuing infrastructure to communicate across heterogeneous networks and with computers that may be offline. Message Queuing provides guaranteed message delivery, efficient routing, security, transaction support, and priority-based messaging. It enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline. Applications send messages to queues and read messages from queues. A queue can hold messages that are generated by multiple sending applications and read by multiple receiving applications. System.Messaging is the .NET layer on top of MSMQ to build queued applications. It gives developer a ability to build queued applications through .NET . .Net Remoting : NET remoting enables you to build widely distributed applications easily, whether application components are all on one computer or spread out across the entire world. You can build client applications that use objects in other processes on the same computer or on any other computer that is reachable over its network. You can also use .NET remoting to communicate with other application domains in the same process. .NET remoting provides an abstract approach to inter process communication that separates the remotable object from a specific client or server application domain and from a specific mechanism of communication. To use .NET remoting to build an application in which two components communicate directly across an application domain boundary, you need to build only the following: •A remotable object. •A host application domain to listen for requests for that object. •A client application domain that makes requests for that object.
5
The components of WCF architecture are Contracts: They describe operations, data , structure of the message and the error returned by the service to the caller that is exchanged by the service and the clients. Service runtime :It describes the runtime aspects of the service. Messaging : This layer describes the channel stack that is used for transferring the messages and the protocol channel used for communication. Activation and Hosting: The various applications that are eligible for Hosting WCF services like console applications, Winforms, WPFForms, NT Services, IIS or WAS. Now Let us discuss in details all of the WCF architecture components . I)Contracts A WCF contract bundles the Operations that can be called by a client. A contract defines the type of input parameters that are required to call an operation. It defines what type of response message the client can expect. It controls the structure of the message exchanged between the client and the service. It determines the runtime behavior of the service. It specifies what information to be passed to the client when an internal error occurs on the service. Thus the Contracts define various aspects of the message system. There are four types of contracts in WCF: • Service contracts : Service contracts describe the functional operations implemented by the service.It expresses the methods that are exposed to the outside world into a single functional unit. Service contracts are implemented as .NET interfaces or classes. A service contract maps the class methods of a .NET type to WSDL services, port types, and operations. An operation contract defines the parameters and return type of an operation. Operation contracts within service contracts describe the service operations, which are the methods that implement functions of the service. • Data contracts: One of the universal types of contracts is the data contract. Inside a service, functional application capabilities are implemented in code. Outside a service, functional capabilities are defined in WSDL. Inside a WCF service, application data is represented in simple and complex types while outside the service data is represented by XML Schema Definitions (XSD). WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service and defines how the yare serialized and de serialized using DataContractSerializer at runtime. Data contracts describe all the data that is sent to or from service operations. • Message contracts: Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly Message contracts map CLR types to SOAP messages and describe the format of the SOAP messages and affect the WSDL and XSD definitions of those messages. Message contracts provide precise control over the SOAP headers and bodies. •Fault contracts : It is associated with a service operation. It signifies errors that can be returned to the caller. An operation can have zero or more faults associated with it. The errors thrown by WCF services are .NET exceptions that are described as SOAP faults. II )Service Runtime : The Service Runtime layer is the layer that specifies and manages the behaviors of the service that occur during service operation, or service runtime . The following lists the various behaviors managed by the Service Runtime layer: Concurrency Behavior: The Concurrency behavior determines how each service, or instance of the service, handles threading. This behavior helps control how many threads can access a given instance of a service. Dispatch Behavior: When a message is processed by the WCF infrastructure, the Dispatch Behavior service determines how the message is to be handled and processed. Error Behavior: The Error behavior specifies what action will be taken if an error occurs during service runtime. Message Inspection: Message Inspection gives the service the ability to inspect all or parts of a message. Metadata Behavior: The Metadata behavior controls whether or not metadata is exposed to the outside world. Instance Behavior: The Instance behavior drives how many instances of the service will be available to process messages. Parameter Filtering: When a message is acted upon by the service, certain actions can be taken based on what is in the message headers. Parameter Filtering filters the message headers and executes preset actions based on the filter of the message headers. Throttling Behavior: The Throttling behavior determines the number of processed messages. Transaction Behavior: The Transaction behavior enables transacted operations. That is, if a process fails during the service runtime it has the ability to rollback the transaction. IV) Messaging Layer The messaging layer describes the communication channels used by the service. It illustrates the possible formats and exchange patterns of the data. A channel is the medium through which all messages pass to and from WCF applications. It is responsible for preparing and delivering messages in a consistent way. Channels are defined for transports, protocols, and message interception. Channels are layered together to create a channel stack. A channel stack is a layered communication stack that processes messages. 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. A. Transport Channels : They are responsible for transporting messages using a transport protocol. WCF provides a number of transport protocols, including HTTP, TCP, MSMQ, peer-to-peer, and named pipes. Some transports use an encoder to convert to and from the byte stream representation used by the network. Examples of encodings XML, MTOM B. Protocol channels : They are responsible for implementing wire-level protocols by transforming and modifying messages. Examples of such protocols include WS-Security and WS-Reliability. The following lists the channels and components that the Messaging layer is composed of: WS Security Channel: The WS Security channel implements the WS-Security specification, which enables message security. WS Reliable Messaging Channel: Guaranteed message delivery is provided by the WS Reliable Messaging channel. Encoders: Encoders let you pick from a number of encodings for the message. HTTP Channel: The HTTP channel tells the service that message delivery will take place via the HTTP protocol. TCP Channel: The TCP channel tells the service that message delivery will take place via the TCP protocol. Transaction Flow Channel: The Transaction Flow channel governs transacted message patterns. NamedPipe Channel: The NamedPipe channel enables inter-process communication. MSMQ Channel: If your service needs to interoperate with MSMQ, this is the channel that enables that. V) Hosting : 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.
6
WCF Application Components : WCF Service A WCF Service is a program that exposes one or more endpoints, with each endpoint exposing one or more service operations that can be invoked by clients or by other services. What is an Endpoint? An endpoint is a construct at which a WCF service can send and receive Messages. What is a Message? A message is a unit of data that is exchanged between service and its clients. What is a Service Host? A host is an application that controls the lifetime of the service. Services can be selfhosted or managed by an existing hosting process like IIS, Winforms or console application. What is a WCF Service Client? A client is a program that consumes a WCF service by exchanging messages with one or more endpoints.
7
8
Every WCF Service will expose endpoints for clients to communicate with it. The client in turn needs to know where the endpoint can be found, How to send the data and What data can be sent. All the above information is defined by the service in the form Service Endpoints and exposes them for client access. What is an Endpoint? An endpoint is a construct at which messages can be sent and received. What are the characteristics or properties on endpoints? •An address that indicates where the endpoint can be found. •A binding that specifies how a client can access the endpoint.
•A contract that identifies the operations available. •Implementation details of an endpoint. An endpoint comprises of (A)ddress, (B)inding and (C)ontract.
9
What does WCF service endpoint comprise of A service endpoint comprises of ABC • “A” is for address, the where. This service listens for incoming requests . Example http://www.Constoso.com/SearchServices/StockService. • “B” is for binding, the how. Bindings specifies how a client can access an endpoint. It includes information about Transport They are responsible for transporting messages using a transport protocol. WCF provides a number of transport protocols, including HTTP, TCP, MSMQ, peer-to-peer, and named pipes. Protocol They are responsible for implementing wire-level protocols by transforming and modifying messages. Examples of such protocols include WS-Security and WS-Reliability for dealing with the necessary security requirements for example, SOAP message security. Encoding : The encoders present a variety of encodings that can be used to suit the needs of the message. Examples are Text, XML, Binary or MTOM. •“C” is for contract, the what. This is the syntactic description of what operations the service responds to and what message formats it expects in and out.
10
A contract specifies: A contract defines the list of operations that can be called by a client as a single unit called Service Contract. The type of input parameters or data required to call the operationOperation Contract. What type of data or message that can be sent or received from the service –Data contract. Specifies how the structure of the message can be controlled precisely –Message Contract. A. Behavior of the service- Service Behaviors like Instancing or Concurrency. Instancing Behavior It controls the number of service objects that are used to process the requests. B. Concurrency Behavior: The Concurrency behavior determines how each service, or instance of the service, C. Metadata Behavior: The Metadata behavior controls whether or not metadata is exposed to the outside world. D. Instance Behavior: The Instance behavior drives how many instances of the service will be available to process messages. E. Fault Contract : It specifies what the error information that is sent to the client when an internal error occurs on the service. Thus WCF service contracts are platform-neutral and standard way of describing what the service does.
11
Defining Endpoints Along with defining operations in a service class and specifying a host process to run those operations, a WCF service must also expose one or more endpoints. Every endpoint specifies three things: 1) An address indicating where this endpoint can be found. Addresses are URLs that identify a machine and a particular endpoint on that machine. 2)A binding determining how this endpoint can be accessed. The binding determines what protocol combination can be used to access this endpoint along with other things, such as whether the communication is reliable and what security mechanisms could be used, the underlying transport protocol used for message transfer. The encoding decides the format of the data that is exchanged between service and clients 3) A contract name indicating which service contract this WCF service class exposes via this endpoint. A service exposes two types of endpoints: 1)Application endpoints and 2)Metadata endpoints Application endpoints : These endpoints provide a means, via standard HTTP, by which external applications can communicate with the WFC Service. Metadata endpoints :WCF service exposes metadata using special endpoints for metadata publishing called as metadata endpoints or MEX endpoints. So what is the this metadata? Metadata is basically to describe how to interact with the service’s endpoints. This includes metadata about: •The operations a service can perform •The structure of the data types that the operations work with or return •Definitions of all the endpoints implemented by the service and the various options needed for each such as security By default service metadata is turned off.
12
WCF Service Contract : A WCF Contract specifies what a service does and the type of information it will make available. WCF supports a variety of contracts for communication and exchanging messages with the client.
Windows Communication Foundation supports the following types of contracts: A. Service contracts B. Operation contract C. Data contracts D. Fault Contract E. Message contracts
13
Service Contract A service contract is used on the service side to specify what the service’s endpoint exposes to consumers. It is a single functional unit that expresses the methods that are exposed to the outside world. A service contract specifies the following: What operations are exposed to the outside world? it is a statement about a set of specific messages organized into basic message exchange patterns (MEPs), such as request/reply, one-way, and duplex. If a service contract is a logically related set of message exchanges, a service operation is a single message exchange. The operations a contract exposes. The signature of the operations in terms of messages exchanged. The data types of these messages. When building a WCF service, you typically start by defining a .NET interface definition to serve as the service contract. Then you implement the service contract in a .NET class, known as the service type, and configure its behavior. The ServiceContract from the System.Servicemodel namespace attribute exposes a CLR interface (or a class) as a WCF contract, independently of that type’s visibility. The type visibility has no bearing on WCF, because visibility is a CLR concept. Applying the ServiceContract attribute on an internal interface exposes that interface as a public service contract, ready to be consumed across the service boundary. Without the ServiceContract attribute, the interface is not visible to WCF clients, in line with the serviceoriented tenet that service boundaries are explicit. To enforce that, all contracts must explicitly opt in: only interfaces (or classes) decorated with the ServiceContract attribute will be considered as WCF contracts. Every method that is a part of the service contract must be decorated with the attribute operation contract attribute. Other methods on the interface (or class) that do not have the OperationContract attribute will not be part of the contract. A contract operation cannot use object references as parameters—only primitive types or data contracts are allowed.
14
In the above example demonstrates hot to define a WCF service contract. A public interface ISimpleService is annotated with [ServiceContract]. Applying the ServiceContract attribute on an internal interface exposes that interface as a public service contract, ready to be consumed across the service boundary. Without the ServiceContract attribute, the interface is not visible to WCF clients. Only interfaces (or classes) decorated with the ServiceContract attribute will be considered as WCF contracts. The service contract groups the service operations. The operations that are a part of Service Contract need to annotated with the [OperationContract]. Failing to do so, the operation will not be callable by client. The operation HelloMessage defined as an operation contract.
15
In the above example the SimpleHelloService class implements the service contract ISimpleService.
16
What is Data contract ? The data contract describes the data that clients and the service will exchange. Clients and services exchange data via XML. When the client calls a service operation that takes arguments, the WCF runtime converts .NET types to XML. When the service receives the operation call, the runtime converts the XML to the appropriate .NET types. If the method returns a value, the same process occurs. The WCF runtime uses the Data Contract Serializer to serialize (convert to XML) and deserialize data (convert from XML). This Serializer automatically works with primitive .NET types, such as string and integers, and types such as DateTime and TimeSpan. However, the Serializer does not automatically work with more complex custom types or user defined types. To make these types serializable, developer needs to define a data contract. To mark a type as a data contract, use the [DataContract ] and [DataMember] attributes from System.Runtime.Serialization namespace. New complex types that you create must have a data contract defined for them to be serializable. The [DataMember] attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized. By default, the DataContractSerializer (DCS) infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized. For partial serialization use the [IgnoreDataMember]. This attribute can be applied to classes, structures, and enumerations. Types that can be serialized by DCS: DataContractSerilizer supports : 1)CLR Primitive Types: Int32, Decimal, Boolean 2)Other Primitive Types: Byte Array, DateTime, etc 3)Enums 4)[DataContract], [CollectionDataContract] 5)Arrays and Collections 6)[Serializable], Iserializable 7)Generic and Nullable Types 8)Supports Classes, interfaces (as Object) and structures It Does Not support :1.[XMLElement] and [XMLAttribute] : Use XmlSerializer to serialize members marked with such attributes
17
The above example demonstrates how to define a WCF Data Contract. A data contract control what data will be exchanged between client an the service via XML. To exchange data as XML WCF uses DCS to serialize and desterilize. The above class HelloMessage is decorated with the attribute [DataContract] and the members of the same are decorated with [DataMember]. Applying these attributes informs the WCF DCS that instance of HelloMessage is used to exchange as the message between the service and the client. The return type of HelloMethod is HelloMessage.
18
What is a Message Contract? WCF communicates with clients by sending SOAP messages to and from the services. SOAP message contain Envelope, Header and Body. SOAP envelope contains name, namespace, header and body element. SOAP Head contain important information which are not directly related to message. SOAP body contains information which is used by the target. Typically when building WCF Services a developers often focus on data that is exchanged between service and the client. But sometimes it may be equally important to control the structure of the message that is exchanged. A message contract is a provision from WCF to achieve the same. A Message contract : Message contracts describe the structure of SOAP messages sent to and from a service. Enables a developer to inspect and completely control the structure of a SOAP message. Allows to use a type for a parameter or return value that serializes directly into the desired SOAP message precisely. It maps a .NET type to SOAP envelope i.e., SOAP Header and SOAP Body. It defines a strongly-typed class that corresponds to a SOAP message. Message contract can be applied to type using MessageContract attribute from System.ServiceModel namespace. Custom Header and Body can be included to message using '[MessageHeader]' and '[MessageBodyMember]' attribute. [MessageHeader] -that a data member is a SOAP message header. [MessageHeader] -Specifies that a member is serialized as an element inside the SOAP body. These attributes can be applied to all fields, properties, and events, regardless of whether they are public, private, protected, or internal.
19
The above example demonstrates how to define a WCF Message Contract. A message contract control controls the structure of the message being exchanged. The above class EmployeeDetails decorated with the attribute [MessageContract] and the members of the same are decorated with [MessageHeader].
Applying these attributes informs the WCF DCS that instance of HelloMessage is used to exchange as the message between the service and the client. The return type of HelloMethod is HelloMessage.
20
What is WCF Fault Contract? WCF communicates with clients by sending SOAP messages to and from the services. SOAP message contain Envelope, Header and Body A SOAP message is an ordinary XML document containing the following elements. Envelope: ( Mandatory ) Defines the start and the end of the message. Header: ( Optional ) Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end point. Body: ( Mandatory ) Contains the XML data comprising the message being sent. Fault: ( Optional ) An optional Fault element that provides information about errors that occurred while processing the message Exceptions that occur either in the service implementation logic or within the mechanics of the service host itself are natively CLR-based & types. Because services need to support communication between any type of client and service regardless of technology, those .NET-specific details must be translated to a standardized format for interoperable communications. Interoperability is ensured by serializing those platform-specific exception details to the common data schema described by the Simple Object Access Protocol (SOAP) specification. The SOAP specification provides for a fault element that may be present in a SOAP message’s body to describe errors . WCF Fault Contract map .NET exception to SOAP faults. Mark an operation with the [FaultContract] attribute to declare one or more specific exception conditions that are added to the Web Service Description Language (WSDL) description of the service operation as explicit SOAP fault messages returned by the operation. So What are SOAP faults ? SOAP faults are publicly described messages that carry fault information for a particular operation. Minimally, a SOAP fault must have two values. The reason -is a description of the error condition. The other required value is an error code-, which can either be a custom indicator or one of the predefined codes enumerated in the SOAP specification. For handling the exceptions, identify the error conditions and create a fault contract for the service that clients can use to properly handle those error conditions when notified by custom SOAP faults. The basic tasks for Handling exceptions are : •Define the error conditions that a client of your service should know about. [ServiceContract] public class CalculatorService { [OperationContract] int Divide(int a, int b) { if (b==0) {throw new ArithmeticException(“Division by zero!”);} return a/b; }} Here the operation Divide is expected to throw ArithmeticException. •Mark your operations so that the specific SOAP faults that they throw are exposed to clients in WSDL. [DataContract] public class MathFault { private string operation; private string problemType; [DataMember] public string Operation { get { return operation; } set { operation = value; } } [DataMember] public string ProblemType { get { return problemType; } set { problemType = value; } } } In the above code snippet shows the creation of a custom SOAP fault, MathFault, which can report errors made using all math operations, including Divide. While the class can specify an operation (the Operation property) and a value that describes the problem (the ProblemType property), the class and these properties must be serializable to be transferred to the client in a custom SOAP fault. Therefore, the System.Runtime.Serialization.DataContractAttribute and System.Runtime.Serialization.DataMemberAttribute attributes are used to make the type and its properties serializable and as interoperable as possible. •Define the custom content of the SOAP faults for those error conditions. [ServiceContract] public interface IMathService { [OperationContract] [FaultContract(typeof(MathFault))] int Divide(int n1, int n2) }
21
Fault Contract WCF communicates with clients by sending SOAP messages to and from the services. SOAP message contain Envelope, Header and Body. SOAP envelope contains name, namespace, header and body element. SOAP Head contain important information which are not directly related to message. SOAP body contains information which is used by the target. Fault Contract attribute : It specifies one or more SOAP faults that are returned when a service operation encounters processing errors. One or more [FaultContract] attributes can be used to decorate a service operation. This indicates to WCF that a service’s WSDL definition should include the details of fault-related information potentially thrown by the operation. Marking an operation with the FaultContractAttribute attribute declares one or more specific exception conditions that are added to the Web Service Description Language (WSDL) description of the service operation as explicit SOAP fault messages returned by the operation. There are two types of SOAP faults : Declared and Undeclared. Declared SOAP faults are those in which an operation has a System.ServiceModel.FaultContract attribute that specifies a custom SOAP fault type. Undeclared SOAP faults are not specified in the contract for an operation.
22
The example on the presentation show how to define [FaultContract] for service operations. The operation PerformDivision is suspected to throw a runtime exception. This runtime exception information needs to be sent to client as a part of the SOAP message describing exceptions as SOAP faults. In the above code the [FaultContract] attribute indicates that the PerformDivision operation may return a fault of type MathFault. A fault can be of any type that can be serialized. In this case, the MathFault is a data contract. The service implementation shows that the method PerformDivision includes a try catch block. In case the runtime error occurs it throws the object of generic FaultException that take a type parameter(theFault an instance of type MathFault) In the catch block the MathFault is instantiated and its values are initialized as obvious in the code above.
23
An public interface marked with [ServiceContract] makes its publicly visible to all service client as a formal contract that they agree on before communicating with each other. This making the services also loosely coupled as the contract are described to client in a language neutral manner-WSDL. Data contract are .NET custom types that are used to exchange data between the service and the client. These types are universally described to clients in a language neutral form across the technology boundary by mapping them XSD-XML schemas. Message contract allows the developer to precisely control the structure of the SOAP message. Here the Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. Message Contracts defines a strongly-typed class that map to a SOAP message.
24
The Standard WCF Bindings BasicHttp binding Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services for example, ASP.NET Web services (ASMX)-based services. This binding uses HTTP as the transport and text/XML as the default message encoding. WsHttpBinding This binding uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet. The messages are secured by default. One of the biggest differences you must have noticed is the security aspect. By default, BasicHttpBinding sends data in plain text while WsHttpBinding sends it in encrypted and secured manner. Another difference between WsHttpBinding and BasicHttpBinding is that WsHttpBinding supports WS-* specification. WS-* specifications are nothing but standards to extend web service capabilities. What is reliable messaging? Reliable messaging works generally like this: A client sends a sequence of messages (the sequence may be as short as one message) across a communication link and asks the receiver to acknowledge that it has received the message(s). The acknowledgement(s) are sent back to the client either individually and for each message, or in a single acknowledgement for a series of messages. Once the client has received the acknowledgement, it knows that the message(s) has been successfully transferred.
25
WsFederationHttpBinding : A secure and interoperable binding that supports federated security. Federation is the ability to share identities across multiple systems for authentication and authorization. These identities can refer to users or to machines. Federated HTTP supports SOAP security as well as mixed-mode security, but it does not support exclusively using transport security. This binding provides Windows Communication Foundation (WCF) support for the WS Federation protocol. Services configured with this binding must use the HTTP transport.
NetTcpBinding : It is a secure, reliable binding suitable for cross-machine communication calls. It is generally suitable for intranet applications. The NetTcpBinding by default, uses transport security, TCP for message delivery, and a binary message encoding. The default configuration for the NetTcpBinding is faster than the configuration provided by the WSHttpBinding, but it is intended only for WCF-to-WCF communication. The security behavior is configurable using the optional securityMode parameter in the constructor. The use of WS-ReliableMessaging is configurable using the optional reliableSessionEnabled parameter. But reliable messaging is off by default. More generally, the HTTP system-provided bindings such as WSHttpBinding and BasicHttpBinding are configured to turn things on by default, whereas the NetTcpBinding binding turns things off by default so that you have to opt-in to get support, for example, for one of the WS-* specifications. This means that the default configuration for TCP is faster at exchanging messages between endpoints than that configured for the HTTP bindings by default. TCP binding is faster than http bindings. NetNamedPipeBinding :The NetNamedPipeBinding by default, uses transport security, named pipes for message delivery, and a binary message encoding. This binding is an appropriate Windows Communication Foundation (WCF) system-provided choice for on-machine communication. It also supports transactions. NetMsmqBinding : Binding for asynchronous communication using Microsoft Message Queue (MSMQ). NetPeerTcpBinding :Provides a secure binding for peer-to-peer network applications.
26
MsmqIntegrationBinding binding that is suitable for cross-machine communication between a WCF application and existing Message Queuing applications.
27
The System.Runtime.Serialization namespace contains classes that can be used for serializing and desterilizing objects. Serialization is the process of converting an object or a graph of objects into a linear sequence of bytes for either storage or transmission to another location. Deserialization is the process of taking in stored information and recreating objects from it. System.ServiceModel.dll It's an assembly which contains the types used to build any sort of WCF applications. It Contains the classes, enumerations, and interfaces necessary to build service and client applications that can be used to build widely distributed applications.
28
System.ServiceModel 窶的t is a primary SCF namespace that contains the classes, enumerations, and interfaces necessary to build WCF service and client applications to build SOA based applications. Few examples of classes are : ServiceHost: An object of ServiceHost is used to load a service, configure endpoints, apply security settings, and start listeners to handle incoming requests. FaultException<(Of <(TDetail>)>) Used in a client application to catch contractually-specified SOAP faults. BasicHttpBidning: a class that represents a binding that exposes a WCF service as legacy asx based web service. Interface: IMetadataExchange : A std. contract for publishing metadata using Http binding. Enumeration:InstanceContextMode Specifies the number of service instances available for handling calls that are contained in incoming messages. System.servicemodel.Configuration Defines numerous types that provide programmatic access to WCF configuration files. Example : BaseAddressElement: Represents a configuration element that specifies the base addresses used by the service host. This class cannot be inherited. MetadataElement Class: Represents a configuration element that specifies how service metadata can be processed. System.servicemodel.Description: Defines types that provide an object model to the addresses, bindings and contracts defined within WCF configuration files . Example:ServiceDebugBehavior Class: Enables debugging and help information features for a Windows Communication Foundation (WCF) service.
29
30
Now, let us understand few WCF terms like reliable sessions, reliable messaging, WCF security features and WCF transactions before we understand WCF binding features What is reliable messaging? Reliable messaging is how a reliable messaging source (called the Sender) transfers messages reliably to a reliable messaging destination (called the Receiver). Reliable messaging has the following key aspects: Transfer assurances for messages sent from a source to a destination regardless of message transfer failure or transport failures. Separation of the source and the destination from each other, which provides independent failure and recovery of the source and the destination as well as reliable transfer and delivery of messages even though the source or destination is unavailable. Reliable messaging frequently comes at the cost of high latency. Latency is the time it takes for the message to reach the destination from the source. WCF, therefore, provides the following types of reliable messaging: What are reliable sessions? The reliable session WCF provides ensures that messages sent between endpoints are transferred across SOAP or transport intermediaries and are delivered only once and, optionally, in the same order in which they were sent. To use a reliable session with a WCF application, either use one of the system-provided bindings in WCF that support a reliable session by default or as an option, or create custom binding that supports the session. WCF reliable sessions is an implementation of SOAP reliable messaging as defined by the WS-ReliableMessaging protocol. WCF SOAP reliable messaging provides an end-to-end reliable session between two endpoints, regardless of the number or type of intermediaries that separate the messaging endpoints. This includes any transport intermediaries that do not use SOAP (for example, HTTP proxies) or intermediaries that use SOAP (for example, SOAP-based routers or bridges) that are required for messages to flow between the endpoints. A reliable session channel supports "interactive" communication so that the services connected by such a channel run concurrently and can exchange and process messages under conditions of low latency, that is, within relatively short intervals of time. This coupling means that these components make progress together or fail together, so there is no isolation provided between them. WCF Security concepts: WCF Security Functional Areas WCF security is divided into three functional areas: transfer security, access control, and auditing. The following sections briefly discuss these areas and provide links for more information. a)Transfer Security Transfer security encompasses three major security functions: integrity, confidentiality, and authentication. Integrity is the ability to detect whether a message has been tampered with. Confidentiality is the ability to keep a message unreadable by anyone other than the intended recipient; this is achieved through cryptography. Authentication is the ability to verify a claimed identity. Together, these three functions help to ensure that messages securely arrive from one point to another. b)Transport and Message Security Modes WCF uses two mode of Transfer Security: i)Transport security mode and ii)Message security mode. Transport security mode It uses a transport-level protocol, such as HTTPS, to achieve transfer security. Transport mode has the advantage of being widely adopted, available on many platforms, and less computationally complex. However, it has the disadvantage of securing messages only from point-to-point. That is, if the message is not secured if it travels between multiple hops in a network. Message security mode WCF uses WS-Security (and other specifications) to implement transfer security. Because the message security is applied directly to the SOAP messages and is contained inside the SOAP envelopes, together with the application data, it has the advantage of being transport protocol-independent, more extensible, and ensuring end-to-end security (versus point-to-point). The only disadvantage is, being several times slower than transport security mode because it has to deal with the XML nature of the SOAP messages. c)Access Control Access control is also known as authorization. Authorization allows different users to have different privileges to view data. d)Auditing Auditing is the logging of security events to the Windows event log. You can log security-related events, such as authentication failures or successes. What are WCF Transactions? Transactions provide a way to group a set of actions or operations into a single indivisible unit of execution that are either a successful commit or rollback. WCF implements support for the WS-AtomicTransaction (WS-AT) protocol that enables WCF applications to flow transactions to interoperable applications, such as interoperable Web services built using third-party technology. In a case where it is not necessary to provide interop functionality to enable transaction flow, OLE Transactions protocol is used. (Note: Details on WS-AtomicTransaction (WS-AT) and OLE Transactions protocol is beyond the scope of this topic) What is Duplex Communication? Duplex messaging is slightly more complex. A duplex channel is really a communication in which with both ends simultaneously acting as both a sender and a receiver (on different channels). A duplex service defines two interfacesâ&#x20AC;&#x201D;one for each side of the wire. WCF Bindings Examples: Example : WsHttpBinding - This binding uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet. The messages are secured by default. One of the biggest differences you must have noticed is the security aspect. By default, BasicHttpBinding sends data in plain text while WsHttpBinding sends it in encrypted and secured manner. Another difference between WsHttpBinding and BasicHttpBinding is that WsHttpBinding supports WS-* specification. WS-* specifications are nothing but standards to extend web service capabilities. NetTcpBinding The NetTcpBinding uses transport security, TCP for message delivery, and a binary message encoding. This binding is an appropriate Windows Communication Foundation system-provided choice for communicating over an Intranet. (Note details on implementing WCF Security, Transactions, WCF reliable Sessions and implementing WS-Addressing is beyond the scope of this session.)
31
Example I: The configuration example on the presentation shows how to configure an endpoint that uses BasicHttpBinding. The endpoint configured above exposes service contract ISimpleContract using BasicHttpBinding at the address http://localhost:7777/SimpleHelloServices .
Example II: The configuration example on the presentation shows how to configure an endpoint that uses NetTcpBinding. The endpoint configured above exposes service contract ISimpleContract using NetTcpBinding at the address net.tcp://localhost:9595/SimpleHelloMessageService.
32
Metadata endpoints : WCF service exposes metadata using special endpoints for metadata publishing called as metadata endpoints or MEX endpoints. By default service metadata is turned off. Exposing Metadata To expose metadata the <serviceMetaData> property in the service behavior needs to be set. This can be done declaratively through the XML .config files. It can be done in 2 steps: 1) configure MEX endpoint 2) Configure <serviceMetadata> under <serviceBehaviors> of behaviors in the .config file.
33
The configuration settings requires to host a WCF Service using Configuration file: The configuration includes the Service name that is a namespace qualified name -SimpleService.SimpleServices and the service behavior also has been configured with the name- SimpleServiceBehavior. The service is available at the base address- http://localhost:7777/SimpleServices. This is the address at which the service is available and keeps listening for incoming requests. The service exposes three endpoints : 1) Exposes BasicHttpBinding 2) WsHttpBinding 3) MEXHttpBinding The service also includes a <serviceBehaviors> under <behaviors> where the <serviceMetadata/> is configured as an empty tag. <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="SimpleService.SimpleServices" behaviorConfiguration ="SimpleServiceBehavior"> <host> <baseAddresses> <add baseAddress ="http://localhost:7777/SimpleServices"/> </baseAddresses> </host> <endpoint name ="HTTPEndpoint" address="BasicService" binding ="basicHttpBinding" contract ="SimpleService.ISimpleContract"/> <endpoint name="wsHTTPEndPoint" address="SecureService" binding ="wsHttpBinding" contract="SimpleService.ISimpleContract"/> <!--Mex Endpoint--> <endpoint name="HTTPMex" address="http://localhost:7777/SimpleMexService" binding ="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name ="SimpleServiceBehavior"> <!--If mex is set then servicemetadata is a empty tag--> <serviceMetadata/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
34
35
Hosting WCF Services WCF Service are not self executable. They execute from within the host process that is responsible for managing life and context of the service. To become active, a service must be hosted within a run-time environment that creates it and controls its context and lifetime. Windows Communication Foundation (WCF) services are designed to run in any Windows process that supports managed code. Service Host hosts the service and controls its context and lifetime. WCF Hosting Options These hosting options range from running inside a console application to server environments such as a Windows service running within a worker process managed by Internet Information Services (IIS) or by Windows Process Activation Service (WAS). Developers choose the hosting environment that satisfies the service's deployment requirements. These requirements might derive from the platform on which the application is deployed, the transport on which it must send and receive messages, or on the type of process recycling and other process management required to ensure adequate availability, or on some other management or reliability requirements. The next section provides information and guidance on hosting options.
36
A .NET application requires a hosting Windows process. An application domain from isolation boundary for managed code. The CLR automatically creates one default application domain in each process where it is initialized. The default application domain is not unloaded until the process in which it runs shuts down. Every process has at least one application domain, and each application domain can host zero or more WCF ServiceHost instances. WCF requires at least an application domain hosted inside a Windows process.
37
Self-Hosting WCF Service : WCF services can be hosted in any managed application. This option enables two common scenarios: WCF services running inside console applications and rich client applications such as those based on Windows Presentation Foundation (WPF) or Windows Forms (WinForms). Hosting in any managed application requires the least infrastructure to deploy. The code for the service is placed inside the managed application code. The service is made available by creating and opening the service instance. Hosting a WCF service inside a console application is typically useful during the application's development phase. This makes them easy to debug, easy to get trace information from to find out what is happening inside of the application, and easy to move around by copying them to new locations. A WCF service also can be hosted in Winforms or WPF forms. A WCF Service can be hosted in any managed EXE like Winforms or WPF forms. When hosted inside any managed .exe , WCF allows services to be run as executables (.EXE files). When hosted in windows service it runs as a Windows NT Service that can be made available to clients over TCP/IP only. Windows NT Services : This hosting option hosts a WCF service as a managed Windows Service (formerly known as NT service). The process lifetime of the service is controlled by the service control manager (SCM) for Windows services. The service is implemented as both a Windows Service and as a WCF service by causing it to inherit from the ServiceBase class as well as from an WCF service contract interface. The ServiceHost is then created and opened within an overridden OnStart method and closed within an overridden OnStop method. Advantage : The lifetime of the service is controlled instead by the operating system. This hosting option allows creating a long-running WCF service all versions of Windows. WCF Service can also be hosted in IIS version 5.0, 6.0 . This model is similar to ASP. Net web services. WCF services hosted in IIS are deployed and managed like any other type of IIS application, including ASP.NET applications and ASMX. Advantages : IIS provides Message based activation –no hosting code required process activation, health management, and recycling capabilities to increase the reliability of hosted applications. Like ASP.NET, WCF services hosted in ASP.NET can take advantage of the ASP.NET shared hosting model where multiple applications reside in a common worker process for improved server density and scalability. IIS hosting is limited to HTTP protocol only. WAS –Windows Activation Service mechanism available with Windows Vista or windows server 2008. The Windows Activation Service (WAS) is a WAS is part of IIS7, but can be installed and configured separately. It is a generalization of Internet Information Services (IIS) features that work with non-HTTP transport protocols. The main difference between IIS and WAS is that the WAS is not limited to HTTP and can be used with any of the available WCF transports, ports, and queues. A WCF service hosted in WAS works similarly to an ASMX Service. For the HTTP protocol, it relies on the ASP.NET HTTP pipeline to transfer data. For non-HTTP protocols such as TCP and Named Pipes, WCF uses the listener adapter interface to communicate activation requests that are received over the non-HTTP protocols supported by WCF. The advantages of WAS are : •IIS is not required. •Process recycling. •Idle shutdown. •Process health monitoring. •Message-based activation. •Works with HTTP, TCP, named pipes, and MSMQ. •It does not require any hosting code as part of the application.
38
In the above code snippet , the instance of ServiceHost is created . This instance take the reference of the service type to be instantiated. On the ServiceHost instance , the Open( ) is called to keep the service in listening mode to accept incoming requests.
39
40
41
42
43
44
45
46