WCF
The Protocol ‘Net.Pipe’ is not supported–WCF/IIS7/WAS
Aug 15th
Want to host a WCF service using the NetNamedPipeBinding? I did too. Except IIS told me I couldn’t. After some frustrated Bing’ing and Googl’ing I found my answer.
This article on MSDN outlines how to enable Net.Pipe in IIS7. First you must enable the binding for the IIS site you are hosting the service in using this command (each command goes on a single line):
%windir%\system32\inetsrv\appcmd.exe set site "{YOUR_SITE_NAME}" -+bindings.protocol=’net.pipe’,bindingInformation=’*']
You can also accomplish this in the IIS Manager. Click on the site you want to enable Net.Pipe on, then click “Bindings”:
Select net.pipe from the list and in the Binding Information put an asterisk “*” (no quotes) ![]()
Click OK and you’re done. Using the IIS manager or the appcmd.exe will have the same effect.
Next we need to allow Net.Pipe for the virtual directory your service will be hosted in.
c:\windows\system32\inetsrv\appcmd.exe set app "{YOUR_SITE_NAME}/{Virtual_Directory"}" /enabledProtocols:http,net.pipe
This can be accomplished in the IIS Manager as well. Click on the virtual directory you want to add net.pipe to and then click “Advanced Settings…”
Next, in the enabled protocols box add the protocols you want, separating them with a comma. ![]()
Click OK and you’re done. Using the IIS manager or the appcmd.exe will have the same effect.
Once you have completed both these steps you should now be able to access your service over Net.Pipe after configuring the binding in your WCF service config.
Redirecting From a WCF REST Service
Mar 27th
REST is based on HTTP and revolves around using the standard HTTP verbs GET, POST, PUT as well as standard HTTP error codes. The error codes that have to do with redirection are in the 300 block. Today we’ll focus on 302 which is the status code for a redirection (other 300 codes, such as 301 indicate that the URI moved permanently).
The following code will redirect the client with a 302 status code:
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Redirect; WebOperationContext.Current.OutgoingResponse.Location = "/someOtherPage.aspx"; return null;
For an additional measure we’ll return null as well so that there is no output emitted to the client. The end result will be that the headers include the 302 status code, the location to redirect to and the body of the response will be empty.
Drop the Soap: WCF, REST, and Pretty URIs in .NET 4
Mar 17th
Years ago I was working in libraries when the Web 2.0 revolution began. One of the things that caught my attention about early start-ups using the AJAX/REST/Web 2.0 model was how nice the URIs were for their applications. Those were my first impressions of REST; pretty URIs. Turns out there is a little more to it than that.
REST is an architectural style that focuses on resources and structured ways to access those resources via the web. REST evolved as an “anti-SOAP” movement, driven by developers who did not want to deal with all the complexity SOAP introduces (which is al lot when you don’t have frameworks hiding it all). One of the biggest benefits to REST is that browsers can talk to rest services directly because REST works using URIs, QueryStrings, Cookies, SSL, and all those HTTP verbs that we don’t have to think about anymore.
If you are familiar with ASP.NET MVC then you have been exposed to rest at some level. MVC is relies heavily on routing to generate consistent and clean URIs. REST for WCF gives you the same type of feel for your services. Let’s dive in.
WCF REST in .NET 3.5 SP1 and .NET 4
This post will cover WCF REST in .NET 4 which drew heavily from the REST Starter Kit and community feedback. There is basic REST support in .NET 3.5 SP1 and you can also grab the REST Starter Kit to enable some of the features you’ll find in .NET 4.
This post will cover REST in .NET 4 and Visual Studio 2010.
Getting Started
To get started we’ll create a basic WCF Rest Service Application using the new on-line templates option in VS 2010:
When you first install a template you are prompted with this dialog:
Dude Where’s my .Svc File?
The WCF REST template shows us the new way we can simply build services. Before we talk about what’s there, let’s look at what is not there:
- The .Svc File
- An Interface Contract
- Dozens of lines of configuration that you have to change to make your service work
REST in .NET 4 is greatly simplified and leverages the Web Routing capabilities used in ASP.NET MVC and other parts of the web frameworks. With REST in .NET 4 you use a global.asax to set the route to your service using the new ServiceRoute class. From there, the WCF runtime handles dispatching service calls to the methods based on the Uri Templates.
global.asax
using System; using System.ServiceModel.Activation; using System.Web; using System.Web.Routing; namespace Blog.WcfRest.TimeService { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { RegisterRoutes(); } private static void RegisterRoutes() { RouteTable.Routes.Add(new ServiceRoute("TimeService", new WebServiceHostFactory(), typeof(TimeService))); } } }
The web.config contains some new structures to support a configuration free deployment. Note that this is the default config generated with the template. I did not make any changes to web.config.
web.config
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </modules> </system.webServer> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <standardEndpoints> <webHttpEndpoint> <!-- Configure the WCF REST service base address via the global.asax.cs file and the default endpoint via the attributes on the <standardEndpoint> element below --> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> </webHttpEndpoint> </standardEndpoints> </system.serviceModel> </configuration>
Building the Time Service
We’ll create a simple “TimeService” that will return the current time. Let’s start with the following code:
using System; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; namespace Blog.WcfRest.TimeService { [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class TimeService { [WebGet(UriTemplate = "CurrentTime")] public string CurrentTime() { return DateTime.Now.ToString(); } } }
The endpoint for this service will be http://[machinename]:[port]/TimeService. To get the current time http://[machinename]:[port]/TimeService/CurrentTime will do the trick.
The Results Are In
Remember That Route In global.asax?
Turns out it is pretty important. When you set the route name, that defines the resource name starting after the host portion of the Uri.
Help Pages in WCF 4
Another feature that came from the starter kit are the help pages. To access the help pages simply append Help to the end of the service’s base Uri.
Dropping the Soap
Having dabbled with REST in the past and after using Soap for the last few years, the WCF 4 REST support is certainly refreshing. I’m currently working on some REST implementations in .NET 3.5 and VS 2008 and am looking forward to working on REST in .NET 4 and VS 2010.
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!

