views:

434

answers:

3

Is there a way to serialize a CodeCompileUnit object as XML.

The problem is that:

XmlSerializer xml = new XmlSerializer( typeof(CodeCompileUnit) );

throws the following exception:

"Cannot serialize member System.CodeDom.CodeObject.UserData of type System.Collections.IDictionary, because it implements IDictionary."

A: 

This is a limitation of the XML serializer : dictionaries can't be serialized (even though I don't see any good reason why). Actually they can be serialized if they implement IXmlSerializable (which, by the way, is a real pain to implement), but that's not the case for the UserData property... so you're stuck

Thomas Levesque
Correct. Just s small addition, this article talks a bit more about the problem, and also has some info on implementing IXmlSerializable:http://msdn.microsoft.com/en-us/magazine/cc164135.aspx
Badaro
The problem is that it would be difficult to make existing .NET classes implement IXmlSerializable.
Darin Dimitrov
A: 

XmlSerializer has issues with IDictionary. It is now deprecated in favor of DataContractSerializer which can serialize a CodeCompileUnit instance:

var serializer = new DataContractSerializer(typeof(CodeCompileUnit));
serializer.WriteObject(Console.OpenStandardOutput(), new CodeCompileUnit());
Darin Dimitrov
Unfortunately it works only for clean object.Trying to serialize a populated object fails.
Jenea
Fails with what exception?
Darin Dimitrov
Well first time it says:Type 'System.CodeDom.CodeTypeDeclaration' with data contract name 'CodeTypeDeclaration:http://schemas.datacontract.org/2004/07/System.CodeDom' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Jenea
Then:Enum value '20482' is invalid for type 'System.CodeDom.MemberAttributes' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.
Jenea
The second time after I have added types it was complaining about.
Jenea
A: 

this may be a long shot but how about serializing the code that it generates and then rehidrating the codedom from the generated code.

this project allows you to go from code to codedom and back.

http://www.codeproject.com/KB/cs/codedom_assistant.aspx

Simon