using System.Collections.Generic; using System.Collections; using System; using System.Linq; namespace Persistence { public class Serializer : IEnumerable { private readonly object obj; private readonly string rootName; private readonly Dictionary obj2id; private readonly Dictionary typeCache; private readonly PersistenceConfiguration persistenceConfiguration; public Dictionary TypeCache { get { Dictionary result = new Dictionary(); foreach ( var pair in typeCache ) result.Add(pair.Key.AssemblyQualifiedName, pair.Value); return result; } } public Serializer(object obj) : this(obj, PersistenceConfiguration.Instance) {} public Serializer(object obj, PersistenceConfiguration persistenceConfiguration) : this(obj, persistenceConfiguration, "ROOT") { } public Serializer(object obj, PersistenceConfiguration persistenceConfiguration, string rootName) { this.obj = obj; this.rootName = rootName; this.persistenceConfiguration = persistenceConfiguration; obj2id = new Dictionary {{new object(), 0}}; typeCache = new Dictionary(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator GetEnumerator() { DataMemberAccessor rootAccessor = new DataMemberAccessor( rootName, obj.GetType(), null, () => obj, null); IEnumerator iterator = Serialize(rootAccessor); while (iterator.MoveNext()) yield return iterator.Current; } private IEnumerator Serialize(DataMemberAccessor accessor) { object value = accessor.Get(); if (value == null) { yield return new NullReferenceToken(accessor.Name); yield break; } if (obj2id.ContainsKey(value)) { yield return new ReferenceToken(accessor.Name, obj2id[value]); yield break; } if ( ! typeCache.ContainsKey(value.GetType())) typeCache.Add(value.GetType(), typeCache.Count); int typeId = typeCache[value.GetType()]; int? id = null; if ( ! value.GetType().IsValueType) { id = obj2id.Count; obj2id.Add(value, (int)id); } IFormatter formatter = persistenceConfiguration.GetFormatter(XmlFormat.Instance, value.GetType()); if (formatter != null) { yield return new PrimitiveToken( accessor.Name, typeId, formatter.Serialize(value), id); yield break; } yield return new BeginToken(accessor.Name, typeId, id); IDecomposer decomposer = persistenceConfiguration.GetDecomposer(value.GetType()); if (decomposer != null) { foreach (object o in decomposer.Serialize(value)) { IEnumerator iterator = Serialize(new DataMemberAccessor(o)); while (iterator.MoveNext()) yield return iterator.Current; } yield return new EndToken(accessor.Name, typeId, id); yield break; } int nSubComponents = 0; foreach (KeyValuePair mapping in StorableAttribute.GetAutostorableAccessors(value)) { nSubComponents += 1; IEnumerator iterator = Serialize(mapping.Value); while (iterator.MoveNext()) { yield return iterator.Current; } } if (nSubComponents == 0) { throw new ApplicationException(String.Format( "Composite value of type \"{0}\" contains no subcomponents", value.GetType().FullName)); } yield return new EndToken(accessor.Name, typeId, id); } } }