public SNKeyPairDerived SNKeyPairDerivedClone(ISerializable inter)
        {
            SerializationInfo info = new SerializationInfo(typeof(StrongNameKeyPair), new FormatterConverter());
            StreamingContext context = new StreamingContext();

            inter.GetObjectData(info, context);

            return new SNKeyPairDerived(info, context);
        }
 public SurrogateForISerializable(ISerializable serializable)
 {
     var serializationInfo = new SerializationInfo(serializable.GetType(), new FormatterConverter());
     var streamingContext = new StreamingContext(StreamingContextStates.Clone);
     serializable.GetObjectData(serializationInfo, streamingContext);
     keys = new string[serializationInfo.MemberCount];
     values = new object[serializationInfo.MemberCount];
     var i = 0;
     foreach(var entry in serializationInfo)
     {
         keys[i] = entry.Name;
         values[i] = entry.Value;
         i++;
     }
     assemblyQualifiedName = serializable.GetType().AssemblyQualifiedName;
 }
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (!JsonTypeReflector.FullyTrusted)
            {
                string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
                                 @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
                message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());

                throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
            }

            OnSerializing(writer, contract, value);
            _serializeStack.Add(value);

            WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);

            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, Serializer._context);

            foreach (SerializationEntry serializationEntry in serializationInfo)
            {
                JsonContract valueContract = GetContractSafe(serializationEntry.Value);

                if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
                {
                    writer.WritePropertyName(serializationEntry.Name);
                    WriteReference(writer, serializationEntry.Value);
                }
                else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
                {
                    writer.WritePropertyName(serializationEntry.Name);
                    SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
                }
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);
            OnSerialized(writer, contract, value);
        }
Пример #4
0
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (!JsonTypeReflector.FullyTrusted)
            {
                throw JsonSerializationException.Create((IJsonLineInfo)null, writer.ContainerPath, StringUtils.FormatWith("Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.\r\nTo fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.", (IFormatProvider)CultureInfo.InvariantCulture, (object)value.GetType()), (Exception)null);
            }
            contract.InvokeOnSerializing((object)value, this.Serializer.Context);
            this._serializeStack.Add((object)value);
            this.WriteObjectStart(writer, (object)value, (JsonContract)contract, member, collectionContract, containerProperty);
            SerializationInfo info = new SerializationInfo(contract.UnderlyingType, (IFormatterConverter) new FormatterConverter());

            value.GetObjectData(info, this.Serializer.Context);
            foreach (SerializationEntry serializationEntry in info)
            {
                writer.WritePropertyName(serializationEntry.Name);
                this.SerializeValue(writer, serializationEntry.Value, this.GetContractSafe(serializationEntry.Value), (JsonProperty)null, (JsonContainerContract)null, member);
            }
            writer.WriteEndObject();
            this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
            contract.InvokeOnSerialized((object)value, this.Serializer.Context);
        }
Пример #5
0
        //SerializationInfo si;

        void SerializeSerializable(ISerializable obj, Type type)
        {
            if (type == null)
            {
                type = obj.GetType();
                SerializeType(type);
            }
            var si = new SerializationInfo(type, new FormatterConverter());
            var sc = new StreamingContext();

            obj.GetObjectData(si, sc);

            var m_data = (object[])m_dataField.GetValue(si);

            //var m_types = (Type[]) m_typesField.GetValue(si);
            //Writer.Write((UInt16) m_data.Length);
            for (int i = 0; i < m_data.Length; i++)
            {
                Serialize(m_data[i]);
            }
        }
Пример #6
0
        public void Serialize(Stream serializationStream, object graph)
        {
            ISerializable _data = (ISerializable)graph;
            SerializationInfo _info = new SerializationInfo(graph.GetType(), new FormatterConverter());
            StreamingContext _context = new StreamingContext(StreamingContextStates.File);
            _data.GetObjectData(_info, _context);
         
            using (StreamWriter stream = new StreamWriter(serializationStream))
            {
                foreach (SerializationEntry _item in _info)
                {
                    stream.Write(_item.Name);
                    stream.Write(':');
                    stream.Write(_item.Value);
                    stream.Write(';'); 
                }
                stream.Write('\n');
                stream.Flush();
            }

        }
