public static void Register(RuntimeTypeModel typeModel) { foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { Register(typeModel, assembly); } }
public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members, bool asReference, bool baseTupleAsReference, bool forceIssueFakeHeader, bool useDynamicTypeWhenNeeded, bool supportNull) { if (ctor == null) throw new ArgumentNullException("ctor"); if (members == null) throw new ArgumentNullException("members"); this.ctor = ctor; this.members = members; this.tails = new IProtoSerializer[members.Length]; this.asReference = asReference; this.baseTupleAsReference = baseTupleAsReference; this.forceIssueFakeHeader = forceIssueFakeHeader; ParameterInfo[] parameters = ctor.GetParameters(); for(int i = 0 ; i < members.Length ; i++) { WireType wireType; Type finalType = parameters[i].ParameterType; Type itemType = null, defaultType = null; MetaType.ResolveListTypes(finalType, ref itemType, ref defaultType); Type tmp = itemType == null ? finalType : itemType; bool dynamicType = useDynamicTypeWhenNeeded && (tmp.IsInterface || tmp == typeof(object)); bool overrideSkipConstructor = i == 7; // if there are 8 class parameters the last one has to be a tuple IProtoSerializer tail = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, tmp, out wireType, asReference, dynamicType, false, overrideSkipConstructor, supportNull), serializer; if (tail == null) throw new InvalidOperationException("No serializer defined for type: " + tmp.FullName); if (itemType != null && supportNull) { tail = new TagDecorator(NullDecorator.Tag, wireType, false, tail); tail = new NullDecorator(tail); tail = new TagDecorator(i + 1, WireType.StartGroup, false, tail); } else { tail = new TagDecorator(i + 1, wireType, false, tail); } if(itemType == null) { serializer = tail; } else { if (finalType.IsArray) { serializer = new ArrayDecorator(tail, i + 1, false, wireType, finalType, false, supportNull, asReference, false); } else { serializer = new ListDecorator(finalType, defaultType, tail, i + 1, false, wireType, true, false, supportNull, asReference, false, false); } } tails[i] = serializer; } }
public ProtobufMessageSerializer(IEnumerable<Message> messages, IEnumerable<MessageHeader> headers) { _model = TypeModel.Create(); _model.AllowParseableTypes = true; _model[typeof(Message)].UseConstructor = false; foreach (var message in messages) { if (message.GetType() == typeof(Message)) continue; var type = message.GetType(); _model[typeof(Message)].AddSubType(GenerateId(type), type); _model[type].UseConstructor = false; } _model[typeof(MessageHeader)].UseConstructor = false; foreach (var header in headers) { if (header.GetType() == typeof(MessageHeader)) continue; var type = header.GetType(); _model[typeof(MessageHeader)].AddSubType(GenerateId(type), type); _model[type].UseConstructor = false; } _model.CompileInPlace(); }
public RuntimeTypeModel Configure(RuntimeTypeModel typeModel) { typeModel.Add(typeof(EntityTypeSurrogate), false) .Add(1, "Id").SetFactory(SurrogateFactory<EntityTypeSurrogate>.Factory.Method); typeModel.Add(typeof(IEntityType), false).SetSurrogate(typeof(EntityTypeSurrogate)); return typeModel; }
internal CompilerContext(ILGenerator il, bool isStatic, bool isWriter, RuntimeTypeModel.SerializerPair[] methodPairs) { if (il == null) throw new ArgumentNullException("il"); if (methodPairs == null) throw new ArgumentNullException("methodPairs"); this.isStatic = isStatic; this.methodPairs = methodPairs; this.il = il; nonPublic = false; this.isWriter = isWriter; }
/// <summary> /// Creates a new PBF reader. /// </summary> public PBFReader(Stream stream) { _stream = stream; _runtimeTypeModel = RuntimeTypeModel.Create(); _runtimeTypeModel.Add(_blockHeaderType, true); _runtimeTypeModel.Add(_blobType, true); _runtimeTypeModel.Add(_primitiveBlockType, true); _runtimeTypeModel.Add(_headerBlockType, true); }
public static void Send(IDomainMapper domainMapper, Socket publisher, RuntimeTypeModel typeModel, MemoryStream stream, DomainBase instance) { var status = publisher.SendMore(domainMapper.Type2Bytes(instance.GetType())); if (status != SendStatus.Sent) throw new InvalidOperationException("Key not sent!"); stream.SetLength(0); typeModel.Serialize(stream, instance); status = publisher.Send(stream.ToArray()); if (status != SendStatus.Sent) throw new InvalidOperationException("Instance not sent!"); }
public void Work(RuntimeTypeModel model) { foreach (Type current in RuntimeReflectionUtilities.GetUnityObjectTypes()) { Type surrogate = typeof(UnityObjectSurrogate<>).MakeGenericType(new Type[] { current }); model.Add(current, false).SetSurrogate(surrogate); } }
private static bool ContainsType(RuntimeTypeModel model, Type type) { foreach (MetaType metaType in model.GetTypes()) { if (metaType.Type == type) { return true; } } return false; }
protected CoreTestBase() { _runtimeModel = ProtoBufNetFactory.GenerateTypeModel(); _runtimeModel.AutoCompile = false; _compileInPlaceModel = ProtoBufNetFactory.GenerateTypeModel(); _compileInPlaceModel.AutoCompile = false; _compileInPlaceModel.CompileInPlace(); //_compileModel = ProtoBufNetFactory.GenerateTypeModel().Compile("TestYo", @"TestYo.dll"); }
/// <summary> /// Creates a new ValueMember instance /// </summary> internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat) { if (memberType == null) throw new ArgumentNullException("memberType"); if (model == null) throw new ArgumentNullException("model"); this.fieldNumber = fieldNumber; this.memberType = memberType; this.itemType = itemType; this.defaultType = defaultType; this.model = model; this.dataFormat = dataFormat; }
public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members) { if (ctor == null) throw new ArgumentNullException("ctor"); if (members == null) throw new ArgumentNullException("members"); this.ctor = ctor; this.members = members; this.tails = new IProtoSerializer[members.Length]; ParameterInfo[] parameters = ctor.GetParameters(); for (int i = 0; i < members.Length; i++) { WireType wireType; Type finalType = parameters[i].ParameterType; Type itemType = null, defaultType = null; MetaType.ResolveListTypes(model, finalType, ref itemType, ref defaultType); Type tmp = itemType == null ? finalType : itemType; bool asReference = false; int typeIndex = model.FindOrAddAuto(tmp, false, true, false); if (typeIndex >= 0) { asReference = model[tmp].AsReferenceDefault; } IProtoSerializer tail = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, tmp, out wireType, asReference, false, false, true), serializer; if (tail == null) { throw new InvalidOperationException("No serializer defined for type: " + tmp.FullName); } tail = new TagDecorator(i + 1, wireType, false, tail); if (itemType == null) { serializer = tail; } else { if (finalType.IsArray) { serializer = new ArrayDecorator(model, tail, i + 1, false, wireType, finalType, false, false); } else { serializer = ListDecorator.Create(model, finalType, defaultType, tail, i + 1, false, wireType, true, false, false); } } tails[i] = serializer; } }
private void RoundtripTypeWithColor(RuntimeTypeModel model) { var orig = new TypeWithColor { Color = new Color { A = 1, R = 2, G = 3, B = 4 } }; var clone = (TypeWithColor)model.DeepClone(orig); Assert.AreEqual(1, clone.Color.A); Assert.AreEqual(2, clone.Color.R); Assert.AreEqual(3, clone.Color.G); Assert.AreEqual(4, clone.Color.B); }
public ServiceAssembly(Assembly assembly, RuntimeTypeModel typeModel, ServiceMessageByIdCollection messagesById, ServiceMessageByTypeCollection messagesByType) { Require.NotNull(assembly, "assembly"); Require.NotNull(typeModel, "typeModel"); Require.NotNull(messagesById, "messagesById"); Require.NotNull(messagesByType, "messagesByType"); Assembly = assembly; TypeModel = typeModel; MessagesById = messagesById; MessagesByType = messagesByType; }
/// <summary> /// Creates a new PBF stream target. /// </summary> public PBFOsmStreamTarget(Stream stream) { _stream = stream; _currentEntities = new List<Osm.OsmGeo>(); _reverseStringTable = new Dictionary<string, int>(); _buffer = new MemoryStream(); _runtimeTypeModel = RuntimeTypeModel.Create(); _runtimeTypeModel.Add(_blobHeaderType, true); _runtimeTypeModel.Add(_blobType, true); _runtimeTypeModel.Add(_primitiveBlockType, true); _runtimeTypeModel.Add(_headerBlockType, true); }
public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members) { if (ctor == null) { throw new ArgumentNullException("ctor"); } if (members == null) { throw new ArgumentNullException("members"); } this.ctor = ctor; this.members = members; this.tails = new IProtoSerializer[members.Length]; ParameterInfo[] parameters = ctor.GetParameters(); for (int i = 0; i < members.Length; i++) { Type parameterType = parameters[i].ParameterType; Type type = null; Type concreteType = null; MetaType.ResolveListTypes(model, parameterType, ref type, ref concreteType); Type type2 = (type != null) ? type : parameterType; bool asReference = false; int num = model.FindOrAddAuto(type2, false, true, false); if (num >= 0) { asReference = model[type2].AsReferenceDefault; } WireType wireType; IProtoSerializer protoSerializer = ValueMember.TryGetCoreSerializer(model, DataFormat.Default, type2, out wireType, asReference, false, false, true); if (protoSerializer == null) { throw new InvalidOperationException("No serializer defined for type: " + type2.FullName); } protoSerializer = new TagDecorator(i + 1, wireType, false, protoSerializer); IProtoSerializer protoSerializer2; if (type == null) { protoSerializer2 = protoSerializer; } else if (parameterType.IsArray) { protoSerializer2 = new ArrayDecorator(model, protoSerializer, i + 1, false, wireType, parameterType, false, false); } else { protoSerializer2 = ListDecorator.Create(model, parameterType, concreteType, protoSerializer, i + 1, false, wireType, true, false, false); } this.tails[i] = protoSerializer2; } }
public ProtobufSerializerFactory() { _runtimeTypeModel = TypeModel.Create(); _runtimeTypeModel.Add(typeof (SomeMessage), true) .Add(1, "Text"); _runtimeTypeModel.Add(typeof (RootObject), true) .Add(1, "BigObjects"); _runtimeTypeModel.Add(typeof (BigObject), true) .Add(1, "Integer") .Add(2, "String"); }
public static void Register(RuntimeTypeModel typeModel, Assembly assembly) { foreach (var type in GetTypesSafely(assembly)) { if (type.IsClass == false && type.IsValueType == false) continue; if (Attribute.GetCustomAttribute(type, typeof(ProtoBuf.ProtoContractAttribute)) == null) continue; var loweredTypeName = type.Name.ToLower(); if (loweredTypeName.Contains("surrogatedirectives")) { foreach (var field in type.GetFields()) { var sourceType = FindSurrogateSourceType(field.FieldType); if (sourceType != null) { if (typeModel.CanSerialize(sourceType)) continue; try { typeModel.Add(sourceType, false).SetSurrogate(field.FieldType); } catch (InvalidOperationException) { } } } } else if (type.Name.ToLower().Contains("surrogate")) { var sourceType = FindSurrogateSourceType(type); if (sourceType != null) { if (typeModel.CanSerialize(sourceType)) continue; try { typeModel.Add(sourceType, false).SetSurrogate(type); } catch (InvalidOperationException) { } } } } }
static RuntimeTypeModel GetProtobufModel() { if (_pbModel == null) { _pbModel = TypeModel.Create(); _pbModel.AllowParseableTypes=true; _pbModel.Add(typeof(Font), false).SetSurrogate(typeof(ProtoFont)); _pbModel.Add(typeof(Color), false).SetSurrogate(typeof(ProtoColor)); _pbModel.Add(typeof(StringFormat), false).SetSurrogate(typeof(ProtoStringFormat)); _pbModel.Add(typeof(Point<float>), true).Add("X", "Y"); _pbModel.Add(typeof(DrawStyle), true).AddSubType(100, typeof(DiagramDrawStyle)); _pbModel[typeof(BoundingBox<float>)].Add("X1", "X2", "Y1", "Y2"); _pbModel[typeof(BoundingBox<float>)].UseConstructor = false; Debug.WriteLine(_pbModel.GetSchema(typeof(DiagramDocumentCore))); } return _pbModel; }
private static void AddProperties(RuntimeTypeModel model, Type type) { var metaType = model.Add(type, true); foreach (var property in type.GetProperties().OrderBy(x => x.Name)) { metaType.Add(property.Name); var propertyType = property.PropertyType; if (!IsBuiltinType(propertyType) && !model.IsDefined(propertyType) && propertyType.GetProperties().Length > 0) { AddProperties(model, propertyType); } } }
public ProtobufSerializer(RuntimeTypeModel runtimeTypeModel) { if (runtimeTypeModel == null) throw new ArgumentNullException(nameof(runtimeTypeModel)); _runtimeTypeModel = runtimeTypeModel; var subscribeRequestType = _runtimeTypeModel.Add(typeof (SubscribeRequest), true); subscribeRequestType.AddField(1, Reflect.Path<SubscribeRequest>(r => r.Topic)); subscribeRequestType.AddField(2, Reflect.Path<SubscribeRequest>(r => r.SubscriberAddress)); var unsubscribeRequestType = _runtimeTypeModel.Add(typeof (UnsubscribeRequest), true); unsubscribeRequestType.AddField(1, Reflect.Path<UnsubscribeRequest>(r => r.Topic)); unsubscribeRequestType.AddField(2, Reflect.Path<UnsubscribeRequest>(r => r.SubscriberAddress)); var dataBusAttachmentType = _runtimeTypeModel.Add(typeof(DataBusAttachment), true); dataBusAttachmentType.AddField(1, Reflect.Path<DataBusAttachment>(r => r.Id)); }
public PerformanceTests() { _model = TypeModel.Create(); _model.Add(typeof(Event), true); _stream = new MemoryStream(); for (var i = 0; i < 1000 * 1000; i++) { var id = Guid.NewGuid(); var item = new OrderPlacedEvent(id, "Ordered by customer number" + i.ToString(CultureInfo.InvariantCulture), new[] { new OrderItem("Test product", i) }); var shipment = new OrderShippedEvent(id, DateTime.Now); _model.SerializeWithLengthPrefix(_stream, item, typeof(Event), Prefix, 0); _model.SerializeWithLengthPrefix(_stream, shipment, typeof(Event), Prefix, 0); } }
/// <summary> /// Creates a new ValueMember instance /// </summary> public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue) : this(model, fieldNumber,memberType, itemType, defaultType, dataFormat) { if (member == null) throw new ArgumentNullException("member"); if (parentType == null) throw new ArgumentNullException("parentType"); if (fieldNumber < 1 && !parentType.IsEnum) throw new ArgumentOutOfRangeException("fieldNumber"); this.member = member; this.parentType = parentType; if (fieldNumber < 1 && !parentType.IsEnum) throw new ArgumentOutOfRangeException("fieldNumber"); if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue)) { defaultValue = ParseDefaultValue(memberType, defaultValue); } this.defaultValue = defaultValue; MetaType type = model.FindWithoutAdd(memberType); if (type != null) this.asReference = type.AsReferenceDefault; }
/// <summary> /// Types which have a [ProtoContract] attribute. /// </summary> private static IEnumerable<Type> GetContracts(RuntimeTypeModel model) { return from assembly in fiRuntimeReflectionUtility.GetRuntimeAssemblies() where IsAssemblyAllowed(assembly) from contractType in assembly.GetTypes() where fsPortableReflection.GetAttribute<ProtoContractAttribute>(contractType) != null // Generic contract types are useless by themselves; they are only used when // requested by some other type that is being serialized, which in that case they // will be instantiated with generic type parameters where contractType.Resolve().IsGenericTypeDefinition == false // Ignore types that have already been added to the model. For example, we // ignore types with a surrogate where ContainsType(model, contractType) == false select contractType; }
internal MetaType(RuntimeTypeModel model, Type type) { if (model == null) throw new ArgumentNullException("model"); if (type == null) throw new ArgumentNullException("type"); WireType defaultWireType; IProtoSerializer coreSerializer = ValueMember.TryGetCoreSerializer(null, DataFormat.Default, type, out defaultWireType, false, false); if (coreSerializer != null) { throw new ArgumentException("Data of this type has inbuilt behaviour, and cannot be added to a model in this way: " + type.FullName); } this.type = type; this.model = model; if (type.IsEnum) { EnumPassthru = type.IsDefined(typeof(FlagsAttribute), false); } }
/// <summary> /// Creates a new ValueMember instance /// </summary> public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue) { if (fieldNumber < 1 && !parentType.IsEnum) throw new ArgumentOutOfRangeException("fieldNumber"); if (member == null) throw new ArgumentNullException("member"); if (parentType == null) throw new ArgumentNullException("parentType"); if (memberType == null) throw new ArgumentNullException("memberType"); if (model == null) throw new ArgumentNullException("model"); this.fieldNumber = fieldNumber; this.memberType = memberType; this.member = member; this.itemType = itemType; this.defaultType = defaultType; this.parentType = parentType; this.model = model; this.dataFormat = dataFormat; if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue)) { defaultValue = ParseDefaultValue(memberType, defaultValue); } this.defaultValue = defaultValue; }
public ProtobufMessageSerializer(params Assembly[] protocolAssemblies) { var types = protocolAssemblies.SelectMany(assembly => assembly.GetTypes()); _model = TypeModel.Create(); _model.AllowParseableTypes = true; _model[typeof(Message)].UseConstructor = false; foreach (var type in types.Where(t => typeof(Message).IsAssignableFrom(t) && t != typeof(Message))) { _model[typeof(Message)].AddSubType(GenerateId(type), type); _model[type].UseConstructor = false; } _model[typeof(MessageHeader)].UseConstructor = false; foreach (var type in types.Where(t => typeof(MessageHeader).IsAssignableFrom(t) && t != typeof(MessageHeader))) { _model[typeof(MessageHeader)].AddSubType(GenerateId(type), type); _model[type].UseConstructor = false; } _model.CompileInPlace(); }
internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, ProtoBuf.DataFormat dataFormat, Type type, out WireType defaultWireType, bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) { IProtoSerializer protoSerializer; Type underlyingType = Helpers.GetUnderlyingType(type); if (underlyingType != null) { type = underlyingType; } if (Helpers.IsEnum(type)) { if (!allowComplexTypes || model == null) { defaultWireType = WireType.None; return(null); } defaultWireType = WireType.Variant; return(new EnumSerializer(type, model.GetEnumMap(type))); } ProtoTypeCode typeCode = Helpers.GetTypeCode(type); switch (typeCode) { case ProtoTypeCode.Boolean: { defaultWireType = WireType.Variant; return(new BooleanSerializer(model)); } case ProtoTypeCode.Char: { defaultWireType = WireType.Variant; return(new CharSerializer(model)); } case ProtoTypeCode.SByte: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new SByteSerializer(model)); } case ProtoTypeCode.Byte: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new ByteSerializer(model)); } case ProtoTypeCode.Int16: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new Int16Serializer(model)); } case ProtoTypeCode.UInt16: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new UInt16Serializer(model)); } case ProtoTypeCode.Int32: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new Int32Serializer(model)); } case ProtoTypeCode.UInt32: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new UInt32Serializer(model)); } case ProtoTypeCode.Int64: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 64); return(new Int64Serializer(model)); } case ProtoTypeCode.UInt64: { defaultWireType = ValueMember.GetIntWireType(dataFormat, 64); return(new UInt64Serializer(model)); } case ProtoTypeCode.Single: { defaultWireType = WireType.Fixed32; return(new SingleSerializer(model)); } case ProtoTypeCode.Double: { defaultWireType = WireType.Fixed64; return(new DoubleSerializer(model)); } case ProtoTypeCode.Decimal: { defaultWireType = WireType.String; return(new DecimalSerializer(model)); } case ProtoTypeCode.DateTime: { defaultWireType = ValueMember.GetDateTimeWireType(dataFormat); return(new DateTimeSerializer(model)); } case ProtoTypeCode.Unknown | ProtoTypeCode.DateTime: { Label0: if (model.AllowParseableTypes) { protoSerializer = ParseableSerializer.TryCreate(type, model); } else { protoSerializer = null; } IProtoSerializer protoSerializer1 = protoSerializer; if (protoSerializer1 != null) { defaultWireType = WireType.String; return(protoSerializer1); } if (allowComplexTypes && model != null) { int key = model.GetKey(type, false, true); if (asReference || dynamicType) { defaultWireType = (dataFormat == ProtoBuf.DataFormat.Group ? WireType.StartGroup : WireType.String); BclHelpers.NetObjectOptions netObjectOption = BclHelpers.NetObjectOptions.None; if (asReference) { netObjectOption = (BclHelpers.NetObjectOptions)((byte)(netObjectOption | BclHelpers.NetObjectOptions.AsReference)); } if (dynamicType) { netObjectOption = (BclHelpers.NetObjectOptions)((byte)(netObjectOption | BclHelpers.NetObjectOptions.DynamicType)); } if (key >= 0) { if (asReference && Helpers.IsValueType(type)) { string str = "AsReference cannot be used with value-types"; str = (type.Name != "KeyValuePair`2" ? string.Concat(str, ": ", type.FullName) : string.Concat(str, "; please see http://stackoverflow.com/q/14436606/")); throw new InvalidOperationException(str); } MetaType item = model[type]; if (asReference && item.IsAutoTuple) { netObjectOption = (BclHelpers.NetObjectOptions)((byte)(netObjectOption | BclHelpers.NetObjectOptions.LateSet)); } if (item.UseConstructor) { netObjectOption = (BclHelpers.NetObjectOptions)((byte)(netObjectOption | BclHelpers.NetObjectOptions.UseConstructor)); } } return(new NetObjectSerializer(model, type, key, netObjectOption)); } if (key >= 0) { defaultWireType = (dataFormat == ProtoBuf.DataFormat.Group ? WireType.StartGroup : WireType.String); return(new SubItemSerializer(type, key, model[type], true)); } } defaultWireType = WireType.None; return(null); } case ProtoTypeCode.String: { defaultWireType = WireType.String; if (!asReference) { return(new StringSerializer(model)); } return(new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference)); } default: { switch (typeCode) { case ProtoTypeCode.TimeSpan: { defaultWireType = ValueMember.GetDateTimeWireType(dataFormat); return(new TimeSpanSerializer(model)); } case ProtoTypeCode.ByteArray: { defaultWireType = WireType.String; return(new BlobSerializer(model, overwriteList)); } case ProtoTypeCode.Guid: { defaultWireType = WireType.String; return(new GuidSerializer(model)); } case ProtoTypeCode.Uri: { defaultWireType = WireType.String; return(new StringSerializer(model)); } case ProtoTypeCode.Type: { defaultWireType = WireType.String; return(new SystemTypeSerializer(model)); } default: { goto Label0; } } break; } } }
/// <summary> /// Creates a new ValueMember instance /// </summary> public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue) : this(model, fieldNumber, memberType, itemType, defaultType, dataFormat) { if (member == null) { throw new ArgumentNullException("member"); } if (parentType == null) { throw new ArgumentNullException("parentType"); } if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) { throw new ArgumentOutOfRangeException("fieldNumber"); } this.member = member; this.parentType = parentType; if (fieldNumber < 1 && !Helpers.IsEnum(parentType)) { throw new ArgumentOutOfRangeException("fieldNumber"); } //#if WINRT if (defaultValue != null && model.MapType(defaultValue.GetType()) != memberType) //#else // if (defaultValue != null && !memberType.IsInstanceOfType(defaultValue)) //#endif { defaultValue = ParseDefaultValue(memberType, defaultValue); } this.defaultValue = defaultValue; MetaType type = model.FindWithoutAdd(memberType); if (type != null) { this.asReference = type.AsReferenceDefault; } else { // we need to scan the hard way; can't risk recursion by fully walking it this.asReference = MetaType.GetAsReferenceDefault(model, memberType); } }
internal static void Build <T>(RuntimeTypeModel runtimeTypeModel) { var type = typeof(T); Build(runtimeTypeModel, type); }
public override void Dispose() { model = null; ClearCustomSerializer(); ClearProtoPool(); }
public static string ExtractGenericTypeName(Type type, RuntimeTypeModel model) { string typeName = type.Name; StringBuilder sb = new StringBuilder(typeName); int split = typeName.IndexOf('`'); if (split >= 0) { sb.Length = split; } sb.Append('<'); var genericArguments = type #if WINRT || COREFX || PROFILE259 .GetTypeInfo().GenericTypeArguments #else .GetGenericArguments() #endif ; for (int i = 0; i < genericArguments.Length; i++) { var arg = genericArguments[i]; Type tmp = arg; int key = model.GetKey(ref tmp); MetaType mt; if (key >= 0 && (mt = model[tmp]) != null && !mt.HasSurrogate) // <=== need to exclude surrogate to avoid chance of infinite loop { sb.Append(mt.GetSchemaTypeName()); } else { if (tmp #if WINRT || COREFX || PROFILE259 .GetTypeInfo() #endif .IsGenericType) { // Nested generic type. string result = TTDUtils.ExtractGenericTypeName(tmp, model); sb.Append(result); } else { RuntimeTypeModel.CommonImports ci = RuntimeTypeModel.CommonImports.None; sb.Append(model.GetSchemaTypeName(tmp, DataFormat.Default, false, false, ref ci)); } } if (i != (genericArguments.Length - 1)) { sb.Append(','); } } sb.Append('>'); return(sb.ToString()); }
// Token: 0x0600040D RID: 1037 RVA: 0x00015408 File Offset: 0x00013608 internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) { Type underlyingType = Helpers.GetUnderlyingType(type); if (underlyingType != null) { type = underlyingType; } if (Helpers.IsEnum(type)) { if (allowComplexTypes && model != null) { defaultWireType = WireType.Variant; return(new EnumSerializer(type, model.GetEnumMap(type))); } defaultWireType = WireType.None; return(null); } else { ProtoTypeCode typeCode = Helpers.GetTypeCode(type); switch (typeCode) { case ProtoTypeCode.Boolean: defaultWireType = WireType.Variant; return(new BooleanSerializer(model)); case ProtoTypeCode.Char: defaultWireType = WireType.Variant; return(new CharSerializer(model)); case ProtoTypeCode.SByte: defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new SByteSerializer(model)); case ProtoTypeCode.Byte: defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new ByteSerializer(model)); case ProtoTypeCode.Int16: defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new Int16Serializer(model)); case ProtoTypeCode.UInt16: defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new UInt16Serializer(model)); case ProtoTypeCode.Int32: defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new Int32Serializer(model)); case ProtoTypeCode.UInt32: defaultWireType = ValueMember.GetIntWireType(dataFormat, 32); return(new UInt32Serializer(model)); case ProtoTypeCode.Int64: defaultWireType = ValueMember.GetIntWireType(dataFormat, 64); return(new Int64Serializer(model)); case ProtoTypeCode.UInt64: defaultWireType = ValueMember.GetIntWireType(dataFormat, 64); return(new UInt64Serializer(model)); case ProtoTypeCode.Single: defaultWireType = WireType.Fixed32; return(new SingleSerializer(model)); case ProtoTypeCode.Double: defaultWireType = WireType.Fixed64; return(new DoubleSerializer(model)); case ProtoTypeCode.Decimal: defaultWireType = WireType.String; return(new DecimalSerializer(model)); case ProtoTypeCode.DateTime: defaultWireType = ValueMember.GetDateTimeWireType(dataFormat); return(new DateTimeSerializer(model)); case (ProtoTypeCode)17: break; case ProtoTypeCode.String: defaultWireType = WireType.String; if (asReference) { return(new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference)); } return(new StringSerializer(model)); default: switch (typeCode) { case ProtoTypeCode.TimeSpan: defaultWireType = ValueMember.GetDateTimeWireType(dataFormat); return(new TimeSpanSerializer(model)); case ProtoTypeCode.ByteArray: defaultWireType = WireType.String; return(new BlobSerializer(model, overwriteList)); case ProtoTypeCode.Guid: defaultWireType = WireType.String; return(new GuidSerializer(model)); case ProtoTypeCode.Uri: defaultWireType = WireType.String; return(new StringSerializer(model)); case ProtoTypeCode.Type: defaultWireType = WireType.String; return(new SystemTypeSerializer(model)); } break; } IProtoSerializer protoSerializer = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null; if (protoSerializer != null) { defaultWireType = WireType.String; return(protoSerializer); } if (allowComplexTypes && model != null) { int key = model.GetKey(type, false, true); if (asReference || dynamicType) { defaultWireType = ((dataFormat == DataFormat.Group) ? WireType.StartGroup : WireType.String); BclHelpers.NetObjectOptions netObjectOptions = BclHelpers.NetObjectOptions.None; if (asReference) { netObjectOptions |= BclHelpers.NetObjectOptions.AsReference; } if (dynamicType) { netObjectOptions |= BclHelpers.NetObjectOptions.DynamicType; } if (key >= 0) { if (asReference && Helpers.IsValueType(type)) { string text = "AsReference cannot be used with value-types"; if (type.Name == "KeyValuePair`2") { text += "; please see http://stackoverflow.com/q/14436606/"; } else { text = text + ": " + type.FullName; } throw new InvalidOperationException(text); } MetaType metaType = model[type]; if (asReference && metaType.IsAutoTuple) { netObjectOptions |= BclHelpers.NetObjectOptions.LateSet; } if (metaType.UseConstructor) { netObjectOptions |= BclHelpers.NetObjectOptions.UseConstructor; } } return(new NetObjectSerializer(model, type, key, netObjectOptions)); } if (key >= 0) { defaultWireType = ((dataFormat == DataFormat.Group) ? WireType.StartGroup : WireType.String); return(new SubItemSerializer(type, key, model[type], true)); } } defaultWireType = WireType.None; return(null); } }
#pragma warning disable IDE0060 // unused params; the idea here is to make the API similar public static ProtoBuf.Meta.TypeModel Compile(this ProtoBuf.Meta.RuntimeTypeModel model, string name, string path) #pragma warning restore IDE0060 { // dummy to avoid lots of test hackery for dll compilation tests return(model.Compile()); }
/// <summary> /// 增加一个类型,使protobuf支持该类型的父类(仅带有ProtoContract的父类)中所有需要序列化的属性 /// </summary> /// <param name="type">需要被支持继承的类</param> public static void AddType(Type type) { if (type == null) { return; } if (!type.IsDefined(type_proto_contract, false)) { return; } if (added_types.ContainsKey(type)) { return; } added_types.Add(type, (byte)0); Type bt = type; RuntimeTypeModel model = RuntimeTypeModel.Default; MemberInfo[] ms = bt.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); for (int i = 0, imax = ms.Length; i < imax; i++) { MemberInfo mi = ms[i]; if (!Attribute.IsDefined(mi, typeof(ProtoMemberAttribute))) { continue; } Type mt = null; switch (mi.MemberType) { case MemberTypes.Field: mt = (mi as FieldInfo).FieldType; break; case MemberTypes.Property: mt = (mi as PropertyInfo).PropertyType; break; } if (mt == null) { continue; } if (mt.IsGenericType) { Type[] gt = mt.GetGenericArguments(); for (int j = 0, jmax = gt.Length; j < jmax; j++) { AddType(gt[j]); } } if (mt.IsArray) { AddType(mt.GetElementType()); } AddType(mt); } while (true) { bt = bt.BaseType; if (bt == null || bt == type_obj) { break; } if (!bt.IsDefined(type_proto_contract, false)) { continue; } ms = bt.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); for (int i = 0, imax = ms.Length; i < imax; i++) { MemberInfo mi = ms[i]; //if (mi.DeclaringType != bt) { continue; } ProtoMemberAttribute pm = Attribute.GetCustomAttribute(mi, typeof(ProtoMemberAttribute)) as ProtoMemberAttribute; if (pm == null) { continue; } try { model[type].Add(pm.Tag, mi.Name); } catch { } //UnityEngine.Debug.LogWarning(type + " " + pm.Tag + " " +mi.Name); } } }
internal CompilerContext(ILGenerator il, bool isStatic, bool isWriter, RuntimeTypeModel.SerializerPair[] methodPairs, TypeModel model, ILVersion metadataVersion, string assemblyName, Type inputType) { if (il == null) throw new ArgumentNullException("il"); if (methodPairs == null) throw new ArgumentNullException("methodPairs"); if (model == null) throw new ArgumentNullException("model"); if (Helpers.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException("assemblyName"); this.assemblyName = assemblyName; this.isStatic = isStatic; this.methodPairs = methodPairs; this.il = il; nonPublic = false; this.isWriter = isWriter; this.model = model; this.metadataVersion = metadataVersion; if (inputType != null) this.inputValue = new Local(null, inputType); }
internal ModelInfo(RuntimeTypeModel model, TypeMetaData metaData) { Model = model; MetaData = metaData; }
internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) { #if !NO_GENERICS { Type tmp = Helpers.GetUnderlyingType(type); if (tmp != null) { type = tmp; } } #endif if (Helpers.IsEnum(type)) { if (allowComplexTypes && model != null) { // need to do this before checking the typecode; an int enum will report Int32 etc defaultWireType = WireType.Variant; return(new EnumSerializer(type, model.GetEnumMap(type))); } else { // enum is fine for adding as a meta-type defaultWireType = WireType.None; return(null); } } ProtoTypeCode code = Helpers.GetTypeCode(type); switch (code) { case ProtoTypeCode.Int32: defaultWireType = GetIntWireType(dataFormat, 32); return(new Int32Serializer(model)); case ProtoTypeCode.UInt32: defaultWireType = GetIntWireType(dataFormat, 32); return(new UInt32Serializer(model)); case ProtoTypeCode.Int64: defaultWireType = GetIntWireType(dataFormat, 64); return(new Int64Serializer(model)); case ProtoTypeCode.UInt64: defaultWireType = GetIntWireType(dataFormat, 64); return(new UInt64Serializer(model)); case ProtoTypeCode.String: defaultWireType = WireType.String; if (asReference) { return(new NetObjectSerializer(model, model.MapType(typeof(string)), 0, BclHelpers.NetObjectOptions.AsReference)); } return(new StringSerializer(model)); case ProtoTypeCode.Single: defaultWireType = WireType.Fixed32; return(new SingleSerializer(model)); case ProtoTypeCode.Double: defaultWireType = WireType.Fixed64; return(new DoubleSerializer(model)); case ProtoTypeCode.Boolean: defaultWireType = WireType.Variant; return(new BooleanSerializer(model)); case ProtoTypeCode.DateTime: defaultWireType = GetDateTimeWireType(dataFormat); return(new DateTimeSerializer(dataFormat, model)); case ProtoTypeCode.Decimal: defaultWireType = WireType.String; return(new DecimalSerializer(model)); case ProtoTypeCode.Byte: defaultWireType = GetIntWireType(dataFormat, 32); return(new ByteSerializer(model)); case ProtoTypeCode.SByte: defaultWireType = GetIntWireType(dataFormat, 32); return(new SByteSerializer(model)); case ProtoTypeCode.Char: defaultWireType = WireType.Variant; return(new CharSerializer(model)); case ProtoTypeCode.Int16: defaultWireType = GetIntWireType(dataFormat, 32); return(new Int16Serializer(model)); case ProtoTypeCode.UInt16: defaultWireType = GetIntWireType(dataFormat, 32); return(new UInt16Serializer(model)); case ProtoTypeCode.TimeSpan: defaultWireType = GetDateTimeWireType(dataFormat); return(new TimeSpanSerializer(dataFormat, model)); case ProtoTypeCode.Guid: defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; return(new GuidSerializer(model)); case ProtoTypeCode.Uri: defaultWireType = WireType.String; return(new StringSerializer(model)); case ProtoTypeCode.ByteArray: defaultWireType = WireType.String; return(new BlobSerializer(model, overwriteList)); case ProtoTypeCode.Type: defaultWireType = WireType.String; return(new SystemTypeSerializer(model)); } IProtoSerializer parseable = model.AllowParseableTypes ? ParseableSerializer.TryCreate(type, model) : null; if (parseable != null) { defaultWireType = WireType.String; return(parseable); } if (allowComplexTypes && model != null) { int key = model.GetKey(type, false, true); MetaType meta = null; if (key >= 0) { meta = model[type]; if (dataFormat == DataFormat.Default && meta.IsGroup) { dataFormat = DataFormat.Group; } } if (asReference || dynamicType) { BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None; if (asReference) { options |= BclHelpers.NetObjectOptions.AsReference; } if (dynamicType) { options |= BclHelpers.NetObjectOptions.DynamicType; } if (meta != null) { // exists if (asReference && Helpers.IsValueType(type)) { string message = "AsReference cannot be used with value-types"; if (type.Name == "KeyValuePair`2") { message += "; please see http://stackoverflow.com/q/14436606/"; } else { message += ": " + type.FullName; } throw new InvalidOperationException(message); } if (asReference && meta.IsAutoTuple) { options |= BclHelpers.NetObjectOptions.LateSet; } if (meta.UseConstructor) { options |= BclHelpers.NetObjectOptions.UseConstructor; } } defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; return(new NetObjectSerializer(model, type, key, options)); } if (key >= 0) { defaultWireType = dataFormat == DataFormat.Group ? WireType.StartGroup : WireType.String; return(new SubItemSerializer(type, key, meta, true)); } } defaultWireType = WireType.None; return(null); }
public ProtoBufSerializer(RuntimeTypeModel rtModel) { _rtModel = rtModel; }
internal static IProtoSerializer TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, Type type, out WireType defaultWireType, bool asReference, bool dynamicType) { #if !NO_GENERICS type = Nullable.GetUnderlyingType(type) ?? type; #endif if (type.IsEnum) { if (model != null) { // need to do this before checking the typecode; an int enum will report Int32 etc defaultWireType = WireType.Variant; return(new EnumSerializer(type, model.GetEnumMap(type))); } else { // enum is fine for adding as a meta-type defaultWireType = WireType.None; return(null); } } ProtoTypeCode code = Helpers.GetTypeCode(type); switch (code) { case ProtoTypeCode.Int32: defaultWireType = GetIntWireType(dataFormat, 32); return(new Int32Serializer()); case ProtoTypeCode.UInt32: defaultWireType = GetIntWireType(dataFormat, 32); return(new UInt32Serializer()); case ProtoTypeCode.Int64: defaultWireType = GetIntWireType(dataFormat, 64); return(new Int64Serializer()); case ProtoTypeCode.UInt64: defaultWireType = GetIntWireType(dataFormat, 64); return(new UInt64Serializer()); case ProtoTypeCode.String: defaultWireType = WireType.String; if (asReference) { return(new NetObjectSerializer(typeof(string), 0, BclHelpers.NetObjectOptions.AsReference)); } return(new StringSerializer()); case ProtoTypeCode.Single: defaultWireType = WireType.Fixed32; return(new SingleSerializer()); case ProtoTypeCode.Double: defaultWireType = WireType.Fixed64; return(new DoubleSerializer()); case ProtoTypeCode.Boolean: defaultWireType = WireType.Variant; return(new BooleanSerializer()); case ProtoTypeCode.DateTime: defaultWireType = GetDateTimeWireType(dataFormat); return(new DateTimeSerializer()); case ProtoTypeCode.Decimal: defaultWireType = WireType.String; return(new DecimalSerializer()); case ProtoTypeCode.Byte: defaultWireType = GetIntWireType(dataFormat, 32); return(new ByteSerializer()); case ProtoTypeCode.SByte: defaultWireType = GetIntWireType(dataFormat, 32); return(new SByteSerializer()); case ProtoTypeCode.Char: defaultWireType = WireType.Variant; return(new CharSerializer()); case ProtoTypeCode.Int16: defaultWireType = GetIntWireType(dataFormat, 32); return(new Int16Serializer()); case ProtoTypeCode.UInt16: defaultWireType = GetIntWireType(dataFormat, 32); return(new UInt16Serializer()); case ProtoTypeCode.TimeSpan: defaultWireType = GetDateTimeWireType(dataFormat); return(new TimeSpanSerializer()); case ProtoTypeCode.Guid: defaultWireType = WireType.String; return(new GuidSerializer()); case ProtoTypeCode.Uri: defaultWireType = WireType.String; return(new StringSerializer()); // treat as string; wrapped in decorator later case ProtoTypeCode.ByteArray: defaultWireType = WireType.String; return(new BlobSerializer()); } IProtoSerializer parseable = ParseableSerializer.TryCreate(type); if (parseable != null) { defaultWireType = WireType.String; return(parseable); } if (model != null) { int key = model.GetKey(type, false, true); if (asReference || dynamicType) { defaultWireType = WireType.String; BclHelpers.NetObjectOptions options = BclHelpers.NetObjectOptions.None; if (asReference) { options |= BclHelpers.NetObjectOptions.AsReference; } if (dynamicType) { options |= BclHelpers.NetObjectOptions.DynamicType; } if (key >= 0) { // exists if (model[type].UseConstructor) { options |= BclHelpers.NetObjectOptions.UseConstructor; } } return(new NetObjectSerializer(type, key, options)); } if (key >= 0) { defaultWireType = WireType.String; return(new SubItemSerializer(type, key, model[type], true)); } } defaultWireType = WireType.None; return(null); }