Thanks to everyone that attended the WCF Data Services (OData) webinar.  Here are the WcfDataServicesIntro slides.

I promised I would report on the issue we ran into during one of the demos.  The first issue was Resource not found for the segment ‘Titles’.The reason that I wasn’t hitting it when I tested was because I was querying for a book already in the system.  However, The fix was very simple (after a Google search).  I needed to add:

context.IgnoreResourceNotFoundException = true;

There was one additional error that I encountered, which I did know about but I didn’t hit it until after I fixed the other error.  The enum property that I added was unable to be serialized back across the wire.  The simple fix was just to make those properties internal.  WCF Data Services only cares about public ones.  With that everything ran.

Here are the BooksDataService demos.

For the G.NET in Boston last week I needed to setup a demo for the WCF 4.0 Announcement and Discovery pieces. After sitting through the Parallel Task library talks I was inspired to try to come up with a way for the client to start trying to discover the service while at the same time the service is trying to announce itself. Whichever one finishes first is the one the client will use. I couldn’t actually get it done before the demo because I ran out of time, but I did manage to get it finished later. So here are the results.

First setup the service with an announcement behavior:

<system.serviceModel>
	<services>
		<service name="GenericService.GenericService"
			behaviorConfiguration="mex">
			<endpoint
				address=""
				binding="basicHttpBinding"
				contract= "Interface.IUniversalContract"/>
			<endpoint name="discoEp"
				kind="udpDiscoveryEndpoint" />
		</service>
	</services>
	<behaviors>
		<serviceBehaviors>
			<behavior name="mex">
				<serviceDiscovery>
					<announcementEndpoints>
						<endpoint kind="udpAnnouncementEndpoint"/>
					</announcementEndpoints>
				</serviceDiscovery>
				<serviceMetadata httpGetEnabled="true"/>
				<serviceDebug includeExceptionDetailInFaults="true"/>
			</behavior>
		</serviceBehaviors>
	</behaviors>
</system.serviceModel>

The tricky part is in the client:

First setup an announcement service so that we can hear when incoming announcement messages arrive.

Here is the field:

static TaskCompletionSource<EndpointAddress> tcsFound;

Here is the code to set it up:

tcsFound = new TaskCompletionSource<EndpointAddress>();

var announceSvc = new AnnouncementService();
announceSvc.OnlineAnnouncementReceived +=
	OnOnlineAnnouncementReceived;
announceSvc.OfflineAnnouncementReceived +=
	OnOfflineAnnouncementReceived;
var announceHost = new ServiceHost(announceSvc);
announceHost.AddServiceEndpoint(new UdpAnnouncementEndpoint());
announceHost.Open();

And the delegate which completes the task:

static void OnOfflineAnnouncementReceived(object sender, AnnouncementEventArgs e)
{
	Console.WriteLine("Service is now offline");
}
static void OnOnlineAnnouncementReceived(object sender, AnnouncementEventArgs e)
{
	Console.WriteLine("Service is now online");
	tcsFound.TrySetResult(e.EndpointDiscoveryMetadata.Address);
}

So that it one part. Now the other part is actively going out to find the service.

Here is the field:

static Task<EndpointAddress> findTask;

Here is the code to set it up:

findTask = new Task<EndpointAddress>(() => {
	EndpointAddress localAddress = null;
	do
	{
		localAddress = FindService();
	} while (localAddress == null);
	return localAddress;
});

And lastly the method to actually find the service…

private static EndpointAddress FindService()
{
	var discoProxy = new DiscoveryClient(new UdpDiscoveryEndpoint());
  	var fc = new FindCriteria(typeof(IUniversalContract));
  	FindResponse fr = discoProxy.Find(fc);
	discoProxy.Close();
  	int count = fr.Endpoints.Count;
	foreach (EndpointDiscoveryMetadata item in fr.Endpoints)
	{
		Console.WriteLine(item.Address);
	}
  	if (count > 0)
		return fr.Endpoints[random.Next() % count].Address;
	return null;
}

With those two pieces in play the only thing left is to call the service when either of the tasks completes first.

