Пример #1
0
 internal BinaryFormatterWriter(Stream outputStream, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle)
 {
     _outputStream = outputStream;
     _formatterTypeStyle = formatterTypeStyle;
     _objectWriter = objectWriter;
     _dataWriter = new BinaryWriter(outputStream, Encoding.UTF8);
 }
 internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId)
 {
     BinaryTypeEnum primitive;
     assemId = 0;
     typeInformation = null;
     if (object.ReferenceEquals(type, Converter.typeofString))
     {
         return BinaryTypeEnum.String;
     }
     if (((objectInfo == null) || ((objectInfo != null) && !objectInfo.isSi)) && object.ReferenceEquals(type, Converter.typeofObject))
     {
         return BinaryTypeEnum.Object;
     }
     if (object.ReferenceEquals(type, Converter.typeofStringArray))
     {
         return BinaryTypeEnum.StringArray;
     }
     if (object.ReferenceEquals(type, Converter.typeofObjectArray))
     {
         return BinaryTypeEnum.ObjectArray;
     }
     if (Converter.IsPrimitiveArray(type, out typeInformation))
     {
         return BinaryTypeEnum.PrimitiveArray;
     }
     InternalPrimitiveTypeE ee = objectWriter.ToCode(type);
     switch (ee)
     {
         case InternalPrimitiveTypeE.Invalid:
         {
             string fullName = null;
             if (objectInfo == null)
             {
                 fullName = type.Assembly.FullName;
                 typeInformation = type.FullName;
             }
             else
             {
                 fullName = objectInfo.GetAssemblyString();
                 typeInformation = objectInfo.GetTypeFullName();
             }
             if (fullName.Equals(Converter.urtAssemblyString))
             {
                 primitive = BinaryTypeEnum.ObjectUrt;
                 assemId = 0;
                 return primitive;
             }
             primitive = BinaryTypeEnum.ObjectUser;
             assemId = (int) objectInfo.assemId;
             if (assemId == 0)
             {
                 throw new SerializationException(Environment.GetResourceString("Serialization_AssemblyId", new object[] { typeInformation }));
             }
             return primitive;
         }
     }
     primitive = BinaryTypeEnum.Primitive;
     typeInformation = ee;
     return primitive;
 }
 internal __BinaryWriter(Stream sout, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle)
 {
     this.sout = sout;
     this.formatterTypeStyle = formatterTypeStyle;
     this.objectWriter = objectWriter;
     this.m_nestedObjectCount = 0;
     this.dataWriter = new BinaryWriter(sout, Encoding.UTF8);
 }
Пример #4
0
        private int nullCount = 0; //Count of consecutive array nulls
 
        // Constructor 
        internal __BinaryWriter(Stream sout, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle)
        { 
            SerTrace.Log( this, "BinaryWriter ");
            this.sout = sout;
            this.formatterTypeStyle = formatterTypeStyle;
            this.objectWriter = objectWriter; 
            m_nestedObjectCount = 0;
            dataWriter = new BinaryWriter(sout, Encoding.UTF8); 
        } 
Пример #5
0
        // 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);
            }
        }
Пример #6
0
        internal void Serialize(Stream serializationStream, object graph, bool check)
        {
            if (serializationStream == null)
            {
                throw new ArgumentNullException(nameof(serializationStream));
            }

            var formatterEnums = new InternalFE()
            {
                _typeFormat = _typeFormat,
                _serializerTypeEnum = InternalSerializerTypeE.Binary,
                _assemblyFormat = _assemblyFormat,
            };

            var sow = new ObjectWriter(_surrogates, _context, formatterEnums, _binder);
            BinaryFormatterWriter binaryWriter = new BinaryFormatterWriter(serializationStream, sow, _typeFormat);
            sow.Serialize(graph, binaryWriter, check);
            _crossAppDomainArray = sow._crossAppDomainArray;
        }
Пример #7
0
        [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);
            }
        }
		public abstract void WriteTypeData (ObjectWriter ow, BinaryWriter writer, bool writeTypes);
		public override void WriteObjectData (ObjectWriter ow, BinaryWriter writer, object data)
		{
			object[] values = FormatterServices.GetObjectData (data, members);
			for (int n=0; n<values.Length; n++)
				ow.WriteValue (writer, ((FieldInfo)members[n]).FieldType, values[n]);
		}
Пример #10
0
 public abstract void WriteTypeData(ObjectWriter ow, BinaryWriter writer, bool writeTypes);
