WCF
WCF 4 – Loosening the Chains of Configuration
Mar 8th
If you have spent anytime in WCF land the first thing you learn about is the joys of configuration. For the coming release of .NET 4 and WCF 4 the team heard that feedback and has made configuration much easier for the development experience.
Let’s take a look at what’s changed:
Sample 1 – WCF Configuration on .NET 3.5 SP1
<system.serviceModel> <services> <service name="WcfServiceConfig35.Service1" behaviorConfiguration="WcfServiceConfig35.Service1Behavior"> <!-- Service Endpoints --> <endpoint address="" binding="wsHttpBinding" contract="WcfServiceConfig35.IService1"> <!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically. --> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WcfServiceConfig35.Service1Behavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
By the way, I left out about 100 lines of other configuration “stuff” that had to do with System.Web, etc.
Sample 2 – WCF Configuration for the same service as Sample 1, in .NET 4
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
Notice there is no (none, nada, zero) system.serviceModel element. That said, if you start your service this way you have one teeny issue:
By default WCF disables metadata publishing (security through obscurity) so no one could query your service WSDL to build a client. In order to do that, you simply need the default code that WCF 4 puts in your config.
Sample 3 – WCF Configuration to enable metadata publishing, in .NET 4
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
I will certainly be looking forward to the easing of the configuration pains in WCF 4!
Five Things to Know About the WCF Runtime
Jan 19th
Since working with WCF I have gleaned quite a bit about how the runtime works through reading various blogs and writing proofs-of-concept/experiments. One thing that has become apparent to me is that many people working with WCF do not fully understand how it works because Visual Studio makes it very easy to create & consume WCF services. In most cases there is no need to understand the “guts” of WCF, but you may reach a point where you want to extend WCF. Here are five things that will help you know where to begin your quest for extension.
.Svc file are the activators that kick off the WCF runtime. In IIS or WAS, .Svc files are what activates a service host which in turn creates a service host and calls your service. The .Svc file specifies the full name of your class and an optional service host factory. If you are self-hosting a service you are responsible for implementing the same functionality in code.
ServiceHosts control your service instances and dispatch calls to your service using ChannelDispatchers. The ServiceHost is the central actor and you can control a lot of behavior by altering the service host or extending it. If you want to use an Inversion of Control container with WCF the best place to stick it is on a custom ServiceHost. The service host also maintains listeners that enable your service to receive calls over the wire at the specified endpoint (e.g., http://mydomain.com/services/myservice.svc).
ServiceHostFactory creates a ServiceHost. If you want to create a custom service host you’ll need a ServiceHostFactory to return an instance of your service host to the WCF runtime.
Everything can be done through configuration or code. I used to be a huge configuration fan, but after dealing with WCF configuration in .NET 3.5 it can get hairy, especially when you have dozens of services. Favor code where you can and save configuration for the stuff that could really change. WCF in .NET 4 has far less configuration, especially in development (which is good because the last thing you want to fight is configuration problems during development of your service).
By default service instances are created per call. This is typically OK and helps you avoid most threading problems. Try to avoid creating expensive objects within your services constructor or any of its dependencies as this could delay your services response time. You can change this using the InstanceContextMode on your service class. Tip: If you are using a container to resolve service instances then you need to remove the InstanceContextMode attribute and let the container manage instances.
(Bonus, a 6th thing to know!) WCF has many extension points, the biggest one being behaviors. Behaviors allow you to control how the service executes at runtime. This applies to anything from instancing to message inspection, and much more. Here are a few posts to get you started:
Put Up your Shields: Shielding Exceptions in WCF Services
Jan 18th
When using services an important best practice is to keep details of exceptions from leaking beyond the service boundary. Letting such details out of the boundary could create unnecessary coupling between the service callers and the service and would expose internal details of the service that you may wish to keep hidden.
Microsoft Patterns & Practices Enterprise Library (EL) provides an extension to the Exception Handling Application Block that hooks directly into WCF to provide the capability to replace service exceptions with custom faults.
Configuring Shielding
Exception shielding requires you to configure a Exception Handling Application Block with an exception policy. The policy consists of the exceptions you want to handle and a post-handling action for each exception. To work with the WCF Exception Shielding you need to set each exceptions post-handling action to ThrowNewException.
Once you have your basic policy set up you need to add a Fault Contract Exception Handler to each exception in your policy.
You can map properties from the exception thrown to the Fault you return. This is set up in the PropertyMapping as the following screenshot indicates. Source represents the source property on the Exception and Name is the property name on your fault to map to the source. In this case the WidgetNotFoundException has a “Message” property which we will map to the “Details” property on our WidgetNotFoundFault.
Lastly, you need to mark your Service Class with the ExceptionShielding Attribute and give it the name of your exception policy.
Once everything is wired up you can test the service to see your exceptions get replaced by the fault contract types.
A Quick Integration Test
When I fired up the service in Visual Studio 2010 and used the WCF Test Client, I ran a quick test to find a widget with the name of “Whatzit”. The service had something to say about that request:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header /> <s:Body> <s:Fault> <faultcode>s:Client</faultcode> <faultstring xml:lang="en-US">Widget Whatzit not found!</faultstring> <detail> <WidgetNotFoundFault xmlns="http://schemas.datacontract.org/2004/07/ExceptionShieldingService2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Details>Widget Whatzit not found!</Details> </WidgetNotFoundFault> </detail> </s:Fault> </s:Body> </s:Envelope>
You can also test this using something like MSTest and decorating your integration test with [ExcpectedException(typeof(FaultContract<MyServiceReference.MyFaultType>)]. Just point the FaultContract<TDetail> to the type from your ServiceReference. You can’t test fault contracts (to my knowledge) by calling the service imlementation class directly, you’ll need to do this by adding a service reference and calling the service that way.
Tips & Common Errors
After setting up a few of these I have run into some configuration problems which seem to be the most common issue hit with any of the EL blocks.
- Use the Enterprise Library “Load from assembly” option to select your Exception and Fault Contract types. EL seems particularly sensitive to using the fully-qualified assembly name including version & public key token.
- Turn on some type of logging while testing your policy. This will help you troubleshoot problems with the policy (mismatched types, etc).
- “The current build operation (…) failed: Value cannot be null” Parameter name: faultContractType – This error stems from EL not being able to resolve your Fault Contract Type. This is typically due to a bad mapping of your Fault Contract Type. Check the Type Name, Assembly and version info to make sure it is correct. Your best bet is to use the EL Config Editor to browse and select your fault type.
What Do You Call It? Naming WCF Operations & Messages
Dec 30th
WCF is a great addition to the .NET framework. Like all parts of the framework it introduces a lot of new concepts to learn. Sometimes it’s hard to separate those technical concepts from the decisions like, “What is the best way to architect this service” or “How should I name things?”
Simon Segal, a fellow .NET and SOA junkie posted back in November about how he names operations and messages within WCF and the nServiceBus framework (an open-source Enterprise Service Bus). Simon, like I do, follows a convention of naming in relation to the business events the operations and messages represent.
When it comes to naming operations we not only imply some intent of the operation we also imply what data might be needed. When designing services that are more coarsely grained you often run into issues with what data is really required for the service to perform its work. Simon linked to an article from Thomas Erl, a respected authority on SOA, in which Thomas made the following statement (my emphasis):
Although it is practical and extensible, the use of optional parameters should be limited within Web services. Optional parameters can lead to convoluted service interface designs and a myriad of confusing data exchange scenarios. Additionally, the extent to which optional values can be accommodated is often limited by the underlying XML schemas that define the message structures. Standardized schemas that represent established corporate documents may impose rigid data structures.
Coming from the NIEM world I often emphasized that data exchanges only need 80% of what we think is needed. There were times when people would want to exchange flags or indicators that could be derived from other fields or were not necessarily needed at all. Any time we strayed away from the 80% the services became more difficult to consume and maintain.
Let’s Look at An Example
Factoring all of this in, let’s consider an example of how we might name service operations and messages.
Definitions:
Service Operation – A method you call on a service.
Message – An input/output of a call to a service operation.
Message Parts – Data elements that are included in the message.
Problem: You need to name messages and service operations for a service that will allow customers to place orders for widgets. This service should also allow orders to be cancelled. Orders consist of a unique ID, a customer Id, and widgets.
Request/Response example:
- Service Operation PlaceWidgetOrder, Message: PlaceWidgetOrderRequest, Message Parts: WidgetOrder (Id, Customer Id, Widgets[] (or WidgetCollection))
- Service Operation CancelWidgetOrder, Message: CancelWidgetOrderRequest, Message Parts: OrderId
Event-Driven example:
- Service Operation: CustomerPlacedWidgetOrder, Message: CustomerPlacedWidgetOrderMessage, Message Parts: same as request/response example
- Service Operation: CustomerCancelledWidgetOrder, Message: CustomerCancelledWidgetOrderMessage, Message Parts: same as request/response example
Notice the difference between the two styles. In the event-driven style we talk about something that has happened (or is happening) and in the Request/Response style we talk in terms of what we want to do. Each style has it’s merit and the style you choose will depend on the situation and the maturity of the partners involved in the service collaboration/data exchange.
Also notice that the event-driven example does not imply any type of response to the operation. Typically event-driven systems will be asynchronously designed and the service operations will reflect that.
Why Messages?
Messages allow us to encapsulate the data needed for the domain as well as data we may need because of technical requirements. Technical requirements may dictate that we have to log messages or protect messages in other ways (which could require message IDs, encryption keys, etc). By encapsulating data in a message we also leave room to include the technical requirements within the same message and keep our domain model free of technical bits that aren’t really part of the domain.
How do you name your service operations and messages?
Simon and I would love to hear. Leave a comment or tweet it!
WCF Test Client in VS 2010
Dec 28th
The other day I fired up a WCF service for the “Take Control of Messages” post and to my surprise a test client opened up which felt very similar to SoapUI.
Loading & Adding the service reference (happens auto-magically)
Double-clicking on a service operation brings up the test form.
Fill out the data elements and press invoke to test the service.
The client was also able to support when I transitioned to a message contract.
After selecting the type, you can then expand the element to view it’s members.
This is a great addition to VS and will greatly help testing services!
Take Control of Messages in WCF
Dec 27th
With WCF you can control many aspects of how service behave and how you interact with them. Let’s take a look at Data & Message Contracts and how each behaves on the wire.
Data Contracts – The Basics
Data contracts are the default method for serializing in WCF. To leverage data contracts you simply markup the classes you wish to expose from the service with the DataContractAttribute. The data contract serializer does not support all the features of Xml Serialization which yields some performance boosts. However, the data contract serializer has some default behaviors which may not suit your needs.
The Contract
[DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } }
The SOAP Message
Request (Showing soap:body only)
<s:Body> <GetDataUsingDataContract xmlns="http://tempuri.org/"> <composite xmlns:a="http://schemas.datacontract.org/2004/07/ContractExamples" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <a:BoolValue>true</a:BoolValue> <a:StringValue>Hello Service!</a:StringValue> </composite> </GetDataUsingDataContract> </s:Body>
Response
<s:Body> <GetDataUsingDataContractResponse xmlns="http://tempuri.org/"> <GetDataUsingDataContractResult xmlns:a="http://schemas.datacontract.org/2004/07/ContractExamples" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <a:BoolValue>true</a:BoolValue> <a:StringValue>Hello Service!Suffix</a:StringValue> </GetDataUsingDataContractResult> </GetDataUsingDataContractResponse> </s:Body>
With the data contract, notice how our messages are actually wrapped in an outer element in the Xml. For the request, the CompositeType is wrapped in a “GetDataUsingDataContract” element which is derived from the operation name. The response is where it is interesting, our message is actually double wrapped.
How do we change this default behavior? Enter Message Contracts.
Message Contracts – For Control Freaks
Message contracts are another way to work with WCF to take more control of how the messages are serialized in the SOAP envelope. These can be a key strategy to creating services that can support better interoperability with other stacks such as Java. You define message contracts with the MessageContractAttribute.
The Message Contract
[MessageContract(IsWrapped=true, WrapperNamespace=http://christopherDeweese.com/WCF/Examples)] public class CompositeTypeRequest { [MessageBodyMember] public CompositeType CompositeData { get; set; } } [MessageContract(IsWrapped=true, WrapperNamespace=http://christopherDeweese.com/WCF/Examples)] public class CompositeTypeResponse { [MessageBodyMember] public CompositeType CompositeData { get; set; } }
Here we have defined a request and a response message which contains our CompositeType. What result does this yield?
The SOAP Message
Request
<s:Body> <CompositeTypeRequest xmlns="http://christopherDeweese.com/WCF/Examples"> <CompositeData xmlns="http://tempuri.org/" xmlns:a="http://schemas.datacontract.org/2004/07/ContractExamples" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <a:BoolValue>true</a:BoolValue> <a:StringValue>Hello Service with messages! </a:StringValue> </CompositeData> </CompositeTypeRequest> </s:Body>
Response
<s:Body> <CompositeTypeResponse xmlns="http://christopherDeweese.com/WCF/Examples"> <CompositeData xmlns="http://tempuri.org/" xmlns:a="http://schemas.datacontract.org/2004/07/ContractExamples" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <a:BoolValue>true</a:BoolValue> <a:StringValue>Hello Service with messages! Suffix</a:StringValue> </CompositeData> </CompositeTypeResponse> </s:Body>
A Little ‘Philosophy’
In past posts on services I’ve discussed the opinion that you interact with services through messages. Encapsulating inputs and outputs to the service using messages allows for a clearer semantic representation of the what the capabilities the service provides access to.
Using Message contracts in WCF lets you explicitly control how the messages are serialized and allows you to build services from canonical data models created in raw Xml. This also provides the greatest interoperability and you don’t have to deal with the default behaviors of the data contract serializer.
Final Thought
You may not always need this type of control. For instance if your service is only being consumed by other .NET clients the messages may not be that important to you. But if you are designing services for an Enterprise SOA, then message contracts will be a great help.
Inverting Control in WCF – Follow Up
Nov 23rd
The code from “Inverting Control in WCF” has been posted to Codeplex here. Feel free to ping me with questions on Twitter or through this blog!
Thanks to all who attended and a big thanks to Alvin Ashcraft for hosting and to all the other organizers & sponsors!
WCF: NetMsmqBinding and Non-Transactional Queues
Aug 10th
Recently we had a situation where we needed to remove transactions from the equation in a WCF service because we were calling a downstream component that could not support transactions. The new transaction infrastructure in .NET 2.0 and the use of ambient transactions makes it easy to leverage transactional functionality in your service calls with no real coding required on your part. By default, using the NetMsmqBinding enables Durable and Exactly once on the binding which implies the use of transactions in the background, and those transactions are applied to any transactional call made including sending to other message queues, database connections, etc.
The new transaction infrastructure leveraged by WCF is great, except when you need to opt out, because the key to getting the result you want is understanding how the different "knobs and switches" (as coined by Juval Lowy) or configuration options on the binding affect each other. In the case of Durable and Exactly Once you may be lead to believe disabling exactly once will remove transactions if you go solely by the descriptions of each option. However, you will quickly be notified by the WCF runtime that enabling Durable and disabling ExactlyOnce on the NetMsmqBinding is not supported.
Disabling both Durable and ExactlyOnce on the NetMsmqBinding ultimately removed transactions from the equation and produced the result we expected once we did this on both the client and the service.
The other key is how we ultimately found the correct way to do this. Once we changed the queue to non-transactional the symptom we saw was that our message we were sending kept ending up in the system wide Transactional Dead-Letter queue. There was no error message or exception logged by our service because the message never got there. A little research and a couple tests and we arrived at our solution. We could have handled this with an IErrorHandler implementation but at the time we knew what direction to look (transactions were the issue) so we took the manual route.
Streaming in WCF: Knowing is Half the Battle
Aug 2nd
WCF provides the ability to stream data from service to client which can aid greatly in transferring large files and improve performance. But as with all things WCF there are a few things you should know before you turn on the streams.
In order to activate streaming in WCF you must supply a service method that accepts or returns the type System.IO.Stream, edit your binding to use the streamed transfer mode (default is buffered), and let the streaming begin. Be sure to consider the following advice from Large Data and Streaming on MSDN: "You should not be using System.IO.Stream derived types inside of data contracts. Stream data should be communicated using the streaming model, explained in the following "Streaming Data" section." This post on MSDN forums explains in more detail how you can handle the stream on the receiving end as you do not have a guarantee that the type of stream you send is how it is received. For example, if you send a MemoryStream, the receiver will receive it as the System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream class (any stream you send is received as this). The data is there, it’s just not the type of stream you sent it as.
Here are a few bullets to keep in mind when streaming with WCF:
- Your contract should accept or return the type System.IO.Stream and not any of the derived types.
- On the receiving end the simplest way to deal with the stream is to treat is as the base System.IO.Stream class.
- Callers of the service will have to understand the format of the stream through a mechanism provided out of band – the WSDL cannot show them what will potentially be in the stream.
- Set the buffer sizes to appropriate values in configuration: MaxBufferSize, MaxReceivedMessageSize, and MaxStringContentLength
- Streaming is only available on BasicHttpBinding, NetTcpBinding, and NetNamedPipeBinding.
- WCF is still Xml based so your stream will be serialized as an xs:base64Binary as evidenced by this WSDL output:
<?xml version="1.0" encoding="utf-8" ?> <xs:schema elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/Message" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/Message"> <xs:simpleType name="StreamBody"> <xs:restriction base="xs:base64Binary" /> </xs:simpleType> </xs:schema>
Now you know, and for those of us who spent the 80’s watching cartoons we know what knowing is.
Beware Writing to the ‘Bin’ Folder in IIS Hosted Services
Jul 14th
The other day we had a issue occur where one of our WCF web services hosted in IIS 6 was getting a ThreadAbortException while processing the first few requests. We had made a change to the service to perform some diagnostic logging and the data was being written to a subfolder in ‘bin’. This turned out to be the cause of our problem. Because of how IIS 6 works in conjunction with .NET, when the ‘bin’ folder is touched it initiated a recycle of the application pool because it thought files had changes. We moved the logging to save to App_Data and our troubles went away.
Buyer beware, if you write to ‘bin’ you might become the victim of a mysterious, but explainable, application pool recycle!


