/// <summary> /// Recupera o substituto para tratar o tipo. /// </summary> /// <param name="handle"></param> /// <param name="cacheContext"></param> /// <returns></returns> internal static ISerializationSurrogate GetSurrogateForTypeHandle(short handle, string cacheContext) { ISerializationSurrogate defaultSurrogate = null; if (handle < CUSTOM_TYPE_RANGE) { defaultSurrogate = (ISerializationSurrogate)handleSurrogateMap[handle]; } else { Hashtable hashtable = (Hashtable)userTypeHandleSurrogateMap[cacheContext]; if ((hashtable != null) && hashtable.Contains(handle)) { if (!(hashtable[handle] is ISerializationSurrogate)) { return(null); } defaultSurrogate = (ISerializationSurrogate)hashtable[handle]; } } if (defaultSurrogate == null) { defaultSurrogate = TypeSurrogateSelector.defaultSurrogate; } return(defaultSurrogate); }
internal Registration(double startVersion, Type targetType, ISerializationSurrogate surrogate) { this.startVersion = startVersion; this.endVersion = Double.MaxValue; this.targetType = targetType; this.surrogate = surrogate; }
/// <summary> /// Deserializes an object from the specified compact binary writer. /// </summary> /// <param name="reader">Stream containing reader</param> /// <param name="cacheContext">Name of the cache</param> /// <param name="skip">True to skip the bytes returning null</param> static internal object Deserialize(CompactBinaryReader reader, string cacheContext, bool skip) { // read type handle short handle = reader.ReadInt16(); reader.Context.CacheContext = cacheContext; // Find an appropriate surrogate by handle ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, cacheContext); if (surrogate == null) { surrogate = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, reader.ReadInt16(), cacheContext); } if (surrogate == null) { throw new CompactSerializationException("Type handle " + handle + "is not registered with Compact Serialization Framework"); } if (!skip) { return(surrogate.Read(reader)); } else { surrogate.Skip(reader); return(null); } }
/// <summary> /// Returns the surrogate for a particular type. /// </summary> /// /// <returns>The surrogate for a particular type.</returns> /// <param name="type">The <see cref="T:System.Type"/> for which the surrogate is /// requested.</param> /// <param name="context">The streaming context.</param> /// <param name="selector">The surrogate to use.</param> /// <exception cref="T:System.ArgumentNullException">The /// <paramref name="type"/>parameter is null.</exception> /// <exception cref="T:System.Security.SecurityException">The caller does not have the /// required permission.</exception> /// <PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter"/></PermissionSet> public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) { if (type == null) { throw new ArgumentNullException("type is null."); } Dictionary <StreamingContextStates, ISerializationSurrogate> surrogates; ISerializationSurrogate serializationSurrogate = null; if (_surrogates.TryGetValue(type, out surrogates)) { surrogates.TryGetValue(context.State, out serializationSurrogate); } if (serializationSurrogate != null) { selector = this; return(serializationSurrogate); } else { if (_nextSelector != null) { return(_nextSelector.GetSurrogate(type, context, out selector)); } selector = null; return(null); } }
private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, string assemblyName) { if (objectType.IsArray) { this.arrayElemObjectInfo = Create(objectType.GetElementType(), surrogateSelector, context, this.objectManager, this.serObjectInfoInit, this.formatterConverter, assemblyName); this.typeAttributeInfo = this.GetTypeAttributeInfo(); this.InitNoMembers(); } else { ISurrogateSelector selector = null; if (surrogateSelector != null) { this.serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out selector); } if (this.serializationSurrogate != null) { this.isSi = true; } else if (!(objectType == Converter.typeofObject) && Converter.typeofISerializable.IsAssignableFrom(objectType)) { this.isSi = true; } if (this.isSi) { this.si = new SerializationInfo(objectType, this.formatterConverter); this.InitSiRead(assemblyName); } else { this.InitMemberInfo(); } } }
/// <summary> /// this method will filter out any IList or IDictionary surrogate if already exists in userTypeMap /// </summary> /// <param name="type"></param> /// <param name="cacheContext"></param> /// <returns></returns> static internal ISerializationSurrogate CheckForListAndDictionaryTypes(Type type, string cacheContext) { ISerializationSurrogate surrogate = null; if (cacheContext != null) { Hashtable userTypeMap = (Hashtable)userTypeSurrogateMap[cacheContext]; if (userTypeMap != null) { Type listOrDictionaryType = null; IDictionaryEnumerator ide = userTypeMap.GetEnumerator(); while (ide.MoveNext()) { listOrDictionaryType = (Type)ide.Key; if (listOrDictionaryType != null && listOrDictionaryType.FullName == typeof(IList <>).FullName && type.FullName == typeof(List <>).FullName) { surrogate = (ISerializationSurrogate)userTypeMap[listOrDictionaryType]; break; } if (listOrDictionaryType != null && listOrDictionaryType.FullName == typeof(IDictionary <,>).FullName && type.FullName == typeof(Dictionary <,>).FullName) { surrogate = (ISerializationSurrogate)userTypeMap[listOrDictionaryType]; break; } } } } return(surrogate); }
public override void Skip(CompactBinaryReader reader) { // read type handle short handle = reader.ReadInt16(); // Find an appropriate surrogate by handle ISerializationSurrogate typeSurr = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, null); if (typeSurr == null) { typeSurr = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, reader.ReadInt16(), reader.Context.CacheContext); } int length = reader.ReadInt32(); T?[] array = new T?[length]; while (true) { int index = reader.ReadInt32(); if (index < 0) { break; } typeSurr.Skip(reader); } }
/// <summary> /// Registra um tipo compacto. /// </summary> /// <param name="type"></param> public static void RegisterCompactType(Type type) { type.Require("type").NotNull(); if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type, null) != null) { throw new ArgumentException(ResourceMessageFormatter.Create(() => Properties.Resources.Argument_TypeAlreadyRegistered2, type.FullName).Format()); } ISerializationSurrogate surrogate = null; if (typeof(IDictionary).IsAssignableFrom(type)) { surrogate = new IDictionarySerializationSurrogate(type); } else if (type.IsArray) { surrogate = new ArraySerializationSurrogate(type); } else if (typeof(IList).IsAssignableFrom(type)) { surrogate = new IListSerializationSurrogate(type); } else if (typeof(ICompactSerializable).IsAssignableFrom(type)) { surrogate = new ICompactSerializableSerializationSurrogate(type); } else if (typeof(Enum).IsAssignableFrom(type)) { surrogate = new EnumSerializationSurrogate(type); } if (surrogate == null) { throw new ArgumentException(ResourceMessageFormatter.Create(() => Properties.Resources.Argument_NoAppropriateSurrogateFound, type.FullName).Format()); } TypeSurrogateSelector.RegisterTypeSurrogate(surrogate); }
/// <summary> /// Reads an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> /// <returns>object read from the stream</returns> public override object ReadObject() { // read type handle short handle = reader.ReadInt16(); // Find an appropriate surrogate by handle ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, context.CacheContext); object obj = null; try { obj = surrogate.Read(this); } catch (CompactSerializationException) { throw; } catch (Exception e) { throw new CompactSerializationException(e.Message, e); } return(obj); }
/// <summary> /// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given /// type handle. /// </summary> /// <param name="handle">type handle</param> /// <returns><see cref="ISerializationSurrogate"/>Object otherwise returns null if typeHandle is base Handle if Portable</returns> static internal ISerializationSurrogate GetSurrogateForTypeHandle(short handle, string cacheContext) { ISerializationSurrogate surrogate = null; if (handle < CUSTOM_TYPE_RANGE) { surrogate = (ISerializationSurrogate)handleSurrogateMap[handle]; } else { Hashtable userTypeMap = (Hashtable)userTypeHandleSurrogateMap[cacheContext.ToLower()]; if (userTypeMap != null) { if (userTypeMap.Contains(handle)) { if (userTypeMap[handle] is ISerializationSurrogate) { surrogate = (ISerializationSurrogate)userTypeMap[handle]; } else { return(null); } } } } if (surrogate == null) { surrogate = defaultSurrogate; } return(surrogate); }
/// <summary> /// Skips an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> public override void SkipObject() { // read type handle short handle = reader.ReadInt16(); // Find an appropriate surrogate by handle ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, context.CacheContext); if (surrogate == null) { surrogate = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, reader.ReadInt16(), context.CacheContext); } //If surrogate not found, returns defaultSurrogate //if (surrogate == null) throw new CompactSerializationException("Type handle " + handle + " is not registered with Compact Serialization Framework"); try { surrogate.Skip(this); } catch (CompactSerializationException) { throw; } catch (Exception e) { throw new CompactSerializationException(e.Message); } }
private protected bool TryGetSurrogate(Type type, out ISerializationSurrogate surrogate, out ISurrogateSelector selector) { surrogate = null; selector = null; if (surrogateSelector == null) { return(false); } if (surrogates.TryGetValue(type, out KeyValuePair <ISerializationSurrogate, ISurrogateSelector> result)) { if (result.Key == null) { return(false); } surrogate = result.Key; selector = result.Value; return(true); } DoGetSurrogate(type, out surrogate, out selector); surrogates[type] = new KeyValuePair <ISerializationSurrogate, ISurrogateSelector>(surrogate, selector); return(surrogate != null); }
internal SurrogateDataContractCriticalHelper(Type type, ISerializationSurrogate serializationSurrogate) : base(type) { _serializationSurrogate = serializationSurrogate; DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(type), out string name, out string ns); SetDataContractName(CreateQualifiedName(name, ns)); }
static Packet() { surrogateSelector = new SurrogateSelector(); streamingContext = new StreamingContext(StreamingContextStates.All); // Our surrogates can be safely used in every context. IEnumerable <Type> types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes() .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(SerializationSurrogate <>) && t.IsClass && !t.IsAbstract)); foreach (Type type in types) { ISerializationSurrogate surrogate = (ISerializationSurrogate)Activator.CreateInstance(type); Type surrogatedType = type.BaseType.GetGenericArguments()[0]; surrogateSelector.AddSurrogate(surrogatedType, streamingContext, surrogate); Log.Debug("Added surrogate " + surrogate.GetType().Name + " for type " + surrogatedType); } // For completeness, we could pass a StreamingContextStates.CrossComputer. serializer = new BinaryFormatter(surrogateSelector, streamingContext); }
private void FixupSpecialObject(ObjectHolder holder) { ISurrogateSelector selector = null; if (holder.HasSurrogate) { ISerializationSurrogate surrogate = holder.Surrogate; object obj = surrogate.SetObjectData(holder.ObjectValue, holder.SerializationInfo, this.m_context, selector); if (obj != null) { if (!holder.CanSurrogatedObjectValueChange && obj != holder.ObjectValue) { throw new SerializationException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Serialization_NotCyclicallyReferenceableSurrogate"), surrogate.GetType().FullName)); } holder.SetObjectValue(obj, this); } holder.m_surrogate = null; holder.SetFlags(); } else { this.CompleteISerializableObject(holder.ObjectValue, holder.SerializationInfo, this.m_context); } holder.SerializationInfo = null; holder.RequiresSerInfoFixup = false; if (holder.RequiresValueTypeFixup && holder.ValueTypeFixupPerformed) { this.DoValueTypeFixup(null, holder, holder.ObjectValue); } this.DoNewlyRegisteredObjectFixups(holder); }
/// <summary> /// Writes <paramref name="graph"/> to the current stream and advances the stream position. /// </summary> /// <param name="graph">Object to write</param> public override void WriteObject(object graph) { // Find an appropriate surrogate for the object ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForObject(graph, context.CacheContext); // write type handle writer.Write(surrogate.TypeHandle); try { surrogate.Write(this, graph); } catch (CompactSerializationException) { throw; } catch (System.Threading.ThreadAbortException) { throw; } catch (System.Threading.ThreadInterruptedException) { throw; } catch (Exception e) { throw new CompactSerializationException(e.Message); } }
internal ObjectHolder(object obj, long objID, System.Runtime.Serialization.SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainingObj, FieldInfo field, int[] arrayIndex) { this.m_object = obj; this.m_id = objID; this.m_flags = 0; this.m_missingElementsRemaining = 0; this.m_missingDecendents = 0; this.m_dependentObjects = null; this.m_next = null; this.m_serInfo = info; this.m_surrogate = surrogate; this.m_markForFixupWhenAvailable = false; if (obj is TypeLoadExceptionHolder) { this.m_typeLoad = (TypeLoadExceptionHolder) obj; } if ((idOfContainingObj != 0L) && (((field != null) && field.FieldType.IsValueType) || (arrayIndex != null))) { if (idOfContainingObj == objID) { throw new SerializationException(Environment.GetResourceString("Serialization_ParentChildIdentical")); } this.m_valueFixup = new ValueTypeFixupInfo(idOfContainingObj, field, arrayIndex); } this.SetFlags(); }
/// <summary> /// Unregisters the surrogate for the Custom specified type that implements /// <see cref="ICompactSerializable"/> from the system. /// </summary> /// <param name="type">the specified type</param> static public void UnregisterCustomCompactType(Type type, string cacheContext) { throw new NotImplementedException(); if (type == null) { throw new ArgumentNullException("type"); } if (cacheContext == null) { throw new ArgumentException("cacheContext can not be null"); } if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type, cacheContext) == null) { return; } if (type.IsArray || //typeof(IDictionary).IsAssignableFrom(type) || //typeof(IList).IsAssignableFrom(type) || typeof(Dictionary <,>).Equals(type) || typeof(List <>).Equals(type) || typeof(ICompactSerializable).IsAssignableFrom(type) || typeof(Enum).IsAssignableFrom(type)) { ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type, cacheContext); TypeSurrogateSelector.UnregisterTypeSurrogate(surrogate, cacheContext); System.Diagnostics.Debug.WriteLine("Unregistered surrogate for type " + type.FullName); } }
public override void WriteDirect(CompactBinaryWriter writer, object graph) { object[] array = (object[])graph; writer.Write(array.Length); if (!typeof(object[]).Equals(graph.GetType())) { object obj = null; for (int i = 0; i < array.Length; i++) { if (array[i] != null) { obj = array[i]; break; } } ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForObject(obj, writer.CacheContext); writer.Write(surrogate.TypeHandle); if (surrogate.SubTypeHandle > 0) { writer.Write(surrogate.SubTypeHandle); } } else { ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForObject(new object(), writer.CacheContext); writer.Write(surrogate.TypeHandle); } for (int i = 0; i < array.Length; i++) { writer.WriteObject(array[i]); } }
private static T FormatterClone <T>( T obj, ISerializationSurrogate surrogate = null, FormatterAssemblyStyle assemblyFormat = FormatterAssemblyStyle.Full, TypeFilterLevel filterLevel = TypeFilterLevel.Full, FormatterTypeStyle typeFormat = FormatterTypeStyle.TypesAlways) { BinaryFormatter f; if (surrogate == null) { f = new BinaryFormatter(); } else { var c = new StreamingContext(); var s = new SurrogateSelector(); s.AddSurrogate(obj.GetType(), c, surrogate); f = new BinaryFormatter(s, c); } f.AssemblyFormat = assemblyFormat; f.FilterLevel = filterLevel; f.TypeFormat = typeFormat; using (var s = new MemoryStream()) { f.Serialize(s, obj); Assert.NotEqual(0, s.Position); s.Position = 0; return((T)(f.Deserialize(s))); } }
public override void Skip(CompactBinaryReader reader) { ISerializationSurrogate decimalSurrogate = TypeSurrogateSelector.GetSurrogateForType(typeof(decimal), null); decimalSurrogate.Skip(reader); decimalSurrogate.Skip(reader); }
/// <summary> /// Skips an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> public override void SkipObject() { // read type handle short handle = reader.ReadInt16(); // Find an appropriate surrogate by handle ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, context.CacheContext); if (surrogate == null) { surrogate = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, reader.ReadInt16(), context.CacheContext); } try { surrogate.Skip(this); } catch (CompactSerializationException) { throw; } catch (Exception e) { throw new CompactSerializationException(e.Message); } }
public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) { if (type == null) { throw new ArgumentNullException("type is null."); } // Check this selector, and if the surrogate is not found, // check the chained selectors string key = type.FullName + "#" + context.ToString(); ISerializationSurrogate surrogate = (ISerializationSurrogate)Surrogates [key]; if (surrogate != null) { selector = this; return(surrogate); } if (nextSelector != null) { return(nextSelector.GetSurrogate(type, context, out selector)); } else { selector = null; return(null); } }
private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context) { if (objectType.IsArray) { InitNoMembers(); return; } ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector != null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); } if (_serializationSurrogate != null) { _isSi = true; } else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType)) { _isSi = true; } if (_isSi) { InitSiRead(); } else { InitMemberInfo(); } }
static Packet() { surrogateSelector = new SurrogateSelector(); streamingContext = new StreamingContext(StreamingContextStates.All); // Our surrogates can be safely used in every context. Type[] types = Assembly.GetExecutingAssembly() .GetTypes(); types.Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(SerializationSurrogate <>) && t.IsClass && !t.IsAbstract) .ForEach(t => { ISerializationSurrogate surrogate = (ISerializationSurrogate)Activator.CreateInstance(t); Type surrogatedType = t.BaseType.GetGenericArguments()[0]; surrogateSelector.AddSurrogate(surrogatedType, streamingContext, surrogate); Log.Debug("Added surrogate " + surrogate + " for type " + surrogatedType); }); // For completeness, we could pass a StreamingContextStates.CrossComputer. Serializer = new BinaryFormatter(surrogateSelector, streamingContext); }
/// <summary> /// /// </summary> /// <returns></returns> public override object ReadObject() { short handle = _reader.ReadInt16(); ISerializationSurrogate surrogateForTypeHandle = TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, _context.CacheContext); if (surrogateForTypeHandle == null) { surrogateForTypeHandle = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, _reader.ReadInt16(), _context.CacheContext); } object obj2 = null; try { obj2 = surrogateForTypeHandle.Read(this); } catch (CompactSerializationException) { throw; } catch (Exception exception) { throw new CompactSerializationException(exception.Message); } return(obj2); }
internal ObjectHolder(object obj, long objID, System.Runtime.Serialization.SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainingObj, FieldInfo field, int[] arrayIndex) { this.m_object = obj; this.m_id = objID; this.m_flags = 0; this.m_missingElementsRemaining = 0; this.m_missingDecendents = 0; this.m_dependentObjects = null; this.m_next = null; this.m_serInfo = info; this.m_surrogate = surrogate; this.m_markForFixupWhenAvailable = false; if (obj is TypeLoadExceptionHolder) { this.m_typeLoad = (TypeLoadExceptionHolder)obj; } if ((idOfContainingObj != 0L) && (((field != null) && field.FieldType.IsValueType) || (arrayIndex != null))) { if (idOfContainingObj == objID) { throw new SerializationException(Environment.GetResourceString("Serialization_ParentChildIdentical")); } this.m_valueFixup = new ValueTypeFixupInfo(idOfContainingObj, field, arrayIndex); } this.SetFlags(); }
private void SerializeObject(object currentObject, long currentObjectId) { bool needsSerializationInfo = false; ISurrogateSelector selector; ISerializationSurrogate surrogate = null; if (_surrogateSelector != null) { surrogate = _surrogateSelector.GetSurrogate( currentObject.GetType(), _context, out selector); } if (currentObject is ISerializable || surrogate != null) { needsSerializationInfo = true; } #if NET_2_0 && !TARGET_JVM _manager.RegisterObject(currentObject); #endif if (needsSerializationInfo) { SerializeISerializableObject(currentObject, currentObjectId, surrogate); } else { if (!currentObject.GetType().IsSerializable) { throw new SerializationException(String.Format("Type {0} in assembly {1} is not marked as serializable.", currentObject.GetType(), currentObject.GetType().Assembly.FullName)); } SerializeSimpleObject(currentObject, currentObjectId); } }
private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context) { if (objectType.IsArray) { this.InitNoMembers(); } else { ISurrogateSelector selector = null; if (surrogateSelector != null) { this.serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out selector); } if (this.serializationSurrogate != null) { this.isSi = true; } else if (!object.ReferenceEquals(objectType, Converter.typeofObject) && Converter.typeofISerializable.IsAssignableFrom(objectType)) { this.isSi = true; } if (this.isSi) { this.InitSiRead(); } else { this.InitMemberInfo(); } } }
internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) { throw new ArgumentNullException("innerSurrogate"); } this.innerSurrogate = innerSurrogate; }
public void GetSurrogateForCyclicalReference_ValidSurrogate_GetsObject() { var surrogate = new NonSerializablePairSurrogate(); ISerializationSurrogate newSurrogate = FormatterServices.GetSurrogateForCyclicalReference(surrogate); Assert.NotNull(newSurrogate); Assert.NotSame(surrogate, newSurrogate); }
public override void SkipObjectAs <T>() { // Find an appropriate surrogate by type ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForType(typeof(T), context.CacheContext); surrogate.Skip(this); }
// Adds a surrogate to the list of surrogates checked. /// <include file='doc\SurrogateSelector.uex' path='docs/doc[@for="SurrogateSelector.AddSurrogate"]/*' /> public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { if (type==null) { throw new ArgumentNullException("type"); } if (surrogate==null) { throw new ArgumentNullException("surrogate"); } SurrogateKey key = new SurrogateKey(type, context); m_surrogates.Add(key, surrogate); // Hashtable does duplicate checking. }
/// <summary> /// Adds a surrogate to the list of checked surrogates. /// </summary> /// <param name="type">The <see cref="T:System.Type"/> for which the surrogate is /// required.</param> /// <param name="context">The context-specific data.</param> /// <param name="surrogate">The surrogate to call for this type.</param> /// <exception cref="T:System.ArgumentNullException">The /// <paramref name="type"/>or /// <paramref name="surrogate"/>parameter is null.</exception> /// <exception cref="T:System.ArgumentException">A surrogate already exists for this type /// and context.</exception> public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { if (type == null || surrogate == null) throw new ArgumentNullException("Null reference."); if (_surrogates.ContainsKey(type)) { throw new ArgumentException("A surrogate for " + type + " already exists."); } if (_surrogates.ContainsKey(type) == false) { _surrogates[type] = new Dictionary<StreamingContextStates, ISerializationSurrogate>(); } _surrogates[type][context.State] = surrogate; }
// Methods public virtual void AddSurrogate (Type type, StreamingContext context, ISerializationSurrogate surrogate) { if (type == null || surrogate == null) throw new ArgumentNullException ("Null reference."); string currentKey = type.FullName + "#" + context.ToString (); if (Surrogates.ContainsKey (currentKey)) throw new ArgumentException ("A surrogate for " + type.FullName + " already exists."); Surrogates.Add (currentKey, surrogate); }
/// <summary> /// Constructs a new <see cref="DotNetSerializationSurrogateSurrogate"/>. /// </summary> /// <param name="context"><see cref="FudgeContext"/> to use.</param> /// <param name="typeData"><see cref="TypeData"/> for the type for this surrogate.</param> /// <param name="surrogate">Surrogate that maps the object to or from a <see cref="SerializationInfo"/>.</param> /// <param name="selector">Selector that produced the surrogate.</param> public DotNetSerializationSurrogateSurrogate(FudgeContext context, TypeData typeData, ISerializationSurrogate surrogate, ISurrogateSelector selector) { if (context == null) throw new ArgumentNullException("context"); if (typeData == null) throw new ArgumentNullException("typeData"); if (surrogate == null) throw new ArgumentNullException("surrogate"); // Don't care if selector is null this.helper = new SerializationInfoMixin(context, typeData.Type, new BeforeAfterSerializationMixin(context, typeData)); this.surrogate = surrogate; this.selector = selector; }
/// <summary> /// Registers a surrogate for a given type, from a given recording version on. /// </summary> public void RegisterSurrogate(double version, Type targetType, ISerializationSurrogate surrogate) { #region Check preconditions if (targetType == null) throw new ArgumentNullException("targetType"); if (surrogate == null) throw new ArgumentNullException("surrogate"); #endregion Check preconditions // Check that no surrogate conflicts: foreach (Registration reg in register) { if (reg.MatchesTypeAndVersion(targetType, version)) { throw new InvalidOperationException("The SerializationSurrogate conflicts with an already registered surrogate for same version and target type."); } } // Register surrogate: register.Add(new Registration(version, targetType, surrogate)); }
public static void AddSurrogate(Type type,ISerializationSurrogate surrogate) { if(__surrogateSelector==null){ __surrogateSelector=new SurrogateSelector(); __streamingContext=new StreamingContext(); } ISurrogateSelector surrogateExist=null; __surrogateSelector.GetSurrogate (type, __streamingContext,out surrogateExist); if(surrogateExist==null) __surrogateSelector.AddSurrogate(type,__streamingContext, surrogate); }
internal ObjectHolder(string obj, long objID, System.Runtime.Serialization.SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainingObj, FieldInfo field, int[] arrayIndex) { this.m_object = obj; this.m_id = objID; this.m_flags = 0; this.m_missingElementsRemaining = 0; this.m_missingDecendents = 0; this.m_dependentObjects = null; this.m_next = null; this.m_serInfo = info; this.m_surrogate = surrogate; this.m_markForFixupWhenAvailable = false; if ((idOfContainingObj != 0L) && (arrayIndex != null)) { this.m_valueFixup = new ValueTypeFixupInfo(idOfContainingObj, field, arrayIndex); } if (this.m_valueFixup != null) { this.m_flags |= 8; } }
internal ObjectHolder(String obj, long objID, SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainingObj, FieldInfo field, int[] arrayIndex) { BCLDebug.Assert(objID>=0,"objID>=0"); m_object=obj; //May be null; m_id=objID; m_flags=0; m_missingElementsRemaining=0; m_missingDecendents = 0; m_dependentObjects=null; m_next=null; m_serInfo = info; m_surrogate = surrogate; m_markForFixupWhenAvailable = false; if (idOfContainingObj!=0 && arrayIndex!=null) { m_valueFixup = new ValueTypeFixupInfo(idOfContainingObj, field, arrayIndex); } if (m_valueFixup!=null) { m_flags|=REQUIRES_VALUETYPE_FIXUP; } }
internal ObjectHolder(Object obj, long objID, SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainingObj, FieldInfo field, int[] arrayIndex) { BCLDebug.Assert(objID>=0,"objID>=0"); m_object=obj; //May be null; m_id=objID; m_flags=0; m_missingElementsRemaining=0; m_missingDecendents = 0; m_dependentObjects=null; m_next=null; m_serInfo = info; m_surrogate = surrogate; m_markForFixupWhenAvailable = false; if (idOfContainingObj!=0 && ((field!=null && field.FieldType.IsValueType) || arrayIndex!=null)) { if (idOfContainingObj == objID) { throw new SerializationException(Environment.GetResourceString("Serialization_ParentChildIdentical")); } m_valueFixup = new ValueTypeFixupInfo(idOfContainingObj, field, arrayIndex); } SetFlags(); }
/// <summary> /// Wraps an ISerializationSurrogate surrogate with special one to enable cyclical references during serialization /// if hotfix http://support.microsoft.com/kb/931634, or later is installed. Wrapping the surrogate /// should fix the "The object with ID X was referenced in a fixup but does not exist." error that occurs during /// deserialization. /// </summary> public static ISerializationSurrogate EnableCyclicalReferences(ISerializationSurrogate surrogate) { // Look for the FormatterServices.GetSurrogateForCyclicalReference() method // This method cannot be called directly because it may not exist in all environments and currently // only exists on the Server-version of Windows. foreach (MethodInfo method in typeof(FormatterServices).GetMethods(BindingFlags.Public | BindingFlags.Static)) { if (method.Name == "GetSurrogateForCyclicalReference") { return (ISerializationSurrogate)method.Invoke(null, new object[] { surrogate }); } } return surrogate; }
[System.Security.SecurityCritical] // auto-generated internal void InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) { SerTrace.Log( this, objectInfoId," Constructor 2 ",objectType); this.objectType = objectType; this.context = context; this.serObjectInfoInit = serObjectInfoInit; if (objectType.IsArray) { InitNoMembers(); return; } InvokeSerializationBinder(binder); ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector!=null) serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); if (serializationSurrogate != null) { // surrogate does not have this problem since user has pass in through the BF's ctor si = new SerializationInfo(objectType, converter); cache = new SerObjectInfoCache(objectType); isSi = true; } else if (Object.ReferenceEquals(objectType, Converter.typeofObject)) { } else if (Converter.typeofISerializable.IsAssignableFrom(objectType)) { si = new SerializationInfo(objectType, converter, !FormatterServices.UnsafeTypeForwardersIsEnabled()); cache = new SerObjectInfoCache(objectType); CheckTypeForwardedFrom(cache, objectType, binderAssemblyString); isSi = true; } if (!isSi) { InitMemberInfo(); CheckTypeForwardedFrom(cache, objectType, binderAssemblyString); } SerTrace.Log( this,objectInfoId," ", objectType," InitSerialize Exit ",isSi); }
// Add a surrogate for a specific type. public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { if(type == null) { throw new ArgumentNullException("type"); } if(surrogate == null) { throw new ArgumentNullException("surrogate"); } table.Add(new KeyInfo(type, context), surrogate); }
internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { Debug.Assert(innerSurrogate != null); _innerSurrogate = innerSurrogate; }
public virtual new void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { }
internal SurrogateDataContract(Type type, ISerializationSurrogate serializationSurrogate) : base(new SurrogateDataContractCriticalHelper(type, serializationSurrogate)) { this.helper = base.Helper as SurrogateDataContractCriticalHelper; }
internal void UpdateData(object obj, System.Runtime.Serialization.SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainer, FieldInfo field, int[] arrayIndex, ObjectManager manager) { this.SetObjectValue(obj, manager); this.m_serInfo = info; this.m_surrogate = surrogate; if ((idOfContainer != 0L) && (((field != null) && field.FieldType.IsValueType) || (arrayIndex != null))) { if (idOfContainer == this.m_id) { throw new SerializationException(Environment.GetResourceString("Serialization_ParentChildIdentical")); } this.m_valueFixup = new ValueTypeFixupInfo(idOfContainer, field, arrayIndex); } this.SetFlags(); if (this.RequiresValueTypeFixup) { this.UpdateDescendentDependencyChain(this.m_missingElementsRemaining, manager); } }
internal SurrogateDataContractCriticalHelper(Type type, ISerializationSurrogate serializationSurrogate) : base(type) { string str; string str2; this.serializationSurrogate = serializationSurrogate; DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(type), out str, out str2); base.SetDataContractName(DataContract.CreateQualifiedName(str, str2)); }
public virtual void UseSoapFormat() { _messageSurrogate = new SoapMessageSurrogate(this); ((SoapMessageSurrogate)_messageSurrogate).SetRootObject(_rootObj); }
[System.Security.SecurityCritical] // auto-generated private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context) { SerTrace.Log( this,objectInfoId," ", objectType," InitReadConstructor Entry ",objectType); if (objectType.IsArray) { InitNoMembers(); return; } ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector!=null) serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); if (serializationSurrogate != null) { isSi = true; } else if (Object.ReferenceEquals(objectType, Converter.typeofObject)) { } else if (Converter.typeofISerializable.IsAssignableFrom(objectType)) isSi = true; if (isSi) { InitSiRead(); } else { InitMemberInfo(); } SerTrace.Log( this,objectInfoId," ", objectType," InitReadConstructor Exit ",isSi); }
/*==================================UpdateData================================== **Action: Update the data in the object holder. This should be called when the object ** is finally registered. Presumably the ObjectHolder was created to track ** some dependencies or preregistered fixups and we now need to actually record the ** object and other associated data. We take this opportunity to set the flags ** so that we can do some faster processing in the future. **Returns: void **Arguments: obj -- The object being held by this object holder. (This should no longer be null). ** info --The SerializationInfo associated with this object, only required if we're doing delayed fixups. ** surrogate -- The surrogate handling this object. May be null. ** idOfContainer -- The id of the object containing this one if this is a valuetype. ** member -- the MemberInfo of this object's position in it's container if this is a valuetype. ** manager -- the ObjectManager being used to track these ObjectHolders. **Exceptions: None. Asserts only. ==============================================================================*/ internal virtual void UpdateData(Object obj, SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainer, FieldInfo field, int[] arrayIndex, ObjectManager manager) { BCLDebug.Assert(obj!=null,"obj!=null"); BCLDebug.Assert(m_id>0,"m_id>0"); //Record the fields that we can. SetObjectValue(obj, manager); m_serInfo = info; m_surrogate = surrogate; if (idOfContainer!=0 && ((field!=null && field.FieldType.IsValueType) || arrayIndex!=null)) { if (idOfContainer == m_id) { throw new SerializationException(Environment.GetResourceString("Serialization_ParentChildIdentical")); } m_valueFixup = new ValueTypeFixupInfo(idOfContainer, field, arrayIndex); } SetFlags(); if (RequiresValueTypeFixup) { UpdateDescendentDependencyChain(m_missingElementsRemaining, manager); } }
public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) { throw new ArgumentNullException(nameof(innerSurrogate)); } return new SurrogateForCyclicalReference(innerSurrogate); }
/// <summary> /// Adds a surrogate to the framework surrogate selector. /// </summary> /// <param name="type">The <see cref="Type"/> for which the surrogate is required.</param> /// <param name="context">The context-specific data.</param> /// <param name="surrogate">The surrogate to call for this type.</param> /// <remarks> /// Surrogates that are added in this way will be used by the piccolo framework for cloning /// operations. For example, if several custom nodes reference a type that is not serializable, /// you might want to add a surrogate here for that type. Alternatively, you could override /// <see cref="PNode.GetObjectData"/> in each custom node and specify how to serialize the type /// there. /// </remarks> public static void AddFrameworkSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { FrameworkSurrogateSelector.AddSurrogate(type, context, surrogate); }
public static ISerializationSurrogate GetSurrogateForCyclicalReference (ISerializationSurrogate innerSurrogate) { return innerSurrogate; }
public RemotingSurrogateSelector() { _messageSurrogate = new MessageSurrogate(this); }
// Write Constructor used for array types or null members internal void InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) { _objectType = objectType; _context = context; _serObjectInfoInit = serObjectInfoInit; if (objectType.IsArray) { InitNoMembers(); return; } InvokeSerializationBinder(binder); ISurrogateSelector surrogateSelectorTemp = null; if (surrogateSelector != null) { _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); } if (_serializationSurrogate != null) { // surrogate does not have this problem since user has pass in through the BF's ctor _si = new SerializationInfo(objectType, converter); _cache = new SerObjectInfoCache(objectType); _isSi = true; } else if (!ReferenceEquals(objectType, Converter.s_typeofObject) && Converter.s_typeofISerializable.IsAssignableFrom(objectType)) { _si = new SerializationInfo(objectType, converter); _cache = new SerObjectInfoCache(objectType); CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString); _isSi = true; } if (!_isSi) { InitMemberInfo(); CheckTypeForwardedFrom(_cache, objectType, _binderAssemblyString); } }
// Write constructor internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) { _context = context; _obj = obj; _serObjectInfoInit = serObjectInfoInit; _objectType = obj.GetType(); if (_objectType.IsArray) { _isArray = true; InitNoMembers(); return; } InvokeSerializationBinder(binder); objectWriter.ObjectManager.RegisterObject(obj); ISurrogateSelector surrogateSelectorTemp; if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out surrogateSelectorTemp)) != null) { _si = new SerializationInfo(_objectType, converter); if (!_objectType.IsPrimitive) { _serializationSurrogate.GetObjectData(obj, _si, context); } InitSiWrite(); } else if (obj is ISerializable) { if (!_objectType.IsSerializable) { throw new SerializationException(SR.Format(SR.Serialization_NonSerType, _objectType.FullName, _objectType.Assembly.FullName)); } _si = new SerializationInfo(_objectType, converter); ((ISerializable)obj).GetObjectData(_si, context); InitSiWrite(); CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString); } else { InitMemberInfo(); CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString); } }
[System.Security.SecurityCritical] // auto-generated internal void InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) { SerTrace.Log( this, objectInfoId," Constructor 1 ",obj); this.context = context; this.obj = obj; this.serObjectInfoInit = serObjectInfoInit; ISurrogateSelector surrogateSelectorTemp; #if FEATURE_REMOTING if (RemotingServices.IsTransparentProxy(obj)) objectType = Converter.typeofMarshalByRefObject; else #endif objectType = obj.GetType(); if (objectType.IsArray) { isArray = true; InitNoMembers(); return; } InvokeSerializationBinder(binder); SerTrace.Log( this, objectInfoId," Constructor 1 trace 2"); objectWriter.ObjectManager.RegisterObject(obj); if (surrogateSelector != null && (serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp)) != null) { SerTrace.Log( this, objectInfoId," Constructor 1 trace 3"); si = new SerializationInfo(objectType, converter); if (!objectType.IsPrimitive) serializationSurrogate.GetObjectData(obj, si, context); InitSiWrite(); } else if (obj is ISerializable) { if (!objectType.IsSerializable) { throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", objectType.FullName, objectType.Assembly.FullName)); } si = new SerializationInfo(objectType, converter, !FormatterServices.UnsafeTypeForwardersIsEnabled()); #if FEATURE_SERIALIZATION ((ISerializable)obj).GetObjectData(si, context); #endif SerTrace.Log( this, objectInfoId," Constructor 1 trace 4 ISerializable "+objectType); InitSiWrite(); CheckTypeForwardedFrom(cache, objectType, binderAssemblyString); } else { SerTrace.Log(this, objectInfoId," Constructor 1 trace 5"); InitMemberInfo(); CheckTypeForwardedFrom(cache, objectType, binderAssemblyString); } }