Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations

May 2006 - Posts

From Accessors to Properties

For various debugging processes, I find myself needing to find several bits of runtime information for my properties. This means I want to get the property's PropertyInfo object by Reflection when that property's code is running.

The problem is that Properties are C# constructs, not IL constructs. My property's get accessor is actually compiled into a get_MyProp() method. This means that while I can easily get the MethodInfo for the current accessor, there doesn't appear to be any easy way of getting the PropertyInfo from the MethodInfo.

The ugly way, of course, is to take the method's name, strip the first four characters from it and do a GetProperty() with that name - and that works, of course, but causes me actual physical pain to use:

PropertyInfo prop = accessorMethod.ReflectedType.GetProperty(accessorMethod.Name.Remove(0, 4));

Is there a better, simpler way I'm missing?

Posted: May 31 2006, 03:02 PM by AvnerK | with 4 comment(s)
Filed under: ,
Serializing Dictionaries

Dictionaries have been an annoyance when serializing for a while now. IDictionary in v1.1 and now IDictionary<K,V> in v2.0 are both non-serializable, forcing us to find workarounds or use DataTables or any number of unsatisfactory solutions.

My guess is that is has something to do with the whole buckets/hashcode implementation. If we serialize a dictionary and then deserialize it on a different machine or process, the keys might have a different hashcode - the default hashcode for a reference type is its reference pointer, AFAIK - and the dictionary will be corrupted.

A quick solution for this is to transform the dictionary into a collection of KeyValuePairs, which is a non-hashed straightforward array, and serialize and deserialize that. This means the hashing algorithm runs again when we deserialize, building the new dictionary from scratch.

Usage is then simple:

DictionarySerializer<string, int> serializer = new DictionarySerializer<string,int>();
serializer.Serialize(myDictionary, myStreamWriter);

When implementing this, it turned out that while KeyValuePair<K,V> is marked as Serializable, it actually isn't possible to meaningfully serialize it. This is due to its Key and Value members being read-only, and the XmlSerializer only serializing public members. (More information here).
Due to this, I simply implemented my own internal SerializableKeyValuePair<K,V> struct and use that instead.
The Serialize method now looks something like this:

public void Serialize (IDictionary<K,V> dictionary, StreamWriter serializationStream)
   List<SerializableKeyValuePair<K,V>> dictionaryItems = GetKeyValueList(dictionary);
   XmlSerializer ser = new XmlSerializer(typeof(List<SerializableKeyValuePair<K,V>>));
   ser.Serialize(serializationStream, dictionaryItems);

Deserialization will follow logically:

public IDictionary<K,V> Deserialize (StreamReader serializationStream)
   XmlSerializer ser = new XmlSerializer(typeof(List<SerializableKeyValuePair<K,V>>));
   List<SerializableKeyValuePair<K,V>> dictionaryItems = ser.Deserialize(serializationStream) as List<SerializableKeyValuePair<K,V>>;

   IDictionary<K,V> dictionary = new Dictionary<K,V>(dictionaryItems.Count);
   foreach (SerializableKeyValuePair<K,V> item in dictionaryItems)
      dictionary.Add(item.Key, item.Value);
   return dictionary;

The problem with making this totally generic is that the serializer can receive a Stream, a TextWriter or an XmlWriter - three classes that do not share any common ancestor. This means we have several overloads doing exactly the same only with different types. A shame.

I've attache the full class for this, slightly more refactored than what I have here. Enjoy.

Posted: May 23 2006, 02:18 PM by AvnerK | with 17 comment(s) |
Filed under: ,
Bad compiler warnings when using anonymous methods for Predicate<T>

I was sitting around munching some code, and needed to filter a list I had:

List<Whatever> list = // get list

outputList = list.FindAll(delegate(Whatever item)
   if (// blah blah)
      return true;
   return false

(Ignore the greyed-out text for now).

When compiling, I got a strange error message:
"cannot convert from 'anonymous method' to 'System.Predicate<Whatever>'".

This put me off for a few minutes while I tried checking code samples and such to make sure that this really SHOULD work. Only when I tried explicitly casting the anonymous delegate to a Predicate<Whatever> did I get a proper compiler error:
'System.Predicate<Whatever>': not all code paths return a value'

Turns out my actual syntax error was being caught by the compiler and incorrectly reported.

Just a heads-up, in case it happens to anyone else.
Ladybug bug ID is FDBK50271, if anyone cares.

Posted: May 22 2006, 09:33 PM by AvnerK | with 21 comment(s)
Filed under: ,
Creating nested directories

Just a quick tip to prevent others from feeling as foolish as I do:

The static CreateDirectory() method of the System.IO.Directory class will create the entire directory tree passed to it. There's no need to write an EnsurePathExists() method that recursively creates the folders. Absolutely no need. Not even just to be safe. It works. Trust me. Trust the framework. The framework is your friend.

[This has been a public service announcement by the Society for the Reinvention of the Wheel]

Posted: May 22 2006, 01:30 PM by AvnerK | with 1 comment(s) |
Filed under:
Non-generic default values in C#? Why not?!

A relatively obscure new keyword in C# 2.0 is the default(T) keyword.
It's shorthand for checking if the given generic parameter T is a value type or reference type. If it's a reference type, it returns null. Otherwise it returns 0/false/0.0 or whatever the default value for the type is.

For some reason, though, it can only be used on generic parameters. Why can't I use default(typeof(int)) to get 0? Or, more realistically, default(myUnknownType) to return the default value?

A workaround is to check if it's a value type with reflection, but it's cumbersome:

if (!myType.IsValueType)
   return null;
   return Activator.CreateInstance(myType);

Luckily, value types (including structs) always have a default parameterless constructor. We can't even override it - it will always initialize all struct members to their default values.

This little code snippet can now be wrapper in some sort of function - call it Default() or GetDefault() or even @default() if you want to keep it as close as possible to the generic keyword.

It's interesting to note that the generic keyword relies on the InitObj IL opcode to initialize the object. If we could embed IL directly in our code we could call this directly. We can do it via Reflection.Emit and DynamicMethods but I feel that's going a bit far overboard when the solution above works just as well.

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<T> or GenericProxy<T> 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<T> class to access it rather than relying on generated proxies and SVCUTIL. Trust me. Your deadline will thank you for it.
Posted: May 17 2006, 03:24 PM by AvnerK | with 5 comment(s)
Filed under: , ,
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.
Posted: May 16 2006, 03:28 PM by AvnerK | with 2 comment(s)
Filed under: , ,
More Posts Next page »