private void SerializeObject(object graph, StreamWriter streamWriter) { var members = FormatterServices.GetSerializableMembers(graph.GetType(), Context); var objectsData = FormatterServices.GetObjectData(graph, members); streamWriter.Write("ClassName={0}", graph.GetType().FullName); for (var i = 0; i < objectsData.Length; ++i) { var name = members[i].Name; if (name.IndexOf("<") != -1 && name.IndexOf(">") != -1) { name = name.Substring(name.IndexOf("<") + 1, name.IndexOf(">") - name.IndexOf("<") - 1); } streamWriter.Write(",{0}={1}", name, objectsData[i]); if (objectsData[i].ToString().IndexOf("List") != -1) { streamWriter.Write("{"); var transports = objectsData[i] as IEnumerable; foreach (var transport in transports) { SerializeObject(transport, streamWriter); } streamWriter.Write("}"); } } streamWriter.Write(";"); }
// Always remember: the whole configuration must be serialized as one single, flat object (or SerializationInfo), we cannot rely on any // nested objects to be deserialized in the right order public static void GetObjectDataForGeneratedTypes( SerializationInfo info, StreamingContext context, object mixin, ConcreteMixinTypeIdentifier identifier, bool serializeBaseMembers, string pipelineIdentifier) { ArgumentUtility.CheckNotNull("info", info); ArgumentUtility.CheckNotNull("mixin", mixin); ArgumentUtility.CheckNotNull("identifier", identifier); info.SetType(typeof(MixinSerializationHelper)); var identifierSerializer = new SerializationInfoConcreteMixinTypeIdentifierSerializer(info, "__identifier"); identifier.Serialize(identifierSerializer); object[] baseMemberValues; if (serializeBaseMembers) { var baseType = mixin.GetType().BaseType; Assertion.IsNotNull(baseType, "Generated mixin types always have a base type."); MemberInfo[] baseMembers = FormatterServices.GetSerializableMembers(baseType); baseMemberValues = FormatterServices.GetObjectData(mixin, baseMembers); } else { baseMemberValues = null; } info.AddValue("__baseMemberValues", baseMemberValues); info.AddValue("__participantConfigurationID", pipelineIdentifier); }
public void GetObjectData_InvalidArguments_ThrowsException() { Assert.Throws <ArgumentNullException>("obj", () => FormatterServices.GetObjectData(null, new MemberInfo[0])); Assert.Throws <ArgumentNullException>("members", () => FormatterServices.GetObjectData(new object(), null)); Assert.Throws <ArgumentNullException>("members", () => FormatterServices.GetObjectData(new object(), new MemberInfo[1])); Assert.Throws <SerializationException>(() => FormatterServices.GetObjectData(new object(), new MethodInfo[] { typeof(object).GetMethod("GetHashCode") })); }
static void Run() { // Create an instance of a Book class // with a title and author. Book Book1 = new Book("Book Title 1", "Masato Kawai"); // Store data about the serializable members in a // MemberInfo array. The MemberInfo type holds // only type data, not instance data. MemberInfo[] members = FormatterServices.GetSerializableMembers (typeof(Book)); // Copy the data from the first book into an // array of objects. object[] data = FormatterServices.GetObjectData(Book1, members); // Create an uninitialized instance of the Book class. Book Book1Copy = (Book)FormatterServices.GetSafeUninitializedObject (typeof(Book)); // Call the PopuluateObjectMembers to copy the // data into the new Book instance. FormatterServices.PopulateObjectMembers (Book1Copy, members, data); // Print the data from the copy. Console.WriteLine("Title: {0}", Book1Copy.Title); Console.WriteLine("Author: {0}", Book1Copy.Author); }
public void GetObjectData(object /*!*/ obj, SerializationInfo /*!*/ info, StreamingContext context) { DObject instance = (DObject)obj; if ((context.State & StreamingContextStates.Persistence) != StreamingContextStates.Persistence) { Serialization.DebugInstanceSerialized(instance, false); // serialization is requested by Remoting -> serialize everything and do not change type MemberInfo[] members = FormatterServices.GetSerializableMembers(instance.GetType()); info.AddValue(MembersSerializationInfoKey, FormatterServices.GetObjectData(instance, members)); } else { Serialization.DebugInstanceSerialized(instance, true); // Serialization was requested by the user via the serialize() PHP function so it is possible that // the type of this instance will be undefined at deserialization time. if (instance.RealObject is Library.SPL.Serializable) { // the instance is PHP5.1 serializable -> reroute the deserialization to SPLDeserializer SPLDeserializer.GetObjectData(instance, info, context); } else { // otherwise reroute the deserialization to Deserializer, which handles __sleep Deserializer.GetObjectData(instance, info, context); } } }
int WriteObject(BinaryWriter writer, Type type, object obj, SerializeAsAttribute attr) { int size = 0; if (type.BaseType != _TypeOfObject) { size += WriteObject(writer, type.BaseType, obj, attr); } MemberInfo[] membersInfo = FormatterServices.GetSerializableMembers(type, _Contex); object[] membersData = FormatterServices.GetObjectData(obj, membersInfo); Debug.Assert(membersInfo.Length == membersData.Length); for (int i = 0; i < membersInfo.Length; i++) { MemberInfo memberInfo = membersInfo[i]; Debug.Assert(memberInfo is FieldInfo); object memberData = membersData[i]; Type memberType = memberData != null?memberData.GetType() : ((FieldInfo)memberInfo).FieldType; SerializeAsAttribute memberAttr = GetSerializeAsAttribute(type, obj, memberInfo); size += WriteMember(writer, memberType, memberData, memberAttr); } return(size); }
private void WorkOnInstanceAndLocal_2() { MemberInfo[] ms = FormatterServices.GetSerializableMembers(typeof(int), new StreamingContext(StreamingContextStates.All)); foreach (MemberInfo m in ms) { if (!m.DeclaringType.Equals(typeof(Int32))) { throw new Exception("Err_23947tsg! error"); } } int i = 5; Object[] os = FormatterServices.GetObjectData(i, ms); if ((int)os[0] != 5) { throw new Exception("Err_32497g! error"); } Object o = FormatterServices.GetUninitializedObject(typeof(int)); Object o1 = FormatterServices.PopulateObjectMembers(o, ms, os); if ((Int32)o1 != 5) { throw new Exception("Err_23947tsg! 2347sg"); } Int32[] iS = { 1, 2, 3 }; if (Buffer.ByteLength(iS) != 12) { throw new Exception("Err_10974! wrong result"); } if (Buffer.GetByte(iS, 4) != 2) { throw new Exception("Err_23408! wrong result"); } }
private void InitMemberInfo() { if (!_serObjectInfoInit.SeenBeforeTable.TryGetValue(_objectType, out _cache)) { _cache = new SerializationObjectInfoCache(_objectType) { MemberInfos = FormatterServices.GetSerializableMembers(_objectType, _context) }; int length = _cache.MemberInfos.Length; _cache.MemberNames = new string[length]; _cache.MemberTypes = new Type[length]; int index = 0; while (true) { if (index >= length) { _serObjectInfoInit.SeenBeforeTable.Add(_objectType, _cache); break; } _cache.MemberNames[index] = _cache.MemberInfos[index].Name; _cache.MemberTypes[index] = ((FieldInfo)_cache.MemberInfos[index]).FieldType; index++; } } if (_obj != null) { _memberData = FormatterServices.GetObjectData(_obj, _cache.MemberInfos); } _isNamed = true; }
void WriteSerializable(object ob, TypeInfo typeInfo, bool writeType) { m_writer.WriteStartObject(); m_writer.WriteWhitespace(" "); m_writer.WriteComment(ob.ToString()); if (writeType) { m_writer.WritePropertyName("$type"); // XXX fully qualified name is rather long... m_writer.WriteValue(typeInfo.Type.AssemblyQualifiedName); } var members = typeInfo.SerializableMembers; var values = FormatterServices.GetObjectData(ob, members); for (int i = 0; i < members.Length; ++i) { var member = (FieldInfo)members[i]; var value = values[i]; m_writer.WritePropertyName(member.Name); SerializeObject(value, member.FieldType); } m_writer.WriteEndObject(); }
private void WriteObject(object graph) { _writer.WriteStartObject(); _writer.WritePropertyName(ID_TYPE); _writer.WriteValue(graph.GetType().FullName); var members = FormatterServices.GetSerializableMembers(graph.GetType(), Context); var objs = FormatterServices.GetObjectData(graph, members); for (int i = 0; i < objs.Length; i++) { _writer.WritePropertyName(members[i].Name); if (objs[i] == null) { _writer.WriteValue(null); continue; } else { this.WriteValue(objs[i]); } } _writer.WriteEndObject(); }
public void Serialize(Stream serializationStream, object graph) { if (!(graph is IEnumerable)) { throw new Exception("This serialize will only work on IEnumerable."); } var headings = typeof(T).GetProperties(); var headerNames = headings.Select(e => e.Name.ToString()).ToArray(); var headers = String.Join(new String(_delimiter, 1), headerNames); using (var stream = new StreamWriter(serializationStream)) { if (_firstLineIsHeaders) { stream.WriteLine(headers); stream.Flush(); } var members = FormatterServices.GetSerializableMembers(typeof(T), Context); foreach (var item in (IEnumerable)graph) { var objs = FormatterServices.GetObjectData(item, members); var valueList = objs.Select(e => e.ToString()).ToArray(); var values = String.Join(new String(_delimiter, 1), valueList); stream.WriteLine(values); } stream.Flush(); } }
private void InitMemberInfo() { if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache)) { _cache = new SerObjectInfoCache(_objectType); _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context); int count = _cache._memberInfos.Length; _cache._memberNames = new string[count]; _cache._memberTypes = new Type[count]; // Calculate new arrays for (int i = 0; i < count; i++) { _cache._memberNames[i] = _cache._memberInfos[i].Name; _cache._memberTypes[i] = ((FieldInfo)_cache._memberInfos[i]).FieldType; } _serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache); } if (_obj != null) { _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos); } _isNamed = true; }
public void TestClass1() { DerivedClass1 derived = new DerivedClass1(); derived.anotherInt = 69; MemberInfo [] members = FormatterServices.GetSerializableMembers(derived.GetType()); Assert.IsTrue(members != null, "#01"); Assert.AreEqual(3, members.Length, "#02"); object [] data = FormatterServices.GetObjectData(derived, members); Assert.IsTrue(data != null, "#03"); Assert.AreEqual(3, data.Length, "#04"); DerivedClass1 o = (DerivedClass1)FormatterServices.GetUninitializedObject(derived.GetType()); Assert.IsTrue(o != null, "#05"); o = (DerivedClass1)FormatterServices.PopulateObjectMembers(o, members, data); Assert.IsTrue(o != null, "#06"); Assert.AreEqual("hola", o.Hello, "#07"); Assert.AreEqual(21, o.IntBase, "#08"); Assert.AreEqual(1, o.IntDerived, "#09"); Assert.AreEqual(69, o.anotherInt, "#10"); Assert.AreEqual("hey", DerivedClass1.hey, "#11"); }
private void InitMemberInfo() { this.cache = (SerObjectInfoCache)this.serObjectInfoInit.seenBeforeTable[this.objectType]; if (this.cache == null) { this.cache = new SerObjectInfoCache(); int length = 0; if (!this.objectType.IsByRef) { this.cache.memberInfos = FormatterServices.GetSerializableMembers(this.objectType, this.context); length = this.cache.memberInfos.Length; } this.cache.memberNames = new string[length]; this.cache.memberTypes = new Type[length]; this.cache.memberAttributeInfos = new SoapAttributeInfo[length]; for (int i = 0; i < length; i++) { this.cache.memberNames[i] = this.cache.memberInfos[i].Name; this.cache.memberTypes[i] = this.GetMemberType(this.cache.memberInfos[i]); this.cache.memberAttributeInfos[i] = Attr.GetMemberAttributeInfo(this.cache.memberInfos[i], this.cache.memberNames[i], this.cache.memberTypes[i]); } this.cache.fullTypeName = this.objectType.FullName; this.cache.assemblyString = this.objectType.Module.Assembly.FullName; this.serObjectInfoInit.seenBeforeTable.Add(this.objectType, this.cache); } if (this.obj != null) { this.memberData = FormatterServices.GetObjectData(this.obj, this.cache.memberInfos); } this.isTyped = true; this.isNamed = true; }
public TObject CopyObject <TObject>(TObject originalObject) { object copy; Type type = originalObject.GetType(); // If type is implementing IClonable then return its Clone implementation if (originalObject is ICloneable) { return((TObject)((ICloneable)originalObject).Clone()); } List <MemberInfo> fields = new List <MemberInfo>(); if (type.GetCustomAttributes(typeof(SerializableAttribute), false).Length == 0) { Type t = type; while (t != typeof(object)) { fields.AddRange(t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); t = t.BaseType; } } else { fields.AddRange(FormatterServices.GetSerializableMembers(originalObject.GetType())); } copy = FormatterServices.GetUninitializedObject(originalObject.GetType()); object[] values = FormatterServices.GetObjectData(originalObject, fields.ToArray()); FormatterServices.PopulateObjectMembers(copy, fields.ToArray(), values); return((TObject)copy); }
// X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Runtime\Serialization\FormatterServices.cs /// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { var o = new xFoo(); Console.WriteLine(new { o }); //var x = typeof(o); var x = o.GetType(); Console.WriteLine("GetUninitializedObject"); // sometime later var oo = FormatterServices.GetUninitializedObject(x); //var isFoo = oo as xFoo; var isFoo = oo is xFoo; // Uncaught TypeError: Cannot read property 'LgEABvEJMzKFrGX3QxjvzA' of null var om = FormatterServices.GetSerializableMembers(x); var ov = FormatterServices.GetObjectData(o, om); FormatterServices.PopulateObjectMembers(oo, om, ov); // 0:34ms {{ isFoo = true, oo = xFoo: {{ xField1 = field1 {{ Counter = 1 }} }} }} // 0:80ms {{ isFoo = true, oo = xFoo: {{ xField1 = null }} }} // do we still see ToString? Console.WriteLine(new { isFoo, oo }); }
/// <summary> /// Shallow copy |instance| to |copy|. Use with care. /// /// (This covers the case where we want to shallow copy into an existing object, /// which is not handled by Object.MemberwiseCopy). /// </summary> /// <typeparam name="T"></typeparam> /// <param name="copy"></param> /// <param name="instance"></param> /// <returns></returns> public static void Copy <T>(T copy, T instance) { var type = instance.GetType(); var fields = new List <MemberInfo>(); if (type.GetCustomAttributes(typeof(SerializableAttribute), false).Length == 0) { var t = type; while (t != typeof(Object)) { Debug.Assert(t != null, "t != null"); fields.AddRange( t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); t = t.BaseType; } } else { fields.AddRange(FormatterServices.GetSerializableMembers(instance.GetType())); } var values = FormatterServices.GetObjectData(instance, fields.ToArray()); FormatterServices.PopulateObjectMembers(copy, fields.ToArray(), values); }
public override void WriteObjectData(ObjectWriter ow, BinaryWriter writer, object data) { object[] values = FormatterServices.GetObjectData(data, members); for (int n = 0; n < values.Length; n++) { ow.WriteValue(writer, ((FieldInfo)members[n]).FieldType, values[n]); } }
public override void WriteObjectData(ObjectWriter ow, BinaryWriter writer, object data) { object[] objectData = FormatterServices.GetObjectData(data, this.members); for (int i = 0; i < objectData.Length; i++) { ow.WriteValue(writer, ((FieldInfo)this.members[i]).FieldType, objectData[i]); } }
public c_Settings() { if (Default == null) { return; } MemberInfo[] members = FormatterServices.GetSerializableMembers(typeof(c_Settings)); FormatterServices.PopulateObjectMembers(this, members, FormatterServices.GetObjectData(Default, members)); }
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) { info.AddValue("type", obj.GetType()); string[] names = null; MemberInfo[] serializableMembers = FormatterServicesNoSerializableCheck.GetSerializableMembers(obj.GetType(), out names); object[] objectData = FormatterServices.GetObjectData(obj, serializableMembers); info.AddValue("memberDatas", objectData); info.SetType(typeof(ObjectSerializedRef)); }
public void GetObjectData(SerializationInfo info, StreamingContext context) { var members = FormatterServices.GetSerializableMembers(GetType(), context); var kernelmembers = FormatterServices.GetObjectData(this, members); info.AddValue("members", kernelmembers, typeof(object[])); info.AddValue("HandlerRegisteredEvent", HandlerRegistered); }
public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); MemberInfo[] members = FormatterServices.GetSerializableMembers(GetType(), context); object[] kernelmembers = FormatterServices.GetObjectData(this, members); info.AddValue("members", kernelmembers, typeof(object[])); }
public static object DeepClone(this object obj, Type type) { var members = FormatterServices.GetSerializableMembers(type); var data = FormatterServices.GetObjectData(obj, members); var cloned = FormatterServices.GetSafeUninitializedObject(type); FormatterServices.PopulateObjectMembers (cloned, members, data); return(cloned); }
protected T DeepClone <T>(Type type) { var members = FormatterServices.GetSerializableMembers(type); var data = FormatterServices.GetObjectData(this, members); var cloned = FormatterServices.GetSafeUninitializedObject(type); FormatterServices.PopulateObjectMembers(cloned, members, data); return((T)cloned); }
private void WriteObject(object graph) { var tp = graph.GetType(); ISerializationSurrogate surrogate; ISurrogateSelector selector; if (this.SurrogateSelector != null && (surrogate = this.SurrogateSelector.GetSurrogate(tp, this.Context, out selector)) != null) { var si = new SerializationInfo(tp, this.Converter); if (tp.IsPrimitive) { surrogate.GetObjectData(graph, si, this.Context); } this.WriteFromSerializationInfo(si); } else if (graph is ISerializable) { if (!tp.IsSerializable) { throw new SerializationException(string.Format("{0} {1} is a non-serializable type.", tp.FullName, tp.Assembly.FullName)); } var si = new SerializationInfo(tp, this.Converter); ((ISerializable)graph).GetObjectData(si, this.Context); this.WriteFromSerializationInfo(si); } else { _writer.WriteStartObject(); _writer.WritePropertyName(ID_TYPE); _writer.WriteValue(tp.FullName); var members = FormatterServices.GetSerializableMembers(graph.GetType(), Context); var objs = FormatterServices.GetObjectData(graph, members); for (int i = 0; i < objs.Length; i++) { _writer.WritePropertyName(members[i].Name); if (objs[i] == null) { _writer.WriteValue(null); continue; } else { this.WriteValue(objs[i]); } } _writer.WriteEndObject(); } }
static void LookIntoSerialization() { //1 MemberInfo[] members = FormatterServices.GetSerializableMembers(typeof(SClass)); //2 SClass sc = new SClass(1, 1); object[] values = FormatterServices.GetObjectData(sc, members); //3 将对象的程序集表示序列化 //4 将字段值序列化 }
public void GetObjectData(SerializationInfo si, StreamingContext context) { Type t = typeof(Employee); MemberInfo[] mi = FormatterServices.GetSerializableMembers(t); Object os = FormatterServices.GetObjectData(this, mi); si.AddValue("EmployeeStuff", os); si.AddValue("Reports", this.m_Reports); si.AddValue("Bonus", this.m_BonusPerReport); }
public static void AddFieldValues(SerializationInfo serializationInfo, object instance) { ArgumentUtility.CheckNotNull("serializationInfo", serializationInfo); ArgumentUtility.CheckNotNull("instance", instance); var members = FormatterServices.GetSerializableMembers(instance.GetType()); var mapping = s_serializableFieldFinder.GetSerializableFieldMapping(members.Cast <FieldInfo>()).ToArray(); var data = FormatterServices.GetObjectData(instance, members); for (int i = 0; i < mapping.Length; i++) { serializationInfo.AddValue(mapping[i].Item1, data[i]); } }
private void SerializeSimpleObject( object currentObject, long currentObjectId) { Type currentType = currentObject.GetType(); // Value type have to be serialized "on the fly" so // SerializeComponent calls SerializeObject when // a field of another object is a struct. A node with the field // name has already be written so WriteStartElement must not be called // again. Fields that are structs are passed to SerializeObject // with a id = 0 if (currentObjectId > 0) { Element element = _mapper.GetXmlElement(currentType); _xmlWriter.WriteStartElement(element.Prefix, element.LocalName, element.NamespaceURI); Id(currentObjectId); } if (currentType == typeof(TimeSpan)) { _xmlWriter.WriteString(SoapTypeMapper.GetXsdValue(currentObject)); } else if (currentType == typeof(string)) { _xmlWriter.WriteString(currentObject.ToString()); } else { MemberInfo[] memberInfos = FormatterServices.GetSerializableMembers(currentType, _context); object[] objectData = FormatterServices.GetObjectData(currentObject, memberInfos); #if FIXED for (int i = 0; i < memberInfos.Length; i++) { FieldInfo fieldInfo = (FieldInfo)memberInfos[i]; SoapFieldAttribute at = (SoapFieldAttribute)InternalRemotingServices.GetCachedSoapAttribute(fieldInfo); _xmlWriter.WriteStartElement(XmlConvert.EncodeLocalName(at.XmlElementName)); SerializeComponent( objectData[i], IsEncodingNeeded(objectData[i], fieldInfo.FieldType)); _xmlWriter.WriteEndElement(); } #endif } if (currentObjectId > 0) { _xmlWriter.WriteFullEndElement(); } }