Indigo (WFC)
If you're doing any kind of Indigo (WCF) development you'll want to checkout: "Exception Handling in Windows Communication Framework and Best Practices".
My own best practices are as follows:
- Never use returnUnknownExceptionsAsFaults. Instead, log the exceptions that occur on the server side and look there when you need to debug the service.
- Always create FaultContracts for your exceptions and specify them in your service contract rather than wrapping .NET exceptions. It's not that much more work to create a FaultContract and it ensures you don't leak information. Specifying them in your service contract allows consumers to know what to expect from you when things go wrong. Being explicit with your services is a good thing, so make it explicit what you are expecting to go "wrong".
- Always implement IErrorHandler so that exceptions are logged and sanitized appropriately.
Technorati tags:
indigo,
wcf,
.net3,
winfx
This past week I got to experiment with securing WCF (Indigo) Operations with AzMan. We ended up with something like this:
[ServiceContract]
public class ICustomerService {
[OperationContract]
[FaultContract(typeof(OperationPermissionFault))]
[Authorization(“FindCustomer”)]
Customer FindCustomer(FindCustomerRequest request);
}
Decorating the operations on our WCF Service with an AuthorizationAttribute ensures that the user calling the service has the appropriate permission to run the operation. The AuthorizationAttribute is an operation behavior (IOperationBehavior) that injects a custom IParameterInspector into the processing pipeline for the given WCF operation. The Parameter Inspector then does an authorization check against AzMan for the user that called the service. All cool stuff.
If your interested in integrating with AzMan for authorization checkout Sam’s most excellent post on the topic entitled: “How To: STS/Windows Authentication with ADAM/AD, Roles in AzMan with WCF”.
Today I’d like to talk about a few of the extensibility points within WCF. I should note that the descriptions below are my interpretation of how each of the extensibility points are meant to be used and not guaranteed to be correct since I couldn’t find any real definitions anywhere 
During my investigation I found a couple different points of extensibility within WCF. The first extensibility point allows you to change the behavior of your services, endpoints, and operations and have the appropriate name of “Behaviors”. The second extensibility point I came across was what I’m going to refer to as “Inspectors”. Inspectors can be added to the processing pipeline of WCF and can control how messages are processed when they enter the pipeline via a request as well as when the messages go back out the other end when sending a response.
Behaviors
While investigating behaviors I came across the following three interfaces: IServiceBehavior, IEndpointBehavior, and IOperationBehavior. The astute reader among you will surely see that these three interfaces allow developers to extend the beahvior of services, endpoints, and operations! Often times the behavior is responsible for configuring “Inspectors” that will then be injected into the processing pipeline. Whether you choose a IServiceBehavior, IEndpointBehavior, or IOperationBehavior depends on the level of granularity by which you want to alter the behavior of WCF.
If you interested in changing the behavior of WCF at the service level you’ll create your own IServiceBehavior. Often times if you create a service behavior you’ll want to apply the behavior to all the endpoints within this service which is where the IEndpointBehavior comes in. If you want to be a little more fine grained you may forgo the IServiceBehavior and IEndpointBehavior in favor of the IOperationBehavior. An IOperationBehavior can be applied on a per Operation basis and are typically done so via attributes (for example the AuthorizationAttribute mentioned above).
While behaviors are the means by which you change the behavior of WCF they often times aren’t the ones doing the actual work. Enter Mr. Inspector.
Inspectors
Inspectors are how you actually change and/or alter the processing pipeline of Indigo. By creating a IDispatchMessageInspector you can pre-process messages as they enter and exit the WCF pipeline. At the IDispatchMessageInspector level you’re dealing with messages before they’ve found their final destination (aka: Operation). Often times your IServiceBehavior or IEndpointBehavior will add a custom IDispatchMessageInspector to the Dispatch Runtime of Indigo. Pre-processing of incoming messages can be done in the AfterReceiveRequest method of your IDispatchMessageInspector, while pre-processing of repy messages can be done in the BeforeSendReply method.
IDispatchMessageInspectors are typically injected into the WCF pipeline in the ApplyDispatchBehavior method of your custom IServiceBehavior or IEndpointBehavior class by adding the message inspector to the “DispatchRuntime.MessageInspectors” collection.
If your developing something more fine grained then the service or endpoint level you’ll likely be injecting IParameterInspector’s into the processing pipeline via a custom IOperationBehavior class. Once a WCF message has gone through the necessary processing and found a home (aka a matching OperationContract) you have one more chance to apply some of your own custom logic via your very own IParameterInspector. The parameter inspector allows pre and post processing of messages via the BeforeCall and AfterCall method. The BeforeCall method is called just before the message is dispatched to the service operation and the AfterCall method is called just before the response message is sent from the service operation back to the client.
In order to do our authorization checks at the operation level we created a custom IParameterInspector that calls out to AzMan and validates that the user has the necessary permissions. If the user does not have permissions we throw a OperationPermissionFault to our client which prevents the operation on the service from executing.
Wrapping Up
While this post overviews several of the extensibility points within WCF it is NOT an exhaustive list. It also doesn’t go into a whole lot of detail regarding the specifics of how all of the above is done in code. I’ll be looking to do some additional posts which detail how all of the above is done in code in the next couple of weeks. Additionally I’ll be digging into some of the extensibility points which I have not investigated thus far. If your interested in a full list of extensibility points within WCF checkout Christian Weyer WCF Extensibility Cornucopia post.
If you have any questions or would like to see sample code for something particular drop me a line and I’ll see what I can do. If your starting to work with WCF I strongly encourage you to start digging into the details of their extensibility model…it kicks ass! 
Patterns and Practices recently made available a drop of their Web Services Software Factory toolkit.
The Service Factory is a cohesive collection of various forms of guidance that have been build with the primary goal of helping you build high quality connected solutions in a more consistent way with less effort. In addition to the forms of guidance you may have already seen from the patterns & practices team, there is a new form of guidance in here, called a guidance package, that allows guidance to be automated from inside Visual Studio 2005 through the use of a wizard-based dialog than can be modified (by an architect perhaps) to fit the needs of a specific solution.
The frist drop includes a reference implemention as well as a set of Guidance Automation recipes for helping automate the development of services using WCF/Indigo. Below is a list of some of the recipes I came across during my experimentation:
-
Create WCF Solution – This builds a nice big solution with seperate projects for all your contracts (service, data/message, fault), as well as your service implementation, data layer, business entities, business logic, host, client, and kitchen sink. The package does a good job of seperating our everything into distinct projects which helps to make the point that things should be be clearly seperated. The structure that was created for my “CustomerService” was as follows:
-
CustomerServiceBusinessEntities
-
CustomerServiceBusinessLogic
-
CustomerServiceDataAccess
-
CustomerServiceDataContracts
-
CustomerServiceFaultContracts
-
CustomerServiceServiceContracts
-
CustomerServiceServiceImplementation
-
CustomerServiceHost
-
CustomerServiceClient
-
Create Data/Fault Contract – This has a couple different options including creating a data contract or fault contract via a wizard, or via code snippets. I hate wizards so I can’t see ever using the wizard to create my data contracts. The amount of time it takes to navigate around the data grid to define your contract would be much better spent in the VS.NET editor. Do we really need a wizard for everything?
-
Create Service Contract – This allows you to define the contract for a service again providing both a wizard and code snippet option. If you like wizards your going to love the P&P team.
-
Create Service Implementation – This allows you to create a service implementation by selecting a service contact. Those familiar with writing code will likely skip this one as well and use the wonderful SHIFT+ALT+F10 keyboard shortcut to implement the service contact after inheriting their concrete implementation for the proper interface (aka: service contact)
-
Create Service Contract Translator using Wizard– This little beauty allows you to map your business entities to your data contracts. While I couldn’t actually get this to run it seems like a nice utility that can help reduce the amount of grunt work required when you translate all your messages into your entities and vice versa. Update: It’s working, something was hosed on my home installation of WinFX). An example below shows a translator created to translate my Customer data contract into my Customer business entity. Pure Fun!
public class TranslateBetweenCustomerAndCustomer {
public CustomerServiceDataContracts.Customer TranslateCustomerToCustomer(CustomerServiceBusinessEntities.Customer from) {
CustomerServiceDataContracts.Customer to = new CustomerServiceDataContracts.Customer();
to.CustomerName = from.CustomerName;
return to;
}
public CustomerServiceBusinessEntities.Customer TranslateCustomerToCustomer(CustomerServiceDataContracts.Customer from) {
CustomerServiceBusinessEntities.Customer to = new CustomerServiceBusinessEntities.Customer();
to.CustomerName = from.CustomerName;
return to;
}
}
-
Decorate Type as Data Contact – This allows you to right click in a class and select for it to be decorated as a data contract. A [DataContract] attribute is added to the class and [DataMember] attributes are applied to all properties.
-
Validate Data Contact – This allows you to right click in a class and have the data contract validated. Amazingly the data contract produced by their wizard validates quite well!
Overall there seems to be some pretty useful nuggets of guidance within the first release. I’m very interested to see the project progress and mature. I just hope the wizard to coding ratio doesn’t get too ridiculous.
One of the changes that was made between beta 1 and recent CTP's of Indigo (WCF) was the way svcutil generated proxies. Within our service layer we have several services that return a generic list to the client. In beta 1 the proxy class generated by svcutil used generic lists. When we migrated over to the Nov CTP (back in November) this behavior changed. Rather then using the List of<T> the proxies were using an array of T. At the time I figured they didn't want to be serializing information about the fact that the service was returning a generic list, since that isn't very interoperable, however as I thought about it more I started thinking I must be missing something. There is no reason that the proxy couldn't still use a generic, Since Indigo is handling the serialization and deserialization it could just as easily deserialize the message into a generic list as it could an array since they are wire compatable.
With this though in hand I jumped to a command prompt to look at what options were available for svcutil. That's when I discovered the /rct command line switch. I tried a couple different variations to try and get svcutil to pick up that I wanted to use System.Collections.Generic.List<T> but I wasn't having much luck. That's when I headed over to the
WCF Forums on MSDN to look for an answer.
Yes - /rct switch is what is needed.
If you are looking for a way to replace all collections with
List<T>, you need to specify that type via /rct using the fully
qualified type name (assembly-qualified name is needed if the assembly
is not loaded via /r; mscorlib is always /r by svcutil).
Ex. /rct:System.Collections.Generic.List`1 should work.
This setting will apply across all your services during code generation.
We allow users to customize this further if they want to map to
different collection types based on the element type T. This can be
done by providing multiple /rct parameters - we will use the most exact
match.
After a quick switch from /rct:System.Collections.Generic.List<T> (which was bombing) to /rct:System.Collections.Generic.List`1 svcutil was once again generating proxies with the generic list!
The January CTP of WinFX has been released, and along with it a Go Live license for WCF and WWF. This is great news for those of us building software using these bits.
Additionally now that there is a go-live license I can start building some personal projects using these bits. Although my personal projects usually aren’t all that exciting I often get a chance to iron out some ideas and thoughts I have with regards to particular technologies so a go live license for Indigo and Workflow is most excellent.
Maybe I’ll even get to include some nice Indigo/Workflow “goo” in ActiveType?
Michele has a very nice article over on the server side about
designing service contracts in WCF (Indigo). If your interested in learning about the various message design options available in Indigo and when they work best you should definitely check out Michele's article.
Thus far we've been decorating our business objects with [DataContract] and [DataMember] attributes. This prevents us from having to create duplicate representations for a single "concept" within our system but it also makes for a slightly less flexible design. We're trying to find the right middle ground. On the one hand we want to design our messages independent from our business and data objects, but on the other hand we don't want to have several representations for the same thing. I have a feeling that as we continue on we'll start to migrate to using MessageContract and DataContracts that are seperate from our business objects. To help reduce the amount of mapping code required for converting business objects to messages we may use a Data-Gateway-esque pattern. We'll see how it goes!
Ralf Westphal and Ingo Rammer are having an interesting discussion about Interface design in distributed solutions. They start by talking about how to design components, and ponder whether interfaces are the appropriate way to define contracts for components. They talk about how coarse grained interfaces should be, discuss whether factory methods are a good way to provide run-time decoupling, and whether interfaces are good for times when there is only one implementation. They then move onto discussing service contracts in the context of Indigo (WCF). One of the topics that I’m particularly interested in is whether data contracts should be kept completely seperate from the data objects used by the components and data layers in the application. If they’re kept completely seperate then at the service layer there will be a good bit of translation logic that will take data contracts and convert them into the data objects that are used by the components that live behind the service layer and perform the “real work”. On the other hand if you decide it’s ok for your data contracts to be shared with your components then you don’t have to worry about the extra translation. Instead you have to worry about how much of your intenal implementation details will be exposed to the outside world due to the tight coupling between your servics and components. They hit the nail right on the head when they state the followign question and answer:
Do you believe in strict decoupling and service autonomy and is this desired in your solution or are you just using a service as a means to an end (for example to avoid deploying database clients to your users' PCs)?
I'm a believer: Manually creating the message's content will be a second nature to you anyway. I think you are already wondering why we might even suggest anything else ;-)
I'm just being pragmatic: You're welcome to use a simple solution (like items #1 or #2 in my previous reply) if you really only use a service as a means to a specific end.
So if you are a true service oriented believer then you most likely want to have seperate data contracts that are only used by your services. This will result in having some duplication in objects (one for services, and one for your components) but will make the overall design more de-coupled. If your just being pragmatic then you might use the same objects within your services and components. This makes your services a lot more fragile since changes in your components and data layers will effect the contract of your services.
Are you a true SO believer or are you just pragmatic?
I’ve recently been investigating svcutil to see if it can generate a set of proxies and data contracts for my clients by pointing at an assembly rather then an endpoint. I’ve been having some issues with pointing svcutil at endpoints when I have several services that share data contracts. It took a little experimentation with svcutil but it looks like the best way to go from assembly (dll) to proxy/contract code for the client is by following these steps:
1) Run svcutil passing the assembly (.dll) as the parameter
> svcutil MyServices.dll
This will create a couple xsd’s as well as a wsdl file that defines your service.
2) Run svcutil with the /dataContractsOnly option and pass the xsd that contains the data contracts for your services
> svcutil /dataContractsOnly /t:code MyServices.xsd
This will create a .cs file with all the data contracts used by the services.
3) Run svcutil and pass the wsdl as the parameter
> svcutil mycompany.com.wsdl
This will create a .cs file with proxies for calling the services.
After executing the above steps you’ll have a C# file with all your data contracts, and a seperate C# file with a proxy for all your services. I’ll most likely be wrapping the sequence of commands up in a batch file so I can run a single command to regenerate everything for the applications consuming my Indigo (WCF) services. I’m also going to experiment a little more with svcutil to see if there is a “hidden option” that does what I want.
One of the things that I’m looking forward to digging into within Indigo is their support for Federated Security. This evening I came across an article on one of the key enabling technologies for providing federeated security, namely SAML. (more from Oasis)
Hopefully as we get closer to a release of Indigo (WCF) we’ll start seeing more articles and books that help provide guidance for building “real” service oriented (SO) applications using WCF. Perhaps Sam Gentile will have some goodies for us in his Service Oriented Indigo book?
Within Indigo we have several bindings to choose from. This allows us to have a single service that is exposed in several different ways for different types of clients. The current set of bindings available along with my interpretation on when and why they should be used is below:
- BasicProfile – Use this binding if you’re supporting the Web Service Interoperability (WS-I) Basic Profile 1.0.
- WsProfile – Use this binding if you need to support the various WS-* specifications such as WS-ReliableMessaging, WS-Security, and WS-AtomicTransaction. If you’re doing interoperability with other platforms that also support these WS specifications then this is the binding for you.
- WsProfileDualHttp – This binding provides all the same features as the WsProfile binding and also allows two way communication between the client and server. To allow a service to communicate with a client you need to specify a callback contract and implement that callback contract in your client.
- Intermediary – If your services need to go through a middle man for additional processing the intermediary binding is where it’s at. The intermediary binding can sit between services that are using Http, Tcp, and the named pipe transports.
- MsmqIntegration – If your services need to read messages off of a queue that is being used by a set of existing applications then the MsmqIntegration binding may be what your after. It allows a non-Indigo application to write messages to a queue that the Indigo service can then read and process.
- NetProfileTcp – If you have the benefit of running in an all Indigo world then the NetProfileTcp binding may be your best bet. Since it’s communicating over Tcp using binary encoding for messages it offers a performance boost over the bindings that communicate over Http using a Text encoding. You do need to ensure the ports that are being used to connect are open and available.
- NetProfileDualTcp – This binding is just like the NetProfileTcp binding except it offers two way communication between client and service.
- NetProfileMsmq – The NetProfileMsmq binding provides queued communication in an all Indigo world. The NetProfileMsmq binding sends binary encoded messages between client and service using MSMQ as the transport.
- NetProfileNamedPipe – If your running your client and service on the same machine, and they’re both Indigo then the NetProfileNamedPipe binding is where it’s at. It provides an efficient cross-process communication using the named pipe transport.
If your building Indigo services you might want to check out the
Microsoft Federated Identity and Access Resource Kit. It provides several samples as well as a couple documents outlining how to implement Federated Identity using Indigo (WCF) and
InfoCard.
dasBlonde is posting some good
Indigo stuff over on her blog. I’ve just added her feed to my blog roll.
Update: As many of you probably guessed when you read this entry it ended up being a stupid user error. Yeah, me!
I’ve recently been experimenting with the netProfileTcpBinding in Indigo to see what kind of performance improvement it offers over the Http bindings. I’ve been able to host Indigo services from a console host application, however, I have not had any luck getting the same services hosted in Windows Services. I’m using the same hosting code within both applications as well as the exact same configuration. When I call my Indigo service hosted in my Windows Service I get the following error:
“A Tcp error (10061: No connection could be made because the target machine actively refused it) occurred while connecting.”
When I call the same service hosted in a console app everything is peachy. What are the differences between hosting Indigo services in a console host as opposed to a windows service host?
Clemens Vasters has a new article on MSDN providing an “
Introduction to Building Windows Communication Foundation Services”. As you might have found, I prefer the the pronunciation that Chris Anderson alluded to when he said…...”and for clarification, yes,
"WPF" is pronounced "Avalon"... the WPF is silent.” I like to think that can be applied to WCF as well. WCF is pronounced “Indigo”…the WCF is silent.
Jurgen Postelmans has posted a couple entries on handling errors in Indigo. It’s definitely worth keeping an eye on his blog for additional entries on the wonderful world of Indigo.