Thursday 6 May 2010

Xsd2Code

If you have used xsd.exe before to generate C# code from XSD schema files you may have bore witness to some of the most horrendous looking serialization code that's ever been generated:
  • A repeating element becomes an array property with full get and set. (How are you supposed to add elements?)
  • Child object properties of generated classes must explicitly be created and assigned when creating a new instance of said class. (A recipe for NullReferenceException hell)
Just to name a few.

I was scouring the web hoping that there would be a better way to do this. I was on the verge of giving up until I encountered this link from stackoverflow:


In the short time I've played with this tool, I am already impressed at the quality of code that it generates. Just to illustrate how good this is:

Here's the Parameter property for the MaestroAPI FeatureSource class as it currently stands (generated by xsd.exe):

[System.Xml.Serialization.XmlElementAttribute("Parameter")]
public NameValuePairTypeCollection Parameter {
get {
return this.m_parameter;
}
set {
this.m_parameter = value;
}
}

If we created a new instance of FeatureSource and tried to access this property a NullReferenceException is thrown because you have to manually new the NameValuePairTypeCollection and assign it to this property yourself!

Here's the same snippet as generated by Xsd2Code

[System.Xml.Serialization.XmlElementAttribute("Parameter")]
public List<NameValuePairType> Parameter
{
get
{
if ((this.parameterField == null))
{
this.parameterField = new List<NameValuePairType>();
}
return this.parameterField;
}
set
{
if ((this.parameterField != null))
{
if ((parameterField.Equals(value) != true))
{
this.parameterField = value;
this.OnPropertyChanged("Parameter");
}
}
else
{
this.parameterField = value;
this.OnPropertyChanged("Parameter");
}
}
}
Creating a new instance of this FeatureSource, we can safely access this property because it has lazy generation logic built in! Xsd2Code does other things as well, such as providing built-in serialization/deserialization logic, object cloning, and much more!

I'm a bit disappointed that the property still has a setter (collection properties should almost never be assignable!), but already this code is much cleaner and easier to work with than the one generated by xsd.exe

Just seeing some of the code that's generated with some of the mapguide xsds, I knew that I have found my saviour. So long xsd.exe!

I will definitely be using this tool for the next (post-2.1) version of the Maestro API and any other projects that involve working with xsd files.

No comments: