WCF

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

WCF Windows Communication Foundation 1]. What is WCF?

? Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types. WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it. A WCF Service is composed of three parts a Service class that implements the service to be provided, a host environment to host the service, and one or more endpoints to which clients will connect. All communications with the WCF service will happen via the endpoints. The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods. The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. WCF provides Windows Activation Services which can be used to host the WCF service. Otherwise the WCF service can also be hosted in IIS or in any process by using the ServiceHost class, which is provided by WCF. Services can also be self-hosted, in a console-based application or a Windows-forms application for example.

Defining WCF services In programming code, a WCF Service is implemented as a class. The class typically implements a Service Contract - a specially annotated interface whose methods stipulate the operations that the service performs. Typically, the methods on the interface accept inputs and output messages, which conform to Data Contracts, described with specially annotated classes. Think of these as Data Transfer Objects. The Data and Service Contracts are defined using annotations in programming code, known formally in .NET as Attributes. Any class that is to be exposed as a WCF service must be either marked with the ServiceContract attribute, or implement an interface marked with it. All methods in the class or interface that a client can invoke using SOAP messages must be marked with OperationContract attribute. All classes or structures that define the data to be passed into or out of the operations are marked with the DataContract attribute. The attributes support the automatic generation of WSDL descriptions for the exposed methods, which can then be accessed by clients, or advertised to them. A service can expose multiple Service Contracts. This can be done by defining multiple .NET interfaces, each marked as a Service Contract. The service class can then implement all the interfaces. The ServiceContract and OperationContract attributes also allow an interface to reference a previously existing contract, thus providing an option for supporting interface versioning. All Service Contracts have an associated implicit or explicit Data Contract which defines the data that the service works on. If the parameters accepted and returned by the service methods consist of primitive types (integer, double, boolean, etc), then the Data Contract is defined implicitly by WCF. If, on the other hand, the data is of a complex type like an object or a struct, then it must be defined explicitly by the programmer via attributes. Data contracts specify how the data is serialized and deserialized, allowing for custom representation of objects passing in and out. A Data contract is defined by using a DataContract attribute on a class or structure. Members of the data structure which will be used by the service need to be marked with the DataMember attribute. Only those members will be transferred between the service and its client. In the same way that different classes can implement the same interface, different classes can implement the same Data Contract, and can serialize and de-serialize the same data. Taking the idea further, a .NET class defined in C# or VB can implement a Data Contract, and serialize to a data packet, that can then be de-serialized by a Java class or a PHP class.

The behavior of the Service in general and the operations in particular can be controlled using the ServiceBehavior and the OperationBehavior attributes respectively. The ServiceBehavior attribute has different properties. The ConcurrencyMode property specifies whether the service will be concurrent, i.e., whether it will support simultaneous clients or not. Similarly, the InstanceMode property specifies whether a single instance of the service will serve all requests or a new instance of the service will be created for each request, or a new instance of the service will be created for each session.

Defining Endpoints A WCF client connects to a WCF service via an endpoint. Each Service exposes its Contract via one or more endpoints. An endpoint has an address, which is a URL specifying where the endpoint can be accessed, and binding properties that specify how the data will be transferred. The mnemonic "ABC" can be used to remember Address / Binding / Contract. Binding specifies what communication protocols are used to access the service, whether security mechanisms are to be used, and the like. WCF includes predefined bindings for most common communication protocols such as SOAP over HTTP, SOAP over TCP, and SOAP over Message Queues etc. When a client wants to access the service via an endpoint, it not only needs to know the Contract, but it also has to adhere to the binding specified by the endpoint. Thus, both client and server must have compatible endpoints. Communication with the service A client can communicate with a WCF service using any of the RPC-based mechanisms in which the service can be invoked as a method call. Using synchronous communications, any call to the service will be blocking - that is, it will halt the execution of the client until the service processes the request. The client has to connect to a service using a proxy object, which is connected to the specified endpoint of the service and abstracts the service as an object. All method calls to the proxy object will be routed to the service and the proxy will return the results returned by the service to the caller. Tools shipped with the .NET Framework SDK can consume WSDL and create client-side proxy classes for use with WCF. Such classes handle the serialization and data transmission to and from the service, as well as faults and exceptions. WCF also supports non-blocking (asynchronous) calls between client and service, via several mechanisms. One option is to use Message Queues as the transport for the delivery and receipt of the messages. (Keep in mind that the use of Message Queues does not imply a change to a Put/Get style programming model. Even with the use of persistent queues, the programming model still uses friendly proxy classes.) A second mechanism for supporting asynchronous communications is via multiple threads - there is a simple mechanism to do this in the generated client-side proxies for WCF. (see Calling WCF Services asynchronously) In addition to the higher-level programming model supported by the tool-generated proxy classes, WCF exposes a lower-level programming model where applications manually construct and pass messages to services. Communicating using messages does not require the use of the proxy object, and provides more control, although lower usability, to the programmer.

REST Support in WCF In the .NET Framework 3.5, WCF added support for REST-style communications. Developers can specify URL Templates on Operation Contracts, to allow methods to be invoked when requests on specific URLs are received. Parameters from the URLs can be automatically extracted and passed to the method. JSON and plain-old-XML data serialization is supported, as well as alternative mechanisms for binary return types (such as JPG).

Adoption

Microsoft partners are supporting WCF. SAP delivers add-ins to the Visual Studio tool that can generate WCF client-side proxies that connect to SAP Enterprise systems. IBM is producing a WCF Channel for MQ. Microsoft has also delivered The WCF Line of Business Adapter SDK to enable developers to create WCF-based communication connectivity to virtually any external system. The WCF LOB Adapter SDK is what enables JNBridge, for example, to build the JMS Adapter for .NET.

2].What is endpoint in WCF? Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding. 3].What is binding and how many types of bindings are there in WCF? A binding defines how an endpoint communicates to the world. 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. WCF supports nine types of bindings. Basic 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. When used by the client, this binding enables new WCF clients to work with old ASMX services. TCP binding Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF. Peer network binding Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it. IPC binding Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding. Web Service (WS) binding Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet. Federated WS binding Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security. Duplex WS binding Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client. MSMQ binding

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls. MSMQ integration binding Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients. For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx 4].Where we can host WCF services? Every WCF services must be hosted somewhere. There are three ways of hosting WCF services. They are 1. IIS 2. Self Hosting 3. WAS (Windows Activation Service) For more details see http://msdn.microsoft.com/en-us/library/bb332338.aspx 5].What is contracts in WCF? In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does. WCF defines four types of contracts. Service contracts Describe which operations the client can perform on the service. Data contracts Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types. Fault contracts Define which errors are raised by the service, and how the service handles and propagates errors to its clients. Message contracts Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with. 6].What is address in WCF and how many types of transport schemas are there in WCF? Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas. WCF supports following transport schemas HTTP TCP Peer network IPC (Inter-Process Communication over named pipes) MSMQ The sample address for above transport schema may look like http://localhost:81 http://localhost:81/MyService net.tcp://localhost:82/MyService

net.pipe://localhost/MyPipeService net.msmq://localhost/private/MyMsMqService net.msmq://localhost/MyMsMqService 7].What is service and client in perspective of data communication? A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service. What is the difference WCF and Web services? WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by MS. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory this reduces the amount of new code needed when porting or changing business needs, targets, etc. ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of MS; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities. WCF gives you all the advantages of web services but adds a whole lot more. It allows you to replace XML serialization with a more performant binary/other serialization technique, control exactly what gets serialized and how (using things like surrogates). So I think it's unlikely you'll run into an unsolvable performance issue in WCF. The only real disadvantages of choosing WCF over web services are that: 1. WCF doesn't have any notion of sessions (well it does but they're not what you would think of as sessions if you're coming from an ASP.NET background) so if you want to maintain context information about the clients on your server you'll have to build your own framework for doing that. 2. A WCF middle tier will have to run on a machine that supports .NET 3.0 (which means Windows XP SP2, Windows 2003 Server or Windows Vista). Depending on how you architect the application (and how you're serializing your data), this may also be a requirement for the clients that use the functionality of your WCF middle tier as well. Also note that none of the solutions proposed above by Luke will address how you should be moving data across the boundary between your middle tier and your client apps. You might use datasets for that (not that I've heard anyone highly recommending that) or that might be some other custom set of objects/classes (maybe an ORM/OPF framework - something like nHibernate). Some other options for the middle tier architecture are things like Genuine Channels (add on for Remoting that adds a bunch of neat features) and RemObjects (which is an alternative to remoting/web services which is somewhat restricted in terms of the types it allows you to transport but does come with a solution for handling data out of the box - namely DataAbstract... which is something none of the other frameworks really have). What is a service contract, operation contract, Data Contract, duplex contracts? Duplex Services A duplex service contract is a message exchange pattern in which both endpoints can send messages to the other independently. A duplex service, therefore, can send messages back to the client endpoint, providing event-like behavior.

Duplex communication occurs when a client connects to a service and provides the service with a channel on which the service can send messages back to the client. Note that the event-like behavior of duplex services only works within a session. To create a duplex contract you create a pair of interfaces. The first is the service contract interface that describes the operations that a client can invoke. That service contract must specify a callback contract in the System.ServiceModel.ServiceContractAttribute.CallbackContract property. The callback contract is the interface that defines the operations that the service can call on the client endpoint. A duplex contract does not require a session, although the system-provided duplex bindings make use of them. The following is an example of a duplex contract. C# [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", SessionMode=SessionMode.Required, CallbackContract=typeof(ICalculatorDuplexCallback))] public interface ICalculatorDuplex { [OperationContract(IsOneWay = true)] void Clear(); [OperationContract(IsOneWay = true)] void AddTo(double n); [OperationContract(IsOneWay = true)] void SubtractFrom(double n); [OperationContract(IsOneWay = true)] void MultiplyBy(double n); [OperationContract(IsOneWay = true)] void DivideBy(double n); }

public interface ICalculatorDuplexCallback { [OperationContract(IsOneWay = true)] void Equals(double result); [OperationContract(IsOneWay = true)] void Equation(string eqn); } The CalculatorService class implements the primary ICalculatorDuplex interface. The service uses the PerSession instance mode to maintain the result for each session. A private property named Callback accesses the callback channel to the client. The service uses the callback for sending messages back to the client through the callback interface, as shown in the following sample code. C# [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] public class CalculatorService : ICalculatorDuplex { double result = 0.0D; string equation; public CalculatorService() {

equation = result.ToString(); } public void Clear() { Callback.Equation(equation + " = " + result.ToString()); equation = result.ToString(); } public void AddTo(double n) { result += n; equation += " + " + n.ToString(); Callback.Equals(result); } public void SubtractFrom(double n) { result -= n; equation += " - " + n.ToString(); Callback.Equals(result); } public void MultiplyBy(double n) { result *= n; equation += " * " + n.ToString(); Callback.Equals(result); } public void DivideBy(double n) { result /= n; equation += " / " + n.ToString(); Callback.Equals(result); } ICalculatorDuplexCallback Callback { get { return OperationContext.Current.GetCallbackChannel<ICalculatorDuplexCallback>(); } } } The client must provide a class that implements the callback interface of the duplex contract, for receiving messages from the service. The following sample code shows a CallbackHandler class that implements the ICalculatorDuplexCallback interface. C# public class CallbackHandler : ICalculatorDuplexCallback

{ public void Equals(double result) { Console.WriteLine("Equals({0})", result); } public void Equation(string eqn) { Console.WriteLine("Equation({0})", eqn); } } The WCF client that is generated for a duplex contract requires a InstanceContext class to be provided upon construction. This InstanceContext class is used as the site for an object that implements the callback interface and handles messages that are sent back from the service. An InstanceContext class is constructed with an instance of the CallbackHandler class. This object handles messages sent from the service to the client on the callback interface. C# // Construct InstanceContext to handle messages on callback interface InstanceContext instanceContext = new InstanceContext(new CallbackHandler()); // Create a client CalculatorDuplexClient client = new CalculatorDuplexClient(instanceContext); The configuration for the service must be set up to provide a binding that supports both session communication and duplex communication. The wsDualHttpBinding element supports session communication and allows duplex communication by providing dual HTTP connections, one for each direction. On the client, you must configure an address that the server can use to connect to the client, as shown in the following sample configuration. Note: Non-duplex clients that fail to authenticate using a secure conversation typically throw a MessageSecurityException. However, if a duplex client that uses a secure conversation fails to authenticate, the client receives a TimeoutException instead.

If you create a client/service using the WSHttpBinding element and you do not include the client callback endpoint, you will receive the following error.

HTTP could not register URL htp://+:80/Temporary_Listen_Addresses/<guid> because TCP port 80 is being used by another application.The following sample code shows how to specify the client endpoint address in code.

WSDualHttpBinding binding = new WSDualHttpBinding(); EndpointAddress endptadr = new EndpointAddress("http://localhost:12000/DuplexTestUsingCode/Server"); binding.ClientBaseAddress = new Uri("http://localhost:8000/DuplexTestUsingCode/Client/");The following sample code shows how to specify the client endpoint address in configuration.