var tasks = new Task<EndpointAddress>[] { findTask, tcsFound.Task };
int index = Task.WaitAny(tasks);
EndpointAddress address = tasks[index].Result;
InvokeService(address);

I will leave the implementation of InvokeService up to the reader, but the rest of it is done – pretty sweet!

This was in the works for a long time, but today I gave a GeekSpeak talk on WCF Extensibility. The hosts were very nice. I have known Lynn for a while now, but it was great to finally meet Glen. Despite the fact that I was extremely nervous I only screwed up once :)

Here are the demos.

Another year, another San Diego Code Camp :) I signed up for this talk way in advance, and forgot to check up on it. There were a couple of presenters giving similar talks. What I tried to do was demo my way through WCF REST support, WCF Data Services, and WCF RIA Services, explaining what each one was and how it differed from the others. I had a *TON* of questions and so the talk ran a little long, and I didn’t get to do any of my RIA demos. I think I stopped after slide 15. However, I did have a couple people come up to me afterwords and say that my talk was there favorite talk of the whole code camp, so in that respect – mission accomplished! The room was jam packed standing room only, so thanks to everyone who came out.

Here are the Slides and Demos

I knew already that Amazon had two ways of calling their services. The first was by consuming the WSDL metadata and calling through SOAP, and the second was through REST. Of course the REST would be too cumbersome by itself but not to fear – there is a SDK which makes that easier from common languages like Java and .NET. But the SOAP should be brain dead simple to consume right? Wrong. After searching the forums for a while I figured out that somebody had managed to get it working through WSE 2.0 but nobody had managed to get it working from WCF. I thought to myself – “Self, I can’t allowed this to happen”. Myself agreed.

OK the first thing was to get it to work any way I could. While I was searching the forums I came across this post which describes how to call AWS using SOAPSonar. So I downloaded my trial edition and gave it a whirl.Using SOAPSonar enterprise I was able to add a certificate that I had saved earlier called ‘brainhz-cert.cer’ and call the service. Excellent. So now all I needed was to do this same task in WCF.

The first step was figuring out how they were securing their service. After looking through their docs I found a couple of helpful snippets.

  1. AWS does not implement a full public key infrastructure. The certificate information is used only to authenticate requests to AWS. AWS uses X.509 certificates only as carriers for public keys and does not trust or use in any way any identity binding that might be included in an X.509 certificate. Pasted from here.
  2. Amazon does not store your private key.  Creating a new certificate/private key pair invalidates your old one.  This only affects your X.509 key used to authenticate AWS requests.  It does not affect the ssh keypairs you use to log into instances (linux) or retrieve their password (windows). Pasted from here.
  3. The WS-Security 1.0 specification requires you to sign the SOAP message with the private key associated with the X.509 certificate and include the X.509 certificate in the SOAP message header. Specifically, you must represent the X.509 certificate as a BinarySecurityToken as described in the WS-Security X.509 token profile (also available if you go to the OASIS-Open web site). Pasted from here.

From this I was able to deduce that they were using the WSS SOAP Message Security X.509 Certificate Token Profile 1.0

I guessed that I needed to use Message based security with the Certificate credential type, but I double checked myself on the MSDN website.

WSS SOAP Message Security X.509 Certificate Token Profile 1.0

<basicHttpBinding>
  <security mode="Message">
    <message credentialType="Certificate"/>
  </security>
</basicHttpBinding>

Pasted from here.

I needed to specify which certificate I was going to use. It looked like I already had one in my Personal store (sometimes called the My store).

<endpointBehaviors>
	<behavior name="cert">
		<clientCredentials>
			<clientCertificate storeLocation="CurrentUser" storeName="My"
				 x509FindType="FindByThumbprint"
				findValue="6b 6a e8 ad b6 61 9c 1d a2 75 21 e4 4a d7 15 53 11 e6 72 27"/>
		</clientCredentials>
	</behavior>
</endpointBehaviors>

After adding that the next error that I ran into was this:
“The service certificate is not provided for target ‘http://ec2.amazonaws.com/’. Specify a service certificate in ClientCredentials.”

OK, so I needed the serviceCertificate. I used FireFox and hit https://ec2.amazonaws.com/ and saved the certificate. Then I imported it into my trusted people store.
Then I went in and added the following in my endpoint behavior:

<serviceCertificate>
	<defaultCertificate storeLocation="CurrentUser" storeName="TrustedPeople"
		x509FindType="FindByThumbprint" findValue="29 ca cd 8f 43 2e ff 31 f2 7f e5 70 e9 2e 1a f3 9e 1b f8 e8"/>
	<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/>
</serviceCertificate>

I had high hopes, before running this time, but no. The next error was:
“Private key is not present in the X.509 certificate”. When I looked at the certificate in the store, sure enough I did not see the “You have a private key that corresponds to this certificate” at the bottom.
Weird that it worked for SOAPSonar, but whatever. I went to Amazon, created and downloaded another certificate, combined the two and put them in my personal store. I then had to switch the certificate thumbprint to the one starting with 72 46.

After doing all of that I received a very strange error.
“Value (xmlenc#) for parameter Version is invalid. Version not well formed. Must be in YYYY-MM-DD format.”
WTF? I had never seen this one before, and I didn’t really know what sort of black magic was going on beneath me. So I turned on message level tracing, did some searching, and ended up trying two things:

  1. Switching the algorithmSuite from Default (Basic256), to (Basic128).
  2. Switching the OperationContract ProtectionLevel to Sign only.

WARNING: this is a HACK do not do this.
I went into the generated code into Reference.cs and changed the attribute on DescribeImages.

        [OperationContract(Action="DescribeImages", ReplyAction="*", ProtectionLevel=ProtectionLevel.Sign)]

Now fervently praying, I ran again. Bad news and good news.
Bad news was it didn’t work, good news was it was a message size issue, which I have fixed so many times in the past. Because we were using Message security I couldn’t turn on streaming. So I had to just up the maximum.
maxBufferSize=”9999999″ maxReceivedMessageSize=”9999999″

After cranking up the number high enough I got
System.ServiceModel.Security.MessageSecurityException occurred
Message=Security processor was unable to find a security header in the message. This might be because the message was an unsecured fault or because there was a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.

This was starting to make me mad. I was saying things that are unfit for children’s ears to my computer. After tracing, I discovered that this was related to the fact that Amazon messages are only secured one way.
The responses, or this response anyway, seemed to be unsecured. After some searching I found a hotfix for this issue in WCF.

http://support.microsoft.com/kb/971493

However, it required a customBinding. ARRGH!

Now the next step was to figure out which of the properties needed to be set so that it matched what I was doing before.
I created a program that created the two bindings, and compared the binding elements using reflection. The outcome of that program was the following binding declaration:

<binding name="customWithUnsecuredResponse">
	<security authenticationMode="MutualCertificate"
		 allowSerializedSigningTokenOnReply="true"
		 defaultAlgorithmSuite="Basic128"
		 messageSecurityVersion="WSSecurity10..."
		 enableUnsecuredResponse="true"
		 securityHeaderLayout="Lax"
		 />
	<textMessageEncoding />
	<httpTransport maxBufferSize="9999999" maxReceivedMessageSize="9999999" />
</binding>

I particularly liked the message security version which has to be high on the list of longest names in all of .NET. It was so long that I had to use ellipses because it was screwing up the CSS layout. The full name is (one piece at a time):
WSSecurity10
WSTrustFebruary2005
WSSecureConversationFebruary2005
WSSecurityPolicy11
BasicSecurityProfile10

Wow – what a mouthful…
Also notice the enableUnsecuredResponse = true, which was the cause of the problem.

After running one more time…

I bet the suspense is killing you…


IT WORKED!!!

I spent the next several minutes whooping it up. After having done it, I can honestly say that may be the only person in the world that has been stupid enough to try and get this working :)

I had a request to post the information on “the hack” that I presented in my demo this past weekend.

