public T GetById(long id) { MySqlConnection conn = DBUtils.GetConnection(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = GetSelectSQL(); cmd.Parameters.AddWithValue("@id", id); MySqlDataReader reader = cmd.ExecuteReader(); if (!reader.Read()) { return(default(T)); } T obj = (T)TargetType.GetConstructor(new Type[0]).Invoke(new object[0]); //List<String> values = new List<>(); foreach (object[] arr in fields) { object value = reader[(string)arr[2]]; ((PropertyInfo)arr[0]).SetValue(obj, value); //values.add(value.toString()); } DBUtils.CloseConnection(conn); return(obj); }
public object Deserialize(JSValue deserializedJson, object resultContainer = null) { if (deserializedJson == null) { throw new ArgumentNullException(nameof(deserializedJson)); } if (deserializedJson._valueType < JSValueType.Object) { return(deserializedJson.Value); } #if NETSTANDARD1_3 var result = resultContainer ?? TargetType.GetTypeInfo().DeclaredConstructors.Where(x => x.IsPublic).First(x => x.GetParameters().Length == 0).Invoke(new object[0]); #else var result = resultContainer ?? TargetType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); #endif var tempSrcObject = deserializedJson._oValue as JSObject; foreach (var property in tempSrcObject._fields) { var prop = getProperty(property.Key); if (prop != null) { object value = property.Value; var deserializer = GetSerializer(value, Context.CurrentGlobalContext); if (deserializer != null) { value = deserializer.Deserialize(property.Value); } else { value = Convert.ChangeType(property.Value.Value, prop.PropertyType); } prop.SetValue(result, value, null); continue; } var field = getField(property.Key); if (field != null) { object value = property.Value; var deserializer = GetSerializer(value, Context.CurrentGlobalContext); if (deserializer != null) { value = deserializer.Deserialize(property.Value); } else { value = Convert.ChangeType(property.Value.Value, field.FieldType); } field.SetValue(result, Convert.ChangeType(property.Value, field.FieldType)); continue; } } return(result); }
/// <summary> /// Generates the proxy constructor. /// </summary> /// <remarks> /// <p> /// This implementation creates instance of the target object for delegation /// using constructor arguments. /// </p> /// </remarks> /// <param name="builder">The constructor builder to use.</param> /// <param name="il">The IL generator to use.</param> /// <param name="constructor">The constructor to delegate the creation to.</param> protected override void GenerateConstructor( ConstructorBuilder builder, ILGenerator il, ConstructorInfo constructor) { int paramCount = constructor.GetParameters().Length; il.Emit(OpCodes.Ldarg_0); for (int i = 1; i <= paramCount; i++) { il.Emit(OpCodes.Ldarg_S, i); } il.Emit(OpCodes.Newobj, TargetType.GetConstructor( ReflectionUtils.GetParameterTypes(constructor.GetParameters()))); il.Emit(OpCodes.Stfld, targetInstance); }
/// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture.</param> /// <param name="value">The <see cref="T:System.Object"/> to convert.</param> /// <returns> /// An <see cref="T:System.Object"/> that represents the converted value. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// The conversion cannot be performed. /// </exception> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string valueAsString = value as string; if (valueAsString != null && valueAsString.StartsWith("(", StringComparison.OrdinalIgnoreCase) && valueAsString.EndsWith(")", StringComparison.OrdinalIgnoreCase)) { if (valueAsString.Equals(_emptyString, StringComparison.OrdinalIgnoreCase)) { return(TargetType.GetConstructor(Type.EmptyTypes).Invoke(null)); } return(TargetType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).Single().Invoke(new object[] { valueAsString.Substring(1, valueAsString.Length - 2).Split(',').Select( s => TypeConversion.FromString(TargetType.GetGenericArguments()[0], s)) })); } return(base.ConvertFrom(context, culture, value)); }
protected internal override Delegate CreateDelegate() { if (ReflectionUtils.IsTargetTypeStruct(TargetType) && ReflectionUtils.IsEmptyTypeList(ParameterTypes)) { // No-arg struct needs special initialization Emit.DeclareLocal(TargetType); // TargetType tmp Emit.ldloca_s(0) // &tmp .initobj(TargetType) // init_obj(&tmp) .ldloc_0.end(); // load tmp } else if (TargetType.IsArray) { Emit.ldarg_0 // load args[] (method arguments) .ldc_i4_0 // load 0 .ldelem_ref // load args[0] (length) .unbox_any(typeof(int)) // unbox stack .newarr(TargetType.GetElementType()); // new T[args[0]] } else { ConstructorInfo ctorInfo = TargetType.GetConstructor(Flags, null, ParameterTypes, null); byte startUsableLocalIndex = 0; if (ReflectionUtils.HasRefParam(ParameterTypes)) { startUsableLocalIndex = CreateLocalsForByRefParams(0, ctorInfo); // create by_ref_locals from argument array Emit.DeclareLocal(TargetType); // TargetType tmp; } PushParamsOrLocalsToStack(0); // push arguments and by_ref_locals Emit.newobj(ctorInfo); // ctor (<stack>) if (ReflectionUtils.HasRefParam(ParameterTypes)) { Emit.stloc(startUsableLocalIndex); // tmp = <stack>; AssignByRefParamsToArray(0); // store by_ref_locals back to argument array Emit.ldloc(startUsableLocalIndex); // tmp } } Emit.boxIfValueType(TargetType) .ret(); // return (box)<stack>; return(Method.CreateDelegate(typeof(ConstructorInvoker))); }
public object Deserialize(JSValue deserializedJson, object resultContainer = null) { if (deserializedJson == null) { throw new ArgumentNullException(nameof(deserializedJson)); } if (deserializedJson._valueType < JSValueType.Object) { return(deserializedJson.Value); } var result = resultContainer ?? TargetType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); var tempSrcObject = deserializedJson._oValue as JSObject; foreach (var property in tempSrcObject._fields) { var prop = getProperty(property.Key); if (prop != null) { object value = property.Value; var deserializer = GetSerializer(value, Context.CurrentGlobalContext); value = deserializer != null?deserializer.Deserialize(property.Value) : Convert.ChangeType(property.Value.Value, prop.PropertyType); prop.SetValue(result, value, null); continue; } var field = getField(property.Key); if (field != null) { field.SetValue(result, Convert.ChangeType(property.Value, field.FieldType)); } } return(result); }
private Func <SerializationInfo, StreamingContext, object> InitCreateInstanceForISerialzableObject() { if (typeof(ISerializable).IsAssignableFrom(targetType)) { var createInstanceReturnType = typeof(object); var createInstanceParamsTypes = new[] { typeof(SerializationInfo), typeof(StreamingContext) }; var dm = new DynamicMethod("CreateInstanceForISerialzableObject" + Guid.NewGuid(), typeof(object), createInstanceParamsTypes, true); var createInstanceIL = dm.GetILGenerator(); var targetCreateInstanceMethod = TargetType.GetConstructor(createInstanceParamsTypes); if (targetCreateInstanceMethod == null) { targetCreateInstanceMethod = TargetType.GetConstructor( BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, createInstanceParamsTypes, null ); } if (targetCreateInstanceMethod == null) { createInstanceIL.ThrowException(typeof(MissingMethodException)); } createInstanceIL.Emit(OpCodes.Ldarg_0); //Load the first argument createInstanceIL.Emit(OpCodes.Ldarg_1); createInstanceIL.Emit(OpCodes.Newobj, targetCreateInstanceMethod); if (TargetType.IsValueType) { createInstanceIL.Emit(OpCodes.Box, TargetType); } createInstanceIL.Emit(OpCodes.Ret); return((Func <SerializationInfo, StreamingContext, object>)dm.CreateDelegate(typeof(Func <SerializationInfo, StreamingContext, object>))); } return(null); }
public List <T> GetAll() { MySqlConnection conn = DBUtils.GetConnection(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = GetSelectAllSQL(); MySqlDataReader reader = cmd.ExecuteReader(); List <T> result = new List <T>(); while (reader.Read()) { T obj = (T)TargetType.GetConstructor(new Type[0]).Invoke(new object[0]); //List<String> values = new List<>(); foreach (object[] arr in fields) { object value = reader[(string)arr[1]]; ((PropertyInfo)arr[0]).SetValue(obj, value); //values.add(value.toString()); } result.Add(obj); } DBUtils.CloseConnection(conn); return(result); }
protected override Expression CreateDeserializeExpression() { ParameterExpression recordList = Expression.Parameter(typeof(List <IReadOffsetRecord>), "recordList"); ParameterExpression recordDictionary = Expression.Parameter(typeof(Dictionary <int, IReadOffsetRecord>), "recordDictionary"); ParameterExpression parsedObject = Expression.Parameter(typeof(object), "parsedObject"); ParameterExpression hasIndex = Expression.Parameter(typeof(bool), "hasIndex"); ParameterExpression streamPosition = Expression.Parameter(typeof(long), "streamPosition"); ParameterExpression index = Expression.Parameter(typeof(int), "i"); LabelTarget labelTargetContinue = Expression.Label("_continue"); LabelTarget labelTargetBreak = Expression.Label("_break"); BlockExpression body = Expression.Block( TargetType, new ParameterExpression[] { ParseFieldParams.Result, recordList, recordDictionary, parsedObject, hasIndex, ParseFieldParams.OffsetRecord, streamPosition, index }, Expression.Assign( ParseFieldParams.Result, Expression.New(TargetType.GetConstructor(Type.EmptyTypes))), Expression.Assign( Expression.Property(DeserializeParams.Stream, _streamPositionProperty), DeserializeParams.Offset), Expression.Assign( streamPosition, Expression.Property(DeserializeParams.Stream, _streamPositionProperty)), Expression.Assign( recordList, Expression.Call(null, _readOffsetsMethod, DeserializeParams.Stream, streamPosition, DeserializeParams.Length)), Expression.Assign( index, Expression.Constant(0)), Expression.Loop( Expression.IfThenElse( Expression.LessThan( index, Expression.Property(recordList, _listCountProperty)), Expression.Block( Expression.Assign( ParseFieldParams.OffsetRecord, Expression.Call(recordList, _listItemGetter, new Expression[] { index })), ParseFieldExpression(), Expression.Assign( index, Expression.Increment(index)), Expression.Continue(labelTargetContinue) ), Expression.Break(labelTargetBreak)), labelTargetBreak, labelTargetContinue), Expression.Label(Expression.Label(typeof(object)), ParseFieldParams.Result), ParseFieldParams.Result ); return(body); }