A site devoted to discussing techniques that promote quality and ethical practices in software development.

Wednesday, August 24, 2011

Good way to study the effect of sgen.exe for XmlSerialization

SGen,exe is a tool from Microsoft to pre-generate a .Net assembly that writes the object to be serialized. There is no shortage of blog posts telling you how to use this, like this one and hence not repeated here.

We developer is often a doubting lot and wanting to know what magical power this sgen.exe has that claims to make some difference in performance or does it? Apart from pre-generating, much like NGen, an serialization assembly to avoid generating it on the fly, one wants to know what is in it and how it works.

The best way answer these questions and to study the output of SGen to convince yourself what it does and that it is indeed loaded is to include the following switches when generating:
  • /debug  - this produces the PDB file
  • /keep    - this keeps all the temporary files that were used in the process of producing the DLL. It is extremely useful because they (the .cs file) allows you to put break points in the generated code. It is also extremely educational to study them.
  • /force   - to force the generation. But would be better if you include /o to generate the files to a different directory and then you can delete all files in that directory before running sgen. In this way you are not accumulating the temporary files creating a very confusing situation.
Don't forget to put the *.XmlSerializers.dll and *.XmlSerializers.pdb into the run directory, otherwise it will not be found.

SGen basically generates derived classes of XmlSerializationWriter and XmlSerializationReader containing code to write your class members out to or read from the xml data stream. It uses an XmlWriter to write to and XmlReader to read from a XML document. If you study these classes, they share some similar methods.

Generating an Xml Document from class or regenerating it from document can be done in many ways. In fact, if study the generated files you will discover that there is really no magic when calling XmlSerializer.Serialize() and XmlSerializer.Deserialize(). Whether you called XmlWriter or XmlReader to handle your class's member yourself or by some generated code, the process is the same.

If these overheads of dynamic code generation and building or using SGen.exe too troublesome or does not meet your needs, you can cook your own with using various techniques and classes available in .Net


No comments:

Blog Archive