Пример #7
0
        public override void Serialize(Stream serializationStream, object graph)
        {
            ISerializable     serializable      = (ISerializable)graph;
            SerializationInfo serializationInfo = new SerializationInfo(graph.GetType(), new FormatterConverter());
            StreamingContext  streamingContext  = new StreamingContext(StreamingContextStates.File);

            CustomBinder.BindToName(graph.GetType(), out string assemblyName, out string typeName);
            serializable.GetObjectData(serializationInfo, streamingContext);

            foreach (SerializationEntry item in serializationInfo)
            {
                this.WriteMember(item.Name, item.Value);
            }

            StringBuilder fileContent = new StringBuilder(
                assemblyName + "->" + typeName + "->" + IDGenerator.GetId(graph, out bool _).ToString());

            foreach (Data data in Values)
            {
                fileContent.Append("\n" + data.ToString());
            }
            fileContent.Append("$\n");

            using (StreamWriter writer = new StreamWriter(serializationStream, Encoding.UTF8, 32, true))
            {
                writer.Write(fileContent.ToString());
            }

            fileContent.Clear();
            Values.Clear();
            AllObjects.Add(graph);
            foreach (Object obj in SerializedObjects)
            {
                if (!AllObjects.Contains(obj))
                {
                    this.Serialize(serializationStream, obj);
                }
            }
        }
Пример #8
0
        private void SerializeISerializableObject(
            object currentObject,
            long currentObjectId,
            ISerializationSurrogate surrogate)
        {
            Type currentType       = currentObject.GetType();
            SerializationInfo info = new SerializationInfo(currentType, new FormatterConverter());


            ISerializable objISerializable = currentObject as ISerializable;

            if (surrogate != null)
            {
                surrogate.GetObjectData(currentObject, info, _context);
            }
            else
            {
                objISerializable.GetObjectData(info, _context);
            }

            // Same as above
            if (currentObjectId > 0L)
            {
                Element element = _mapper.GetXmlElement(info.FullTypeName, info.AssemblyName);
                _xmlWriter.WriteStartElement(element.Prefix, element.LocalName, element.NamespaceURI);
                Id(currentObjectId);
            }

            foreach (SerializationEntry entry in info)
            {
                _xmlWriter.WriteStartElement(XmlConvert.EncodeLocalName(entry.Name));
                SerializeComponent(entry.Value, IsEncodingNeeded(entry.Value, null));
                _xmlWriter.WriteEndElement();
            }
            if (currentObjectId > 0)
            {
                _xmlWriter.WriteFullEndElement();
            }
        }
Пример #9
0
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            if (!JsonTypeReflector.FullyTrusted)
            {
                string str = string.Concat("Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.", Environment.NewLine, "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.", Environment.NewLine);
                str = str.FormatWith(CultureInfo.InvariantCulture, value.GetType());
                throw JsonSerializationException.Create(null, writer.ContainerPath, str, null);
            }
            this.OnSerializing(writer, contract, value);
            this._serializeStack.Add(value);
            this.WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, this.Serializer._context);
            SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();

            while (enumerator.MoveNext())
            {
                SerializationEntry current      = enumerator.Current;
                JsonContract       contractSafe = this.GetContractSafe(current.Value);
                if (!this.ShouldWriteReference(current.Value, null, contractSafe, contract, member))
                {
                    if (!this.CheckForCircularReference(writer, current.Value, null, contractSafe, contract, member))
                    {
                        continue;
                    }
                    writer.WritePropertyName(current.Name);
                    this.SerializeValue(writer, current.Value, contractSafe, null, contract, member);
                }
                else
                {
                    writer.WritePropertyName(current.Name);
                    this.WriteReference(writer, current.Value);
                }
            }
            writer.WriteEndObject();
            this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
            this.OnSerialized(writer, contract, value);
        }
Пример #10
0
        private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract)
        {
            contract.InvokeOnSerializing(value, Serializer.Context);
            SerializeStack.Add(value);

            writer.WriteStartObject();

            SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());

            value.GetObjectData(serializationInfo, Serializer.Context);

            foreach (SerializationEntry serializationEntry in serializationInfo)
            {
                writer.WritePropertyName(serializationEntry.Name);
                SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null);
            }

            writer.WriteEndObject();

            SerializeStack.RemoveAt(SerializeStack.Count - 1);
            contract.InvokeOnSerialized(value, Serializer.Context);
        }
Пример #11
0
        static IObjectMemberInfo[] GetMembers(ISerializable value, Type type)
        {
            IObjectMemberInfo[] mis = null;
            if (value == null)
            {
                if (serialCache.TryGetValue(type, out mis))
                {
                    return(mis);
                }

                // 尝试创建type的实例
                value = GetDefaultObject(type) as ISerializable;
            }

            var info = new SerializationInfo(type, new FormatterConverter());

            value.GetObjectData(info, DefaultStreamingContext);

            var list = new List <IObjectMemberInfo>();

            foreach (var item in info)
            {
                list.Add(CreateObjectMemberInfo(item.Name, item.ObjectType, item.Value));
            }
            mis = list.ToArray();

            if (!serialCache.ContainsKey(type))
            {
                lock (serialCache)
                {
                    if (!serialCache.ContainsKey(type))
                    {
                        serialCache.Add(type, mis);
                    }
                }
            }

            return(mis);
        }
