Reflection Based Serialization

Similar to the Flex side, serializing complex objects can be faciliated using class AttributeBasedSerializer. This serializer uses reflection to serialize objects of different class types.

AttributeBasedSerializer handles all classes which are located in a package that is registered in the attribute XmlnsDefinition. This attribute is defined with the target assembly and maps a CLR namespace to a XML namespace.

Example 8.3. Mapping a CLR namespace to a XML namespace

// XmlnsDefinition is defined in yWorks.Canvas.Support
using yWorks.Canvas.Support;
// [assembly: XmlnsDefinition("xml namespace", "clr namespace")]
[assembly: XmlnsDefinition("http://www.yworks.com/demo/style", "yWorks.yFiles.Graph.Web.Demo")]

The XML namespace is a namespace URI which will be used for the elements representing the serialized object in the GraphML.

AttributeBasedSerializer serializes all public read- and writable properties, i.e. properties which have a public getter and setter. It will not serialize public fields.

The corresponding deserializer is class XamlDeserializer. It handles all XML elements which are defined in a namespace whose URI is mapped to a CLR namespace using the XmlnsDefinition attribute.

Reflection based (de)serialization has to be enabled on GraphRoundtripSupport by setting the SupportAutoSerialization property to true. AttributeBasedSerializer and XamlDeserializer will only be invoked if no other serializer / deserializer which can handle the current object is found.

Example 8.4, “Class to be serialized with the AttributeBasedSerializer” shows the .NET class Person which corresponds to the Flex class Person shown as example in the section called “Reflection Based Serialization”. Note that the public property identifiers are written in lowerCamelCase to match their Flex side counterparts.

Example 8.4. Class to be serialized with the AttributeBasedSerializer

[assembly: XmlnsDefinitionAttribute("http://www.yworks.com/demo/style",
                                    "yWorks.yFiles.Graph.Web.Demo")]
namespace yWorks.yFiles.Graph.Web.Demo
{
    public class Person {
    
        private String _name;
        public String name {
            get { return _name; }
            set { this._name = value; }
        }

        private bool _vip;
        public bool vip {
            get { return _vip; }
            set { this._vip = value; }
        }

        private System.Drawing.Pen _pen;
        public System.Drawing.Pen pen
        {
            get { return _pen; }
            set { this._pen = value; }
        }
    }
}

AttributeBasedSerializer generates the GraphML which is shown in Example 8.5, “GraphML generated by AttributeBasedSerializer” .

Example 8.5. GraphML generated by AttributeBasedSerializer

<Person name="Another Person" vip="True" 
        xmlns="http://www.yworks.com/demo/style">
    <Person.pen>
        <y:Pen name="SolidColor" color="Red" width="3"/>
    </Person.pen>
</Person>