How can I migrate a configuration to a new class from a list of bools? Previously it used a list of bool, but the list was being abused as a class, with each index having a specific meaning like a field.
I want to migrate it from a List, to a class that instead acts as the list for serialization purposes, but exposes normal fields to the rest of the application.
How can I write class ListEmulator so that it serializes out to a list, without introducing new xml tags?
old code
namespace
{
[DataContract]
public class Configuration
{
public const string FileName = "Configuration.xml";
public Configuration()
{
AList = new List<bool>();
AGuidList = new List<Guid>();
}
[DataMember]
public List<Guid> AGuidList { get; set; }
[DataMember]
public List<bool> AList { get; set; }
}
}
new code.
namespace
{
[DataContract]
public class Configuration
{
public const string FileName = "Configuration.xml";
public Configuration()
{
AListEmulator = new ListEmulator();
AGuidList = new List<Guid>();
}
[DataMember]
public List<Guid> AGuidList { get; set; }
[DataMember]
public ListEmulator AListEmulator { get; set; }
}
}
public class ListEmulator
{
public ListEmulator()
{
new ListEmulator(true, true, true, true);
}
public ListEmulator(bool item0, bool item1, bool item2, bool item3)
{
this.IsPlanned = item0;
this.IsCompleted = item1;
this.IsRemaining = item2;
this.IsSerial = item3;
}
public bool IsPlanned { get; set; }
public bool IsCompleted { get; set; }
public bool IsRemaining { get; set; }
public bool IsSerial { get; set; }
}
The reason a list is needed, is there is old migration code that needs to be ported for when there was only 1 element, then 2, 3, 4 with different defaults for each. If it weren't for the fact that I have existing deployed configuration files in the original format, it would probably be time for them to all be named in the XML individually. However, I need to retain the current format for now. For the sake of migration I'm wondering how I can accomplish the above.
One option would be for your
ListEmulator
to inherit fromCollection<bool>
, and then add specific named properties to access elements in the array, like so:Then in your
Configuration
simply replaceList<bool>
withListEmulator
, keeping the old element name:Because this type implements
IEnumerable<T>
, theDataContractSerializer
will serialize it as a collection rather than as an object with properties. (You might want to change the class name since it's really not a list emulator at this point.) However, this only works if you do not add any initial values to the collection from within the default constructor.Another option would be to add a surrogate property to
Configuration
that handles the necessary conversions, and mark theListEmulator AList
as not serialized:Both options use the following extension method: