Troubleshooting with the XmlSerializer

The XmlSerializer in the .NET Framework is a great tool to convert Xml into runtime objects and vice versa – when it works. Unfortunately in some cases it doesn’t work right away and those situations can be very frustrating.

 

This is partially because the XmlSerializer throws exceptions that don’t provide a lot of information why the XmlSerializer wouldn’t do its job. At least it doesn’t provide that information in a prominent spot for programmers to see it right away.

 

In most cases an exception handler will catch a System.InvalidOperationException thrown in Serialize() or Deserialize(), which makes the StackTrace property useless because it does not offer any more insight into the root cause of the exception. To make matters worse, the exception’s Message property only yields very generic information. If we are trying to serialize an undeclared type for example, the Serialize() method would throw an exception with the following message:

 

There was an error generating the XML document.

 

This message is annoying at best, because we already figured that much when we saw an exception and doesn’t help us troubleshooting the problem.

 

The trick to get to the “real information” about the problem is to examine the exception’s InnerException property, which contains very detailed information about the problem and where it occurred.

 

The InnerException’s message is usually very descriptive, pinpoints the problem and, in many cases, even offers a possible solution. When we are trying to serialize an undeclared type the InnerExcpetion reads something like this:

 

The type XmlSerializationApp.XmlCar was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

 

The following listing demonstrates how to set up the exception handler and how to access the InnerException property.

 

using System;

 

public static ParkingLot DeserializeParkingLot( XmlReader reader )

{

  ParkingLot lot = null;

  try

  {

    XmlSerializer ser = new XmlSerializer( typeof(ParkingLot));

    lot = (ParkingLot) ser.Deserialize( reader );

  }

  catch( Exception ex )              

  {                                   

    DumpException( ex );            

  }                                   

  return lot;

}

public static void DumpException( Exception ex )

{

  WriteExceptionInfo( ex );                     

  if( null != ex.InnerException )              

  {                                             

    WriteExceptionInfo( ex.InnerException );   

  }

}

public static void WriteExceptionInfo( Exception ex )

{

  Console.WriteLine( "--------- Exception Data ---------" );        

  Console.WriteLine( "Message: {0}", ex.Message );                 

  Console.WriteLine( "Exception Type: {0}", ex.GetType().FullName );

  Console.WriteLine( "Source: {0}", ex.Source );                   

  Console.WriteLine( "StrackTrace: {0}", ex.StackTrace );          

  Console.WriteLine( "TargetSite: {0}", ex.TargetSite );           

}

 

Inspecting the InnerException will help you resolve a lot of problems around the XmlSerializer. However, there is group of problems where even the InnerException does not provide enough information to diagnose the problem. The typical exception message in this case is:


System.IO.FileNotFoundException: File or assembly name
abcdef.dll, or one of its dependencies, was not found.
File name: "abcdef.dll"

 

The call stack of these exceptions show that the exception originated while the XmlSerializer attempted to load an assembly generated by CodeDOM using System.Reflection.Assembly.Load. These exception are typically caused by errors during the compilation of classes that the XmlSerializer creates on-the-fly when you instantiate it. These compilation errors are not part of any exception error message and we would have a really hard time to figure the problem out. Fortunately, Chris Sells has a command-line tool that helps diagnosing these problems. The tool will go through the same steps as the XmlSerializer to reflect over the classes you need to (de-)serialize, compiles them and writes out the errors that occured to the compilation.

 

Now there are some situations where you can’t get enough information from neither the exception nor from Chris Sells’ tool. In those cases your last chance is an undocumented feature of the XmlSerializer.

 

You can instruct the XmlSerializer to keep the source code for the temporary serialization classes to our hard disk. Under normal circumstances, the XmlSerializer deletes this classes once it’s done it’s job, but you can set a diagnostics switch in you applications config file to prevent it from doing so.

 