Пример #12
0
            private void WriteObject(object /*!*/ obj)
            {
                _writer.Write((byte)'o');
                RubyClass theClass = _context.GetClassOf(obj);

                TestForAnonymous(theClass);
                WriteSymbol(theClass.Name);

#if !SILVERLIGHT
                ISerializable serializableObj = (obj as ISerializable);
                if (serializableObj != null)
                {
                    SerializationInfo info = new SerializationInfo(theClass.GetUnderlyingSystemType(), new FormatterConverter());
                    serializableObj.GetObjectData(info, _streamingContext);
                    int count = info.MemberCount;
                    try {
                        // We need this attribute for CLR serialization but it's not compatible with MRI serialization
                        // Unfortunately, there's no way to test for a value without either iterating over all values
                        // or throwing an exception if it's not present
                        if (info.GetValue("#class", typeof(RubyClass)) != null)
                        {
                            count--;
                        }
                    } catch (Exception) {
                    }
                    WriteInt32(count);
                    foreach (SerializationEntry entry in info)
                    {
                        if (!entry.Name.Equals("#class"))
                        {
                            WriteSymbol(entry.Name);
                            WriteAnObject(entry.Value);
                        }
                    }
                    return;
                }
#endif
            }
Пример #13
0
        public static void SerializeText(ISerializable so, StreamWriter writer)
        {
            SerializationInfo info    = new SerializationInfo(so.GetType(), new FormatterConverter());
            StreamingContext  context = new StreamingContext();

            so.GetObjectData(info, context);
            SerializationInfoEnumerator e = info.GetEnumerator();

            while (e.MoveNext())
            {
                string name  = e.Current.Name;
                string value = e.Current.Value.ToString();
                if (e.Current.ObjectType.IsArray)
                {
                    Array array = e.Current.Value as Array;
                    foreach (ISerializable item in array)
                    {
                        SerializeText(item, writer);
                    }
                }
                writer.WriteLine(name + "," + value);
            }
        }
        private void OrderClass(RecordClassDispatcher first, ISerializable visitor, CollectionProperty dic, ProductInstanceExpression selection2, InitializerTest cust3, ProductInstanceExpression asset4)
        {
            //Discarded unreachable code: IL_0002
            //IL_0003: Incompatible stack heights: 0 vs 1
            if (!ConfigProperty._0002())
            {
                string asset5 = "Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
                asset5 = asset5.ListReader(CultureInfo.InvariantCulture, visitor.GetType());
                throw StrategyError.ValidateComposer(null, first._0001(), asset5, null);
            }
            ManageBroadcaster(first, dic, visitor);
            wrapperProperty.Add(visitor);
            SortBroadcaster(first, visitor, dic, selection2, cust3, asset4);
            SerializationInfo serializationInfo = new SerializationInfo(((ProcTest)dic)._0002(), new FormatterConverter());

            visitor.GetObjectData(serializationInfo, baseProperty.roleError);
            SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();

            while (enumerator.MoveNext())
            {
                SerializationEntry current  = enumerator.Current;
                ProcTest           procTest = DeleteBroadcaster(current.Value);
                if (CountBroadcaster(current.Value, null, procTest, dic, selection2))
                {
                    first._0002(current.Name);
                    QueryBroadcaster(first, current.Value);
                }
                else if (CustomizeBroadcaster(first, current.Value, null, procTest, dic, selection2))
                {
                    first._0002(current.Name);
                    InvokeBroadcaster(first, current.Value, procTest, null, dic, selection2);
                }
            }
            first._0011();
            wrapperProperty.RemoveAt(wrapperProperty.Count - 1);
            InitBroadcaster(first, dic, visitor);
        }
Пример #15
0
        /// <summary>
        /// deconstructs objects that inhert ISerializable
        /// </summary>
        /// <returns></returns>
        private static string SeriObjDeconstructor(ISerializable obj)
        {
            SerializationInfo info    = new SerializationInfo(obj.GetType(), new FormatterConverter());
            StreamingContext  context = new StreamingContext(StreamingContextStates.All);

            obj.GetObjectData(info, context);
            var           node          = info.GetEnumerator();
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(serializerEntry);

            ///Object Type Change
            stringBuilder.Append(info.ObjectType.AssemblyQualifiedName);
            stringBuilder.Append(equals);
            ///Object Type Change

            while (node.MoveNext())
            {
                stringBuilder.Append(startClass + node.Name + typeEntry + node.ObjectType + equals + Deconstruction(node.Value) + endClass);
                //stringBuilder.Append(startClass + node.Name + typeEntry + node.ObjectType + equals + Deconstruct(node.Value) + endClass);
            }
            stringBuilder.Append(serializerExit);
            return(stringBuilder.ToString());
        }
Пример #16
0
        static IObjectMemberInfo[] GetMembers(ISerializable value, Type type)
        {
            IObjectMemberInfo[] mis = null;
            if (value == null)
            {
                if (serialCache.TryGetValue(type, out mis)) return mis;

                // 尝试创建type的实例
                value = GetDefaultObject(type) as ISerializable;
            }

            SerializationInfo info = new SerializationInfo(type, new FormatterConverter());

            value.GetObjectData(info, DefaultStreamingContext);

            List<IObjectMemberInfo> list = new List<IObjectMemberInfo>();
            foreach (SerializationEntry item in info)
            {
                list.Add(CreateObjectMemberInfo(item.Name, item.ObjectType, item.Value));
            }
            mis = list.ToArray();

            if (!serialCache.ContainsKey(type))
            {
                lock (serialCache)
                {
                    if (!serialCache.ContainsKey(type)) serialCache.Add(type, mis);
                }
            }

            return mis;
        }
Пример #17
0
 internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context)
 {
     // Demand the serialization formatter permission every time
     Globals.SerializationFormatterPermission.Demand();
     obj.GetObjectData(serInfo, context);
 }
		private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract)
		{
			contract.InvokeOnSerializing(value, Serializer.Context);
			SerializeStack.Add(value);

			writer.WriteStartObject();

			SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
			value.GetObjectData(serializationInfo, Serializer.Context);

			foreach (SerializationEntry serializationEntry in serializationInfo)
			{
				writer.WritePropertyName(serializationEntry.Name);
				SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null);
			}

			writer.WriteEndObject();

			SerializeStack.RemoveAt(SerializeStack.Count - 1);
			contract.InvokeOnSerialized(value, Serializer.Context);
		}
Пример #19
0
        public void SerializationRequiresSerializationInfo()
        {
            ISerializable tested = PluginFilter.Create.Implements(typeof(Stream));

            DoAssert.Throws <ArgumentNullException>(() => tested.GetObjectData(null, new StreamingContext()));
        }
Пример #20
0
        private IEnumerable <CustomSerializationEntry> GetMemberInfo(
            object objectToSerialize,
            [NotNull] Type objectToSerializeType,
            [NotNull] FormatterConverter converter)
        {
            ISurrogateSelector      selector1;
            ISerializationSurrogate serializationSurrogate;
            SerializationInfo       info = null;

            // if the passed object is null, break the iteration.
            if (objectToSerialize == null)
            {
                yield break;
            }

            if ((SurrogateSelector != null) &&
                ((serializationSurrogate = SurrogateSelector.GetSurrogate(objectToSerializeType, Context, out selector1)) !=
                 null))
            {
                // use a surrogate to get the members.
                info = new SerializationInfo(objectToSerializeType, converter);

                if (!objectToSerializeType.IsPrimitive)
                {
                    // get the data from the surrogate.
                    serializationSurrogate.GetObjectData(objectToSerialize, info, Context);
                }
            }
            else
            {
                ISerializable serializable = objectToSerialize as ISerializable;
                if (serializable != null)
                {
                    // object implements ISerializable
                    if (!objectToSerializeType.IsSerializable)
                    {
                        throw new SerializationException(
                                  string.Format(
                                      // ReSharper disable once AssignNullToNotNullAttribute
                                      Resources.XmlFormatter_GetMemberInfo_TypeNotSerializable,
                                      objectToSerializeType.FullName));
                    }

                    info = new SerializationInfo(objectToSerializeType, converter);
                    // get the data using ISerializable.
                    serializable.GetObjectData(info, Context);
                }
            }

            if (info != null)
            {
                // either the surrogate provided the members, or the members were retrieved
                // using ISerializable.
                // create the custom entries collection by copying all the members
                foreach (SerializationEntry member in info)
                {
                    CustomSerializationEntry entry = new CustomSerializationEntry(
                        // ReSharper disable AssignNullToNotNullAttribute
                        member.Name,
                        member.ObjectType,
                        // ReSharper restore AssignNullToNotNullAttribute
                        false,
                        member.Value);

                    // yield return will return the entry now and return to this point when
                    // the enclosing loop (the one that contains the call to this method)
                    // request the next item.
                    yield return(entry);
                }
            }
            else
            {
                // The item does not have a surrogate, nor does it implement ISerializable.
                // We use reflection to get the objects state.
                if (!objectToSerializeType.IsSerializable)
                {
                    throw new SerializationException(
                              string.Format(
                                  // ReSharper disable once AssignNullToNotNullAttribute
                                  Resources.XmlFormatter_GetMemberInfo_TypeNotSerializable,
                                  objectToSerializeType.FullName));
                }

                // Get all serializable members
                MemberInfo[] members = FormatterServices.GetSerializableMembers(objectToSerializeType, Context);
                Debug.Assert(members != null);

                foreach (MemberInfo member in members)
                {
                    Debug.Assert(member != null);
                    if (CanSerialize(member))
                    {
                        // create the entry
                        CustomSerializationEntry entry = new CustomSerializationEntry(
                            member.Name,
                            // ReSharper disable once AssignNullToNotNullAttribute
                            member.ReflectedType,
                            false);

                        if (typeof(IList).IsAssignableFrom(entry.ObjectType))
                        {
                            entry.IsList = true;
                        }

                        // get the value of the member
                        entry.Value = GetMemberValue(objectToSerialize, member);
                        // yield return will return the entry now and return to this point when
                        // the enclosing loop (the one that contains the call to this method)
                        // request the next item.
                        yield return(entry);
                    }
                }
            }
        }
 internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
 {
     Type type = obj.GetType();
     SerializationInfo info = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter);
     obj.GetObjectData(info, base.GetStreamingContext());
     if (DataContract.GetClrTypeFullName(type) != info.FullTypeName)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(System.Runtime.Serialization.SR.GetString("ChangingFullTypeNameNotSupported", new object[] { info.FullTypeName, DataContract.GetClrTypeFullName(type) })));
     }
     base.WriteSerializationInfo(xmlWriter, type, info);
 }
Пример #22
0
        private void serializeFromISerializable(ISerializable data)
        {
            m_CustomData = new Dictionary<string,CustomTypedEntry>();

                    var info = new SerializationInfo(data.GetType(), new FormatterConverter());
                    StreamingContext streamingContext = new StreamingContext(StreamingContextStates.Persistence);
                    data.GetObjectData(info, streamingContext);

                    var senum = info.GetEnumerator();
                    while(senum.MoveNext())
                    {
                        var value = new CustomTypedEntry();
                        value.TypeIndex = MetaType.GetExistingOrNewMetaTypeIndex( m_Document, senum.ObjectType );
                        value.Data = m_Document.NativeDataToPortableData( senum.Value );
                        m_CustomData[senum.Name] = value;
                    }
        }
Пример #23
0
 /// <summary>
 /// Write the specified value.
 /// </summary>
 /// <param name="value">Value.</param>
 public override void Write(object value)
 {
     if (value == null)
     {
         m_Writer.Write("null");
     }
     else
     {
         Type type = value.GetType();
         if (type == typeof(string) || type.IsEnum)
         {
             m_Writer.Write("\"{0}\"", value);
         }
         else if (type == typeof(short) || type == typeof(int) || type == typeof(long) ||
                  type == typeof(ushort) || type == typeof(uint) || type == typeof(ulong) ||
                  type == typeof(byte) || type == typeof(sbyte) || type == typeof(decimal) ||
                  type == typeof(double) || type == typeof(float))
         {
             m_Writer.Write(Convert.ChangeType(value, typeof(string)));
         }
         else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
         {
             m_Writer.Write("{");
             Write("Key");
             m_Writer.Write(":");
             Write(type.GetProperty("Key").GetValue(value, BindingFlags.Default, null, null, null));
             m_Writer.Write(",");
             Write("Value");
             m_Writer.Write(":");
             Write(type.GetProperty("Value").GetValue(value, BindingFlags.Default, null, null, null));
             m_Writer.Write("}");
         }
         else if (value is IDictionary)
         {
             IDictionary dictionary = value as IDictionary;
             bool        isFirst    = true;
             m_Writer.Write("{");
             foreach (var key in dictionary.Keys)
             {
                 if (isFirst)
                 {
                     isFirst = false;
                 }
                 else
                 {
                     m_Writer.Write(",");
                 }
                 Write(key);
                 m_Writer.Write(":");
                 Write(dictionary[key]);
             }
             m_Writer.Write("}");
         }
         else if (value is IEnumerable)
         {
             IEnumerable enumerable = value as IEnumerable;
             IEnumerator e          = enumerable.GetEnumerator();
             bool        isFirst    = true;
             m_Writer.Write("[");
             while (e.MoveNext())
             {
                 if (isFirst)
                 {
                     isFirst = false;
                 }
                 else
                 {
                     m_Writer.Write(",");
                 }
                 Write(e.Current);
             }
             m_Writer.Write("]");
         }
         else if (value is ISerializable)
         {
             SerializationInfo info         = new SerializationInfo(type, new FormatterConverter());
             ISerializable     serializable = value as ISerializable;
             serializable.GetObjectData(info, m_Context);
             WriteSerializationInfo(info);
         }
         else
         {
             if (m_SurrogateSelector != null)
             {
                 ISurrogateSelector      selector;
                 ISerializationSurrogate surrogate = m_SurrogateSelector.GetSurrogate(type, m_Context, out selector);
                 if (surrogate != null)
                 {
                     SerializationInfo info = new SerializationInfo(type, new FormatterConverter());
                     surrogate.GetObjectData(value, info, m_Context);
                     WriteSerializationInfo(info);
                 }
             }
             else
             {
                 WriteObject(value, type);
             }
         }
     }
 }
Пример #24
0
        private void GetObjectData(object obj, out TypeMetadata metadata, out object data)
        {
            Type instanceType = obj.GetType();

            // Check if the formatter has a surrogate selector, if it does,
            // check if the surrogate selector handles objects of the given type.

            if (_surrogateSelector != null)
            {
                ISurrogateSelector      selector;
                ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate(instanceType, _context, out selector);
                if (surrogate != null)
                {
                    SerializationInfo info = new SerializationInfo(instanceType, new FormatterConverter());
                    surrogate.GetObjectData(obj, info, _context);
                    metadata = new SerializableTypeMetadata(instanceType, info);
                    data     = info;
                    return;
                }
            }

            // Check if the object is marked with the Serializable attribute

            BinaryCommon.CheckSerializable(instanceType, _surrogateSelector, _context);

#if NET_2_0
            _manager.RegisterObject(obj);
#endif

            ISerializable ser = obj as ISerializable;

            if (ser != null)
            {
                SerializationInfo info = new SerializationInfo(instanceType, new FormatterConverter());
                ser.GetObjectData(info, _context);
                metadata = new SerializableTypeMetadata(instanceType, info);
                data     = info;
            }
            else
            {
                data = obj;
                if (_context.Context != null)
                {
                    // Don't cache metadata info when the Context property is not null sice
                    // we can't control the number of possible contexts in this case
                    metadata = new MemberTypeMetadata(instanceType, _context);
                    return;
                }

                Hashtable typesTable;
                bool      isNew = false;
                lock (_cachedTypes) {
                    typesTable = (Hashtable)_cachedTypes [_context.State];
                    if (typesTable == null)
                    {
                        typesTable = new Hashtable();
                        _cachedTypes [_context.State] = typesTable;
                        isNew = true;
                    }
                }

                metadata = null;
                lock (typesTable) {
                    if (!isNew)
                    {
                        metadata = (TypeMetadata)typesTable [instanceType];
                    }

                    if (metadata == null)
                    {
                        metadata = CreateMemberTypeMetadata(instanceType);
                    }

                    typesTable [instanceType] = metadata;
                }
            }
        }
Пример #25
0
        static bool TryGetKeyContainer(ISerializable key_pair, out byte [] key, out string key_container)
        {
            var info = new SerializationInfo (typeof (StrongNameKeyPair), new FormatterConverter ());
            key_pair.GetObjectData (info, new StreamingContext ());

            key = (byte []) info.GetValue ("_keyPairArray", typeof (byte []));
            key_container = info.GetString ("_keyPairContainer");
            return key_container != null;
        }
Пример #26
0
        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            ISerializable serializable = _dateTime;

            serializable.GetObjectData(info, context);
        }
