views:

169

answers:

2

I’m working with a poorly-engineered API. I have a class that I need to serialize, and I have control over the makeup of the class, but not the types that make up the properties the class is serialzing. An example is below:

<Project>
  <SomeProperty1 />
  <Install>
    <DefaultStep></DefaultStep>
  </Install>
  <Uninstall>
    <DefaultStep></DefaultStep>
  </Uninstall>
</Project>

The problem is, I have no control over the “Install” and “Uninstall” types, and their nested types have the same name. "Install" resides in MyCompany.Install.dll, and "Uninstall" resides in MyCompany.Uninstall.dll. But the kicker is, MyCompany.Uninstall.dll refererences MyCompany.Install.dll, which is completely pointless. I know this is bad design (the whole Framework I’m dealing with is terrible) but I don’t have a choice in working with it.

The error I get is:

"Types 'MyCompany.Install.Uninstall.DefaultStep' and 'MyCompany.Install.DefaultStep' both use the XML type name, 'DefaultStep', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type."

That would be a nice idea, except I have zero control over the assemblies that contain the "Install" and "Uninstall" classes.

Any ideas?

+3  A: 

If you have access to .NET 3.5, I would use the DataContract serializer, and implement an IDataContractSurrogate. Surrogate serialization allows you to replace a fussy type that is screwing up serialization with an alternative type at serialization time. You have full control over the surrogate. That should help you solve the problem.

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx

jrista
Slick, I've never seen that before.
Greg D
@Greg: I was amazed when I found it too. The endless foresight of Microsoft engineers never ceases to amaze me. The accounted for every scenario. ;)
jrista
Thanks for your help guys. I posted the solution I found below.
interscape
A: 

I found an answer that works. Comments in this article: http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx

Led me to this article: http://mfharoon.blogspot.com/2006/12/using-ixmlserializable-to-overcome-not.html

The only thing you need to change is line 108, which needs to read:

writer.WriteAttributeString("type", _parameters.GetType().AssemblyQualifiedName.ToString());

That will let the serialization work if the type is in a separate assembly.

HTH!

interscape