<client> <endpoint name ="ServerEndpoint" address="http://localhost:12000/DuplexTestUsingConfig/Server" bindingConfiguration="WSDualHttpBinding_IDuplexTest" binding="wsDualHttpBinding" contract="IDuplexTest" /> </client> <bindings> <wsDualHttpBinding> <binding name="WSDualHttpBinding_IDuplexTest" clientBaseAddress="http://localhost:8000/myClient/" > <security mode="None"/> </binding> </wsDualHttpBinding> </bindings> What are the main components of WCF? 1. Service class. 2. Hosting environment 3. End point Which specifications does WCF follow? WCF supports specifications defined by WS-* specifications. WS-* specifications are defined together by Microsoft, IBM, SUN and many other big companies so that they can expose there service through a common protocol. WCF supports all specifications defined we will understand them one by one. Messaging (WS-Addressing):- SOAP is the fundamental protocol for web services. WS-Addressing defines some extra additions to SOAP headers which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML optimized packaging (XOP). Because the data will sent in binary and optimized format it will give us huge performance gain. Security (WS-Security, WS-Trust and WS-SecureConversation):- All the three WS- define authentication, security, data integrity and privacy features for a service. Reliability (WS-ReliableMessaging):- This specification ensures end-to-end communication when we want SOAP messages to be traversed to and fro many times. Transactions (WS-Coordination and WS-AtomicTransaction):- These two specifications enables transaction with SOAP messages. Metadata (WS-Policy and WS-Metadataexchange):- WSDL is a implementation of WS-MetadataExchange protocol. WS-Policy defines more dynamic features of a service which can not be expressed by WSDL. We have stressed on the WS-* specification as its a specification which a service has to follow to be compatible with other languages. Because WCF follows WS-* specifications other languages like JAVA , C++ can also exploit features like Messaging , Security , Reliability and transactions written in C# or VB.NET. This is the biggest achievement of WCF to integrate the above features with other languages. Note: - During interview the interviewer expects that you know what WS* specification are supported by WCF and its advantages with respect to interacting with other languages. What are the important principles of SOA (Service oriented Architecture)? Which are the various programming approaches for WCF? Programming Model In WCF programming we frequently deal with some concepts such as Service Contract, Data Contract, Message Contract and Service Operation on the service side. Each of these concepts has a corresponding concept in object oriented programming and we will use them to implement our WCF concepts. Usually we use an Object Oriented concept and mark it with an attribute to build our WCF concept.

These are some examples: Service Contract, Data Contract and Message Contract are implemented as interface. For Service Contract we use ServiceContract, for Data Contract we use DataContract and for Message Contract we use MessageContract attributes. In previous articles I mentioned that there are three approaches in WCF programming: Declarative Imperative Configuration Based

And also I mentioned that normally we use a combination of these three approaches to build our WCF applications. The declarative part of WCF programming is where we mark our classes, methods and interfaces with attributes to build WCF concepts. Imperative part is where we write programming code logic for our applications and Configuration is where we configure our applications, define service endpoints, behaviors, etc. We have three levels of programming in WCF (from top to down): Typed Services: We write services like our Object Oriented applications and use methods and functions to get parameters and return results in simple and complex data types. Untyped Services: We write services to use messages as parameters and returns types rather than simple or complex types. Messaging-Layer: In this level we come down to the lowest level and directly work with messages. Here you need to code for many details of your application. One common example of this level is writing intermediaries.

What is one way operation? How can we host a service on two different protocols on a single server? How can we use MSMQ bindings in WCF? Can you explain transactions in WCF? What different transaction isolation levels provided in WCF? Can we do transactions using MSMQ? Can we have two way communications in MSMQ? What are Volatile queues? What are Dead letter queues? What is a poison message? 8].How to define a service as REST based service in WCF? WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding. The below code shows how to expose a RESTful service [ServiceContract] interface IStock { [OperationContract] [WebGet] int GetStock(string StockId);

} By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.

WPF Windows Presentation Foundation What is WPF? What is XAML? Are XAML file compiled or built on runtime? What are dependency properties? Can you explain how we can separate code and XAML? How can we access XAML objects in behind code? What are the kind of documents are supported in WPF? WWF - Windows Workflow Foundation(Vista series) What is Windows Workflow Foundation? What is a Workflow?. What are different types of Workflow in Windows Workflow foundation? When should we use a sequential workflow and when should we use state machiHow do we create workflows using designer? How do we specify conditions in Work flow? How do you handle exceptions in workflow? What is the use of XOML files? How can we pass parameters to workflow? AJAX Asychronous Javascript and XML What problem does Ajax solve? What is Ajax? What is the basic fundamental behind Ajax? What is JSON? How do we use XMLHttpRequest object in JavaScript? How do we do asynchronous processing using Ajax? What are the various states in XMLHttpRequest and how do we check the same? How can we get response text? How can we create XMLHttpRequest component? How can we create a class in JavaScript using Atlas? How do we do inheritance using Atlas? How do we define interfaces using Atlas? How do we reference HTML controls using Atlas? Can you explain server controls in Atlas? Can you explain ScriptManager control? What is the importance of UpdatePanel Control? Can you explain update progress control? Can you explain control extenders?

Comparing ASP.NET Web Services to WCF Based on Development

Windows Communication Foundation (WCF) has an ASP.NET compatibility mode option to enable WCF applications to be programmed and configured like ASP.NET Web services, and mimic their behavior. The following sections compare ASP.NET Web services and WCF based on what is required to develop applications using both technologies. Data Representation The development of a Web service with ASP.NET typically begins with defining any complex data types the service is to use. ASP.NET relies on the XmlSerializer to translate data represented by .NET Framework types to XML for transmission to or from a service and to translate data received as XML into .NET Framework objects. Defining the complex data types that an ASP.NET service is to use requires the definition of .NET Framework classes that the XmlSerializer can serialize to and from XML. Such classes can be written manually, or generated from definitions of the types in XML Schema using the command-line XML Schemas/Data Types Support Utility, xsd.exe. The following is a list of key issues to know when defining .NET Framework classes that the XmlSerializer can serialize to and from XML: Only the public fields and properties of .NET Framework objects are translated into XML. Instances of collection classes can be serialized into XML only if the classes implement either the IEnumerable or ICollection interface. Classes that implement the IDictionary interface, such as Hashtable, cannot be serialized into XML. The great many attribute types in the System.Xml.Serialization namespace can be added to a .NET Framework class and its members to control how instances of the class are represented in XML. WCF application development usually also begins with the definition of complex types. WCF can be made to use the same .NET Framework types as ASP.NET Web services. The WCF DataContractAttribute and DataMemberAttribute can be added to .NET Framework types to indicate that instances of the type are to be serialized into XML, and which particular fields or properties of the type are to be serialized, as shown in the following sample code.

//Example One: [DataContract] public class LineItem { [DataMember] public string ItemNumber; [DataMember] public decimal Quantity; [DataMember] public decimal UnitPrice; } //Example Two: public class LineItem { [DataMember] private string itemNumber; [DataMember]

private decimal quantity; [DataMember] private decimal unitPrice; public string ItemNumber { get { return this.itemNumber; } set { this.itemNumber = value; } } public decimal Quantity { get { return this.quantity; } set { this.quantity = value; } } public decimal UnitPrice { get { return this.unitPrice; } set { this.unitPrice = value; } } } //Example Three: public class LineItem { private string itemNumber; private decimal quantity; private decimal unitPrice;

[DataMember] public string ItemNumber { get { return this.itemNumber; } set { this.itemNumber = value; } } [DataMember] public decimal Quantity { get { return this.quantity; } set { this.quantity = value; } } [DataMember] public decimal UnitPrice { get { return this.unitPrice; } set { this.unitPrice = value; } } } The DataContractAttribute signifies that zero or more of a types fields or properties are to be serialized, while the DataMemberAttribute indicates that a particular field or property is to be serialized. The DataContractAttribute can be applied to a class or structure. The DataMemberAttribute can be applied to a field or a property, and the fields and properties to which the attribute is applied can be either public or private. Instances of types that have the DataContractAttribute applied to them are referred to as data contracts in WCF. They are serialized into XML using DataContractSerializer. The following is a list of the important differences between using the DataContractSerializer and using the XmlSerializer and the various attributes of the System.Xml.Serialization namespace.