Пример #27
0
 /// <summary>
 /// Write the specified value.
 /// </summary>
 /// <param name="value">Value.</param>
 public virtual void Write(object value)
 {
     if (value == null)
     {
         m_Writer.Write(0);
     }
     else
     {
         Type type = value.GetType();
         if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal))
         {
             if (type == typeof(string))
             {
                 m_Writer.Write(( string )value);
             }
             else if (type == typeof(decimal))
             {
                 m_Writer.Write(( decimal )value);
             }
             else if (type == typeof(short))
             {
                 m_Writer.Write(( short )value);
             }
             else if (type == typeof(int))
             {
                 m_Writer.Write(( int )value);
             }
             else if (type == typeof(long))
             {
                 m_Writer.Write(( long )value);
             }
             else if (type == typeof(ushort))
             {
                 m_Writer.Write(( ushort )value);
             }
             else if (type == typeof(uint))
             {
                 m_Writer.Write(( uint )value);
             }
             else if (type == typeof(ulong))
             {
                 m_Writer.Write(( ulong )value);
             }
             else if (type == typeof(double))
             {
                 m_Writer.Write(( double )value);
             }
             else if (type == typeof(float))
             {
                 m_Writer.Write(( float )value);
             }
             else if (type == typeof(byte))
             {
                 m_Writer.Write(( byte )value);
             }
             else if (type == typeof(sbyte))
             {
                 m_Writer.Write(( sbyte )value);
             }
             else if (type == typeof(char))
             {
                 m_Writer.Write(( char )value);
             }
             else if (type == typeof(bool))
             {
                 m_Writer.Write(( bool )value);
             }
         }
         else if (type.IsEnum)
         {
             m_Writer.Write(value.ToString());
         }
         else if (type == typeof(DateTime))
         {
             m_Writer.Write((( DateTime )value).ToBinary());
         }
         else if (type == typeof(TimeSpan))
         {
             m_Writer.Write((( TimeSpan )value).ToString());
         }
         else if (value is ISerializable)
         {
             SerializationInfo info         = new SerializationInfo(type, new FormatterConverter());
             ISerializable     serializable = value as ISerializable;
             serializable.GetObjectData(info, m_Context);
             WriteSerializationInfo(info);
         }
         else if (type.IsSerializable && !type.IsArray)
         {
             WriteObject(value, type);
         }
         else if (type.IsArray)
         {
             Array array = value as Array;
             m_Writer.Write(array.Rank);
             for (int i = 0; i < array.Rank; i++)
             {
                 m_Writer.Write(array.GetLength(i));
             }
             int [] indices = new int[array.Rank];
             for (int i = 0; i < array.Rank; i++)
             {
                 for (int j = 0; j < array.GetLength(i); j++)
                 {
                     indices [i] = j;
                     Write(array.GetValue(indices));
                 }
             }
         }
         else if (value is IEnumerable && value is ICollection)
         {
             IEnumerable enumerable = value as IEnumerable;
             ICollection collection = value as ICollection;
             IEnumerator e          = enumerable.GetEnumerator();
             m_Writer.Write(collection.Count);
             while (e.MoveNext())
             {
                 Write(e.Current);
             }
         }
         else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
         {
             Write(type.GetProperty("Key").GetValue(value, BindingFlags.Default, null, null, null));
             Write(type.GetProperty("Value").GetValue(value, BindingFlags.Default, null, null, null));
         }
         else
         {
             ISerializationSurrogate surrogate = null;
             if (m_SurrogateSelector != null)
             {
                 ISurrogateSelector selector;
                 surrogate = m_SurrogateSelector.GetSurrogate(type, m_Context, out selector);
                 if (surrogate != null)
                 {
                     SerializationInfo info = new SerializationInfo(type, new FormatterConverter());
                     surrogate.GetObjectData(value, info, m_Context);
                     WriteSerializationInfo(info);
                 }
             }
             if (surrogate == null)
             {
                 WriteObject(value, type);
             }
         }
     }
 }
Пример #28
0
        private void GetObjectData(object obj, out TypeMetadata metadata, out object data)
        {
            Type type = obj.GetType();

            if (this._surrogateSelector != null)
            {
                ISurrogateSelector      surrogateSelector;
                ISerializationSurrogate surrogate = this._surrogateSelector.GetSurrogate(type, this._context, out surrogateSelector);
                if (surrogate != null)
                {
                    SerializationInfo serializationInfo = new SerializationInfo(type, new FormatterConverter());
                    surrogate.GetObjectData(obj, serializationInfo, this._context);
                    metadata = new SerializableTypeMetadata(type, serializationInfo);
                    data     = serializationInfo;
                    return;
                }
            }
            BinaryCommon.CheckSerializable(type, this._surrogateSelector, this._context);
            this._manager.RegisterObject(obj);
            ISerializable serializable = obj as ISerializable;

            if (serializable != null)
            {
                SerializationInfo serializationInfo2 = new SerializationInfo(type, new FormatterConverter());
                serializable.GetObjectData(serializationInfo2, this._context);
                metadata = new SerializableTypeMetadata(type, serializationInfo2);
                data     = serializationInfo2;
            }
            else
            {
                data = obj;
                if (this._context.Context != null)
                {
                    metadata = new MemberTypeMetadata(type, this._context);
                    return;
                }
                bool      flag        = false;
                Hashtable cachedTypes = ObjectWriter._cachedTypes;
                Hashtable hashtable;
                lock (cachedTypes)
                {
                    hashtable = (Hashtable)ObjectWriter._cachedTypes[this._context.State];
                    if (hashtable == null)
                    {
                        hashtable = new Hashtable();
                        ObjectWriter._cachedTypes[this._context.State] = hashtable;
                        flag = true;
                    }
                }
                metadata = null;
                Hashtable obj2 = hashtable;
                lock (obj2)
                {
                    if (!flag)
                    {
                        metadata = (TypeMetadata)hashtable[type];
                    }
                    if (metadata == null)
                    {
                        metadata = this.CreateMemberTypeMetadata(type);
                    }
                    hashtable[type] = metadata;
                }
            }
        }
 internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context)
 {
     obj.GetObjectData(serInfo, context);
 }
 // Token: 0x06000C07 RID: 3079
 // RVA: 0x00047744 File Offset: 0x00045944
 private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
 {
     if (!JsonTypeReflector.FullyTrusted)
     {
         string text = "Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + "To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
         text = StringUtils.FormatWith(text, CultureInfo.InvariantCulture, value.GetType());
         throw JsonSerializationException.Create(null, writer.ContainerPath, text, null);
     }
     this.OnSerializing(writer, contract, value);
     this._serializeStack.Add(value);
     this.WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
     SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
     value.GetObjectData(serializationInfo, this.Serializer._context);
     SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();
     while (enumerator.MoveNext())
     {
         SerializationEntry current = enumerator.Current;
         JsonContract contractSafe = this.GetContractSafe(current.Value);
         if (this.ShouldWriteReference(current.Value, null, contractSafe, contract, member))
         {
             writer.WritePropertyName(current.Name);
             this.WriteReference(writer, current.Value);
         }
         else if (this.CheckForCircularReference(writer, current.Value, null, contractSafe, contract, member))
         {
             writer.WritePropertyName(current.Name);
             this.SerializeValue(writer, current.Value, contractSafe, null, contract, member);
         }
     }
     writer.WriteEndObject();
     this._serializeStack.RemoveAt(this._serializeStack.Count - 1);
     this.OnSerialized(writer, contract, value);
 }
