Hi all,
I've written a simple class (with source; attached) that will serialize any property of any type, so long as all members are marked Serializable.
Which means: no more writing serializers by hand for your types, and you can now serialize collections (lists, dictionaries, etc) with ease. Yay!
It works well (hence the "!"), but has a couple kinks I can't figure out (hence the "..?").
It requires that you have .NET 3.0+ installed, as it uses WCF's DataContractSerializer.
A simple example:
<%@ CodeTemplate Language="C#" %>
<%@ Property Name="MyDogs" Type="List<Dog>" Serializer="AnyPropertySerializer" %>
<%@ Assembly Name="AnyPropertySerializer" %>
<%@ Import Namespace="RHencke.CodeSmith" %>
<%@ Import Namespace="System.Collections.Generic" %>
<script runat="template">
[Serializable]
public class Dog
{
public string Name { get { return _Name; } set { _Name = value; } } string _Name;
public bool IsWagging { get { return _IsWagging; } set { _IsWagging = value; } } bool _IsWagging;
}
</script>
That should do it! MyDogs should pop up in your property window. It will use the built in TypeUIEditor for editing, and AnyPropertySerializer for saving. You can test it out by adding some dogs, saving the values to a .cst, and loading it up again, or by copying the properties.
Now, the stuff I can't figure out...
- Compiling the template the first time does not produce the list as expected; you need to compile the template twice.
- Compiling the template after modifying the property results in the odd error:
Object of type 'System.Collections.Generic.List`1[_CodeSmith.ClassGen_cst+Dog]' cannot be converted to type 'System.Collections.Generic.List`1[_CodeSmith.ClassGen_cst+Dog]'.,
after which the property resets until loaded from disk.
Example saved properties:
<codeSmith xmlns="http://www.codesmithtools.com/schema/csp.xsd">
<propertySets>
<propertySet output="ClassGen.txt" template="x:\CodeSmith\Templates\ClassGen.cst">
<property name="MyDogs">
<ArrayOfClassGen_cst.Dog xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/_CodeSmith">
<ClassGen_cst.Dog>
<_IsWagging>false</_IsWagging>
<_Name>Mister Waggy</_Name>
</ClassGen_cst.Dog>
<ClassGen_cst.Dog>
<_IsWagging>true</_IsWagging>
<_Name>Buttons</_Name>
</ClassGen_cst.Dog>
</ArrayOfClassGen_cst.Dog>
</property>
</propertySet>
</propertySets>
</codeSmith>
Please let me know your thoughts/fixes/complaints - thanks!
Robert Hencke
Read the complete post at http://community.codesmithtools.com/forums/thread/29893.aspx
Posted
Feb 14 2008, 03:28 PM
by
CodeSmith on NewsGator Online