public static Task SendResult <TIn, TOut>(this IPayloadV2Server src, DeviceIdentity devId, MethodInfo <TIn, TOut> method, TOut msg, SerializeDelegate <TOut> serialize, SerializeSizeDelegate <TOut> size, byte sequenceId = 0, CancellationToken cancel = default) { return(src.SendResult(devId, method, msg, serialize, size, sequenceId, cancel)); }
public DynamicObjectFormatter(CerasSerializer serializer) { _ceras = serializer; var type = typeof(T); BannedTypes.ThrowIfNonspecific(type); var meta = _ceras.GetTypeMetaData(type); var typeConfig = _ceras.Config.GetTypeConfig(type); typeConfig.VerifyConstructionMethod(); var schema = meta.PrimarySchema; if (schema.Members.Count > 0) { _dynamicSerializer = GenerateSerializer(schema); _dynamicDeserializer = GenerateDeserializer(schema); } else { _dynamicSerializer = (ref byte[] buffer, ref int offset, T value) => { }; _dynamicDeserializer = (byte[] buffer, ref int offset, ref T value) => { }; } }
public RestfulServiceRequest(IRequestAuthentication authentication, HttpWebRequest httpWebRequest, SerializeDelegate serializeBody, DeserializationDelegate deserializeBody) { _auth = authentication; _request = httpWebRequest; _serializeBody = serializeBody; _deserializeBody = deserializeBody; }
/// <summary> /// Registers an artifact type with his serialization methods. /// </summary> /// <param name="name">The artifact extension.</param> /// <param name="serialize">The serialization method.</param> /// <param name="deserialize">The deserialization method.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="name"/> /// or /// <paramref name="serialize"/> /// or /// <paramref name="deserialize"/> /// </exception> /// <exception cref="System.ArgumentException">The specified artifact name is already registered.</exception> public void RegisterArtifactType(string name, SerializeDelegate serialize, DeserializeDelegate deserialize) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (serialize == null) { throw new ArgumentNullException("serialize"); } if (deserialize == null) { throw new ArgumentNullException("deserialize"); } if (!name.StartsWith(".")) { name = "." + name; } if (artifactSerializers.ContainsKey(name)) { throw new ArgumentException(@"The specified artifact name is already registered.", "name"); } artifactSerializers.Add(name, new Serializer { Serialize = serialize, Deserialize = deserialize }); }
public DynamicFormatter(CerasSerializer serializer, bool isStatic) { _ceras = serializer; var type = typeof(T); BannedTypes.ThrowIfNonspecific(type); var schema = isStatic ? _ceras.GetStaticTypeMetaData(type).PrimarySchema : _ceras.GetTypeMetaData(type).PrimarySchema; var typeConfig = _ceras.Config.GetTypeConfig(type, isStatic); typeConfig.VerifyConstructionMethod(); if (!schema.IsPrimary) { throw new InvalidOperationException("Non-Primary Schema requires SchemaFormatter instead of DynamicFormatter!"); } if (schema.Members.Count == 0) { _serializer = (ref byte[] buffer, ref int offset, T value) => { }; _deserializer = (byte[] buffer, ref int offset, ref T value) => { }; return; } _serializer = GenerateSerializer(_ceras, schema, false, isStatic).Compile(); _deserializer = GenerateDeserializer(_ceras, schema, false, isStatic).Compile(); }
public BlobSerializerDelegate(SerializeDelegate serializeDelegate, DeserializeDelegate deserializeDelegate, CanSerializeDelegate canDeserializeDelegate) { _serializeDelegate = serializeDelegate; _deserializeDelegate = deserializeDelegate; _canDeserializeDelegate = canDeserializeDelegate; }
private void Clear() { _auth = null; _request = null; _serializeBody = null; _deserializeBody = null; _bodyBytes = null; }
public CallSite(MySynchronizedTypeInfo owner, uint id, MethodInfo info, CallSiteFlags flags, Action <T1, T2, T3, T4, T5, T6, T7> handler, SerializeDelegate <T1, T2, T3, T4, T5, T6, T7> serializer, Func <T1, T2, T3, T4, T5, T6, T7, bool> validator) : base(owner, id, info, flags) { Handler = handler; Serializer = serializer; Validator = validator; }
public BlobSerializerDelegate(SerializeDelegate serializeDelegate, DeserializeDelegate deserializeDelegate, CanSerializeDelegate canDeserializeDelegate) { this.serializeDelegate = serializeDelegate; this.deserializeDelegate = deserializeDelegate; this.canDeserializeDelegate = canDeserializeDelegate; }
public SchemaDynamicFormatter(CerasSerializer ceras, Schema schema) { _ceras = ceras; _schema = schema; _serializer = GenerateSerializer(schema); _deserializer = GenerateDeserializer(schema); }
public TypeSchema Initialize(KnownSerializers serializers, TypeSchema targetSchema) { var schema = TypeSchema.FromType(typeof(T), serializers.RuntimeVersion, this.GetType(), Version); this.serializeImpl = Generator.GenerateSerializeMethod <T>(il => Generator.EmitPrimitiveSerialize(typeof(T), il)); this.deserializeImpl = Generator.GenerateDeserializeMethod <T>(il => Generator.EmitPrimitiveDeserialize(typeof(T), il)); return(targetSchema ?? schema); }
public ScriptInfoSerializeHelper(FieldInfo info, ScriptInfoAttribute fieldInfo, SerializeAttribute serializer) { this.GetValue = info.GetValue; this.SetValue = info.SetValue; this.defaultValue = fieldInfo.DefaultValue; if (serializer != null) { //custom this.Deserialize = deserializeCustom(this, serializer.Deserialize); this.DeserializeExact = deserializeCustomExact(this, serializer.Deserialize); if (fieldInfo.IsOptional) { this.Serialize = serializeOptional(this, serializer.Serialize); } else { this.Serialize = serialize(this, serializer.Serialize); } this.format = fieldInfo.FieldName + ": {0}"; return; } //enum, nullable and others if (fieldInfo.IsOptional) { this.Serialize = serializeOptional(this); } else { this.Serialize = serialize(this); } var fieldType = info.FieldType; this.format = fieldInfo.FieldName + ": {0:" + fieldInfo.Format + "}"; Type nullableInner; if ((nullableInner = Nullable.GetUnderlyingType(fieldType)) != null) { //nullable if (this.defaultValue?.GetType() == nullableInner) { this.defaultValue = Activator.CreateInstance(fieldType, new[] { this.defaultValue }); } this.Deserialize = deserializeNullable(this, fieldType, nullableInner); this.DeserializeExact = deserializeNullableExact(this, fieldType, nullableInner); return; } if (fieldType.GetTypeInfo().IsEnum) { //enum this.Deserialize = deserializeEnum(this, fieldType); this.DeserializeExact = deserializeEnumExact(this, fieldType); return; } //default this.Deserialize = deserializeDefault(this, fieldType); this.DeserializeExact = deserializeDefaultExact(this, fieldType); }
public TypeSchema Initialize(KnownSerializers serializers, TypeSchema targetSchema) { var runtimeSchema = TypeSchema.FromType(typeof(T), serializers.RuntimeVersion, this.GetType(), Version); var members = runtimeSchema.GetCompatibleMemberSet(targetSchema); this.serializeImpl = Generator.GenerateSerializeMethod <T>(il => Generator.EmitSerializeFields(typeof(T), serializers, il, members)); this.deserializeImpl = Generator.GenerateDeserializeMethod <T>(il => Generator.EmitDeserializeFields(typeof(T), serializers, il, members)); return(targetSchema ?? runtimeSchema); }
private void InitSerializePropertiesDelegate(Type type) { Dictionary <string, MemberInfo> properties = HproseHelper.GetProperties(type); DynamicMethod dynamicMethod = new DynamicMethod("$SerializeProperties", typeofVoid, typeofArgs, type, true); ILGenerator gen = dynamicMethod.GetILGenerator(); LocalBuilder value = gen.DeclareLocal(typeofObject); LocalBuilder e = gen.DeclareLocal(typeofException); foreach (KeyValuePair <string, MemberInfo> property in properties) { PropertyInfo propertyInfo = (PropertyInfo)property.Value; Label exTryCatch = gen.BeginExceptionBlock(); if (type.IsValueType) { gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Unbox, type); } else { gen.Emit(OpCodes.Ldarg_0); } MethodInfo getMethod = propertyInfo.GetGetMethod(); if (getMethod.IsVirtual) { gen.Emit(OpCodes.Callvirt, getMethod); } else { gen.Emit(OpCodes.Call, getMethod); } if (propertyInfo.PropertyType.IsValueType) { gen.Emit(OpCodes.Box, propertyInfo.PropertyType); } gen.Emit(OpCodes.Stloc_S, value); gen.Emit(OpCodes.Leave_S, exTryCatch); gen.BeginCatchBlock(typeofException); gen.Emit(OpCodes.Stloc_S, e); gen.Emit(OpCodes.Ldstr, "The property value can\'t be serialized."); gen.Emit(OpCodes.Ldloc_S, e); gen.Emit(OpCodes.Newobj, hproseExceptionCtor); gen.Emit(OpCodes.Throw); gen.Emit(OpCodes.Leave_S, exTryCatch); gen.EndExceptionBlock(); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Ldloc_S, value); gen.Emit(OpCodes.Call, serializeMethod); } gen.Emit(OpCodes.Ret); serializePropertiesDelegate = (SerializeDelegate)dynamicMethod.CreateDelegate(typeofSerializeDelegate); }
void ActivateSchema(Schema schema) { // What schema changes are relevant to us? // - Schema of own type // - Schema of value-types inside us (dispatches for ref types are handled by RefFormatter anyway) // For now we only adapt to change to the current type schema. // Do we have serializers prepared for this schema already? // Important sanity check, if this happens the user should definitely know about it! if (_deserializationDepth > 0) { if (schema.Type.IsValueType) { throw new InvalidOperationException("Schema of a value-type has changed while an object-type is being deserialized. This is feature is WIP, check out GitHub for more information."); } } // Use already compiled serializers if (_generatedSerializerPairs.TryGetValue(schema, out var pair)) { _serializer = pair.Serializer; _deserializer = pair.Deserializer; _currentSchema = schema; return; } bool isStatic = schema.IsStatic; // Generate if (schema.IsPrimary) { _serializer = DynamicFormatter <T> .GenerateSerializer(_ceras, schema, true, isStatic).Compile(); _deserializer = DynamicFormatter <T> .GenerateDeserializer(_ceras, schema, true, isStatic).Compile(); } else { // Different Schema -> generate no serializer! // Writing data in some old format is not supported (yet, maybe in the future). // In theory we could do it. But it's not implemented because there would have to be some way for the user to specify what Schema to use. // And we get into all sorts of troubles with type-conversion (not implemented yet, but it will probably arrive earlier than this...) // This also protects us against bugs! _serializer = ErrorSerializer; _deserializer = DynamicFormatter <T> .GenerateDeserializer(_ceras, schema, true, isStatic).Compile(); } _currentSchema = schema; _generatedSerializerPairs.Add(schema, new SerializerPair(_serializer, _deserializer)); }
public CallbacksImpl(ICallbacks callbacks) { _callbacks = callbacks; _isTypeValidDelegate = IsTypeValid; GCHandle.Alloc(_isTypeValidDelegate); _releaseNetReferenceDelegate = ReleaseNetReference; GCHandle.Alloc(_releaseNetReferenceDelegate); _releaseNetDelegateGCHandleDelegate = ReleaseNetDelegateGCHandle; GCHandle.Alloc(_releaseNetDelegateGCHandleDelegate); _createLazyTypeInfoDelegate = CreateLazyTypeInfo; GCHandle.Alloc(_createLazyTypeInfoDelegate); _loadTypeInfoDelegate = LoadTypeInfo; GCHandle.Alloc(_loadTypeInfoDelegate); _instantiateTypeDelgate = InstantiateType; GCHandle.Alloc(_instantiateTypeDelgate); _callComponentCompletedDelegate = CallComponentCompleted; GCHandle.Alloc(_callComponentCompletedDelegate); _callObjectDestroyedDelegate = CallObjectDestroyed; GCHandle.Alloc(_callObjectDestroyedDelegate); _readPropertyDelegate = ReadProperty; GCHandle.Alloc(_readPropertyDelegate); _writePropertyDelegate = WriteProperty; GCHandle.Alloc(_writePropertyDelegate); _invokeMethodDelegate = InvokeMethod; GCHandle.Alloc(_invokeMethodDelegate); _gcCollectDelegate = GCCollect; GCHandle.Alloc(_gcCollectDelegate); _raiseNetSignalsDelegate = RaiseNetSignals; GCHandle.Alloc(_raiseNetSignalsDelegate); _awaitTaskDelegate = AwaitTask; GCHandle.Alloc(_awaitTaskDelegate); _serializeDelegate = Serialize; GCHandle.Alloc(_serializeDelegate); _invokeDelegateDelegate = InvokeDelegate; GCHandle.Alloc(_invokeDelegateDelegate); }
public static void Serialize(this SerializingContainer2 sc, ref byte[] arr, SerializeDelegate <byte> serialize = null) { int count = arr?.Length ?? 0; sc.Serialize(ref count); if (sc.IsLoading) { arr = sc.ms.ReadBytes(count); } else if (count > 0) { sc.ms.Writer.WriteBytes(arr); } }
public static void Serialize <T>(this SerializingContainer2 sc, ref T[] arr, SerializeDelegate <T> serialize) { int count = arr?.Length ?? 0; sc.Serialize(ref count); if (sc.IsLoading) { arr = new T[count]; } for (int i = 0; i < count; i++) { serialize(sc, ref arr[i]); } }
internal uint GetTypeIdAndSerializer(Type type, out SerializeDelegate <object> del) { var data = m_runtimeTypeMap[type]; if (data.WriterTrampolineDelegate != null) { del = data.WriterTrampolineDelegate; return(data.TypeID); } lock (m_modifyLock) { del = GenerateWriterTrampoline(type); return(data.TypeID); } }
private void InitSerializeFieldsDelegate(Type type) { Dictionary <string, MemberInfo> fields = HproseHelper.GetFields(type); DynamicMethod dynamicMethod = new DynamicMethod("$SerializeFields", typeofVoid, typeofArgs, type, true); ILGenerator gen = dynamicMethod.GetILGenerator(); LocalBuilder value = gen.DeclareLocal(typeofObject); LocalBuilder e = gen.DeclareLocal(typeofException); foreach (KeyValuePair <string, MemberInfo> field in fields) { FieldInfo fieldInfo = (FieldInfo)field.Value; Label exTryCatch = gen.BeginExceptionBlock(); if (type.IsValueType) { gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Unbox, type); } else { gen.Emit(OpCodes.Ldarg_0); } gen.Emit(OpCodes.Ldfld, fieldInfo); if (fieldInfo.FieldType.IsValueType) { gen.Emit(OpCodes.Box, fieldInfo.FieldType); } gen.Emit(OpCodes.Stloc_S, value); gen.Emit(OpCodes.Leave_S, exTryCatch); gen.BeginCatchBlock(typeofException); gen.Emit(OpCodes.Stloc_S, e); gen.Emit(OpCodes.Ldstr, "The field value can\'t be serialized."); gen.Emit(OpCodes.Ldloc_S, e); gen.Emit(OpCodes.Newobj, hproseExceptionCtor); gen.Emit(OpCodes.Throw); gen.Emit(OpCodes.Leave_S, exTryCatch); gen.EndExceptionBlock(); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Ldloc_S, value); gen.Emit(OpCodes.Call, serializeMethod); } gen.Emit(OpCodes.Ret); serializeFieldsDelegate = (SerializeDelegate)dynamicMethod.CreateDelegate(typeofSerializeDelegate); }
public StructPropertyConverter(Type owner, PropertyInfo property, IJsonConverter valueConverter) { var instance = Expression.Parameter(owner.MakeByRefType()); var converter = Expression.Constant(valueConverter, valueConverter.GetType()); Serialize = SerializationUtils.BuildSerialize <SerializeDelegate>(instance, property, converter); Write = SerializationUtils.BuildWrite <WriteDelegate>(instance, property, converter); if (property.CanWrite) { Deserialize = SerializationUtils.BuildDeserialize <DeserializeDelegate>(instance, property, converter); Read = SerializationUtils.BuildRead <ReadDelegate>(instance, property, converter); } else { Deserialize = ReadonlyProperty; Read = ReadonlyProperty; } }
protected Tuple <long, string> SerializeTime <T>(SerializeDelegate <T> serializer, T input) { var output = new List <string>(WarmCount + TestCount); for (var i = 0; i < WarmCount; i++) { var json = serializer(input); output.Add(json); } var start = PerformGc(); for (var i = 0; i < TestCount; i++) { var json = serializer(input); output.Add(json); } var end = Ticks(); return(new Tuple <long, string>(end - start, output[Random.Next(WarmCount + TestCount)])); }
public DynamicObjectFormatter(CerasSerializer serializer) { _ceras = serializer; var type = typeof(T); ThrowIfBanned(type); ThrowIfNonspecific(type); var schema = serializer.GetSerializationSchema(type, _ceras.Config.DefaultTargets, _ceras.Config.ShouldSerializeMember); if (schema.Members.Count > 0) { _dynamicSerializer = GenerateSerializer(schema.Members); _dynamicDeserializer = GenerateDeserializer(schema.Members); } else { _dynamicSerializer = (ref byte[] buffer, ref int offset, T value) => { }; _dynamicDeserializer = (byte[] buffer, ref int offset, ref T value) => { }; } }
public FieldSerializeHelper(FieldInfo info, EntryFieldAttribute fieldInfo, SerializeAttribute serializer) { this.defaultValue = fieldInfo.DefaultValue; this.GetValue = info.GetValue; this.SetValue = info.SetValue; if (serializer != null) { this.Serialize = serializeCustom(this, serializer.Serialize); this.Deserialize = deserializeCustom(this, serializer.Deserialize); this.DeserializeExact = deserializeCustomExact(this, serializer.Deserialize); return; } this.Serialize = serializeDefault(this, fieldInfo.Format); if (info.FieldType.GetTypeInfo().IsEnum) { this.Deserialize = deserializeEnum(this, info.FieldType); this.DeserializeExact = deserializeEnumExact(this, info.FieldType); } else { this.Deserialize = deserializeDefault(this, info.FieldType); this.DeserializeExact = deserializeDefaultExact(this, info.FieldType); } }
public void Setup() { var ceras = new CerasSerializer(); var parent1 = new Person { Age = -901, FirstName = "Parent 1", LastName = "abc", Sex = Sex.Male, }; var parent2 = new Person { Age = 7881964, FirstName = "Parent 2", LastName = "xyz", Sex = Sex.Female, }; _person = new Person { Age = 5, FirstName = "Riki", LastName = "Example Person Object", Sex = Sex.Unknown, Parent1 = parent1, Parent2 = parent2, }; var meta = ceras.GetTypeMetaData(typeof(Person)); var schema = meta.PrimarySchema; _serializer1 = DynamicFormatter <Person> .GenerateSerializer(ceras, schema, false, false).Compile(); //_serializer2 = DynamicFormatter<Person>.GenerateSerializer2(ceras, schema, false, false); }
private SerializeDelegate BuildSerializationDelegate_old(Type type) { var typeMetadata = _metadataProvider.GetMetadata(type); var result = new SerializeDelegate(o => { var stringBuilder = new StringBuilder(); foreach (var memberMetadata in typeMetadata.MembersMetadata) { var memberValue = memberMetadata.MemberInfo is FieldInfo ? (memberMetadata.MemberInfo as FieldInfo).GetValue(o) : (memberMetadata.MemberInfo as PropertyInfo).GetValue(o); if (memberValue == null) { continue; } if (stringBuilder.Length > 0) { stringBuilder.Append("&"); } stringBuilder .Append(memberMetadata.ValueName) .Append("=") .Append(memberValue); } return(stringBuilder.ToString()); }); return(result); }
public static void SerializeBulkData <T>(this SerializingContainer2 sc, ref T[] arr, SerializeDelegate <T> serialize) { int bulkdataflags = 0; sc.Serialize(ref bulkdataflags); int elementCount = arr?.Length ?? 0; sc.Serialize(ref elementCount); int sizeOnDisk = 0; long sizeOnDiskPosition = sc.ms.Position; sc.Serialize(ref sizeOnDisk); //when saving, come back and rewrite this after writing arr int offsetInFile = sc.FileOffset + 4; sc.Serialize(ref offsetInFile); if (sc.IsLoading) { arr = new T[elementCount]; } for (int i = 0; i < elementCount; i++) { serialize(sc, ref arr[i]); } if (sc.IsSaving) { long curPos = sc.ms.Position; sc.ms.JumpTo(sizeOnDiskPosition); sc.ms.WriteInt32((int)(curPos - (sizeOnDiskPosition + 8))); sc.ms.JumpTo(curPos); } }
public static void Serialize <TKey, TValue>(this SerializingContainer2 sc, ref OrderedMultiValueDictionary <TKey, TValue> dict, SerializeDelegate <TKey> serializeKey, SerializeDelegate <TValue> serializeValue) { int count = dict?.Count ?? 0; sc.Serialize(ref count); if (sc.IsLoading) { dict = new OrderedMultiValueDictionary <TKey, TValue>(count); for (int i = 0; i < count; i++) { TKey key = default; serializeKey(sc, ref key); TValue value = default; serializeValue(sc, ref value); dict.Add(key, value); } } else { for (int i = 0; i < count; i++) { var key = dict[i].Key; serializeKey(sc, ref key); var value = dict[i].Value; serializeValue(sc, ref value); } } }
public static void Serialize <T>(this SerializingContainer2 sc, ref List <T> arr, SerializeDelegate <T> serialize) { int count = arr?.Count ?? 0; sc.Serialize(ref count); if (sc.IsLoading) { arr = new List <T>(count); for (int i = 0; i < count; i++) { T tmp = default; serialize(sc, ref tmp); arr.Add(tmp); } } else { for (int i = 0; i < count; i++) { T tmp = arr[i]; serialize(sc, ref tmp); } } }
public SerializerPair(SerializeDelegate <T> serializer, DeserializeDelegate <T> deserializer) { Serializer = serializer; Deserializer = deserializer; }