views:

201

answers:

2

Serialization exception occurs when I try to serialize a class in C#, cause it holds a reference to a non serializable class. The problem is that the class I want to serialize is very complicated, and contains a lot of references to other complicated classes, and I can't find the reference to the problematic class in this huge amount of code. Is there a way to find out where is the property or filed with the non serializable class is? Perhaps somewhere in the exception details? I didn't find something like it.

Thanks :)

+1  A: 

You should start examining the exception’s stack trace.

If necessary, configure Visual Studio to stop on any thrown exceptions (Debug -> Exception -> Check Thrown checkbox column for Common Language Runtime Exceptions)

That should stop Visual Studio at the exact place where the exception was thrown and that will give you a stack trace wich you can examine.

If that is not enough and depending on how your serializable classes are created, you can try running your assembly trough sgen.exe to create another assembly responsible for the serialization.

sgen.exe has na option “/k” for keeping the source code. You can add this code to a project from where you should be able to breakpoint into it.

Alfred Myers
A: 

Try to get the information from the exception by "catch (Exception exceptionObject) and wrapping the serialization call in a try block (opening a file in this example):

try 
{
    FileStream inputFileStream = 
      new FileStream(aSaveFileNameFullPath, FileMode.Open, FileAccess.Read);
}
catch (Exception exceptionObject) 
{
    displayStandardExceptionInfo(exceptionObject, "Could not open file " + aSaveFileNameFullPath);
}


displayStandardExceptionInfo() is defined as:

public static void displayStandardExceptionInfo(
  ref System.Exception anExceptionObject, ref string aStartText)
{
    string errMsg1 = 
      "Error: " + anExceptionObject.ToString() + "\n";
    string errMsg2 =
      "\n" + "Message: " + anExceptionObject.Message + "\n";

    string errMsg3 = "";
    if (anExceptionObject.InnerException != null)
    {
        errMsg3 = 
          "Extra info: " + 
          anExceptionObject.InnerException.Message +
          "\n";
    }
    string errMsg =
      aStartText + "\n" + "\n" + errMsg1 + errMsg2 + errMsg3;
    System.Windows.Forms.MessageBox.Show(errMsg);
}
Peter Mortensen
You could append the `InnerException.Message` in a (recursive/iterative) loop until there's no exception message left to add.
Scoregraphic