First a little bit about why I needed the hack in the first place. Recall that the goal was to get a single service to support both REST and SOAP. Yes I could have done this another way by simply having two separate services and factoring the common code into a shared assembly, but I liked the idea of them sharing the same base address. I had no problems implementing GET methods with the same interface. The problem arose when I wanted to support upload. In WCF when uploading files of arbitrary length you should probably implement streaming. Streaming requires the body of the message to consist of a single Stream object. Of course I also need to send over the name or title of the picture. In REST the name should be sent via the URL and in SOAP it needs to be a header. As it turns out this means I have to support two separate methods. So I factored a single interface into three: a common, a SOAP, and a REST version.

[ServiceContract]
public interface IPictureServiceCommon
{
  [OperationContract]
  [WebGet(UriTemplate = "titles")]
  string[] GetPictureTitles();</code><code>[OperationContract]
  [WebGet(UriTemplate = "{title}")]
  Stream GetPicture(string title);
}

[ServiceContract]
public interface IPictureServiceRest : IPictureServiceCommon
{
  [OperationContract]
  [WebInvoke(UriTemplate = "{title}", Method = "PUT")]
  void UploadPicture(string title, Stream picture);
}

[ServiceContract]
public interface IPictureServiceSoap : IPictureServiceCommon
{
  [OperationContract]
  void UploadPicture(FileMessage fileMessage);
}

Unfortunately WCF as it stands right now (in .NET 3.5 SP1) only supports turning Metadata on and off at the service level. So when I try to access the Metadata for the REST endpoint it ignores the URI Template aspect and tells me that I have an illegal method.

System.InvalidOperationException: For request in operation UploadPicture to be a stream the operation must have a single parameter whose type is Stream.

So that is where the hack came in as I needed to be able to turn off Metadata for a single endpoint. It turns out it was quite simple (although very hacky).

var host = new ServiceHost(typeof(PictureService));
// This is SUCH a HACK, but it works...
Assembly serviceModel = typeof(ServiceHostBase).Assembly;
Type type = serviceModel.GetType("System.ServiceModel.Description.ServiceMetadataContractBehavior");
var behavior = (IContractBehavior)Activator.CreateInstance(type, new object[] { true });

foreach (ServiceEndpoint ep in   host.Description.Endpoints)
{
  // apply the hack to all REST endpoints
  if (ep.Binding is WebHttpBinding)
    ep.Contract.Behaviors.Add(behavior);
  Console.WriteLine(ep.Address);
}
host.Open();

Just as you want to aspect out the functionality around the client calling a service, so you may also want to aspect out the functionality around a service receiving a call from a client. WCF already has something built in for this: the OperationInvoker. Although the OperationInvoker is an Operation level construct I wanted to be able to take it a step further and be able to turn these aspects on or off via the config file. Furthermore I wanted to be able to apply these behaviors at either the endpoint or the service level depending on what I was debugging. Specifically when I encountered an issue in the service not behaving correctly I wanted to be able to turn on logging or possibly performance counters to see what the problem was.

    As I have mentioned before: the three steps to WCF extensibility are here:
  1. Implement the interface you are trying to plug in (in my case IOperationInvoker)
  2. Author a behavior to replace the WCF functionality with your functionality written in step 1
  3. (optional) If you are plugging into the config file you will need to author a class that describes your config element
  4. (optional) If you are applying the behaviors programmatically consider creating a custom service host that automatically applies your behaviors

OK, so on to step 1:

class LoggingOperationInvoker : IOperationInvoker
{
	private static readonly ILog log = LogManager.GetLogger(typeof(LoggingOperationInvoker));
	readonly IOperationInvoker innerOperationInvoker;
	private readonly string methodName;
	private readonly bool writeInput;
	private readonly bool writeOutput;
	private readonly bool ignored;

	public LoggingOperationInvoker(IOperationInvoker innerOperationInvoker,
		string methodName, bool writeInput, bool writeOutput, bool ignored)
	{
		this.innerOperationInvoker = innerOperationInvoker;
		this.methodName = methodName;
		this.writeInput = writeInput;
		this.writeOutput = writeOutput;
		this.ignored = ignored;
	}

