views:

30

answers:

1

I have a class that is able to serialize and deserialize with ease after my WPF application has loaded. I am now trying to add in the ability to load a project on startup when passing in the project file. Unfortunately, it is throwing an InvalidOperationException stating:

There is an error in XML document (2, 2). ---> System.InvalidOperationException: <WeightingParametersBit xmlns=''> was not expected.

The WeightingParametersBit is the type of a member of the class I am trying to serialize. It is basically just a container for a Dictionary. The odd thing is, the file does not contain a tag for <WeightingParametersBit xmlns=.... anywhere in the file. Once this exception is thrown and the application starts. If I click the load button and select the same project file, it loads up just fine.

Here is the class I am trying to serialize (small container class):

public class WeightSettings
{
    public double UserScoreSlagging;
    public double UserScoreFouling;
    public WeightMode BitWeightMode = WeightMode.Manual;
    public WeightMode LigWeightMode = WeightMode.Manual;
    public WeightingParametersBit BitWeights = new WeightingParametersBit();
    public WeightingParametersLig LigWeights = new WeightingParametersLig();
}

And here is the xml it generates (trimmed down for viewing purposes):

<?xml version="1.0" encoding="utf-8"?>
<WeightSettings>
    <UserScoreSlagging>0</UserScoreSlagging>
    <UserScoreFouling>0</UserScoreFouling>
    <BitWeightMode>Manual</BitWeightMode>
    <LigWeightMode>Manual</LigWeightMode>
    <BitWeights>
        <bituminous>
            ...
        </bituminous>
    </BitWeights>
    <LigWeights>
        <lignitic>
          ...
        </lignitic>
    </LigWeights>
</WeightSettings>

My generic serialize code:

public static void Serialize<T>(this T source, TextWriter writer)
{
    // Don't serialize a null object
    if (Object.ReferenceEquals(source, null))
    {
        throw new ArgumentException("Trying to serialize null object.", "source");
    }

    XmlSerializer s = new XmlSerializer(typeof(T));
    s.Serialize(writer, source);
    writer.WriteLine();
}

And deserialize code:

public static T Deserialize<T>(this T source, TextReader reader)
{
    XmlSerializer s = new XmlSerializer(typeof(T));
    source = (T)s.Deserialize(reader);
    return source;
}

The call to deserialize is from a property called WeightSettings (of type WeightSettings) which is not null:

WeightSettings = WeightSettings.Deserialize(sr);

How can I fix this behavior? Perhaps more importantly: why do I see this behavior only on the Window Loaded event?

A: 

@Jon Skeet was on the right track. I was not changing the current working directory until after my application was fully loaded, so it could not find the file.

Very cryptic exception when it simply should have been FileNotFoundException

Brazzle