Пример #31
0
        /// <summary>
        /// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"></see> with the data needed to serialize the target object.
        /// </summary>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"></see> to populate with data.</param>
        /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"></see>) for this serialization.</param>
        /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission. </exception>
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            ISerializable serializable = dict as ISerializable;

            serializable.GetObjectData(info, context);
        }
Пример #32
0
 public void GetObjectData(SerializationInfo info, StreamingContext context)
 {
     info.SetType(_ser.GetType());
     _ser.GetObjectData(info, context);
 }
    private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
    {
      if (!JsonTypeReflector.FullyTrusted)
      {
        throw JsonSerializationException.Create(null, writer.ContainerPath, @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
      }

      contract.InvokeOnSerializing(value, Serializer.Context);
      _serializeStack.Add(value);

      WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);

      SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
      value.GetObjectData(serializationInfo, Serializer.Context);

      foreach (SerializationEntry serializationEntry in serializationInfo)
      {
        writer.WritePropertyName(serializationEntry.Name);
        SerializeValue(writer, serializationEntry.Value, GetContractSafe(serializationEntry.Value), null, null, member);
      }

      writer.WriteEndObject();

      _serializeStack.RemoveAt(_serializeStack.Count - 1);
      contract.InvokeOnSerialized(value, Serializer.Context);
    }
        public StreamWriter SerializeToString(StreamWriter stream, object graph)
        {
            ISerializable     _data    = (ISerializable)graph;
            SerializationInfo _info    = new SerializationInfo(graph.GetType(), new FormatterConverter());
            StreamingContext  _context = new StreamingContext(StreamingContextStates.File);

            _data.GetObjectData(_info, _context);
            string assembly;
            string typeName;
            long   objectID;
            bool   firstTime = false;

            stream.AutoFlush = true;
            objectID         = objectIDGenerator.GetId(graph, out firstTime);
            if (!firstTime)
            {
                stream.Write("IDREF");
                stream.Write(':');
                stream.Write(objectID);
                stream.Write(';');
                Binder.BindToName(graph.GetType(), out assembly, out typeName);
                stream.Write("TypeName");
                stream.Write(':');
                stream.Write(typeName);
                stream.Write(';');
            }
            else
            {
                stream.Write("ID");
                stream.Write(':');
                stream.Write(objectID);
                stream.Write(';');

                Binder.BindToName(graph.GetType(), out assembly, out typeName);
                stream.Write("TypeName");
                stream.Write(':');
                stream.Write(typeName);
                stream.Write(';');

                foreach (SerializationEntry _item in _info)
                {
                    if (checkObjectType(_item.Value.GetType()))
                    {
                        objectID = objectIDGenerator.GetId(graph, out firstTime);
                        stream.Write('\n');
                        stream.Write('{');
                        stream.Write('\n');
                        this.SerializeToString(stream, _item.Value);
                        stream.Write('}');
                    }
                    else
                    {
                        stream.Write(_item.Name);
                        stream.Write(':');
                        stream.Write(_item.Value);
                        stream.Write(';');
                    }
                }
            }
            stream.Write('\n');
            return(stream);
        }