	public object[] AllocateInputs()
	{
		return innerOperationInvoker.AllocateInputs();
	}

	public object Invoke(object instance, object[] inputs, out object[] outputs)
	{
		if (!ignored && writeInput)
			LogUtils.LogMethodCall(log, methodName, inputs);
		// Invoke the operation using the inner operation invoker.
		object result;
		try
		{
			result = innerOperationInvoker.Invoke(instance, inputs, out outputs);
		}
		catch (Exception ex)
		{
			if (!ignored && writeOutput)
				LogUtils.LogMethodThrow(log, methodName, ex);
			throw;
		}
		if (!ignored && writeOutput)
			LogUtils.LogMethodReturn(log, methodName, result);
		return result;
	}

	public IAsyncResult InvokeBegin(object instance, object[] inputs,
		AsyncCallback callback, object state)
	{
		if (!ignored && writeInput)
			LogUtils.LogMethodCall(log, methodName, inputs);
		return innerOperationInvoker.InvokeBegin(instance, inputs, callback, state);
	}

	public object InvokeEnd(object instance, out object[] outputs, IAsyncResult asyncResult)
	{
		// Finish invoking the operation using the inner operation invoker.
		object result;
		try
		{
			result = innerOperationInvoker.InvokeEnd(instance, out outputs, asyncResult);
		}
		catch (Exception ex)
		{
			if (!ignored && writeOutput)
				LogUtils.LogMethodThrow(log, methodName, ex);
			throw;
		}
		if (!ignored && writeOutput)
			LogUtils.LogMethodReturn(log, methodName, result);
		return result;
	}

	public bool IsSynchronous
	{
		get { return innerOperationInvoker.IsSynchronous; }
	}
}

Notice that there are lots of variables in the constructor which let this particular operation invoker know what to log. We will talk about how all of this gets set in just a minute.

In order to get that plugged in to WCF we need to to implement a behavior (here an operation behavior).

public class LoggingOperationBehavior : Attribute, IOperationBehavior
{
	private readonly bool writeInput;
	private readonly bool writeOutput;
	private readonly ICollection<string> ignoredMethodNames;

	public LoggingOperationBehavior(bool writeInput, bool writeOutput, ICollection<string> ignoredMethodNames)
	{
		this.writeInput = writeInput;
		this.writeOutput = writeOutput;
		this.ignoredMethodNames = ignoredMethodNames;
	}

	public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
	{
	}

	public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
	{
	}

	public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
	{
		bool ignored = ignoredMethodNames.Contains(dispatchOperation.Name);
		dispatchOperation.Invoker = new LoggingOperationInvoker(dispatchOperation.Invoker, dispatchOperation.Name, writeInput, writeOutput, ignored);
	}

	public void Validate(OperationDescription operationDescription)
	{
	}
}

This step may be the easiest of the lot. We simply pass along the things we are constructed with and set the invoker.

On to step 3. I want to be able to plug this in to the config file at both the endpoint behavior and the service behavior level. Let’s start at the endpoint level. In order to plug into the config file at the endpoint level we need a endpoint behavior extension element. But the extension element is responsible for creating a behavior, and we don’t yet have an endpoint behavior. So we will have to create both, ugh!

public class LoggingEndpointBehavior : IEndpointBehavior
{
	private readonly bool writeInput;
	private readonly bool writeOutput;
	private readonly ICollection<string> ignoredMethodNames;

	public LoggingEndpointBehavior(bool writeInput, bool writeOutput, ICollection<string> ignoredMethodNames)
	{
		this.writeInput = writeInput;
		this.writeOutput = writeOutput;
		this.ignoredMethodNames = ignoredMethodNames;
	}

	public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
	{
	}

	public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
	{
	}

	public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
	{
		foreach (DispatchOperation dispatchOp in endpointDispatcher.DispatchRuntime.Operations)
		{
			bool ignored = ignoredMethodNames.Contains(dispatchOp.Name);
			dispatchOp.Invoker = new LoggingOperationInvoker(dispatchOp.Invoker, dispatchOp.Name, writeInput, writeOutput, ignored);
		}
	}