If your problem happens in a big web application you may want to copy the class that’s causing your serialization troubles into a small, forms-based test application to speed up your troubleshooting efforts. Now add a diagnostics switch like in the example below to the application’s config file:

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <system.diagnostics>

        <switches>

            <add name="XmlSerialization.Compilation" value="1" />

        </switches>

    </system.diagnostics>

</configuration>

 

Now you can run the test application with this switch in place and then search our temp directory for *.cs files after you ran code that would reproduce the problem.

 

On a computer running Windows 2000 or later, the default location for the temp directory is <System Drive>\Documents and Settings\<Your User Name>\LocalSettings\Temp or <Windows Directory>\Temp for web applications running under the ASPNET account. The .cs files are easy to miss because they have very odd looking, randomly generated file names, something like: oinmcjqh.0.cs.

 

If you are running your application under the Visual Studio debugger you see messages about assemblies with these names being loaded into your application the first time you instantiate an XmlSerializer instance for a certain type. Once these assemblies are loaded into the application process you can set breakpoints, inspect variables and everything else you can do to your own code. When you have to go that far, chances are that you are diagnosing a bug in the XmlSerializer. In those cases maye sure you post your findings to a place that’s monitored by Microsoft, such as the public newsgroup microsoft.public.dotnet.xml or let me forward it to somebody on the XmlSerialization team. Honestly, I hope you never encounter any of these situations.

 

You can now find an extended version of that article at the MSDN XML Developer Center

Published Wednesday, October 22, 2003 9:54 PM by ChristophDotNet
Filed under:

Comments

# Xml Schemas/DataTypes support utility: xsd.exe

Thursday, October 23, 2003 5:37 PM by Dumky
I found the xsd.exe useful in some cases. It provides much more details than the runtime exception, when you get serialization errors because your classes aren't serializable for some reason.

# re: Troubleshooting with the XmlSerializer

Thursday, December 11, 2003 6:25 PM by Kevin
Thanks a lot for the XmlSerialize precompile help. This will save me a lot of debug time. Keep up the good work.

# re: Troubleshooting with the XmlSerializer

Wednesday, February 04, 2004 3:39 AM by Dave Buckner
This can aslo occur if the namespace is Serialization

# Debugging XmlSerialization: viewing the generated code

Tuesday, May 04, 2004 9:09 AM by TrackBack
Doug Purdy shares how to debug XmlSerializer code.

# Virtual Thought » Serializing the game data

Saturday, July 24, 2004 5:06 AM by TrackBack
Virtual Thought &raquo; Serializing the game data

# Coalesce

Wednesday, August 04, 2004 7:18 PM by TrackBack

# re: Troubleshooting with the XmlSerializer

Wednesday, August 04, 2004 7:31 PM by Dheeraj Dhondalkar
Hi,
It really helped me to find the problem. But what about solution?
I am getting error "System.ArgumentException: Unable to generate permission set, input xml may be malformed.."

I put the diagnostic switch and found that it is successfully creating rundime csharp file. But when I use that csharp file and try to compile, then also I am getting same error.

I really do not understand what this error is. With the user's profile, I can create a new permission set even at Enterprise, machine level. (using .net configuration tool.). The user is administartor. There is full permission to Everyone to Temp directory.

The error is on this line
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.LinkDemand, Name="FullTrust")]

Looks like it is unable to create permission set. But why? Whats the reason? This bug is really making me mad. Please help me