The XmlSerializer and the attributes of the System.Xml.Serialization namespace are designed to allow you to map .NET Framework types to any valid type defined in XML Schema, and so they provide for very precise control over how a type is represented in XML. The DataContractSerializer, DataContractAttribute and DataMemberAttribute provide very little control over how a type is represented in XML. You can only specify the namespaces and names used to represent the type and its fields or properties in the XML, and the sequence in which the fields and properties appear in the XML:

[DataContract( Namespace="urn:Contoso:2006:January:29", Name="LineItem")] public class LineItem { [DataMember(Name="ItemNumber",IsRequired=true,Order=0)] public string itemNumber; [DataMember(Name="Quantity",IsRequired=false,Order = 1)] public decimal quantity; [DataMember(Name="Price",IsRequired=false,Order = 2)] public decimal unitPrice; }Everything else about the structure of the XML used to represent the .NET type is determined by the DataContractSerializer. By not permitting much control over how a type is to be represented in XML, the serialization process becomes highly predictable for the DataContractSerializer, and, thereby, easier to optimize. A practical benefit of the design of the DataContractSerializer is better performance, approximately ten percent better performance. The attributes for use with the XmlSerializer do not indicate which fields or properties of the type are serialized into XML, whereas the DataMemberAttribute for use with the DataContractSerializer shows explicitly which fields or properties are serialized. Therefore, data contracts are explicit contracts about the structure of the data that an application is to send and receive. The XmlSerializer can only translate the public members of a .NET object into XML, the DataContractSerializer can translate the members of objects into XML regardless of the access modifiers of those members. As a consequence of being able to serialize the non-public members of types into XML, the DataContractSerializer has fewer restrictions on the variety of .NET types that it can serialize into XML. In particular, it can translate into XML types like Hashtable that implement the IDictionary interface. The DataContractSerializer is much more likely to be able to serialize the instances of any pre-existing .NET type into XML without having to either modify the definition of the type or develop a wrapper for it. Another consequence of the DataContractSerializer being able to access the non-public members of a type is that it requires full trust, whereas the XmlSerializer does not. The Full Trust code access permission give complete access to all resources on a machine that can be access using the credentials under which the code is executing. This options should be used with care as fully trusted code accesses all resources on your machine. The DataContractSerializer incorporates some support for versioning: The DataMemberAttribute has an IsRequired property that can be assigned a value of false for members that are added to new versions of a data contract that were not present in earlier versions, thereby allowing applications with the newer version of the contract to be able to process earlier versions. By having a data contract implement the IExtensibleDataObject interface, one can allow the DataContractSerializer to pass members defined in newer versions of a data contract through applications with earlier versions of the contract.

Despite all of the differences, the XML into which the XmlSerializer serializes a type by default is semantically identical to the XML into which the DataContractSerializer serializes a type, provided the namespace for the XML is explicitly defined. The following class, which has attributes for use with both of the serializers, are translated into semantically identical XML by the XmlSerializer and by the DataContractAttribute:

[Serializable] [XmlRoot(Namespace="urn:Contoso:2006:January:29")] [DataContract(Namespace="urn:Contoso:2006:January:29")] public class LineItem { [DataMember] public string ItemNumber; [DataMember] public decimal Quantity; [DataMember] public decimal UnitPrice; } The Windows software development kit (SDK) includes a command-line tool called the Service Model Metadata Tool (Svcutil.exe).Like the xsd.exe tool used with ASP.NET Web services, Svcutil.exe can generate definitions of .NET data types from XML Schema. The types are data contracts if the DataContractSerializer can emit XML in the format defined by the XML Schema; otherwise, they are intended for serialization using the XmlSerializer. The tool, Svcutil.exe, can also be made to generate XML Schema from data contracts using its /dataContractOnly switch. Note: Although ASP.NET Web services use the XmlSerializer, and WCF ASP.NET compatibility mode makes WCF services mimic the behavior of ASP.NET Web services, the ASP.NET compatibility option does not restrict one to using the XmlSerializer. One can still use the DataContractSerializer with services running in the ASP.NET compatibility mode.

Service Development To develop a service using ASP.NET, it has been customary to add the WebService attribute to a class, and the WebMethodAttribute to any of that class methods that are to be operations of the service:

[WebService] public class Service : T:System.Web.Services.WebService { [WebMethod] public string Echo(string input) { return input; } }ASP.NET 2.0 introduced the option of adding the attribute WebService and WebMethodAttribute to an interface rather than to a class, and writing a class to implement the interface:

[WebService] public interface IEcho {

[WebMethod] string Echo(string input); } public class Service : IEcho { public string Echo(string input) { return input; } }Using this option is to be preferred, because the interface with the WebService attribute constitutes a contract for the operations performed by the service that can be reused with various classes that might implement that same contract in different ways. A WCF service is provided by defining one or more WCF endpoints. An endpoint is defined by an address, a binding and a service contract. The address defines where the service is located. The binding specifies how to communicate with the service. The service contract defines the operations that the service can perform. The service contract is usually defined first, by adding ServiceContractAttribute and OperationContractAttribute to an interface:

[ServiceContract] public interface IEcho { [OperationContract] string Echo(string input); }The ServiceContractAttribute specifies that the interface defines a WCF service contract, and the OperationContractAttribute indicates which, if any, of the methods of the interface define operations of the service contract. Once a service contract has been defined, it is implemented in a class, by having the class implement the interface by which the service contract is defined:

public class Service : IEcho { public string Echo(string input) { return input; } }A class that implements a service contract is referred to as a service type in WCF. The next step is to associate an address and a binding with a service type. That is typically done in a configuration file, either by editing the file directly, or by using a configuration editor provided with WCF. Here is an example of a configuration file.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="Service ">

<endpoint address="EchoService" binding="basicHttpBinding" contract="IEchoService "/> </service> </services> </system.serviceModel> </configuration> The binding specifies the set of protocols for communicating with the application. The following table lists the system-provided bindings that represent common options. Name Purpose BasicHttpBinding Interoperability with Web services and clients supporting the WS-BasicProfile 1.1 and Basic Security Profile 1.0. WSHttpBinding Interoperability with Web services and clients that support the WS-* protocols over HTTP. WSDualHttpBinding Duplex HTTP communication, by which the receiver of an initial message does not reply directly to the initial sender, but may transmit any number of responses over a period of time by using HTTP in conformity with WS-* protocols. WSFederationBinding HTTP communication, in which access to the resources of a service can be controlled based on credentials issued by an explicitly-identified credential provider. NetTcpBinding Secure, reliable, high-performance communication between WCF software entities across a network. NetNamedPipeBinding Secure, reliable, high-performance communication between WCF software entities on the same machine. NetMsmqBinding Communication between WCF software entities by using MSMQ. MsmqIntegrationBinding Communication between a WCF software entity and another software entity by using MSMQ. NetPeerTcpBinding Communication between WCF software entities by using Windows Peer-to-Peer Networking.