	public void Validate(ServiceEndpoint endpoint)
	{
	}
}

public class LoggingEndpointBehaviorExtensionElement : BehaviorExtensionElement
{
	private const string WriteInputPropertyName = "writeInput";
	private const string WriteOutputPropertyName = "writeOutput";
	private const string IgnoredMethodNamesPropertyName = "ignoredMethodNames";

	public override Type BehaviorType
	{
		get { return typeof(LoggingEndpointBehavior); }
	}

	protected override object CreateBehavior()
	{
		var listIgnoredMethods = (ICollection<string>)IgnoredMethodNames.Split(',');
		return new LoggingEndpointBehavior(WriteInput, WriteOutput, listIgnoredMethods);
	}

	[ConfigurationProperty(WriteInputPropertyName, DefaultValue = true)]
	public bool WriteInput
	{
		get { return (bool)base[WriteInputPropertyName]; }
		set { base[WriteInputPropertyName] = value; }
	}

	[ConfigurationProperty(WriteOutputPropertyName, DefaultValue = true)]
	public bool WriteOutput
	{
		get { return (bool)base[WriteOutputPropertyName]; }
		set { base[WriteOutputPropertyName] = value; }
	}

	[ConfigurationProperty(IgnoredMethodNamesPropertyName, DefaultValue = "")]
	public string IgnoredMethodNames
	{
		get { return (string)base[IgnoredMethodNamesPropertyName]; }
		set { base[IgnoredMethodNamesPropertyName] = value; }
	}
}

You can see that the EndpointBehavior is basically the same as the OperationBehavior, but because we start at a higher level (the endpoint) we have to dig a little deeper to get to the individual operations. The LoggingEndpointBehaviorExtensionElement allows the WriteInput, WriteOutput and IgrnoredMethods names be set correctly in the config file.

I will leave it as an exercise to the reader to implement the service behavior, but it is almost exactly like the other two.

The last thing that I want to do is show you how to turn these things on and off from the config file. Here is an excerpt from the system.serviceModel section

		<extensions>
			<behaviorExtensions>
				<add name="logEndpointCalls" type="Interface.LoggingEndpointBehaviorExtensionElement, Interface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
			</behaviorExtensions>
		</extensions>
		<services>
			<service name="Service.MyService">
				<endpoint address="" behaviorConfiguration="log"
                  		binding="netTcpBinding"
                  		contract="Interface.IService" />
			</service>
		</services>
		<behaviors>
			<endpointBehaviors>
				<behavior name="log">
					<logEndpointCalls />
				</behavior>
			</endpointBehaviors>
		</behaviors>

That’s it, happy WCFing…

I love Aspect Oriented Programming. The idea of centralizing the code of a specific nature (logging, performance counting/monitoring, exception handling, etc.) is very compelling form a clean code point of view. WCF allows me to get this "for free". I have been aspecting out my calls to WCF services for a while now, but I recently discovered a better way that allows for type safety and intellisense.

The calls used to look like this:

helper.CallService("GetSamplesByState", state);

But they now look like this:

helper.CallService(p => p.GetSamplesByState(state));

Here is the code with the changes highlighted:

using System;
using System.Reflection;
using System.ServiceModel;

