Monday, July 15, 2013

Data Transfer in Service Contracts

Service operations can receive messages, process them, and send them messages. Messages are described using operation contracts

Out and Ref Parameters:

If the return value alone is not enough to describe a reply message, out parameters may be used. Additionally, you may use reference parameters to make a parameter part of both the request and the reply message. The parameters must be of types that can be serialized (converted to XML). By default, WCF uses a component called the DataContractSerializer class to perform this conversion. Most primitive types (such as int, string, float, and DateTime.) are supported. User-defined types must normally have a data contract
Message Parameter:
To isolate .NET parameter names from contract names, you can use the MessageParameterAttribute attribute, and use the Name property to set the contract name.
           public int SomeOperation([MessageParameter(Name="fromCity")] string originCity);
Message Contracts:
Message contracts allow you to exercise more control over resultant messages. For instance, you can decide which pieces of information should be in the message body and which should be in the message headers
Describing Messages by Using Streams:
Another way to describe messages in operations is to use the Stream class or one of its derived classes in an operation contract or as a message contract body member (it must be the only member in this case). For incoming messages, the type must be Stream—you cannot use derived classes.
Instead of invoking the serializer, WCF retrieves data from a stream and puts it directly into an outgoing message, or retrieves data from an incoming message and puts it directly into a stream. The following sample shows the use of streams.

        public Stream DownloadFile(string fileName);

You cannot combine Stream and non-stream data in a single message body. Use a message contract to put the extra data in message headers. The following example shows the incorrect usage of streams when defining the operation contract.

        // Incorrect:
        // [OperationContract]
        // public void UploadFile (string fileName, Stream fileData);

The following sample shows the correct usage of streams when defining an operation contract.
        public void FileUpload(UploadFileMessage message);
        public class UploadFileMessage
            public string fileName;
            public Stream fileData;

Using Derived Types

You may want to use a base type in an operation or a message contract, and then use a derived type when actually invoking the operation. In this case, you must use either the ServiceKnownTypeAttribute attribute or some alternative mechanism to allow the use of derived types. Consider the following operation.
public bool IsLibraryItemAvailable(LibraryItem item);
Assume that two types, Book and Magazine, derive from LibraryItem. To use these types in the IsLibraryItemAvailable operation, you can change the operation as follows:
        public bool IsLibraryItemAvailable(LibraryItem item);
Alternatively, you can use the KnownTypeAttribute attribute when the default DataContractSerializer is in use, as shown in the following example code.

        public bool IsLibraryItemAvailable(LibraryItem item);

        // code omitted

        public class LibraryItem
            //code omitted
Controlling the Serialization Process

You can do a number of things to customize the way data is serialized.

Changing Server Serialization Settings

When the default DataContractSerializer is in use, you can control some aspects of the serialization process on the service by applying the ServiceBehaviorAttribute attribute to the service. Specifically, you may use the MaxItemsInObjectGraph property to set the quota that limits the maximum number of objects the DataContractSerializer deserializes. You can use the IgnoreExtensionDataObject property to turn off the round-tripping versioning feature.
[ServiceBehavior(MaxItemsInObjectGraph = 100000)]
        public class MyDataService : IDataService
            public DataPoint[] GetData()
                // Implementation omitted
Shared Type Serialization, Object Graph Preservation, and Custom Serializers

The DataContractSerializer serializes using data contract names and not .NET type names. This is consistent with service-oriented architecture tenets and allows for a great degree of flexibility—the .NET types can change without affecting the wire contract. In rare cases, you may want to serialize actual .NET type names, thereby introducing a tight coupling between the client and the server, similar to the .NET Framework remoting technology. This is not a recommended practice, except in rare cases that usually occur when migrating to WCF from .NET Framework remoting. In this case, you must use the NetDataContractSerializer class instead of the DataContractSerializer class.