Пример #11
0
        // From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire
        internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId)
        {
            BinaryTypeEnum binaryTypeEnum;

            assemId         = 0;
            typeInformation = null;

            if (ReferenceEquals(type, Converter.s_typeofString))
            {
                binaryTypeEnum = BinaryTypeEnum.String;
            }
            else if (((objectInfo == null) || ((objectInfo != null) && !objectInfo._isSi)) && (ReferenceEquals(type, Converter.s_typeofObject)))
            {
                // If objectInfo.Si then can be a surrogate which will change the type
                binaryTypeEnum = BinaryTypeEnum.Object;
            }
            else if (ReferenceEquals(type, Converter.s_typeofStringArray))
            {
                binaryTypeEnum = BinaryTypeEnum.StringArray;
            }
            else if (ReferenceEquals(type, Converter.s_typeofObjectArray))
            {
                binaryTypeEnum = BinaryTypeEnum.ObjectArray;
            }
            else if (Converter.IsPrimitiveArray(type, out typeInformation))
            {
                binaryTypeEnum = BinaryTypeEnum.PrimitiveArray;
            }
            else
            {
                InternalPrimitiveTypeE primitiveTypeEnum = objectWriter.ToCode(type);
                switch (primitiveTypeEnum)
                {
                case InternalPrimitiveTypeE.Invalid:
                    string assembly = null;
                    if (objectInfo == null)
                    {
                        assembly        = type.Assembly.FullName;
                        typeInformation = type.FullName;
                    }
                    else
                    {
                        assembly        = objectInfo.GetAssemblyString();
                        typeInformation = objectInfo.GetTypeFullName();
                    }

                    if (assembly.Equals(Converter.s_urtAssemblyString) || assembly.Equals(Converter.s_urtAlternativeAssemblyString))
                    {
                        binaryTypeEnum = BinaryTypeEnum.ObjectUrt;
                        assemId        = 0;
                    }
                    else
                    {
                        binaryTypeEnum = BinaryTypeEnum.ObjectUser;
                        Debug.Assert(objectInfo != null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object");
                        assemId = (int)objectInfo._assemId;
                        if (assemId == 0)
                        {
                            throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, typeInformation));
                        }
                    }
                    break;

                default:
                    binaryTypeEnum  = BinaryTypeEnum.Primitive;
                    typeInformation = primitiveTypeEnum;
                    break;
                }
            }

            return(binaryTypeEnum);
        }
        [System.Security.SecurityCritical]  // auto-generated
        internal static WriteObjectInfo Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
        {
            WriteObjectInfo soi = GetObjectInfo(serObjectInfoInit);

            soi.InitSerialize(obj, surrogateSelector, context, serObjectInfoInit, converter, objectWriter, binder);
            return soi;
        }
Пример #13
0
 private DatabaseCompat GetNorthwindObject()
 {
     string json = GetNorthwindJson();
     ObjectWriter<DatabaseCompat> objectWriter = new ObjectWriter<DatabaseCompat>();
     JsonReader.Read(json, objectWriter);
     return objectWriter.Result;
 }
 internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
 {
     this.context = context;
     this.obj = obj;
     this.serObjectInfoInit = serObjectInfoInit;
     if (RemotingServices.IsTransparentProxy(obj))
     {
         this.objectType = Converter.typeofMarshalByRefObject;
     }
     else
     {
         this.objectType = obj.GetType();
     }
     if (this.objectType.IsArray)
     {
         this.isArray = true;
         this.InitNoMembers();
     }
     else
     {
         ISurrogateSelector selector;
         this.InvokeSerializationBinder(binder);
         objectWriter.ObjectManager.RegisterObject(obj);
         if ((surrogateSelector != null) && ((this.serializationSurrogate = surrogateSelector.GetSurrogate(this.objectType, context, out selector)) != null))
         {
             this.si = new SerializationInfo(this.objectType, converter);
             if (!this.objectType.IsPrimitive)
             {
                 this.serializationSurrogate.GetObjectData(obj, this.si, context);
             }
             this.InitSiWrite();
         }
         else if (obj is ISerializable)
         {
             if (!this.objectType.IsSerializable)
             {
                 throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", new object[] { this.objectType.FullName, this.objectType.Assembly.FullName }));
             }
             this.si = new SerializationInfo(this.objectType, converter, !FormatterServices.UnsafeTypeForwardersIsEnabled());
             ((ISerializable) obj).GetObjectData(this.si, context);
             this.InitSiWrite();
             CheckTypeForwardedFrom(this.cache, this.objectType, this.binderAssemblyString);
         }
         else
         {
             this.InitMemberInfo();
             CheckTypeForwardedFrom(this.cache, this.objectType, this.binderAssemblyString);
         }
     }
 }
