November 2006 - Posts

Hunting for window handles
11-23-2006 11:08 AM

I am working on a fairy large WinForms project and after a certain build our application suddenly started crashing. Click, click, boem... gone.... no exception, no event log entry, nothing. The annoying part was that this didn't happened while executing inside the debugger, only when the testers were clicking around inside the application and even then very undeterministically.

If you get problems like this the first thing to do is to attach a event handler to the Application.ThreadException event to try to figure out who is causing this error:

Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

Inside this event handler you can basically do diagnostics to find out what exception is being raised by looking at the ThreadExceptionEventArgs parameter.

So in this case the exception was "Error Creating Window Handle"... exactly the kind of exception that scares me. As Julia Lerman writes in a blog-post:

”Error Creating Window Handle” is a Win32 error, therefore the first thing I should have been looking at was any code that did anything with unmanaged items.

And it just so happened to be that one of the changes that we made to the application involved some GDI+ brushes and stuff like that. The first thing I did was making sure every brush and bitmap was disposed after being used by including them in the using pattern. Unfortunatly that alone didn't help much.

The specific part where we were using GDI+ drawing was inside a renderer for a given tabcontrol from a third party product that we are using in this application. Our application also needs to clear this tabcontrol and re-create all the tabs again quite often (for instance when the user navigates to a new area).

My huntch was that somehow every time this tabcontrol was refilled again the old tabs were still floating around somehwere in memory and not being garbage collected, it turned out that I was right... after changing the code from simply doing a:

leftTabControl.TabPages.Clear();

...to removing and disposing each individual item...

foreach (TabPage tab in leftTabControl.TabPages)
{
    leftTabControl.TabPages.Remove(tab);
    tab.Dispose();
}

...the problem went away.

Hope this helps.

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }
Using generics to easy the pain of (xml) serialization
11-22-2006 1:55 PM

Sometimes it happens (especially when writing application frameworks) that you need to write a piece of code that needs to perform something as generically as possible. Being the OO guys that we are we tend to work a lot with polymorphism to accomplish this. Unfortunatly, polymorphism and xml serialization don't nescessarilly go hand-in-hand that well.

Say for instance that you have a class called Response which has has a derived class called DerivedResponse1:

public class Response
{
}
public class DerivedResponse1 : Response
{
}

Nothing fancy here. The code to serialize this DerivedResponse1 class would be something like the following:

void SerializeResponse(Response response)
{
    using (MemoryStream ms = new MemoryStream())
    {
        XmlSerializer ser = new XmlSerializer(typeof(Response));
        ser.Serialize(ms, response);
    }
}

Unfortunatly this doesn't work because the XML serializer complains about an error in the XML document (look at the InnerException to find out what the real error message is, which in this case is "The type DerivedResponse1 was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.")

To fix this you need to exactly what the error message sais and that is to add the XmlInclude attribute to the base type like this:

[XmlInclude(typeof(DerivedResponse1))]
public abstract class Response
{
}

Ok, now comes the part where you have 70 classes deriving from Response like I did... it would be very annoying to have to attach each and every class using the XmlInclude attribute. This was kind of the problem that I had.

What I did was create a generic 'helper' class that I used as a container for the Response object. The class looks very simple kind of like this:

public class SerializationContainer<T> where T : Response
{
    private MemoryStream ms = new MemoryStream();
    
    public T Instance;
    
    public SerializationContainer(T instance)
    {
        Instance = instance;
    }
    
    public void Serialize()
    {
        ms.Seek(0, SeekOrigin.Begin);
        
        XmlSerializer ser = new XmlSerializer(typeof(T));
        ser.Serialize(ms, Instance);
    }
    
    public void Deserialize()
    {
        ms.Seek(0, SeekOrigin.Begin);

        XmlSerializer ser = new XmlSerializer(typeof(T));
        Instance = (T)ser.Deserialize(ms);
    }
}

The trick here is that this is a generic type and each time the serializer is invoked it creates a new serialization assembly specific to the generic type (T) using which this type is created. This way the Response base-class doesn't need to know about all its descendants in order to be able to serialize itself. There is a performance penalty though, the Xml serializer will create a so-called serialization assembly for each generic type. Fortunatly there are ways to improve the Xml serializer's performance.

The real power of this approach becomes apparant when doing late instantiation of the generic parameter type (ie; not knowing the exact generic parameter type at compile-time).

I have created a small sample project to demonstrate this approach. You can download it here.

Hope this helps somebody.