namespace Common.Utilities
{
    public class CommunicationHelper<T> : IDisposable
        where T : class
    {
        ChannelFactory<T> factory;
        T channel;

        public CommunicationHelper(string channelName)
        {
            using (TimedLock.Lock(factory))
            {
                factory = new ChannelFactory<T>(channelName);
            }
        }

        public string Address
        {
            get
            {
                using (TimedLock.Lock(factory))
                {
                    return factory.Endpoint.Address.ToString();
                }
            }
        }

        private void EnsureChannelCreated()
        {
            using (TimedLock.Lock(factory))
            {
                if ((channel == null) ||
                    (((IClientChannel)channel).State == CommunicationState.Faulted))
                {
                    channel = factory.CreateChannel();
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                using (TimedLock.Lock(factory))
                {
                    factory.Close();
                }
            }
        }

        public void CallService(string methodName, params object[] args)
        public void CallService(Action<T> handler)
        {
            CallServiceInternal(methodName, args);
            CallServiceInternal(handler);
        }

        public TReturnType CallService<TReturnType>(string methodName, params object[] args)
        public object CallService(Func<T,object> handler)
        {
            return (TReturnType)CallServiceInternal(methodName, args);
            return CallServiceInternal(handler);
        }

        internal object CallServiceInternal(Delegate handler)
        {
            object returnObj = null;

            try
            {
                EnsureChannelCreated();
                try
                {
                    if (factory != null)
                    {
                        using (TimedLock.Lock(factory))
                        {
                            MethodInfo methodInfo = typeof(T).GetMethod(methodName);
                            returnObj = methodInfo.Invoke(channel, args);
                            returnObj = handler.DynamicInvoke(channel);
                        }
                    }
                }
                catch (TargetInvocationException e)
                {
                    throw e.InnerException;
                }
            }
            catch (FaultException)
            {
                throw; // don't want to catch FaultExceptions which are a subclass of CommunicationException
            }
            catch (CommunicationException e)
            {
                throw new CommunicationHelperException(e.Message, e);
            }
            catch (TimeoutException e)
            {
                throw new CommunicationHelperException(e.Message, e);
            }

            return returnObj;
        }
    }
}

I presented my first code camp talk this weekend and it was a great experience. Here are the talks I attended:

Day 1

A Technical Drilldown into Microsoft’s ESB Guidance
by Brian Loesgen

Agile Programming
by Llewellyn Falco & Carl Manaster

Lunch

Fixing Legacy Code
by Jason Kerney & Llewellyn Falco

Aspect Oriented Programming in .NET, an Introduction with ASPECT.NET
by Adnan Masood

Agile Coding Techniques for Legacy Apps
by Woody Zuill

Dynamic Languages and the DLR
by Mike Vincent

Day 2

Integrating Silverlight 2.0 into an Existing Web Application
by Robert Altland

Creating Cmdlets for PowerShell
by Steve Evans

Windows Workflows (300 Level)
by Mark Bosley

Overview of the Composite Application Guidance for WPF
by Adam Calderon

Followed by my session on WCF Advanced Topics…

I was amazed and dismayed at the number of presenters who did nothing but show slides. Here is some advice that I can offer newbie speakers

  1. Tell a story
  2. Use something besides just powerpoint (use the whiteboard, do some demos, etc)

I just finished a huge WCF teaching tour. I was teaching every other week for several months. During that time I finally realized the best way to teach WCF extensibility.

But first some background. There are two types of extensibility in WCF – channel layer extensibility and service model extensibility. At the channel layer you are dealing explicitly with messages. There are only two reasons why you might want to write a channel:

  1. You need to create a new way of transporting the bits to the other process. For example you might want to create a file channel, that uses file sharing to move the bits across, or a UDP channel. BTW – you can find samples for doing both of those things, so don’t reinvent the wheel.
  2. You need a single outgoing message to result in more than one outgoing message. Most of the protocol channels fall into this category: security, transactions, reliable messaging, chunking, etc.

That’s it. There are no other valid reasons. The channel layer is more complicated than the service model layer, and more difficult to get right, so avoid it when you can.

With that out of the way, let’s focus on the other type of extensibility – service model extensibility. At this layer its hard to understand why it is so complicated. It all goes back to the WCF design goal – To be the single best way of getting any two pieces of software to communicate under any circumstances. In other words the WCF team has to support not only any known way of communicating, but any unknown way of communicating as well. Not just any way that exists now, but any way that might ever be invented. With a design goal like that you have to be REALLY flexible. And with flexibility comes the lesser liked ugly cousin – Complexity.

So the way extensibility at the service model layer works is like this. You have to author two classes. One is the actual functionality that you are trying to provide, and the other is used to plug that into the WCF plumbing (more about that later).

So for the first class what functionality can be extended? Well, there are so many hooks in WCF that it would be impossible to list them all, but some of the interfaces you might need to implement are listed here (courtesy of MSDN)

Interface Description
ICallContextInitializer Defines the methods that enable the initialization and recycling of thread-local storage with the thread that invokes user code.
IChannelInitializer Defines the interface to notify a service or client when a channel is created.
IClientMessageFormatter Defines methods that are used to control the conversion of messages into objects and objects into messages for client applications.
IClientMessageInspector Defines a message inspector object that can be added to the MessageInspectors collection to view or modify messages.
IClientOperationSelector Defines the contract for an operation selector.
IDispatchMessageFormatter Defines methods that deserialize request messages and serialize response messages in a service application.
IDispatchMessageInspector Defines the methods that enable custom inspection or modification of inbound and outbound application messages in service applications.
IDispatchOperationSelector Defines the contract that associates incoming messages with a local operation to customize service execution behavior.
IErrorHandler Allows an implementer to control the fault message returned to the caller and optionally perform custom error processing such as logging.
IInputSessionShutdown Defines the contract that must be implemented to shut down an input session.
IInstanceContextInitializer Defines the methods necessary to inspect or modify the creation of InstanceContext objects when required.
IInstanceContextProvider Implement to participate in the creation or choosing of a System.ServiceModel.InstanceContext object, especially to enable shared sessions.
IInstanceProvider Declares methods that provide a service object or recycle a service object for a Windows Communication Foundation (WCF) service.
IInteractiveChannelInitializer Defines the methods that enable a client application to display a user interface to collect identity information prior to creating the channel.
IOperationInvoker Declares methods that take an object and an array of parameters extracted from a message, invoke a method on that object with those parameters, and return the method’s return value and output parameters.
IParameterInspector Defines the contract implemented by custom parameter inspectors that enables inspection or modification of information prior to and subsequent to calls on either the client or the service.

Pasted from here

However, it is the second class is really the focus of this blog entry. This class is responsible for plugging the first class into WCF. You can extend WCF at three different levels, as shown in the diagram below. At the innermost level in red you can extend WCF for a single operation. You can also effect an entire endpoint (shown in purple), or even the entire service consisting of all endpoints.

Let me back up for just a second. The WCF service model extensibility is very similar to the extensibility model of you car. You open up the hood, then you can add parts, remove parts, change one part for another, but you have to know exactly what you are doing. Then you close the hood and use the newly altered engine to actually drive the car. So although it is not exactly easy, if you have seen a show like “Pimp My Ride”, you know there is nothing you can’t do. The same is true of WCF. WCF calls your behavior and it passes your behavior the “engine” at the place you trying to extend it. You alter the plumbing in any way you want, and then WCF uses the plumbing you have altered to actually run your service / endpoint / operation.

So if I am implementing an IServiceBehavior in the ApplyDispatchBehavior method I get a ServiceHostBase class which I can manipulate in any way I see fit. Actually I get two pieces of information. The first is the description of what should happen or the “manual”, and the second is the engine.

public interface IServiceBehavior
{
	void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase);
	// other members elided for clarity...
}

After the ApplyDispatchBehavior is called and my behavior has altered the ServiceHostBase, WCF uses the altered ServiceHostBase to “drive” my service.

Similarly for IEndpointBehavior in both the ApplyClientBehavior and the ApplyDispatchBehavior I get the WCF description and the plumbing for an endpoint.

public interface IEndpointBehavior
{
	void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime);
	void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher);
	// other members elided for clarity...
}

The same is true for an Operation.

public interface IOperationBehavior
{
	void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation);
	void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation);
	// other members elided for clarity...
}

The last part of the extensibility mechanism is how WCF actually finds out about the behavior that you wrote in step 2. This can be done in one of three ways: by applying an attribute, by programmatically adding the behavior (i.e. host.Description.Behaviors.Add) or by authoring a third class which inherits from BehaviorExtensionElement that describes what your behavior’s XML element can contain.