The DataContractSerializer normally serializes object graphs as object trees. That is, if the same object is referred to more than once, it is serialized more than once. For example, consider a PurchaseOrder instance that has two fields of type Address called billTo and shipTo. If both fields are set to the same Address instance, there are two identical Address instances after serialization and deserialization. This is done because there is no standard interoperable way to represent object graphs in XML (except for the legacy SOAP encoded standard available on the XmlSerializer, as described in the previous section on Style and Use). Serializing object graphs as trees has certain disadvantages, for example, graphs with circular references cannot be serialized. Occasionally, it is necessary to switch to true object graph serialization, even though it is not interoperable. This can be done by using the DataContractSerializer constructed with the preserveObjectReferences parameter set to true.

WCF Hosting Options

Self-Hosting in a Managed Application
WCF services can be hosted in any managed application. This is the most flexible option because it requires the least infrastructure to deploy. You embed the code for the service inside the managed application code and then create and open an instance of the ServiceHost to make the service available.
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 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. This hosting option also makes it easy for rich client applications, such as WPF and WinForms applications, to communicate with the outside world. For example, a peer-to-peer collaboration client that uses WPF for its user interface and also hosts a WCF service that allows other clients to connect to it and share information.

Benefits: Flexible, Easy to deploy, Not an enterprise solution for services.

Managed Windows Services
This hosting option consists of registering the application domain (AppDomain) that hosts an WCF service as a managed Windows Service (formerly known as NT service) so that the process lifetime of the service is controlled by the service control manager (SCM) for Windows services. Like the self-hosting option, this type of hosting environment requires that some hosting code is written as part of the application. The service is implemented as both a Windows Service and as an 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. An installer class that inherits from Installer must also be implemented to allow the program to be installed as a Windows Service by the Installutil.exe tool. The scenario enabled by the managed Windows Service hosting option is that of a long-running WCF service hosted outside of IIS in a secure environment that is not message-activated. The lifetime of the service is controlled instead by the operating system. This hosting option is available in all versions of Windows.

Benefits: Service process lifetime controlled by the operating system, not message-activated, Supported by all versions of Windows, Secure environment.

Internet Information Services (IIS)
The IIS hosting option is integrated with ASP.NET and uses the features these technologies offer, such as process recycling, idle shutdown, process health monitoring, and message-based activation. On the Windows XP and Windows Server 2003 operating systems, this is the preferred solution for hosting Web service applications that must be highly available and highly scalable. IIS also offers the integrated manageability that customers expect from an enterprise-class server product. This hosting option requires that IIS be properly configured, but it does not require that any hosting code be written as part of the application

Note that IIS-hosted services can only use the HTTP transport. Its implementation in IIS 5.1 has introduced some limitations in Windows XP. The message-based activation provided for an WCF service by IIS 5.1 on Windows XP blocks any other self-hosted WCF service on the same computer from using port 80 to communicate. WCF services can run in the same AppDomain/Application Pool/Worker Process as other applications when hosted by IIS 6.0 on Windows Server 2003. But because WCF and IIS 6.0 both use the kernel-mode HTTP stack (HTTP.sys), IIS 6.0 can share port 80 with other self-hosted WCF services running on the same machine, unlike IIS 5.1.

Benefits: Process recycling, Idle shutdown, Process health monitoring, Message-based activation, HTTP only.

Windows Process Activation Service (WAS)
Windows Process Activation Service (WAS) is the new process activation mechanism for the Windows Server 2008 that is also available on Windows Vista. It retains the familiar IIS 6.0 process model (application pools and message-based process activation) and hosting features (such as rapid failure protection, health monitoring, and recycling), but it removes the dependency on HTTP from the activation architecture. IIS 7.0 uses WAS to accomplish message-based activation over HTTP. Additional WCF components also plug into WAS to provide message-based activation over the other protocols that WCF supports, such as TCP, MSMQ, and named pipes. This allows applications that use communication protocols to use the IIS features such as process recycling, rapid fail protection, and the common configuration system that were only available to HTTP-based applications.
This hosting option requires that WAS be properly configured, but it does not require you to write any hosting code as part of the application.

Benefits: IIS is not required, Process recycling, Idle shutdown, Process health monitoring, Message-based activation, Works with HTTP, TCP, named pipes, and MSMQ.