Пример #15
0
        static public Type GenerateMetadataTypeInternal(Type type, StreamingContext context)
        {
            string name  = type.Name + "__TypeMetadata";
            string sufix = "";
            int    n     = 0;

            while (_module.GetType(name + sufix) != null)
            {
                sufix = (++n).ToString();
            }

            name += sufix;

            MemberInfo[] members = FormatterServices.GetSerializableMembers(type, context);

            TypeBuilder typeBuilder = _module.DefineType(name, TypeAttributes.Public, typeof(ClrTypeMetadata));

            Type[]        parameters;
            MethodBuilder method;
            ILGenerator   gen;

            // *********************
            //  METHOD public constructor (Type t): base (t);

            parameters = Type.EmptyTypes;

            ConstructorBuilder ctor     = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameters);
            ConstructorInfo    baseCtor = typeof(ClrTypeMetadata).GetConstructor(new Type[] { typeof(Type) });

            gen = ctor.GetILGenerator();

            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldtoken, type);
            gen.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null);
            gen.Emit(OpCodes.Call, baseCtor);
            gen.Emit(OpCodes.Ret);

            // *********************
            //  METHOD public override void WriteAssemblies (ObjectWriter ow, BinaryWriter writer);

            parameters = new Type[] { typeof(ObjectWriter), typeof(BinaryWriter) };
            method     = typeBuilder.DefineMethod("WriteAssemblies", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), parameters);
            gen        = method.GetILGenerator();

            foreach (FieldInfo field in members)
            {
                Type memberType = field.FieldType;
                while (memberType.IsArray)
                {
                    memberType = memberType.GetElementType();
                }

                if (memberType.Assembly != ObjectWriter.CorlibAssembly)
                {
                    // EMIT ow.WriteAssembly (writer, memberType.Assembly);
                    gen.Emit(OpCodes.Ldarg_1);
                    gen.Emit(OpCodes.Ldarg_2);
                    EmitLoadTypeAssembly(gen, memberType, field.Name);
                    gen.EmitCall(OpCodes.Callvirt, typeof(ObjectWriter).GetMethod("WriteAssembly"), null);
                    gen.Emit(OpCodes.Pop);
                }
            }
            gen.Emit(OpCodes.Ret);
            typeBuilder.DefineMethodOverride(method, typeof(TypeMetadata).GetMethod("WriteAssemblies"));

            // *********************
            // METHOD public override void WriteTypeData (ObjectWriter ow, BinaryWriter writer, bool writeTypes);

            parameters = new Type[] { typeof(ObjectWriter), typeof(BinaryWriter), typeof(bool) };
            method     = typeBuilder.DefineMethod("WriteTypeData", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), parameters);
            gen        = method.GetILGenerator();

            // EMIT writer.Write (members.Length);
            gen.Emit(OpCodes.Ldarg_2);
            gen.Emit(OpCodes.Ldc_I4, members.Length);
            EmitWrite(gen, typeof(int));

            // Names of fields
            foreach (FieldInfo field in members)
            {
                // EMIT writer.Write (name);
                gen.Emit(OpCodes.Ldarg_2);
                gen.Emit(OpCodes.Ldstr, field.Name);
                EmitWrite(gen, typeof(string));
            }

            Label falseLabel = gen.DefineLabel();

            gen.Emit(OpCodes.Ldarg_3);
            gen.Emit(OpCodes.Brfalse, falseLabel);

            // Types of fields
            foreach (FieldInfo field in members)
            {
                // EMIT writer.Write ((byte) ObjectWriter.GetTypeTag (type));
                gen.Emit(OpCodes.Ldarg_2);
                gen.Emit(OpCodes.Ldc_I4_S, (byte)ObjectWriter.GetTypeTag(field.FieldType));
                EmitWrite(gen, typeof(byte));
            }

            // Type specs of fields
            foreach (FieldInfo field in members)
            {
                // EMIT ow.WriteTypeSpec (writer, field.FieldType);
                EmitWriteTypeSpec(gen, field.FieldType, field.Name);
            }
            gen.MarkLabel(falseLabel);

            gen.Emit(OpCodes.Ret);
            typeBuilder.DefineMethodOverride(method, typeof(TypeMetadata).GetMethod("WriteTypeData"));

            // *********************
            // METHOD public override void WriteObjectData (ObjectWriter ow, BinaryWriter writer, object data)

            parameters = new Type[] { typeof(ObjectWriter), typeof(BinaryWriter), typeof(object) };
            method     = typeBuilder.DefineMethod("WriteObjectData", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), parameters);
            gen        = method.GetILGenerator();

            LocalBuilder localBuilder = gen.DeclareLocal(type);
            OpCode       lload        = OpCodes.Ldloc;

            gen.Emit(OpCodes.Ldarg_3);
            if (type.IsValueType)
            {
                gen.Emit(OpCodes.Unbox, type);
                LoadFromPtr(gen, type);
                lload = OpCodes.Ldloca_S;
            }
            else
            {
                gen.Emit(OpCodes.Castclass, type);
            }

            gen.Emit(OpCodes.Stloc, localBuilder);

            foreach (FieldInfo field in members)
            {
                // EMIT ow.WriteValue (writer, ((FieldInfo)members[n]).FieldType, values[n]);
                Type ftype = field.FieldType;
                if (BinaryCommon.IsPrimitive(ftype))
                {
                    gen.Emit(OpCodes.Ldarg_2);
                    gen.Emit(lload, localBuilder);
                    if (ftype == typeof(DateTime) || ftype == typeof(TimeSpan) || ftype == typeof(decimal))
                    {
                        gen.Emit(OpCodes.Ldflda, field);
                    }
                    else
                    {
                        gen.Emit(OpCodes.Ldfld, field);
                    }
                    EmitWritePrimitiveValue(gen, ftype);
                }
                else
                {
                    gen.Emit(OpCodes.Ldarg_1);
                    gen.Emit(OpCodes.Ldarg_2);
                    gen.Emit(OpCodes.Ldtoken, ftype);
                    gen.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null);
                    gen.Emit(lload, localBuilder);
                    gen.Emit(OpCodes.Ldfld, field);
                    if (ftype.IsValueType)
                    {
                        gen.Emit(OpCodes.Box, ftype);
                    }
                    gen.EmitCall(OpCodes.Call, typeof(ObjectWriter).GetMethod("WriteValue"), null);
                }
            }

            gen.Emit(OpCodes.Ret);
            typeBuilder.DefineMethodOverride(method, typeof(TypeMetadata).GetMethod("WriteObjectData"));

            return(typeBuilder.CreateType());
        }