The system-provided binding, BasicHttpBinding, incorporates the set of protocols supported by ASP.NET Web services. Custom bindings for WCF applications are easily defined as collections of the binding element classes that WCF uses to implement individual protocols. New binding elements can be written to represent additional protocols. The internal behavior of service types can be adjusted using the properties of a family of classes called behaviors. Here, the ServiceBehaviorAttribute class is used to specify that the service type is to be multithreaded.

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple] public class DerivativesCalculatorServiceType: IDerivativesCalculator Some behaviors, like ServiceBehaviorAttribute, are attributes. Others, the ones with properties that administrators would want to set, can be modified in the configuration of an application. In programming service types, frequent use is made of the OperationContext class. Its static Current property provides access to information about the context in which an operation is running. OperationContext is similar to both the HttpContext and ContextUtil classes. Hosting ASP.NET Web services are compiled into a class library assembly. A file called the service file is provided that has the extension .asmx and contains an @ WebService directive that identifies the class that contains the code for the service and the assembly in which it is located.

<%@ WebService Language="C#" Class="Service,ServiceAssembly" %>The service file is copied into an ASP.NET application root in Internet Information Services (IIS), and the assembly is copied into the \bin subdirectory of that application root. The application is then accessible by using the uniform resource locator (URL) of the service file in the application root. WCF services can readily be hosted within IIS 5.1 or 6.0, the Windows Process Activation Service (WAS) that is provided as part of IIS 7.0, and within any .NET application. To host a service in IIS 5.1 or 6.0, the service must use HTTP as the communications transport protocol. To host a service within IIS 5.1, 6.0 or within WAS, use the follows steps: Compile the service type into a class library assembly. Create a service file with a .svc extension with an @ ServiceHost directive to identify the service type:

<%@ServiceHost language=c# Service="MyService" %>Copy the service file into a virtual directory, and the assembly into the \bin subdirectory of that virtual directory. Copy the configuration file into the virtual directory, and name it Web.config. The application is then accessible by using the URL of the service file in the application root. To host a WCF service within a .NET application, compile the service type into a class library assembly referenced by the application, and program the application to host the service using the ServiceHost class. The following is an example of the basic programming required:

string httpBaseAddress = "http://www.contoso.com:8000/"; string tcpBaseAddress = "net.tcp://www.contoso.com:8080/"; Uri httpBaseAddressUri = new Uri(httpBaseAddress); Uri tcpBaseAddressUri = new Uri(tcpBaseAddress); Uri[] baseAdresses = new Uri[] { httpBaseAddressUri, tcpBaseAddressUri};

