Tag Archive for WCF

Context-Bound Thread Queuer – FunFun.

As I mentioned in my previous post, I have a need to consistently pass an operation context to any thread I choose to spin. Doing so manually, as I did here, involves a lot of ugly, repetitive code for every thread. A lot of room for mistakes and bugs.
So using the power that .NET delegates give us, I’ve built a generic Context-bound threadpool queue class to wrap this logic for me.

This class has two methods – the first (executing on the originator thread) wraps the call to ThreadPool.QueueUserWorkItem, passing it my operation context and details on what to execute on the new thread. The second is launched on the new thread, sets its own context to the parameter and invokes the requested method.

Using delegates and the params statement, we can have this work for any delegate taking any number of arguments. Naturally, since this executes on a different thread, there’s no point in having the delegate have a return value.

public void QueueDelegate(Delegate function, params object[] parameters)
    ParameterStruct param;
    param.Context = OperationContext.Current;
    param.Function = function;
    param.Parameters = parameters;

    ThreadPool.QueueUserWorkItem(Launcher, param);

private void Launcher (object state)
    ParameterStruct param = (ParameterStruct)state;
    OperationContext.Current = param.Context;

Notes and warning:

  • To allow any number of arguments to pass through, my method takes a params object[] argument. This means that calling our delegate through the context-bound threadqueue is inherently NOT typesafe. There are no checks made to ensure the given parameters match the delegate. This can be added manually using reflection, but I decided to leave it out.
  • This class will spin threads from the threadpool. It can be easily adapted to start custom threads using Thread.Start(), and this can even be passed as a parameter. I’ll leave it as an exercise for whomever feels like doing it.
  • This code was written to pass WCF’s OperationContext object to a new thread. It can be used to transfer anything else with very little modification. With a bit of work, you can write it so it can transfer anything you tell it to.

Using this class is as easy as calling the ThreadPool methods. The main difference is that instead of having a method that matches the WaitCallback delegate, we can pass in any delegate we want

public delegate void MyCustomDelegate(int param1, string param2);
public void MyCustomMethod (int param1, string param2)
      // Do work;

public void Main ()
   ContextThreadQueuer.QueueDelegate(new MyCustomDelegate(MyCustomMethod, 5, “whoo!”);

Note that because we use the base System.Delegate object as a parameter, we have to implicitly call “new MyCustomDelegate()” and can’t have the compiler automatically infer the delegate type.

 The full code and usage sample can be found here. Enjoy.

OperationContext is ThreadStatic

WCF Services tend to be big, heavy duty things. When I write a service I often want it to do a lot of work for a lot of clients, and it should do it efficiently. This usually means that I will use multithreaded code to get things done concurrently. Whether using the ThreadPool or instantiating a thread of my own, I expect this is a common scenario for WCF service writers.

That’s why I was suprised today to find out that the OperationContext of the current service call, our entry point for getting context information about the current call, its headers and so forth – is marked as [ThreadStatic]. This means that the moment I fork off to another thread, I lose all context information. If I want it available, I have to do it myself.

I don’t know how ASP.NET deals with this problem. If I spin a new thread under ASP.NET, I don’t lose my current HttpContext. A quick glance with Reflector shows that there’s no [ThreadStatic] anywhere. Whatever features of IIS they use there, it’s probably unavailable for WCF, so we have to do it manually.

The simplest way to pass the context to a thread is just to send it as a parameter:

void Method ()
    ThreadPool.QueueUserWorkItem(ThreadMethod, OperationContext.Current);

void ThreadMethod(object state)
    OperationContext.Current = state as OperationContext;
    // Do whatever.

Side note: Note the automatic delegate inference that .NET 2.0 does, rather than forcing me to manually create a WaitCallback delegate:
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), OperationContext.Current);
I don’t think this was possible in v1.1.

If we want to spin a thread of our own, we can use the ParameterizedThreadStart delegate:

void Method ()
    Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod), OperationContext.Current);

If we have parameters to pass to our method, though, we need to be even hackier – maybe define a struct or class to hold our OperationContext as well as the custom parameters, and pass that on to the ThreadMethod and have it disassemble it.

There is a better way to build a Thread Launcher than can pass the ObjectContext. I’ll elaborate on that in my next post.