Пример #16
0
        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);

            if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out _)) != 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);
            }
        }
Пример #17
0
        internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector?surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder?binder)
        {
            WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit);

            woi.InitSerialize(obj, surrogateSelector, context, serObjectInfoInit, converter, objectWriter, binder);
            return(woi);
        }
Пример #18
0
 public abstract void WriteObjectData(ObjectWriter ow, BinaryWriter writer, object data);
Пример #19
0
		public static void WriteMethodCall (BinaryWriter writer, object obj, Header[] headers, ISurrogateSelector surrogateSelector, StreamingContext context, FormatterAssemblyStyle assemblyFormat, FormatterTypeStyle typeFormat)
		{
			IMethodCallMessage call = (IMethodCallMessage)obj;
			writer.Write ((byte) BinaryElement.MethodCall);

			MethodFlags methodFlags;
			int infoArraySize = 0;
			object info = null;
			object[] extraProperties = null;

			if (call.LogicalCallContext != null && call.LogicalCallContext.HasInfo)
			{
				methodFlags = MethodFlags.IncludesLogicalCallContext;
				infoArraySize++;
			}
			else
				methodFlags = MethodFlags.ExcludeLogicalCallContext;

			if (RemotingServices.IsMethodOverloaded (call))
			{
				infoArraySize++;
				methodFlags |= MethodFlags.IncludesSignature;
			}

			if (call.Properties.Count > MethodCallDictionary.InternalKeys.Length)
			{
				extraProperties = GetExtraProperties (call.Properties, MethodCallDictionary.InternalKeys);
				infoArraySize++;
			}

#if NET_2_0
			if (call.MethodBase.IsGenericMethod) {
				infoArraySize++;
				methodFlags |= MethodFlags.GenericArguments;
			}
#endif
			if (call.ArgCount == 0)
				methodFlags |= MethodFlags.NoArguments;
			else {
				if (AllTypesArePrimitive (call.Args)) 
					methodFlags |= MethodFlags.PrimitiveArguments;
				else {
					if (infoArraySize == 0)
						methodFlags |= MethodFlags.ArgumentsInSimpleArray;
					else {
						methodFlags |= MethodFlags.ArgumentsInMultiArray;
						infoArraySize++;
					}
				}
			}

			writer.Write ((int) methodFlags);

			// Method name
			writer.Write ((byte) BinaryTypeCode.String);
			writer.Write (call.MethodName);

			// Class name
			writer.Write ((byte) BinaryTypeCode.String);
			writer.Write (call.TypeName);

			// Arguments

			if ((methodFlags & MethodFlags.PrimitiveArguments) > 0)
			{
				writer.Write ((uint)call.Args.Length);
				for (int n=0; n<call.ArgCount; n++)
				{
					object arg = call.GetArg(n);
					if (arg != null) {
						writer.Write (BinaryCommon.GetTypeCode (arg.GetType()));
						ObjectWriter.WritePrimitiveValue (writer, arg);
					}
					else
						writer.Write ((byte)BinaryTypeCode.Null);
				}
			}

			if ( infoArraySize > 0)
			{
				object[] ainfo = new object[infoArraySize];
				int n=0;
				if ((methodFlags & MethodFlags.ArgumentsInMultiArray) > 0) ainfo[n++] = call.Args;

#if NET_2_0
				if ((methodFlags & MethodFlags.GenericArguments) > 0) ainfo[n++] = call.MethodBase.GetGenericArguments ();
#endif

				if ((methodFlags & MethodFlags.IncludesSignature) > 0) ainfo[n++] = call.MethodSignature;
				if ((methodFlags & MethodFlags.IncludesLogicalCallContext) > 0) ainfo[n++] = call.LogicalCallContext;
				if (extraProperties != null) ainfo[n++] = extraProperties;
				info = ainfo;
			}
			else if ((methodFlags & MethodFlags.ArgumentsInSimpleArray) > 0)
				info = call.Args;

			if (info != null)
			{
				ObjectWriter objectWriter = new ObjectWriter (surrogateSelector, context, assemblyFormat, typeFormat);
				objectWriter.WriteObjectGraph (writer, info, headers);
			}
			else
				writer.Write ((byte) BinaryElement.End);
		}