using(ServiceHost host = new ServiceHost( typeof(Service), //Service is the name of the service type baseAdresses)) { host.Open(); *+ //Wait to receive messages host.Close(); }This example shows how addresses for one or more transport protocols are specified in the construction of a ServiceHost. These addresses are referred to as base addresses. The address provided for any endpoint of a WCF service is an address relative to a base address of the endpoints host. The host can have one base address for each communication transport protocol. The base address of an endpoint is relative to whichever of the base addresses of the host is the base address for the communication transport protocol of the endpoint. In the sample configuration in the preceding configuration file, the BasicHttpBinding selected for the endpoint uses HTTP as the transport protocol, so the address of the endpoint, EchoService, is relative to the hosts HTTP base address. In the case of the host in the preceding example, the HTTP base address is http://www.contoso.com:8000/. For a service hosted within IIS or WAS, the base address is the URL of the services service file. Only services hosted in IIS or WAS, and which are configured with HTTP as the transport protocol exclusively, can be made to use WCF ASP.NET compatibility mode option. Turning that option on requires the following steps. The programmer must add the AspNetCompatibilityRequirementsAttribute attribute to the service type and specify that ASP.NET compatibility mode is either allowed or required.

[System.ServiceModel.Activation.AspNetCompatibilityRequirements( RequirementsMode=AspNetCompatbilityRequirementsMode.Require)] public class DerivativesCalculatorServiceType: IDerivativesCalculatorThe administrator must configure the application to use the ASP.NET compatibility mode.

<configuration> <system.serviceModel> <services> *+ </services> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> </system.serviceModel> </configuration>WCF applications can also be configured to use .asmx as the extension for their service files rather than .svc.

<system.web> <compilation> <compilation debug="true"> <buildProviders> <remove extension=".asmx"/> <add extension=".asmx" type="System.ServiceModel.ServiceBuildProvider, Systemm.ServiceModel, Version=3.0.0.0,

Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </buildProviders> </compilation> </compilation> </system.web>That option can save you from having to modify clients that are configured to use the URLs of .asmx service files when modifying a service to use WCF. Client Development Clients for ASP.NET Web services are generated using the command-line tool, WSDL.exe, which provides the URL of the .asmx file as input. The corresponding tool provided by WCF is Service Model Metadata Tool (Svcutil.exe). It generates a code module with the definition of the service contract and the definition of a WCF client class. It also generates a configuration file with the address and binding of the service. In programming a client of a remote service it is generally advisable to program according to an asynchronous pattern. The code generated by the WSDL.exe tool always provides for both a synchronous and an asynchronous pattern by default. The code generated by the Service Model Metadata Tool (svcutil.exe) can provide for either pattern. It provides for the synchronous pattern by default. If the tool is executed with the /async switch, then the generated code provides for the asynchronous pattern. There is no guarantee that names in the WCF client classes generated by ASP.NETs WSDL.exe tool, by default, match the names in WCF client classes generated by the Svcutil.exe tool. In particular, the names of the properties of classes that have to be serialized using the XmlSerializer are, by default, given the suffix Property in the code generated by the Svcutil.exe tool, which is not the case with the WSDL.exe tool. Message Representation The headers of the SOAP messages sent and received by ASP.NET Web services can be customized. A class is derived from SoapHeader to define the structure of the header, and then the SoapHeaderAttribute is used to indicate the presence of the header.

public class SomeProtocol : SoapHeader { public long CurrentValue; public long Total; } [WebService] public interface IEcho { SomeProtocol ProtocolHeader { get; set; } [WebMethod] [SoapHeader("ProtocolHeader")] string PlaceOrders(PurchaseOrderType order); }

public class Service: WebService, IEcho { private SomeProtocol protocolHeader; public SomeProtocol ProtocolHeader { get { return this.protocolHeader; } set { this.protocolHeader = value; } } string PlaceOrders(PurchaseOrderType order) { long currentValue = this.protocolHeader.CurrentValue; } }The WCF provides the attributes, MessageContractAttribute, MessageHeaderAttribute, and MessageBodyMemberAttribute to describe the structure of the SOAP messages sent and received by a service.

[DataContract] public class SomeProtocol { [DataMember] public long CurrentValue; [DataMember] public long Total; } [DataContract] public class Item { [DataMember] public string ItemNumber; [DataMember] public decimal Quantity; [DataMember] public decimal UnitPrice; } [MessageContract] public class ItemMesage { [MessageHeader] public SomeProtocol ProtocolHeader; [MessageBody]

public Item Content; } [ServiceContract] public interface IItemService { [OperationContract] public void DeliverItem(ItemMessage itemMessage); }This syntax yields an explicit representation of the structure of the messages, whereas the structure of messages is implied by the code of an ASP.NET Web service. Also, in the ASP.NET syntax, message headers are represented as properties of the service, such as the ProtocolHeader property in the previous example, whereas in WCF syntax, they are more accurately represented as properties of messages. Also, WCF allows message headers to be added to the configuration of endpoints.

<service name="Service "> <endpoint address="EchoService" binding="basicHttpBinding" contract="IEchoService "> <headers> <dsig:X509Certificate xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"> ... </dsig:X509Certificate> </headers> </endpoint> </service> That option allows you to avoid any reference to infrastructural protocol headers in the code for a client or service: the headers are added to messages because of how the endpoint is configured. Service Description Issuing an HTTP GET request for the .asmx file of an ASP.NET Web service with the query WSDL causes ASP.NET to generate WSDL to describe the service. It returns that WSDL as the response to the request. ASP.NET 2.0 made it possible to validate that a service is compliant with the Basic Profile 1.1 of the Web ServicesInteroperability Organization (WS-I), and to insert a claim that the service is compliant into its WSDL. That is done using the ConformsTo and EmitConformanceClaims parameters of the WebServiceBindingAttribute attribute.

[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1, EmitConformanceClaims=true)] public interface IEchoThe WSDL that ASP.NET generates for a service can be customized. Customizations are made by creating a derived class of ServiceDescriptionFormatExtension to add items to the WSDL. Issuing an HTTP GET request with the query WSDL for the .svc file of a WCF service with an HTTP endpoint hosted within IIS 51, 6.0 or WAS causes WCF to respond with WSDL to describe the service. Issuing an HTTP GET request with the query WSDL to the HTTP base address of a service hosted within a .NET application has the same effect.

However, WCF also responds to WS-MetadataExchange requests with WSDL that it generates to describe a service. ASP.NET Web services do not have built-in support for WS-MetadataExchange requests. The WSDL that WCF generates can be extensively customized. The ServiceMetadataBehavior class provides some facilities for customizing the WSDL. The WCF can also be configured to not generate WSDL, but rather to use a static WSDL file at a given URL.

<behaviors> <behavior name="DescriptionBehavior"> <metadataPublishing enableMetadataExchange="true" enableGetWsdl="true" enableHelpPage="true" metadataLocation= "http://localhost/DerivativesCalculatorService/Service.WSDL"/> </behavior> </behaviors>Exception Handling In ASP.NET Web services, unhandled exceptions are returned to clients as SOAP faults. You can also explicitly throw instances of the SoapException class and have more control over the content of the SOAP fault that gets transmitted to the client. In WCF services, unhandled exceptions are not returned to clients as SOAP faults to prevent sensitive information being inadvertently exposed through the exceptions. A configuration setting is provided to have unhandled exceptions returned to clients for the purpose of debugging. To return SOAP faults to clients, you can throw instances of the generic type, FaultException, using the data contract type as the generic type. You can also add FaultContractAttribute attributes to operations to specify the faults that an operation might yield.

[DataContract] public class MathFault { [DataMember] public string operation; [DataMember] public string problemType; } [ServiceContract] public interface ICalculator { [OperationContract] [FaultContract(typeof(MathFault))] int Divide(int n1, int n2); }Doing so results in the possible faults being advertised in the WSDL for the service, allowing client programmers to anticipate which faults can result from an operation, and write the appropriate catch statements.

try {

result = client.Divide(value1, value2); } catch (FaultException<MathFault> e) { Console.WriteLine("FaultException<MathFault>: Math fault while doing " + e.Detail.operation + ". Problem: " + e.Detail.problemType); }State Management The class used to implement an ASP.NET Web service may be derived from WebService.

public class Service : WebService, IEcho { public string Echo(string input) { return input; } }In that case, the class can be programmed to use the WebService base class Context property to access a HttpContext object. The HttpContext object can be used to update and retrieve application state information by using its Application property, and can be used to update and retrieve session state information by using its Session property. ASP.NET provides considerable control over where the session state information accessed by using the Session property of the HttpContext is actually stored. It may be stored in cookies, in a database, in the memory of the current server, or in the memory of a designated server. The choice is made in the services configuration file. The WCF provides extensible objects for state management. Extensible objects are objects that implement IExtensibleObject. The most important extensible objects are ServiceHostBase and InstanceContext. ServiceHostBase allows you to maintain state that all of the instances of all of the service types on the same host can access, while InstanceContext allows you to maintain state that can be accessed by any code running within the same instance of a service type. Here, the service type, TradingSystem, has a ServiceBehaviorAttribute that specifies that all calls from the same WCF client instance are routed to the same instance of the service type.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] public class TradingSystem: ITradingServiceThe class, DealData, defines state that can be accessed by any code running in the same instance of a service type.

internal class DealData: IExtension<InstanceContext> { public string DealIdentifier = null; public Trade[] Trades = null; }In the code of the service type that implements one of the operations of the service contract, a DealData state object is added to the state of the current instance of the service type.

string ITradingService.BeginDeal() {

string dealIdentifier = Guid.NewGuid().ToString(); DealData state = new DealData(dealIdentifier); OperationContext.Current.InstanceContext.Extensions.Add(state); return dealIdentifier; }That state object can then be retrieved and modified by the code that implements another of the service contracts operations.

void ITradingService.AddTrade(Trade trade) { DealData dealData = OperationContext.Current.InstanceContext.Extensions.Find<DealData>(); dealData.AddTrade(trade); }Whereas ASP.NET provides control over where state information in the HttpContext class is actually stored, WCF, at least in its initial version, provides no control over where extensible objects are stored. That constitutes the very best reason for selecting the ASP.NET compatibility mode for a WCF service. If configurable state management is imperative, then opting for the ASP.NET compatibility mode allows you to use the facilities of the HttpContext class exactly as they are used in ASP.NET, and also to configure where state information managed by using the HttpContext class is stored. Security The options for securing ASP.NET Web services are those for securing any IIS application. Because WCF applications can be hosted not only within IIS but also within any .NET executable, the options for securing WCF applications must be made independent from the facilities of IIS. However, the facilities provided for ASP.NET Web services are also available for WCF services running in ASP.NET compatibility mode. Security: Authentication IIS provides facilities for controlling access to applications by which you can select either anonymous access or a variety of modes of authentication: Windows Authentication, Digest Authentication, Basic Authentication, and .NET Passport Authentication. The Windows Authentication option can be used to control access to ASP.NET Web services. However, when WCF applications are hosted within IIS, IIS must be configured to permit anonymous access to the application, so that authentication can be managed by WCF itself, which does support Windows authentication among various other options. The other options that are built-in include username tokens, X.509 certificates, SAML tokens, and CardSpace card, but custom authentication mechanisms can also be defined. Security: Impersonation ASP.NET provides an identity element by which an ASP.NET Web service can be made to impersonate a particular user or whichever users credentials are provided with the current request. That element can be used to configure impersonation in WCF applications running in ASP.NET compatibility mode. The WCF configuration system provides its own identity element for designating a particular user to impersonate. Also, WCF clients and services can be independently configured for impersonation. Clients can be configured to impersonate the current user when they transmit requests.