Atleast give me a workaround. (I can not serialize all my code by just writing text like <MyClass></MyClass> etc. because I have heavily used microsoft's xml serialization code.

PLEEESSSSSSSEEEEE HELP!!

Thanks in advance
Dheeraj

# XmlSerializer Problems

Wednesday, September 27, 2006 12:38 AM by Stuart Jones Weblog

Today I was using XSD.exe to generate types from XSDs and using XmlSerializer to serialize the instantiated...

# re: Troubleshooting with the XmlSerializer

Saturday, June 23, 2007 5:44 PM by Yoav Sion

I have a question regarding this subject and would love some help from anyone:

I am looking to inherit from List<T> and hold some properties of my own in that inherited class.

Is there ANY WAY I can get an XmlSerializer to serialize (and deserialize) my class, along with its properties AND the List's items as well?

I've marked my class as Serializable (the properties are simple boolean primitives).

I've been searching the web for quite a long time and can't seem to find a simple, clean and mosy - a WORKING solution.

Anybody?

# clone dvd

Thursday, March 20, 2008 9:07 PM by clone dvd

Recent Posts Drive traffic, make money. Win 180 premium accs! Kenapa terengganu tidak ditawan PAS Step Down la Pak Lah.. Should Pak Lah (Abdullah Badawi) Resign? Mahathir Mengaku Anwar Tidak Bersalah? History lessons Sponsors Categories Anime (8) Computer

# Registry Cleaner

Wednesday, April 30, 2008 3:10 PM by Registry Cleaner

In C, allocate even uninitialized global variables in the data section of the object file, rather than generating them as common blocks. This has the effect that if the same variable is declared (without extern) in two different compilations, you will get

# dvd decoders

Tuesday, July 15, 2008 6:25 AM by dvd decoders

One of the most feared colors in the NT world is blue. The infamous Blue Screen of Death (BSOD) will pop up on an NT system whenever something has gone terribly wrong. Bluescreen is a screen saver that not only authentically mimics a BSOD, but will simulate

# dvd decrypt download

Tuesday, July 15, 2008 8:23 AM by dvd decrypt download

Here are some tests done by pc magazine of Apache running on Osx and Xserve with WebBench. As you can see, the results are very strong, something completely different to what AnandTech tries to make us believe. That’ s very strange that the resutlts are

# how copy dvd

Wednesday, July 16, 2008 4:09 AM by how copy dvd

Assistance from RWC Computer Services Your browser doesn\'t support IFrames. a href \"http:// siteneighbors. com/ blogs/ widget/ 86\" target \"_ blank\" Visit this blog\'s neighborhood. /

# dvd decrypter download

Wednesday, July 16, 2008 7:17 AM by dvd decrypter download

The makers of Spybot have recently come into conflict over claims of incompatiblity with Norton Internet Security. ref/ ref Symantec is recommending the uninstallion of Spybot Search and Destory before installing Norton Internet Security. According to

# how to record dvd

Wednesday, July 16, 2008 9:13 AM by how to record dvd

So anyway- I make a visit to the eye doc yesterday. I’ m due- it’ s been three years since my last vision check up. I do wear glasses for reading and computer work and lately, I’ ve been feeling the strain on my eyes like never before. I take regular

# burning a dvd

Wednesday, July 16, 2008 5:04 PM by burning a dvd

A Wrench In The Works Entertainment is proud to present five of the most talented Indian stand up comedians in North America, taped live, in High Definition, before a sold out audience in Hollywood, California.

# shrink to dvd

Thursday, July 17, 2008 10:03 AM by shrink to dvd

First thing we did was to get the damaged disk offline and use up the spare disk in the SAN. We contacted Microsoft for this issue and there were two options facing us. As the error log above clearly says it is a hardware issue, Microsoft suggested that

# re: Troubleshooting with the XmlSerializer

Tuesday, July 21, 2009 11:46 AM by dlatimer

This doesn't seem to work on Windows 2003 with VS 2008. Any ideas?

# XmlSerializer Problems - Berwick Heights Software

Friday, November 06, 2009 11:48 AM by XmlSerializer Problems - Berwick Heights Software

Pingback from  XmlSerializer Problems - Berwick Heights Software

# XmlSerializer Problems - Berwick Heights Software

Thursday, November 12, 2009 8:45 PM by XmlSerializer Problems - Berwick Heights Software

Pingback from  XmlSerializer Problems - Berwick Heights Software

Leave a Comment

(required) 
(required) 
(optional)
(required)