Пример #20
0
        public void VerifyNorthwindDeserializeReserialize()
        {
            string originalJson = GetNorthwindJson();
            ObjectWriter<Database> writer = new ObjectWriter<Database>();
            JsonReader.Read(originalJson, writer);

            Database db = writer.Result;

            db.ShouldNotBeNull();

            StringWriter stringWriter = new StringWriter();
            PrettyPrintingJsonStringWriter jsonWriter = new PrettyPrintingJsonStringWriter(stringWriter);
            ObjectReader.Read(db, jsonWriter, new ObjectParsingOptions { SerializeTypeInformation = TypeInformationLevel.None });

            string result = stringWriter.ToString();

            result.ShouldBe(originalJson);
        }
        // From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire
 
        internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, String typeName, ObjectWriter objectWriter, out Object typeInformation, out int assemId)
        {
            SerTrace.Log("BinaryConverter", "GetBinaryTypeInfo Entry type ",type,", typeName ",typeName," objectInfo "+objectInfo);
            BinaryTypeEnum binaryTypeEnum; 

            assemId = 0; 
            typeInformation = null; 

            if (Object.ReferenceEquals(type, Converter.typeofString)) 
                binaryTypeEnum = BinaryTypeEnum.String;
            else if (((objectInfo == null) || ((objectInfo != null) && !objectInfo.isSi))
                     && (Object.ReferenceEquals(type, Converter.typeofObject)))
            { 
                // If objectInfo.Si then can be a surrogate which will change the type
                binaryTypeEnum = BinaryTypeEnum.Object; 
            } 
            else if (Object.ReferenceEquals(type, Converter.typeofStringArray))
                binaryTypeEnum = BinaryTypeEnum.StringArray; 
            else if (Object.ReferenceEquals(type, Converter.typeofObjectArray))
                binaryTypeEnum = BinaryTypeEnum.ObjectArray;
            else if (Converter.IsPrimitiveArray(type, out typeInformation))
                binaryTypeEnum = BinaryTypeEnum.PrimitiveArray; 
            else
            { 
                InternalPrimitiveTypeE primitiveTypeEnum = objectWriter.ToCode(type); 
                switch (primitiveTypeEnum)
                { 
                    case InternalPrimitiveTypeE.Invalid:
                        String assembly = null;
                        if (objectInfo == null)
                        { 
                            assembly = type.Assembly.FullName;
                            typeInformation = type.FullName; 
                        } 
                        else
                        { 
                            assembly = objectInfo.GetAssemblyString();
                            typeInformation = objectInfo.GetTypeFullName();
                        }
 
                        if (assembly.Equals(Converter.urtAssemblyString))
                        { 
                            binaryTypeEnum = BinaryTypeEnum.ObjectUrt; 
                            assemId = 0;
                        } 
                        else
                        {
                            binaryTypeEnum = BinaryTypeEnum.ObjectUser;
                            Contract.Assert(objectInfo!=null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object"); 
                            assemId = (int)objectInfo.assemId;
                            if (assemId == 0) 
                                throw new SerializationException(Environment.GetResourceString("Serialization_AssemblyId",typeInformation)); 
                        }
                        break; 
                    default:
                        binaryTypeEnum = BinaryTypeEnum.Primitive;
                        typeInformation = primitiveTypeEnum;
                        break; 
                }
            } 
 
            SerTrace.Log( "BinaryConverter", "GetBinaryTypeInfo Exit ",((Enum)binaryTypeEnum).ToString(),", typeInformation ",typeInformation," assemId ",assemId);
            return binaryTypeEnum; 
        }
        // Commences the process of serializing the entire graph.  All of the data (in the appropriate format
        // is emitted onto the stream).
        internal void Serialize(Stream serializationStream, Object graph, Header[] headers, bool fCheck)
        {
            if (serializationStream==null)
            {
                throw new ArgumentNullException("serializationStream", String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentNull_WithParamName"),serializationStream));             
            }
            SerTrace.Log(this, "Serialize Entry");

            InternalFE formatterEnums = new InternalFE();
            formatterEnums.FEtypeFormat = m_typeFormat;
            formatterEnums.FEserializerTypeEnum = InternalSerializerTypeE.Binary;
            formatterEnums.FEassemblyFormat = m_assemblyFormat;    

            ObjectWriter sow = new ObjectWriter(m_surrogates, m_context, formatterEnums);
            __BinaryWriter binaryWriter = new __BinaryWriter(serializationStream, sow, m_typeFormat); 
            sow.Serialize(graph, headers, binaryWriter, fCheck);
            m_crossAppDomainArray = sow.crossAppDomainArray;
        }
        internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
        {
            this.context           = context;
            this.obj               = obj;
            this.serObjectInfoInit = serObjectInfoInit;
            if (RemotingServices.IsTransparentProxy(obj))
            {
                this.objectType = Converter.typeofMarshalByRefObject;
            }
            else
            {
                this.objectType = obj.GetType();
            }
            if (this.objectType.IsArray)
            {
                this.isArray = true;
                this.InitNoMembers();
                return;
            }
            this.InvokeSerializationBinder(binder);
            objectWriter.ObjectManager.RegisterObject(obj);
            ISurrogateSelector surrogateSelector2;

            if (surrogateSelector != null && (this.serializationSurrogate = surrogateSelector.GetSurrogate(this.objectType, context, out surrogateSelector2)) != null)
            {
                this.si = new SerializationInfo(this.objectType, converter);
                if (!this.objectType.IsPrimitive)
                {
                    this.serializationSurrogate.GetObjectData(obj, this.si, context);
                }
                this.InitSiWrite();
                return;
            }
            if (!(obj is ISerializable))
            {
                this.InitMemberInfo();
                WriteObjectInfo.CheckTypeForwardedFrom(this.cache, this.objectType, this.binderAssemblyString);
                return;
            }
            if (!this.objectType.IsSerializable)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", new object[]
                {
                    this.objectType.FullName,
                    this.objectType.Assembly.FullName
                }));
            }
            this.si = new SerializationInfo(this.objectType, converter, !FormatterServices.UnsafeTypeForwardersIsEnabled());
            ((ISerializable)obj).GetObjectData(this.si, context);
            this.InitSiWrite();
            WriteObjectInfo.CheckTypeForwardedFrom(this.cache, this.objectType, this.binderAssemblyString);
        }