<behaviors> <behavior name="DerivativesCalculatorClientBehavior"> <clientCredentials> <windows allowedImpersonationLevel="Impersonation"/> </clientCredentials> </behavior> </behaviors>Service operations can be configured to impersonate whichever users credentials are provided with the current request.

[OperationBehavior(Impersonation = ImpersonationOption.Required)] public void Receive(Message input)Security: Authorization using Access Control Lists Access Control Lists (ACLs) can be used to restrict access to .asmx files. However, ACLs on WCF .svc files are ignored except in ASP.NET compatibility mode. Security: Role-based Authorization The IIS Windows Authentication option can be used in conjunction with the authorization element provided by the ASP.NET configuration language to facilitate role-based authorization for ASP.NET Web services based on the Windows groups to which users are assigned. ASP.NET 2.0 introduced a more general role-based authorization mechanism: role providers. Role providers are classes that all implement a basic interface for enquiring about the roles to which a user is assigned, but each role provider knows how to retrieve that information from a different source. ASP.NET 2.0 provides a role provider that can retrieve role assignments from a Microsoft SQL Server database, and another that can retrieve role assignments from the Windows Server 2003 Authorization Manager. The role provider mechanism can actually be used independently of ASP.NET in any .NET application, including a WCF application. The following sample configuration for a WCF application shows how the use of an ASP.NET role provider is an option selected by means of the ServiceAuthorizationBehavior.

<system.serviceModel> <services> <service name="Service.ResourceAccessServiceType" behaviorConfiguration="ServiceBehavior"> <endpoint address="ResourceAccessService" binding="wsHttpBinding" contract="Service.IResourceAccessContract"/> </service> </services> <behaviors> <behavior name="ServiceBehavior"> <serviceAuthorization principalPermissionMode="UseAspNetRoles"/> </behavior> </behaviors> </system.serviceModel>Security: Claims-based Authorization One of the most important innovations of WCF is its thorough support for authorizing access to protected resources based on claims. Claims consist of a type, a right and a value, a drivers license, for example. It makes a set of claims about the bearer, one of which is the bearers date of birth. The type of that claim is date of birth, while the value of the claim is the drivers birth date. The right that a claim confers on the bearer specifies what the bearer can do with the claims value. In the case of the claim of the drivers date of birth, the right is possession: the driver possesses that date of birth but cannot, for example, alter it. Claims-based authorization encloses role-based authorization, because roles are a type of claim. Authorization based on claims is accomplished by comparing a set of claims to the access requirements of the operation and, depending on the outcome of that comparison, granting or denying access to the operation. In WCF, you can specify a class to use to run claims-based authorization, once again by assigning a value to the ServiceAuthorizationManager property of ServiceAuthorizationBehavior.

<behaviors> <behavior name='ServiceBehavior'> <serviceAuthorization serviceAuthorizationManagerType= 'Service.AccessChecker, Service' /> </behavior> </behaviors>Classes used to run claims-based authorization must derive from ServiceAuthorizationManager, which has just one method to override, AccessCheck(). WCF calls that method whenever an operation of the service is invoked and provides a OperationContext object, which has the claims for the user in its ServiceSecurityContext.AuthorizationContext property. WCF does the work of assembling claims about the user from whatever security token the user provided for authentication, which leaves the of task of evaluating whether those claims suffice for the operation in question. That WCF automatically assembles claims from any kind of security token is a highly significant innovation, because it makes the code for authorization based on the claims entirely independent of the authentication mechanism. By contrast, authorization using ACLs or roles in ASP.NET is closely tied to Windows authentication. Security: Confidentiality The confidentiality of messages exchanged with ASP.NET Web services can be ensured at the transport level by configuring the application within IIS to use the Secure Hypertext Transfer Protocol (HTTPS). The same can be done for WCF applications hosted within IIS. However, WCF applications hosted outside of IIS can also be configured to use a secure transport protocol. More important, WCF applications can also be configured to secure the messages before they are transported, using the WS-Security protocol. Securing just the body of a message using WS-Security allows it to be transmitted confidentially across intermediaries before reaching its final destination. Globalization The ASP.NET configuration language allows you to specify the culture for individual services. The WCF does not support that configuration setting except in ASP.NET compatibility mode. To localize a WCF service that does not use ASP.NET compatibility mode, compile the service type into culture-specific assemblies, and have separate culture-specific endpoints for each culturespecific assembly.

---10 Principles of SOA--In many customer engagements, I need to establish a basic set of principles of SOA. The following sections introduce fundamental principles that a Service-oriented Architecture (SOA) should expose.These are not introduced as an absolute truth, but rather as a frame of reference for SOA-related discussions. Youll note that the first four are based on Don Boxs four tenets, although over time they may have acquired a slight personal spin. (Im putting them up now because someone asked me for a version that can be referenced; I havent reviewed them again now and may actually have changed my mind with regards to some of them.) 1. Explicit Boundaries Everything needed by the service to provide its functionality should be passed to it when it is invoked. All access to the service should be via its publicly exposed interface; no hidden assumptions must be necessary to invoke the service. Services are inextricably tied to messaging in that the only way into and out of a service are through messages. A service i nvocation should as a general pattern not rely on a shared context; instead service invocations should be modeled as stateless. An interface exposed by a service is governed by a contract that describes its functional and non-functional capabilities and characteristics. The invocation of a service is an action that has a business effect, is possibly expensive in terms of resource consumption, and introduces a category of errors different than those of a local method invocation or remote procedure call. A service invocation is not a remote procedure call.

While consuming and providing services certainly should be as easy as possible, it is therefore undesirable to hide too much of the fact that an interaction with a service takes place. The message sent to or received from the service, the service contract, and the service itself should all be first-class constructs within the SOA. This means, for example, that programming models and tools that are used should at least provide an API that exposes these concepts to the service programmer. In summary, a service exposes its functionality through an explicit interface that encapsulates its internals; interaction with a service is an explicit act, relying on the passing of messages between consumer and provider. 2. Shared Contract and Schema, not Class Starting from a service description (a contract), both a service consumer and a service provider should have everything they need to consume or provide the service. Following the principle of loose coupling, a service provider can not rely on the consumers ability to reuse any code that it provides in its own environment; after all, it might be using a different develo pment or runtime environment. This principle puts severe limits on the type of data that can be exchanged in an SOA. Ideally, the data is exchanged as XML documents validatable against one or more schemas, since these are supported in every programming environment one can imagine. 3. Policy-driven To interact with a service, two orthogonal requirement sets have to be met: the functionality, syntax and semantics of the provider must fit the consumers requirements, the technical capabilities and needs must match. For example, a service provider may offer exactly the service a consumer needs, but offer it over JMS while the consumer can only use HTTP (e.g. because it is implemented on the .NET platform); a provider might require message-level encryption via the XML Encryption standard, while the consumer can only support transport-level security using SSL. Even in those cases where both partners do have the necessary capabilities, they might need to be activated e.g. a provider might encrypt response messages to different consumers using different algorithms, based on their needs. To support access to a service from the largest possible number of differently equipped and capable consumers, a policy mechanism has been introduced as part of the SOA tool set. While the functional aspects are described in the service interface, the orthogonal, non-functional capabilities and needs are specified using policies. 4. Autonomous Related to the explicit boundaries principle (5.4.1.1), a service is autonomous in that its only relation to the outside world at least from the SOA perspective is through its interface. In particular, it must be possible to change a services runtime environment, e.g. from a lightweight prototype implementation to a full-blown, application server-based collection of collaborating components, without any effect on its consumers. Services can be changed and deployed, versioned and managed independently of each other. A service provider can not rely on the ability of its consumers to quickly adapt to a new version of the service; some of them might not even be able, or willing, to adapt to a new version of a service interface at all (especially if they are outside the service providers sphere of control). 5. Wire formats, not Programming Language APIs Services are exposed using a specific wire format that needs to be supported. This principle is strongly related to the explicitness of boundaries principle, but introduces a new perspective: To ensure the utmost accessibility (and therefore, longterm usability), a service must be accessible from any platform that supports the exchange of messages adhering to the service interface as long as the interaction conforms to the policy defined for the service. For example, it is a useful test for conformance to this principle to consider whether it is possible to consume or provide a specific service from a mainstream dynamic programming language such as Perl, Python or Ruby. Even though none of these may currently play any role in the current technology landscape, this consideration can serve as a litmus test to assess whether the following criteria are met: All message formats are described using an open standard, or a human readable description It is possible to create messages adhering to those schemas with reasonable effort without requiring a specific programmers library

The semantics and syntax for additional information necessary for successful communication, such as headers for purposes such as security or reliability, follow a public specification or standard At least one of the transport (or transfer) protocols used to interact with the service is a (or is accessible via a) standard network protocol 6. Document-oriented To interact with services, data is passed as documents. A document is an explicitly modeled, hierarchical container for data. The self-descriptiveness, as outlined in the previous section, is one important aspect of document-orientation. Ideally, a document will be modeled after real-world documents, such as purchase orders, invoices, or account statements. Documents should be designed so that they are useful on the context of a problem domain, which may suggest their use with one or more services. Similarly to a real-world paper document, a document exchanged with a service will include redundant information. For example, a customer ID might be included along with the customers address information (although the customer ID would be enough). This redundancy is explicitly accepted since it serves to isolate the service interface from the underlying data model of both service consumer and service provider. Whena document-oriented pattern is applied, service invocations become meaningful exchanges of business messages instead of context-free RPC calls. While not an absolute required, it can usually be assumed that XML will be used as the document format/syntax. Messages flowing between participants in an SOA connect disparate systems that evolve independently of each other. The loose coupling principle mandates that the dependence on common knowledge ought to be as small as possible. When messages are sent in a Distributed Objects or RPC infrastructure, client and server can rely on a set of proxy classes (stubs and skeletons) generated from the same interface description document. If this is not the case, communication ceases on the assumption that the contract does not support interaction between those two parties. For this reason, RPC-style infrastructures require synchronized evolution of client and server program code. This is illustrated by the following comparison. Consider the following message: 2006-03-1347113 and compare it to: <order> <date>2006-03-13</date> <product-id>4711</product-id> <quantity>3</quantity> </order> While it is obvious that the second alternative is human-readable while the first one is not, it is also notable that in the second case, a participant that accesses the information via a technology such as XPath will be much better isolated against smaller, non-breaking changes than one that relies on the fixed syntax. Conversely, using a self-descriptive message format such as XML while still using RPC patterns, such as stub and skeleton generation, serves only to increase XMLs reputation as the most effective way to waste bandwidth. If one uses XML, the benefits should be exploited, too. (See this paper for an excellent discussion of why many current Web services stacks fail this test.) 7. Loosely coupled Most SOA proponents will agree that loose coupling is an important concept. Unfortunately, there are many different opinions about the characteristics that make a system loosely coupled. There are multiple dimensions in which a system can be loosel y or tightly coupled, and depending on the requirements and context, it may be loosely coupled in some of them and tightly coupled in others. Dimensions include: Time: When participants are loosely coupled in time, they dont have to be up and running at the same time to communicate. This requires some way of buffering/queuing in between them, although the approach taken for this is irrelevant. When one participant sends a message to the other one, it does not rely on an immediate answer message to continue processing (neither logically, nor physically).

Location: If participants query for the address of participants they intend to communicate with, the location can change without having to re-program, reconfigure or even restart the communication partners. This implies some sort of lookup process using a directory or address that stores service endpoint addresses. Type: In an analogy to the concept of static vs. dynamic and weak vs. strong typing in programming languages, a participant can either rely on all or only on parts of a document structure to perform its work. Version: Participants can depend on a specific version of a service interface, or be resilient to change (to a certain degree). The more exact the version match has to be, the less loosely coupled the participants (in this dimension). A good principle to follow is Postels Law: Service providers should be implemented to accept as many different versions as possible, and thus be libera l in what they accept (and possibly even tolerant of errors), while service consumers should do their best to conform to exact grammars and document types. This increases the overall systems stability and flexibility. Cardinality: There may be a 1:1-relationship between service consumers and service providers, especially in cases where a request/response interaction takes place or an explicit message queue is used. In other cases, a service consumer (which in this case is more reasonably called a message sender or event source may neither know nor care about the number of recipients of a message. Lookup: A participant that intends to invoke a service can either rely on a (physical or logical) name of a service provider to communicate with, or it can perform a lookup operation first, using a description of a set of capabilities instead. This implies a registry and/or repository that is able to match the consumers needs to a providers capabilities (either directly or indirectly). Interface: Participants may require adherence to a service-specific interface or they may support a generic interface. If a generic interface is used, all participants consuming this generic interface can interact with all participants providing it. While this may seem awkward at first sight, the principle of a single generic (uniform) interface is at the core of the WWWs architecture. It is not always feasible nor even desirable to create a system that is loosely coupled in all of the dimensions mentioned above. For different types of services, different trade-offs need to be made. 8. Standards-compliant A key principle to be followed in an SOA approach is the reliance on standards instead of proprietary APIs. Standards exists for technical aspects such as data formats, metadata, transport and transfer protocols, as well as for business-level artifacts such as document types (e.g. in UBL). 9. Vendor independent No architectural principle should rely on any particular vendors product. To transform an abstract concept into a concrete, running system, its unavoidable to decide on specific products, both commercial and free/open source software. None of these decisions must have implications on an architectural level. This implies reliance on both interoperability and portability standards as much as reasonably possible. As a result, a participant can be built using any technology that supports the appropriate standards, not restricted by any vendor roadmap. 10. Metadata-driven All of the metadata artifacts within the overall SOA need to be stored in a way that enables them to be discovered, retrieved and interpreted at both design and run time. Artifacts include descriptions of service interfaces, participants, endpoint and binding information, organizational units and responsibility, document types/schemas, consumer/provider relationships etc. As much as possible, usage of these artifacts should be automated by either code generation or interpretation and become part of the service and participant life cycle.

You might also like