Faster XML Serialization

A lot of run-time compilation is involved when the XmlSerializer is used. For better performance it is recommended to run sgen.exe to generate a serialization assembly to speed up the XML serialization. In a way, the idea behind SGen is the same as for NGen.

There is a Generate Serialization Assembly drop-down in the project settings in Visual Studio, but this covers only available Web service proxies. To have Visual Studio run SGen automatically for other types, you need to manually add the following lines to your project file:

<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)"  Outputs="$(OutputPath)$(_SGenDllName)">         
    <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)"  References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
        <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
    </SGen>
</Target>
Advertisements

Serializing DateTime to XML

The XmlConvert class has been obsolete since .NET 2.0. I found this out when I needed to manually serialize and deserialize DateTime values to XML and all the examples used the old class. After some researching I found out that the following call will return the date time alue in the same format as the XmlSerializer uses:

DateTime.Now.ToString("o");
Returns “2008-11-17T12:28:09.9862678+02:00”

The value is easily converted back using the DateTime.Parse() function.

If you happen to need the functions of the XmlConvert class, you can achive the same results by combining the XmlSerializer with the TextWriter/TextReader classes. The following deserializes a XML value back to the correct type.

XmlSerializer dateSerializer = new XmlSerializer(type);
StringReader reader = new StringReader(stringValue);
return dateSerializer.Deserialize(reader);