Пример #24
0
		public override void WriteTypeData (ObjectWriter ow, BinaryWriter writer, bool writeTypes)
		{
			writer.Write (types.Length);

			// Names of fields
			foreach (string name in names)
				writer.Write (name);

			// Types of fields
			foreach (Type type in types)
				ObjectWriter.WriteTypeCode (writer, type);

			// Type specs of fields
			foreach (Type type in types)
				ow.WriteTypeSpec (writer, type);
		}
        [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);
            }
        }
Пример #26
0
		public override void WriteAssemblies (ObjectWriter ow, BinaryWriter writer)
		{
			foreach (FieldInfo field in members)
			{
				Type type = field.FieldType;
				while (type.IsArray) 
					type = type.GetElementType();
					
				ow.WriteAssembly (writer, type.Assembly);
			}
		}
 internal void Serialize(Stream serializationStream, object graph, Header[] headers, bool fCheck)
 {
     if (serializationStream == null)
     {
         throw new ArgumentNullException("serializationStream", Environment.GetResourceString("ArgumentNull_WithParamName", new object[] { serializationStream }));
     }
     InternalFE formatterEnums = new InternalFE {
         FEtypeFormat = this.m_typeFormat,
         FEserializerTypeEnum = InternalSerializerTypeE.Binary,
         FEassemblyFormat = this.m_assemblyFormat
     };
     ObjectWriter objectWriter = new ObjectWriter(this.m_surrogates, this.m_context, formatterEnums, this.m_binder);
     __BinaryWriter serWriter = new __BinaryWriter(serializationStream, objectWriter, this.m_typeFormat);
     objectWriter.Serialize(graph, headers, serWriter, fCheck);
     this.m_crossAppDomainArray = objectWriter.crossAppDomainArray;
 }
Пример #28
0
 public abstract void WriteAssemblies(ObjectWriter ow, BinaryWriter writer);
Пример #29
0
		public override void WriteAssemblies (ObjectWriter ow, BinaryWriter writer)
		{
			foreach (Type mtype in types)
			{
				Type type = mtype;
				while (type.IsArray) 
					type = type.GetElementType();
					
				ow.WriteAssembly (writer, type.Assembly);
			}
		}
Пример #30
0
		public void Serialize(Stream serializationStream, object graph, Header[] headers)
		{
			if(serializationStream==null) {
				throw new ArgumentNullException ("serializationStream");
			}

			BinaryWriter writer = new BinaryWriter (serializationStream);
			WriteBinaryHeader (writer, headers!=null);

			if (graph is IMethodCallMessage) {
				MessageFormatter.WriteMethodCall (writer, graph, headers, this);
			}
			else if (graph is IMethodReturnMessage)  {
				MessageFormatter.WriteMethodResponse (writer, graph, headers, this);
			}
			else {
				ObjectWriter serializer = new ObjectWriter (this);
				serializer.WriteObjectGraph (writer, graph, headers);
			}
			writer.Flush();
		}
Пример #31
0
		public override void WriteObjectData (ObjectWriter ow, BinaryWriter writer, object data)
		{
			SerializationInfo info = (SerializationInfo) data;
			SerializationInfoEnumerator e = info.GetEnumerator ();

			while (e.MoveNext ())
				ow.WriteValue (writer, e.ObjectType, e.Value);
		}
Пример #32
0
        // From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire
        internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId)
        {
            BinaryTypeEnum binaryTypeEnum;

            assemId = 0;
            typeInformation = null;

            if (ReferenceEquals(type, Converter.s_typeofString))
            {
                binaryTypeEnum = BinaryTypeEnum.String;
            }
            else if (((objectInfo == null) || ((objectInfo != null) && !objectInfo._isSi)) && (ReferenceEquals(type, Converter.s_typeofObject)))
            {
                // If objectInfo.Si then can be a surrogate which will change the type
                binaryTypeEnum = BinaryTypeEnum.Object;
            }
            else if (ReferenceEquals(type, Converter.s_typeofStringArray))
            {
                binaryTypeEnum = BinaryTypeEnum.StringArray;
            }
            else if (ReferenceEquals(type, Converter.s_typeofObjectArray))
            {
                binaryTypeEnum = BinaryTypeEnum.ObjectArray;
            }
            else if (Converter.IsPrimitiveArray(type, out typeInformation))
            {
                binaryTypeEnum = BinaryTypeEnum.PrimitiveArray;
            }
            else
            {
                InternalPrimitiveTypeE primitiveTypeEnum = objectWriter.ToCode(type);
                switch (primitiveTypeEnum)
                {
                    case InternalPrimitiveTypeE.Invalid:
                        string assembly = null;
                        if (objectInfo == null)
                        {
                            assembly = type.Assembly.FullName;
                            typeInformation = type.FullName;
                        }
                        else
                        {
                            assembly = objectInfo.GetAssemblyString();
                            typeInformation = objectInfo.GetTypeFullName();
                        }

                        if (assembly.Equals(Converter.s_urtAssemblyString))
                        {
                            binaryTypeEnum = BinaryTypeEnum.ObjectUrt;
                            assemId = 0;
                        }
                        else
                        {
                            binaryTypeEnum = BinaryTypeEnum.ObjectUser;
                            Debug.Assert(objectInfo != null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object");
                            assemId = (int)objectInfo._assemId;
                            if (assemId == 0)
                            {
                                throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, typeInformation));
                            }
                        }
                        break;
                    default:
                        binaryTypeEnum = BinaryTypeEnum.Primitive;
                        typeInformation = primitiveTypeEnum;
                        break;
                }
            }

            return binaryTypeEnum;
        }
Пример #33
0
		public override void WriteTypeData (ObjectWriter ow, BinaryWriter writer, bool writeTypes)
		{
			writer.Write (members.Length);

			// Names of fields
			foreach (FieldInfo field in members)
				writer.Write (field.Name);

			if (writeTypes) {
				// Types of fields
				foreach (FieldInfo field in members)
					ObjectWriter.WriteTypeCode (writer, field.FieldType);
	
				// Type specs of fields
				foreach (FieldInfo field in members)
					ow.WriteTypeSpec (writer, field.FieldType);
			}
		}
        // Write constructor
        internal void InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
        {
            SerTrace.Log( this, objectInfoId," Constructor 1 ",obj);
            this.context = context;
            this.obj = obj;
            this.serObjectInfoInit = serObjectInfoInit;
            ISurrogateSelector surrogateSelectorTemp;

            if (RemotingServices.IsTransparentProxy(obj))
                objectType = Converter.typeofMarshalByRefObject;
            else
                objectType = obj.GetType();

            if (objectType.IsArray)
            {
                isArray = true;
                InitNoMembers();
                return;
            }

            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(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Serialization_NonSerType"),
                                                                   objectType.FullName, objectType.Assembly.FullName));
                }
                si = new SerializationInfo(objectType, converter);
                ((ISerializable)obj).GetObjectData(si, context);
                SerTrace.Log( this, objectInfoId," Constructor 1 trace 4 ISerializable "+objectType);
                InitSiWrite();
            }
            else
            {
                SerTrace.Log(this, objectInfoId," Constructor 1 trace 5");
                InitMemberInfo();
            }
        }
Пример #35
0
		public abstract void WriteAssemblies (ObjectWriter ow, BinaryWriter writer);
Пример #36
0
		public static void WriteMethodResponse (BinaryWriter writer, object obj, Header[] headers, ISurrogateSelector surrogateSelector, StreamingContext context, FormatterAssemblyStyle assemblyFormat, FormatterTypeStyle typeFormat)
		{
			IMethodReturnMessage resp = (IMethodReturnMessage)obj;
			writer.Write ((byte) BinaryElement.MethodResponse);

			string[] internalProperties = MethodReturnDictionary.InternalReturnKeys;

			int infoArrayLength = 0;
			object info = null;
			object[] extraProperties = null;

			// Type of return value

			ReturnTypeTag returnTypeTag;
			MethodFlags contextFlag = MethodFlags.ExcludeLogicalCallContext;

			if (resp.Exception != null) {
				returnTypeTag = ReturnTypeTag.Exception | ReturnTypeTag.Null;
				internalProperties = MethodReturnDictionary.InternalExceptionKeys;
				infoArrayLength = 1;
			}
			else if (resp.ReturnValue == null) {
				returnTypeTag = ReturnTypeTag.Null;
			}
			else if (IsMethodPrimitive(resp.ReturnValue.GetType())) {
				returnTypeTag = ReturnTypeTag.PrimitiveType;
			}
			else {
				returnTypeTag = ReturnTypeTag.ObjectType;
				infoArrayLength++;
			}

			// Message flags

			MethodFlags formatFlag;

			if ((resp.LogicalCallContext != null) && resp.LogicalCallContext.HasInfo) 
			{
				contextFlag = MethodFlags.IncludesLogicalCallContext;
				infoArrayLength++;
			}

			if (resp.Properties.Count > internalProperties.Length && ((returnTypeTag & ReturnTypeTag.Exception) == 0))
			{
				extraProperties = GetExtraProperties (resp.Properties, internalProperties);
				infoArrayLength++;
			}

			if (resp.OutArgCount == 0)
				formatFlag = MethodFlags.NoArguments;
			else 
			{
				if (AllTypesArePrimitive (resp.Args)) 
					formatFlag = MethodFlags.PrimitiveArguments;
				else 
				{
					if (infoArrayLength == 0)
						formatFlag = MethodFlags.ArgumentsInSimpleArray; 
					else {
						formatFlag = MethodFlags.ArgumentsInMultiArray;
						infoArrayLength++;
					}
				}
			}

			writer.Write ((byte) (contextFlag | formatFlag));
			writer.Write ((byte) returnTypeTag);

			// FIXME: what are the following 2 bytes for?
			writer.Write ((byte) 0);
			writer.Write ((byte) 0);

			// Arguments

			if (returnTypeTag == ReturnTypeTag.PrimitiveType)
			{
				writer.Write (BinaryCommon.GetTypeCode (resp.ReturnValue.GetType()));
				ObjectWriter.WritePrimitiveValue (writer, resp.ReturnValue);
			}

			if (formatFlag == MethodFlags.PrimitiveArguments)
			{
				writer.Write ((uint)resp.ArgCount);
				for (int n=0; n<resp.ArgCount; n++)
				{
					object val = resp.GetArg(n);
					if (val != null) {
						writer.Write (BinaryCommon.GetTypeCode (val.GetType()));
						ObjectWriter.WritePrimitiveValue (writer, val);
					}
					else
						writer.Write ((byte)BinaryTypeCode.Null);
				}
			}

			if (infoArrayLength > 0)
			{
				object[] infoArray = new object[infoArrayLength];
				int n = 0;

				if ((returnTypeTag & ReturnTypeTag.Exception) != 0)
					infoArray[n++] = resp.Exception;
				
				if (formatFlag == MethodFlags.ArgumentsInMultiArray)
					infoArray[n++] = resp.Args;

				if (returnTypeTag == ReturnTypeTag.ObjectType)
					infoArray[n++] = resp.ReturnValue;

				if (contextFlag == MethodFlags.IncludesLogicalCallContext)
					infoArray[n++] = resp.LogicalCallContext;

				if (extraProperties != null)
					infoArray[n++] = extraProperties;

				info = infoArray;
			}
			else if ((formatFlag & MethodFlags.ArgumentsInSimpleArray) > 0)
				info = resp.Args;

			if (info != null)
			{
				ObjectWriter objectWriter = new ObjectWriter (surrogateSelector, context, assemblyFormat, typeFormat);
				objectWriter.WriteObjectGraph (writer, info, headers);
			}
			else
				writer.Write ((byte) BinaryElement.End);
		}
Пример #37
0
		public abstract void WriteObjectData (ObjectWriter ow, BinaryWriter writer, object data);
Пример #38
0
 public static void WriteTypeCode(BinaryWriter writer, Type type)
 {
     writer.Write((byte)ObjectWriter.GetTypeTag(type));
 }