private object DeserializeObject(object sourceValue, Type destinationType) { byte[] buffer; Exception ex; if (!this.CanConvert(sourceValue, destinationType, out buffer, out ex)) { throw ex; } object obj; using (MemoryStream memoryStream = new MemoryStream(buffer)) { AppDomain.CurrentDomain.AssemblyResolve += SerializationTypeConverter.AssemblyHandler; try { BinaryFormatter binaryFormatter = new BinaryFormatter(); obj = binaryFormatter.Deserialize(memoryStream); IDeserializationCallback deserializationCallback = obj as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(sourceValue); } } finally { AppDomain.CurrentDomain.AssemblyResolve -= SerializationTypeConverter.AssemblyHandler; } } return(obj); }
public void Deserialization() { TextInfo ti = CultureInfo.CurrentCulture.TextInfo; IDeserializationCallback dc = (ti as IDeserializationCallback); dc.OnDeserialization(null); }
/// <summary> /// Runs when the entire object graph has been deserialized. /// </summary> /// <param name="sender">The object that initiated the callback. The functionality for this parameter is not currently implemented.</param> public void OnDeserialization(object sender) { IDeserializationCallback callback = dict as IDeserializationCallback; if (callback != null) { callback.OnDeserialization(sender); } }
public void Interfaces() { WindowsIdentity id = WindowsIdentity.GetAnonymous(); IIdentity i = (id as IIdentity); Assert.IsNotNull(i, "IIdentity"); IDeserializationCallback dc = (id as IDeserializationCallback); Assert.IsNotNull(dc, "IDeserializationCallback"); ISerializable s = (id as ISerializable); Assert.IsNotNull(s, "ISerializable"); }
object IObjectReference.GetRealObject(StreamingContext context) { ExtensionRegistry registry = context.Context as ExtensionRegistry; TBuilder builder = TemplateInstance.DefaultInstanceForType.CreateBuilderForType(); builder.MergeFrom(_message, registry ?? ExtensionRegistry.Empty); IDeserializationCallback callback = builder as IDeserializationCallback; if (callback != null) { callback.OnDeserialization(context); } return(builder); }
public virtual void RaiseDeserializationEvent() { for (int i = _onDeserializedCallbackRecords.Count - 1; i >= 0; i--) { ObjectRecord record = (ObjectRecord)_onDeserializedCallbackRecords [i]; RaiseOnDeserializedEvent(record.OriginalObject); } for (int i = _deserializedRecords.Count - 1; i >= 0; i--) { ObjectRecord record = (ObjectRecord)_deserializedRecords [i]; IDeserializationCallback obj = record.OriginalObject as IDeserializationCallback; if (obj != null) { obj.OnDeserialization(this); } } }
private object deserialize(XmlReader xmlReader, int id, SerializationInfo info, List <int> dimensionLengths, IFormatterConverter converter) { System.Diagnostics.Debug.Assert(null != xmlReader, "The 'xmlReader' argument cannot be null."); System.Diagnostics.Debug.Assert(null != info, "The 'info' argument cannot be null."); System.Diagnostics.Debug.Assert(null != converter, "The 'converter' argument cannot be null."); string assemblyQualifiedTypeName = string.Format("{0}, {1}", info.FullTypeName, info.AssemblyName); Type objectType = new TypeParser().Resolve(assemblyQualifiedTypeName); object deserialized = null; // Return value if (this.isSimpleType(objectType)) { deserialized = this.readValue(xmlReader, objectType, converter); } else if (objectType.IsArray) { Type elementType = objectType.GetElementType(); deserialized = this.deserializeArray(xmlReader, id, elementType, dimensionLengths, converter); } else { deserialized = this.deserializeObject(xmlReader, id, objectType, info, converter); } IObjectReference objectReference = deserialized as IObjectReference; if (null != objectReference) { deserialized = objectReference.GetRealObject(this.context); } IDeserializationCallback deserializationCallback = deserialized as IDeserializationCallback; if (null != deserializationCallback) { deserializationCallback.OnDeserialization(this); } if (XmlNodeType.EndElement == xmlReader.NodeType) { xmlReader.ReadEndElement(); } return(deserialized); }
/// <summary>Raises the deserialization event to any registered object that implements <see cref="T:System.Runtime.Serialization.IDeserializationCallback" />.</summary> public virtual void RaiseDeserializationEvent() { for (int i = this._onDeserializedCallbackRecords.Count - 1; i >= 0; i--) { ObjectRecord objectRecord = (ObjectRecord)this._onDeserializedCallbackRecords[i]; this.RaiseOnDeserializedEvent(objectRecord.OriginalObject); } for (int j = this._deserializedRecords.Count - 1; j >= 0; j--) { ObjectRecord objectRecord2 = (ObjectRecord)this._deserializedRecords[j]; IDeserializationCallback deserializationCallback = objectRecord2.OriginalObject as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(this); } } }
public static object FromJson(Type type, string str) { object t = JsonUtility.FromJson(str, type); ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize != null) { iSupportInitialize.EndInit(); } IDeserializationCallback deserializationCallback = t as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(t); } return(t); }
public static T FromJson <T>(string str) { T t = JsonUtility.FromJson <T>(str); ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize != null) { iSupportInitialize.EndInit(); } IDeserializationCallback deserializationCallback = t as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(t); } return(t); }
/// <summary> /// Deserializes a value of type <see cref="T" /> using a specified <see cref="IDataReader" />. /// </summary> /// <param name="reader">The reader to use.</param> /// <returns> /// The deserialized value. /// </returns> public T Deserialize(IDataReader reader) { var context = reader.Context; T value = this.GetUninitializedObject(); // We allow the above method to return null (for reference types) because of special cases like arrays, // where the size of the array cannot be known yet, and thus we cannot create an object instance at this time. // // Therefore, those who override GetUninitializedObject and return null must call RegisterReferenceID and InvokeOnDeserializingCallbacks manually. if (BaseFormatter <T> .IsValueType) { this.InvokeOnDeserializingCallbacks(ref value, context); } else { if (object.ReferenceEquals(value, null) == false) { this.RegisterReferenceID(value, reader); this.InvokeOnDeserializingCallbacks(ref value, context); if (ImplementsIObjectReference) { try { value = (T)(value as IObjectReference).GetRealObject(context.StreamingContext); this.RegisterReferenceID(value, reader); } catch (Exception ex) { context.Config.DebugContext.LogException(ex); } } } } try { this.DeserializeImplementation(ref value, reader); } catch (Exception ex) { context.Config.DebugContext.LogException(ex); } // The deserialized value might be null, so check for that if (BaseFormatter <T> .IsValueType || object.ReferenceEquals(value, null) == false) { for (int i = 0; i < OnDeserializedCallbacks.Length; i++) { try { OnDeserializedCallbacks[i](ref value, context.StreamingContext); } catch (Exception ex) { context.Config.DebugContext.LogException(ex); } } if (ImplementsIDeserializationCallback) { IDeserializationCallback v = value as IDeserializationCallback; v.OnDeserialization(this); value = (T)v; } if (ImplementsISerializationCallbackReceiver) { try { UnityEngine.ISerializationCallbackReceiver v = value as UnityEngine.ISerializationCallbackReceiver; v.OnAfterDeserialize(); value = (T)v; } catch (Exception ex) { context.Config.DebugContext.LogException(ex); } } } return(value); }
object Unpack(MsgPackReader reader, Type t) { if (t.IsPrimitive) { if (!reader.Read()) { throw new FormatException(); } if (t.Equals(typeof(int)) && reader.IsSigned()) { return(reader.ValueSigned); } else if (t.Equals(typeof(uint)) && reader.IsUnsigned()) { return(reader.ValueUnsigned); } else if (t.Equals(typeof(float)) && reader.Type == TypePrefixes.Float) { return(reader.ValueFloat); } else if (t.Equals(typeof(double)) && reader.Type == TypePrefixes.Double) { return(reader.ValueDouble); } else if (t.Equals(typeof(long))) { if (reader.IsSigned64()) { return(reader.ValueSigned64); } if (reader.IsSigned()) { return((long)reader.ValueSigned); } } else if (t.Equals(typeof(ulong))) { if (reader.IsUnsigned64()) { return(reader.ValueUnsigned64); } if (reader.IsUnsigned()) { return((ulong)reader.ValueUnsigned); } } else if (t.Equals(typeof(bool)) && reader.IsBoolean()) { return(reader.Type == TypePrefixes.True); } else if (t.Equals(typeof(byte)) && reader.IsUnsigned()) { return((byte)reader.ValueUnsigned); } else if (t.Equals(typeof(sbyte)) && reader.IsSigned()) { return((sbyte)reader.ValueSigned); } else if (t.Equals(typeof(short)) && reader.IsSigned()) { return((short)reader.ValueSigned); } else if (t.Equals(typeof(ushort)) && reader.IsUnsigned()) { return((ushort)reader.ValueUnsigned); } else if (t.Equals(typeof(char)) && reader.IsUnsigned()) { return((char)reader.ValueUnsigned); } else { throw new NotSupportedException(); } } UnpackDelegate unpacker; if (UnpackerMapping.TryGetValue(t, out unpacker)) { return(unpacker(this, reader)); } if (t.IsArray) { if (!reader.Read() || (!reader.IsArray() && reader.Type != TypePrefixes.Nil)) { throw new FormatException(); } if (reader.Type == TypePrefixes.Nil) { return(null); } Type et = t.GetElementType(); Array ary = Array.CreateInstance(et, (int)reader.Length); for (int i = 0; i < ary.Length; i++) { ary.SetValue(Unpack(reader, et), i); } return(ary); } if (!reader.Read()) { throw new FormatException(); } if (reader.Type == TypePrefixes.Nil) { return(null); } if (t.IsInterface) { if (reader.Type != TypePrefixes.FixArray && reader.Length != 2) { throw new FormatException(); } if (!reader.Read() || !reader.IsRaw()) { throw new FormatException(); } CheckBufferSize((int)reader.Length); reader.ReadValueRaw(_buf, 0, (int)reader.Length); t = Type.GetType(Encoding.UTF8.GetString(_buf, 0, (int)reader.Length)); if (!reader.Read() || reader.Type == TypePrefixes.Nil) { throw new FormatException(); } } if (!reader.IsMap()) { throw new FormatException(); } object o = FormatterServices.GetUninitializedObject(t); ReflectionCacheEntry entry = ReflectionCache.Lookup(t); int members = (int)reader.Length; for (int i = 0; i < members; i++) { if (!reader.Read() || !reader.IsRaw()) { throw new FormatException(); } CheckBufferSize((int)reader.Length); reader.ReadValueRaw(_buf, 0, (int)reader.Length); string name = Encoding.UTF8.GetString(_buf, 0, (int)reader.Length); FieldInfo f; if (!entry.FieldMap.TryGetValue(name, out f)) { throw new FormatException(); } f.SetValue(o, Unpack(reader, f.FieldType)); } IDeserializationCallback callback = o as IDeserializationCallback; if (callback != null) { callback.OnDeserialization(this); } return(o); }
public void RegisterObject(object obj, long objectID, SerializationInfo info, long idOfContainingObj, MemberInfo member, int[] arrayIndex) { ISerializationSurrogate surrogate = null; if (obj == null) { throw new ArgumentNullException("obj"); } if (objectID <= 0L) { throw new ArgumentOutOfRangeException("objectID", Environment.GetResourceString("ArgumentOutOfRange_ObjectID")); } if (((member != null) && !(member is RuntimeFieldInfo)) && !(member is SerializationFieldInfo)) { throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo")); } if (this.m_selector != null) { ISurrogateSelector selector; Type type = null; if (this.CanCallGetType(obj)) { type = obj.GetType(); } else { type = typeof(MarshalByRefObject); } surrogate = this.m_selector.GetSurrogate(type, this.m_context, out selector); } if (obj is IDeserializationCallback) { IDeserializationCallback callback1 = (IDeserializationCallback)obj; DeserializationEventHandler handler = new DeserializationEventHandler(callback1.OnDeserialization); this.AddOnDeserialization(handler); } if (arrayIndex != null) { arrayIndex = (int[])arrayIndex.Clone(); } ObjectHolder holder = this.FindObjectHolder(objectID); if (holder == null) { holder = new ObjectHolder(obj, objectID, info, surrogate, idOfContainingObj, (FieldInfo)member, arrayIndex); this.AddObjectHolder(holder); if (holder.RequiresDelayedFixup) { this.SpecialFixupObjects.Add(holder); } this.AddOnDeserialized(obj); } else { if (holder.ObjectValue != null) { throw new SerializationException(Environment.GetResourceString("Serialization_RegisterTwice")); } holder.UpdateData(obj, info, surrogate, idOfContainingObj, (FieldInfo)member, arrayIndex, this); if (holder.DirectlyDependentObjects > 0) { this.CompleteObject(holder, false); } if (holder.RequiresDelayedFixup) { this.SpecialFixupObjects.Add(holder); } if (holder.CompletelyFixed) { this.DoNewlyRegisteredObjectFixups(holder); holder.DependentObjects = null; } if (holder.TotalDependentObjects > 0) { this.AddOnDeserialized(obj); } else { this.RaiseOnDeserializedEvent(obj); } } }
public void OnDeserialization(object sender) { IDeserializationCallback callback = m_dictionaryTyped as IDeserializationCallback; callback.OnDeserialization(sender); }
private object DeserializeObject(object sourceValue, Type destinationType) { Exception ex = null; byte[] array; string text; if (!this.CanConvert(sourceValue, destinationType, out array, out text, out ex)) { throw ex; } ExTraceGlobals.SerializationTracer.TraceFunction <object, string>((long)this.GetHashCode(), "SerializationTypeConverter.DeserializeObject(); SerializationData.Length = {0}; ToStringValue = '{1}'", (array == null) ? "<null>" : array.Length, text); object obj = null; try { using (MemoryStream memoryStream = new MemoryStream(array)) { AppDomain.CurrentDomain.AssemblyResolve += SerializationTypeConverter.AssemblyHandler; try { int tickCount = Environment.TickCount; if (SerializationTypeConverter.IsRunningInRPSServerSide.Value) { if (SerializationTypeBinder.Instance == null) { throw new InvalidCastException("SerializationTypeBinder initialization failed."); } obj = TypedBinaryFormatter.DeserializeObject(memoryStream, SerializationTypeBinder.Instance); } else { BinaryFormatter binaryFormatter = ExchangeBinaryFormatterFactory.CreateBinaryFormatter(null, new string[] { "System.Management.Automation.PSObject", "System.DelegateSerializationHolder" }); obj = binaryFormatter.Deserialize(memoryStream); } ExTraceGlobals.SerializationTracer.TraceDebug <string, int>((long)this.GetHashCode(), "DeserializeObject of type {0} succeeded in {1} ms.", (obj != null) ? obj.GetType().Name : "null", Environment.TickCount - tickCount); IDeserializationCallback deserializationCallback = obj as IDeserializationCallback; if (deserializationCallback != null) { deserializationCallback.OnDeserialization(sourceValue); } } finally { AppDomain.CurrentDomain.AssemblyResolve -= SerializationTypeConverter.AssemblyHandler; } } } catch (SerializationException ex2) { ExTraceGlobals.SerializationTracer.TraceDebug <SerializationException>((long)this.GetHashCode(), "Deserialization Failed. Error = {0}", ex2); if (ValueConvertor.TryConvertValueFromString(text, destinationType, null, out obj, out ex)) { ExTraceGlobals.SerializationTracer.TraceDebug <SerializationException>((long)this.GetHashCode(), "String Conversion Succeeded.", ex2); } else { ex = new InvalidCastException(string.Format("Deserialization fails due to one SerializationException: {0}", ex2.ToString()), ex2); } } catch (DataSourceTransientException ex3) { ex = new InvalidCastException(string.Format("Deserialization fails due to an DataSourceTransientException: {0}", ex3.ToString()), ex3); } if (ex is InvalidCastException) { throw ex; } return(obj); }
/// <summary> /// Runs when the entire object graph has been deserialized. /// </summary> /// <param name="sender">The object that initiated the callback. The functionality for this parameter is not currently implemented.</param> public void OnDeserialization(object sender) { IDeserializationCallback callback = dict as IDeserializationCallback; callback.OnDeserialization(sender); }
object Unpack(MsgPackReader reader, Type t) { if (t.IsPrimitive) { if (!reader.Read()) { throw new FormatException(); } if (t.Equals(typeof(int)) && reader.IsSigned()) { return(reader.ValueSigned); } else if (t.Equals(typeof(uint)) && reader.IsUnsigned()) { return(reader.ValueUnsigned); } else if (t.Equals(typeof(float)) && reader.Type == TypePrefixes.Float) { return(reader.ValueFloat); } else if (t.Equals(typeof(double)) && reader.Type == TypePrefixes.Double) { return(reader.ValueDouble); } else if (t.Equals(typeof(long))) { if (reader.IsSigned64()) { return(reader.ValueSigned64); } if (reader.IsSigned()) { return((long)reader.ValueSigned); } } else if (t.Equals(typeof(ulong))) { if (reader.IsUnsigned64()) { return(reader.ValueUnsigned64); } if (reader.IsUnsigned()) { return((ulong)reader.ValueUnsigned); } } else if (t.Equals(typeof(bool)) && reader.IsBoolean()) { return(reader.Type == TypePrefixes.True); } else if (t.Equals(typeof(byte)) && reader.IsUnsigned()) { return((byte)reader.ValueUnsigned); } else if (t.Equals(typeof(sbyte)) && reader.IsSigned()) { return((sbyte)reader.ValueSigned); } else if (t.Equals(typeof(short)) && reader.IsSigned()) { return((short)reader.ValueSigned); } else if (t.Equals(typeof(ushort)) && reader.IsUnsigned()) { return((ushort)reader.ValueUnsigned); } else if (t.Equals(typeof(char)) && reader.IsUnsigned()) { return((char)reader.ValueUnsigned); } else { throw new NotSupportedException(); } } UnpackDelegate unpacker; if (UnpackerMapping.TryGetValue(t, out unpacker)) { return(unpacker(this, reader)); } if (typeof(Packable).IsAssignableFrom(t)) { Packable p = Activator.CreateInstance(t) as Packable; return(p.Unpack(this, reader)); } if (t.IsArray) { if (!reader.Read() || (!reader.IsArray() && reader.Type != TypePrefixes.Nil)) { throw new FormatException(); } if (reader.Type == TypePrefixes.Nil) { return(null); } Type et = t.GetElementType(); Array ary = Array.CreateInstance(et, (int)reader.Length); for (int i = 0; i < ary.Length; i++) { ary.SetValue(Unpack(reader, et), i); } return(ary); } // IEnumerable 型の場合 // 現在は IList, ISet, IDictionary をサポート if (typeof(IEnumerable).IsAssignableFrom(t) && t.IsGenericType) { Type[] generics = t.GetGenericArguments(); // IList 型の場合 if (typeof(IList).IsAssignableFrom(t)) { if (!reader.Read() || (!reader.IsArray() && reader.Type != TypePrefixes.Nil)) { throw new FormatException(); } if (reader.Type == TypePrefixes.Nil) { return(null); } Type et = generics.Single(); int count = (int)reader.Length; Array ary = Array.CreateInstance(et, count); for (int i = 0; i < count; i++) { ary.SetValue(Unpack(reader, et), i); } return(Activator.CreateInstance(t, new object[] { ary })); } // ISet 型の場合 var setType = typeof(ISet <>).MakeGenericType(generics[0]); if (setType.IsAssignableFrom(t)) { if (!reader.Read() || (!reader.IsArray() && reader.Type != TypePrefixes.Nil)) { throw new FormatException(); } if (reader.Type == TypePrefixes.Nil) { return(null); } Type et = generics.Single(); int count = (int)reader.Length; Array ary = Array.CreateInstance(et, count); for (int i = 0; i < count; i++) { ary.SetValue(Unpack(reader, et), i); } return(Activator.CreateInstance(t, new object[] { ary })); } if (typeof(IDictionary).IsAssignableFrom(t)) { if (!reader.Read() || (!reader.IsArray() && reader.Type != TypePrefixes.Nil)) { throw new FormatException(); } if (reader.Type == TypePrefixes.Nil) { return(null); } Type kt = generics[0]; Type vt = generics[1]; IDictionary dict = (IDictionary)Activator.CreateInstance(t); int count = (int)reader.Length; for (int i = 0; i < count; i++) { dict[Unpack(reader, kt)] = Unpack(reader, vt); } return(dict); } } if (!reader.Read()) { throw new FormatException(); } if (reader.Type == TypePrefixes.Nil) { return(null); } if (t.IsInterface) { if (reader.Type != TypePrefixes.FixArray && reader.Length != 2) { throw new FormatException(); } if (!reader.Read() || !reader.IsRaw()) { throw new FormatException(); } CheckBufferSize((int)reader.Length); reader.ReadValueRaw(_buf, 0, (int)reader.Length); t = Type.GetType(Encoding.UTF8.GetString(_buf, 0, (int)reader.Length)); if (!reader.Read() || reader.Type == TypePrefixes.Nil) { throw new FormatException(); } } if (!reader.IsMap()) { throw new FormatException(); } object o = FormatterServices.GetUninitializedObject(t); ReflectionCacheEntry entry = ReflectionCache.Lookup(t); int members = (int)reader.Length; for (int i = 0; i < members; i++) { if (!reader.Read() || !reader.IsRaw()) { throw new FormatException(); } CheckBufferSize((int)reader.Length); reader.ReadValueRaw(_buf, 0, (int)reader.Length); string name = Encoding.UTF8.GetString(_buf, 0, (int)reader.Length); FieldInfo f; if (!entry.FieldMap.TryGetValue(name, out f)) { throw new FormatException(); } f.SetValue(o, Unpack(reader, f.FieldType)); } IDeserializationCallback callback = o as IDeserializationCallback; if (callback != null) { callback.OnDeserialization(this); } return(o); }