Share your interfaces – avoid static proxies.

When using WCF services, we have several options for creating the proxies. We can create them statically using SVCUTIL or the build-in IDE support (Add Service Reference…), or we can generate them dynamically using the ChannelFactory or GenericProxy approaches.

The advantage of the static proxy approach is that it we local code for us based on remote metadata (WSDL). Even if the service is somewhere out of our reach and control, all we need is for it to expose metadata for us to access it. We get a copy of the service contract and interfaces and we’re good to go.
The problems with it is that I have to maintain that proxy. If the service changes, our proxy needs to adapt too. I’m not referring to versioning issues and new methods added, but to big changes in the service contract itself. This may not be an issue when accessing stable services, but certainly happens a lot during development.

The second approach is much more limited – for it to work we need to have a reference to a shared assembly containing the contracts. It means our services and contracts are .NET classes using the WCF framework, rather than generic WS-* services that can have any implementation. This approach is only useful when we have access to the our services’ code or assemblies, so it’s out of the question for public services.
In short, the dynamic proxy approach is only for use when we control both client and server in the scope of a single application (or group of familiar applications).

But in this context, this is the best way to work. I’ll stress the point again – if we meet all the criteria above for using dynamic proxies, we should use them without hesitation.
The amount of work that goes into maintaining the static proxies, making sure that the client and server copies of the contracts are identical, hours of debugging mysterious errors caused by contract mismatches – all with perplexing error messages and little documentation – all these things are simply not worth it.

I’ll say it again – if you’re writing an N-tier application that uses WCF for communication, have the contracts shared by both client and server and use the GenericProxy class to access it rather than relying on generated proxies and SVCUTIL. Trust me. Your deadline will thank you for it.

Deperplexing WCF errors pt. 3 – Interfaces and KnownTypes

Another error message that stumped me today (after I had removed the IsOneWay parameter and actually got to see it) was the following exception:

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error

This little gem was caused when calling a method on a service with an interface as a parameter, something like this:

void DoSomething (IMessage message)

When deserializing the IMessage, WCF had no way of knowing what type to deserialize it as, so it through the charming message above.
I don’t know how this situation came to be, since the proxy generated by svcutil seems to create the message as DoSomething(object message) and not IMessage, but the principle should be the same.

The immediate solution that fixed this was adding the [KnownType(typeof(myMessage))] attribute to the method. This allows the deserialization engine to understand the message and do something constructive with it rather than crashing.

Naturally, I am less than pleased with this solution. The whole purpose of using interfaces is that I won’t have to know, when coding, what objects will be passed to my service. I just want to expose the interface.

One way to keep this flexibility can be found in the very last paragraph of the long and detailed Data Contract Known Types article on MSDN – it seems that the list of Known Types can be defined globally in the system using the section in the config file. Details about that are also sparse, and I’m not at all sure if it’s possible in the January CTP – the section names seem to have changed from to between January and February, and there are no samples to explain the proper structure for the January version. I hope this gets clearer with the next beta.

Deperplexing WCF errors pt. 2 – IsOneWay swallowing exceptions

The first step in understanding WCF error messages is making sure you actually get them.

You can have an OperationContract defined with the IsOneWay parameter set to True, thus optimizing it by not requiring a reply message.
Since faults and exceptions are represented as replies to the message sent, however, setting IsOneWay to true will cause WCF to simply swallow the exception and not report it – as far as the framework is concerned the message was sent successfully and that’s it.

If you want to use the IsOneWay optimization, it’s best to save it for later parts of development, after the basic debugging work is done.

Deperplexing WCF errors pt. 1 – CommunicationObjectAbortedException for security mismatch

As a follow-up to this post: another reason why we get CommunicationObjectAbortedExceptions is because our client channel definition does not send any credentials (using a binding that has the SecurityMode set to None) while the service is still set to the default settings, expecting Windows authentication. Rather than throwing some sort of SecurityException, the exception is raised.
Just a heads up.

Indigo Errors Perplexing

I was writing a very simple WCF service. Nothing fancy – just returning an array of structs via TCP, just like 3 others already implemented. Started testing, stepped through the server code, returned the value from the service interface, then WHAM – a big scary exception:

