I have a classic COM object that returns me and interface via a PIA. I want
to serialize this interface into an XML stream (the xml is just used for
reporting, it doesn't have to reflect the entire interface, just it's public
properties).
So, I created a class with the same public properties as the interface, and
pass them both into this helper class:
public class XmlSerializationHelper< TXmlObject, TInterface>
where TXmlObject : new()
{
public static void FromInterface(TXmlObject x, TInterface i)
{
foreach (PropertyInfo interfaceproperty in
typeof(TInterface).GetProperties())
{
PropertyInfo xmlproperty =
typeof(TXmlObject).GetProperty(interfaceproperty.Name);
if (xmlproperty != null)
{
try
{
if
(interfaceproperty.PropertyType.Equals(xmlproperty.PropertyType))
{
xmlproperty.SetValue(x,
interfaceproperty.GetValue(i, null), null);
}
else
{
xmlproperty.SetValue(x,
Convert.ChangeType(interfaceproperty.GetValue(i, null),
xmlproperty.PropertyType), null);
}
}
catch (Exception)
{
}
}
}
}
}
The issue I have is that the Interface has a RegistryRootKey property that
it exposes as a UInt32, but in my Xml class I want to use a
Microsoft.Win32.RegistryHive enum. So, I added the else clause when the
types don't match, and try to use ChangeType, but I still get an illegal cast
exception.
I believe the issue is that the RegistryHive enum is full of negative
values, while the UInt32 values are obviously positive (though they have the
exact same bytes).
When I want to do is something akin to:
xmlproperty.SetValue(x, (xmlproperty.PropertyType)
interfaceproperty.GetValue(...), null)
but obviously that doesn't compile.
Anyone know if/how I can do this via Reflection or some other method?
In the meantime I have 2 properties on my Xml class:
private uint _RegistryRootKey ;
[XmlIgnore()]
public uint RegistryRootKey
{
get { return _RegistryRootKey ; }
set { _RegistryRootKey = value; }
}
[XmlAttribute("registryrootkey")]
public Microsoft.Win32.RegistryHive RootRegistryHive
{
get { return (Microsoft.Win32.RegistryHive)_RegistryRootKey ; }
set { _RegistryRootKey = (uint)value; }
}
To force the cast in my serialization, but now I'm curious if there's a
better way.
Thanks,
Ryan