Tag Archive for WinFX

Problems I’ve encountered today when installing the WinFX January 2006 CTP

1)    Documentation Errors

When reading the documentation, I get scripting errors when accessing every page – a 80041001 script error, after which the page is readable but suffers from some layout issues. Oh, and occasionally it crashes.

 

According to this forum discussion, this is caused by an IE7 incompatibility with some of the content in the SDK. One solution is to downgrade IE, and the other is to switch to a newer CTP release (where some of the help content has been fixed). Since I am loathe to uninstall IE7 (which rocks) and I can’t upgrade the SDK to the Feb. CTP (since our project uses the January bits), I’ll just bite the bullet and live with the errors, and wait for the next IE7 beta drop which may fix it.

 

Resolution: None.

 

2)    Visual Studio extensions.

For some reason, after installing the SDK and the Runtime Components on my XPSP2 machine, I can’t get the Visual Studio extensions to install. It pops up an error dialog saying I don’t have the proper prerequisites and exits.

 

Resolution: Downloaded the extensions again from the Microsoft site. I suspect that the version I had wasn’t matched to the Jan CTP. The error didn’t indicate anything to that effect, but the filedate on it was March 2nd, so maybe it’s for the Feb. CTP.

           

3)    Merging help collections

The WinFX SDK installs a large set of help files that are accessible independently from the Start Menu folder. I was looking for a way to merge those help files with the Visual Studio Combined Collection, and ran into a wall. I found various references to the H2 help-file format and various tools to build these collections, but nothing to do this supposedly simple task.

And then I got the Developer Extensions working (see #2) and it’s supposed to do the work for me. Yay!

 

Resolution: Developer Extensions merge the help collections. You may be required to close and maybe kill all running DEXPLORE.EXE processes. You’ll probably have to close all Visual Studio instances. You might have to turn off the lights and wait in absolute silence. MSDN Library may take 3-4 years to recalculate its indexes when you start.  Eventually, though, you’ll be rewarded with having the WinFX documentation integrated so seamlessly into the MSDN Library that you repeat the process above again, thinking that nothing had happened. Hint: It’s under .NET Development -> .NET Framework SDK -> WinFX Development.

Adding custom headers to a WCF message – Jan CTP

Guy Burstein, again, writes about adding custom headers to a call made by a WCF proxy.
This is all very nice and well, but his code only works with the Feb. CTP of WCF, while I’m still using January here.
The differences seemed subtle at first – his instantiation of the OperationContextScope passed the proxy to the constructor, but there is no such constructor in the January CTP.
Simply instantiating the OperationContextScope with no parameters and adding headers seemed to work, but those headers never made it to the server-side.

After much fussing and digging, it turns out that the headers were transferred, but the way to fetch them was obscure. I don’t know if this was a design change from Jan to Feb or maybe it was just a bug that was fixed, but instead of accessing the headers like this:

string myHeader = OperationContext.Current.IncomingMessageHeaders.GetHeader(“myHeader”, “myNS”);

we have to do it like this:

string myHeader = OperationContext.Current.RequestContext.RequestMessage.Headers.GetHeader(“myHeader”, “myNS”);

Hope it helps.

Genericizing the GenericProxy

A few days ago, Guy Burstein wrote a entry on avoiding design-time generated proxies by extending the ClientBase class to create a GenericProxy. This proxy uses the client binding data in the app.config file to auto-create an appropriate proxy when the interface is shared by both client and server.

I gleefully lifted that piece of code for use in my emerging WCF project, but needed it a bit more generic than that. Seeing as I currently have no need for any fine-tuned configuration, I can get by with a GenericProxy that explicitly gets the Binding and EndpointAddress of the service in question. Since the ClientBase already supports this, I just have to make sure that my GenericProxy exposes this too:

public GenericProxy(Binding binding, EndpointAddress address)
            : base(binding, address)
{ }

Which now allows me to instantiate my proxy like this:

EndpointAddress address = new EndpointAddress(serviceUri);
Binding binding = new NetTcpBinding();
GenericProxy configurationProxy = new GenericProxy(binding, address);

As long as I don’t need any customizations beyond the basic binding and URI, I don’t need any configuration files whatsoever in my client.

Creating metadata from WCF executables

So I’ve started messing around with WinFX and WCF.
It certainly feels like it needs more work, especially on the dev-tool end of things.

I was trying to run SvcUtil to generate metadata and proxy from a console application and ran into this error message:
 
Error: There was an error exporting the ContractDescription loaded from the type
: Strawjackal.WCFTest.IService, MyService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
    Duplicate contract QNames are not supported.
Another ContractDescription with the Name: IService and Namespace:
Strawjackal.WCFTest has already been exported.

This was very confusing until I found this page here explaining that SvcUtil is simply broken when running on EXE assemblies. The original poster’s solution was to recompile his assembly as a class, but I’ve discovered that an even simpler solution is to just rename my EXE to a DLL, run SvcUtil against it, and rename it back.

WSDL created.
Me happy.

Serializing a Binding object – TimeSpan serialization error.

Seeing as our project is all distributed and stuff, with various services possibly running on different servers, we wanted to have the whole service address business be flexible, and not rely on hardcoded values in app.config files.
We have a Configuration service, which is the only hardcoded address, and it can return the address for any given service.

The item we’re using here is my own ServiceAddress object, which contains an EndpointAddress object and a Binding object for a given service. This way we can easily have a service switch from TCP to HTTP binding if necessary without redeploying. All is well.

The problem is that this configuration is stored on the Config server as an XML file with the ServiceAddress object serialized to XML. This means that the Binding object is also serialized to XML, and there lies the problem – the TimeSpan structure in .NET 2.0 cannot be serialized to XML. It loses all data and becomes an empty node, recreated as a 0-length TimeSpan when deserialized.
Since the Binding class has several TimeSpan properties for the timeout values, my service agents timeout immediately when attempting to contact the service.

Apparently the TimeSpan problem is a well-known one (here, there and everywhere), but the common workaround (of adding a new property with the TimeSpan’s Ticks value) isn’t really feasible a WinFX framework class.

I can extract and store the values manually during the serialization phase, but that seems ridiculously inelegant.
Another idea is to store the configuration files in the same format as they are defined in the app.config, and use the ClientSection class from System.ServiceModel.Configuration namespace to save and load the data. This is probably more complicated since I don’t know if I can generate a section from a Binding object. This means I can only read the configuration, not write to it from within my program.

Anyone have any other ideas?

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”);
            request.Headers.Add(
myHeader);
            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.
        }

        #endregion
               
        #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());
        }

        #endregion
    }

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.

[ServiceContract]
[CallContext]
public interface ILocalizationServices
{
   [OperationContract]
   [CallContext]
   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    
            OperationContextScope(standardContextObject))
{
   …
}

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)
      {
          contextScope.Dispose();
      }
    }     
 }

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?

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:

System.ServiceModel.CommunicationObjectAbortedException
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:
System.Net.SocketException
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.

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.

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);
    t.Start();
}

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.