The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue.

Inner Exception:
An existing connection was forcibly closed by the remote host

This rather scary error message is not very helpful. Was it because of a timeout? (Unlikely, as it happened immediately). Underlying network resource issue? Happens too predictably. Error processing your message? What does that mean, anyway? WHAT error processing my message? And anyway, the inner SocketException seems to imply that it’s a network error, not a message error.

But of course it is. WCF didn’t really point me towards it, but it seems I had forgotten to mark my struct as a [DataContract] and its members as [DataMember]s. No contract, nothing to serialize, no message.

Perfectly understandable, once you know what’s going on. Totally perplexing until you do.

Now let’s give this entry some Googlejuice so people who are experiencing this problem can find it:
WCF, Indigo, CommunicationObjectAbortedException,  SocketException, DataContract.
There. That should do it.

Adding custom headers to every WCF call – a solution

At last, a solution presented itself. While I must admit that at first I was very skeptical of the extensibilty model for WCF which seemed far too involved and complicated, but after implementing a simple extension I must say it’s simple and quite intuitive.

My goal was to have several custom headers added to each call made through a proxy, rather than manually adding them to each call’s OperationContext. With a little help from Ralph Squillace’s blog, I was able to get an extension up and running within minutes, and it Just Works.

The first item to build is the actual extension logic. In this case, I needed an IProxyMessageInspector object that inspects each outgoing message and adds the custom headers:

public class ContextPusher : IProxyMessageInspector
        public void AfterReceiveReply(ref Message reply, object correlationState)
            // Do nothing.

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
            MessageHeader myHeader = new MessageHeader(“HeaderValue”).GetUntypedHeader(“MyHeader”, “ns”);
            return null;

Now we want to attach that inspector to proxy. We do that wth Behavior objects. This can be done on an operation-by-operation basis or for all operations on a given channel. We can make the same class implement both behaviors, for flexibility:

public class CallContextAttribute : Attribute, IChannelBehavior, IOperationBehavior
        #region IOperationBehavior Members

        public void ApplyBehavior(OperationDescription description, ProxyOperation proxy, BindingParameterCollection parameters)
            // Add my MessageInspector to each message sent by the proxy.
            proxy.Parent.MessageInspectors.Add(new ContextPusher());

        public void ApplyBehavior(OperationDescription description, DispatchOperation dispatch, BindingParameterCollection parameters)
            // No server-side behaviors for now.

        #region IChannelBehavior Members

        public void ApplyBehavior(ChannelDescription description, ProxyBehavior behavior, BindingParameterCollection parameters)
            // Add the MessageInspector to every message sent through the channel.
            behavior.MessageInspectors.Add(new ContextPusher());


And then simply put it on a Service or Operation.
I think in this case, putting the attribute on both will result in an error when trying to add duplicate headers. But this allows me flexibility in adding the headers only to certain calls.

public interface ILocalizationServices
   string DoSomething(string param);

I think this is the first time I got really excited by the WCF framework and the ease of using and extending it. This is FUN.

How do I add a custom header to every WCF message?

One thing I still haven’t managed to do is create my proxy in such a way that a custom header is added to every call that is made through that proxy.
Currently, this is done by instantiating a new OperationContext around each call through the proxy. This can be optimized in several ways:
1) Create a shared OperationContext object and always instatiate the OperationContextScope with it:
using (OperationContextScope scope = new    

I don’t know if it’s a good idea, though. Should OperationContext objects be persisted between calls, or would it have unexpected side effects?

2) Create a wrapper around the OperationContextScope class that fills the OperationContext with the proper headers:

public class MyOperationContextScope : IDisposable
   OperationContextScope contextScope;

   public MyOperationContextScope ()
      contextScope = new OperationContextScope();
      MessageHeader standardHeader = new   
      MessageHeader(“StringHeaderValue”).GetUntypedHeader(“StringHeader”, “ns”);
      OperationContext.Current.OutgoingMessageHeaders.Add(standardHeader );

    public void Dispose()
      if (contextScope != null)

This is a bit cleaner, but still requires me to wrap every proxy call with a using() statement.

Is there a way to interecept all calls and have my headers added automatically?