public static object ConvertTo(this object from, Type type)
        {
            if (from == null)
            {
                return(null);
            }

            if (from.GetType() == type)
            {
                return(from);
            }

            if (from.GetType().IsValueType || type.IsValueType)
            {
                return(ChangeValueType(from, type));
            }

            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                var listResult = TranslateListWithElements.TryTranslateCollections(
                    from.GetType(), type, from);

                return(listResult);
            }

            var to = type.CreateInstance();

            return(to.PopulateWithNonDefaultValues(from));
        }
        public static T ConvertTo <T>(this object from)
        {
            if (from == null)
            {
                return(default(T));
            }

            var fromType = from.GetType();

            if (fromType == typeof(T))
            {
                return((T)from);
            }

            var toType = typeof(T);

            if (fromType.IsValueType || toType.IsValueType)
            {
                return((T)ChangeValueType(from, toType));
            }

            if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
            {
                var listResult = TranslateListWithElements.TryTranslateCollections(
                    fromType, typeof(T), from);

                return((T)listResult);
            }

            var to = typeof(T).CreateInstance <T>();

            return(to.PopulateWith(from));
        }
        public virtual object FromListAttributeValue(List <AttributeValue> attrs, Type toType)
        {
            var elType = toType.GetCollectionType();
            var from   = attrs.Map(x => FromAttributeValue(x, elType));
            var to     = TranslateListWithElements.TryTranslateCollections(
                from.GetType(), toType, from);

            return(to);
        }
        public IEnumerable MapValues(IEnumerable fromList, Type toInstanceOfType)
        {
            var to = (ICollection <T>) TranslateListWithElements <T> .CreateInstance(toInstanceOfType);

            foreach (var item in fromList)
            {
                to.Add(ValueMapper.MapValue <T>(item));
            }
            return(to);
        }
Example #5
0
        public void Can_convert_from_List_SubType()
        {
            var from = 3.Times(i => new SubCar {
                Age = i, Name = "Name" + i
            });
            var to = (List <Car>)TranslateListWithElements.TryTranslateCollections(
                typeof(List <SubCar>), typeof(List <Car>), from);

            Assert.That(to.Count, Is.EqualTo(3));
            Assert.That(to[0].Age, Is.EqualTo(0));
            Assert.That(to[0].Name, Is.EqualTo("Name0"));
        }
Example #6
0
    /// <summary>
    /// Translates to generic i collection.
    /// </summary>
    /// <param name="fromList">From list.</param>
    /// <param name="toInstanceOfType">Type of to instance of.</param>
    /// <returns>ICollection&lt;TTo&gt;.</returns>
    public static ICollection <TTo> TranslateToGenericICollection(
        ICollection <TFrom> fromList, Type toInstanceOfType)
    {
        if (fromList == null)
        {
            return(null);                  //AOT
        }
        var to = (ICollection <TTo>) TranslateListWithElements <TTo> .CreateInstance(toInstanceOfType);

        foreach (var item in fromList)
        {
            var toItem = ConvertFn(item);
            to.Add(toItem);
        }
        return(to);
    }
        public static T CreateCopy <T>(this T from)
        {
            if (typeof(T).IsValueType)
            {
                return((T)ChangeValueType(from, typeof(T)));
            }

            if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
            {
                var listResult = TranslateListWithElements.TryTranslateCollections(
                    from.GetType(), typeof(T), from);

                return((T)listResult);
            }

            var to = typeof(T).CreateInstance <T>();

            return(to.PopulateWith(from));
        }
Example #8
0
        public static object ConvertTo(this object from, Type type)
        {
            if (from == null)
            {
                return(null);
            }

            if (from.GetType() == type)
            {
                return(from);
            }

            if (from.GetType().IsValueType || type.IsValueType)
            {
                return(ChangeValueType(from, type));
            }

            if (from is string str)
            {
                return(TypeSerializer.DeserializeFromString(str, type));
            }
            if (from is ReadOnlyMemory <char> rom)
            {
                return(TypeSerializer.DeserializeFromSpan(type, rom.Span));
            }

            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                var listResult = TranslateListWithElements.TryTranslateCollections(
                    from.GetType(), type, from);

                return(listResult);
            }

            var to = type.CreateInstance();

            return(to.PopulateWithNonDefaultValues(from));
        }
Example #9
0
            internal static void RegisterElement <T, TElement, TSerializer>() where TSerializer : ITypeSerializer
            {
                DeserializeDictionary <TSerializer> .ParseDictionary <T, TElement>(null, null, null, null);

                DeserializeDictionary <TSerializer> .ParseDictionary <TElement, T>(null, null, null, null);

                ToStringDictionaryMethods <T, TElement, TSerializer> .WriteIDictionary(null, null, null, null);

                ToStringDictionaryMethods <TElement, T, TSerializer> .WriteIDictionary(null, null, null, null);

                // Include List deserialisations from the Register<> method above.  This solves issue where List<Guid> properties on responses deserialise to null.
                // No idea why this is happening because there is no visible exception raised.  Suspect IOS is swallowing an AOT exception somewhere.
                DeserializeArrayWithElements <TElement, TSerializer> .ParseGenericArray(null, null);

                DeserializeListWithElements <TElement, TSerializer> .ParseGenericList(null, null, null);

                // Cannot use the line below for some unknown reason - when trying to compile to run on device, mtouch bombs during native code compile.
                // Something about this line or its inner workings is offensive to mtouch. Luckily this was not needed for my List<Guide> issue.
                // DeserializeCollection<JsonTypeSerializer>.ParseCollection<TElement>(null, null, null);
                TranslateListWithElements <TElement> .LateBoundTranslateToGenericICollection(null, typeof(List <TElement>));

                TranslateListWithConvertibleElements <TElement, TElement> .LateBoundTranslateToGenericICollection(null, typeof(List <TElement>));
            }
        public static T ConvertTo <T>(this object from)
        {
            if (from.GetType() == typeof(T))
            {
                return((T)from);
            }

            if (from.GetType().IsValueType())
            {
                return((T)Convert.ChangeType(from, typeof(T), provider: null));
            }

            if (typeof(IEnumerable).IsAssignableFromType(typeof(T)))
            {
                var listResult = TranslateListWithElements.TryTranslateCollections(
                    from.GetType(), typeof(T), from);

                return((T)listResult);
            }

            var to = typeof(T).CreateInstance <T>();

            return(to.PopulateWith(from));
        }
Example #11
0
            internal static int Register <T, TSerializer>() where TSerializer : ITypeSerializer
            {
                var i = 0;

                if (JsonWriter <T> .WriteFn() != null)
                {
                    i++;
                }
                if (JsonWriter.Instance.GetWriteFn <T>() != null)
                {
                    i++;
                }
                if (JsonReader.Instance.GetParseFn <T>() != null)
                {
                    i++;
                }
                if (JsonReader <T> .Parse(null) != null)
                {
                    i++;
                }
                if (JsonReader <T> .GetParseFn() != null)
                {
                    i++;
                }
                //if (JsWriter.GetTypeSerializer<JsonTypeSerializer>().GetWriteFn<T>() != null) i++;
                if (new List <T>() != null)
                {
                    i++;
                }
                if (new T[0] != null)
                {
                    i++;
                }

                JsConfig <T> .ExcludeTypeInfo = false;

                if (JsConfig <T> .OnDeserializedFn != null)
                {
                    i++;
                }
                if (JsConfig <T> .HasDeserializeFn)
                {
                    i++;
                }
                if (JsConfig <T> .SerializeFn != null)
                {
                    i++;
                }
                if (JsConfig <T> .DeSerializeFn != null)
                {
                    i++;
                }
                //JsConfig<T>.SerializeFn = arg => "";
                //JsConfig<T>.DeSerializeFn = arg => default(T);
                if (TypeConfig <T> .Properties != null)
                {
                    i++;
                }

                WriteListsOfElements <T, TSerializer> .WriteList(null, null);

                WriteListsOfElements <T, TSerializer> .WriteIList(null, null);

                WriteListsOfElements <T, TSerializer> .WriteEnumerable(null, null);

                WriteListsOfElements <T, TSerializer> .WriteListValueType(null, null);

                WriteListsOfElements <T, TSerializer> .WriteIListValueType(null, null);

                WriteListsOfElements <T, TSerializer> .WriteGenericArrayValueType(null, null);

                WriteListsOfElements <T, TSerializer> .WriteArray(null, null);

                TranslateListWithElements <T> .LateBoundTranslateToGenericICollection(null, null);

                TranslateListWithConvertibleElements <T, T> .LateBoundTranslateToGenericICollection(null, null);

                QueryStringWriter <T> .WriteObject(null, null);

                return(i);
            }
        public static GetMemberDelegate CreateTypeConverter(Type fromType, Type toType)
        {
            if (fromType == toType)
            {
                return(null);
            }

            if (fromType == typeof(string))
            {
                return(fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType));
            }

            if (toType == typeof(string))
            {
                return(TypeSerializer.SerializeToString);
            }

            var underlyingToType   = Nullable.GetUnderlyingType(toType) ?? toType;
            var underlyingFromType = Nullable.GetUnderlyingType(fromType) ?? fromType;

            if (underlyingToType.IsEnum)
            {
                if (underlyingFromType.IsEnum || fromType == typeof(string))
                {
                    return(fromValue => Enum.Parse(underlyingToType, fromValue.ToString(), ignoreCase: true));
                }

                if (underlyingFromType.IsIntegerType())
                {
                    return(fromValue => Enum.ToObject(underlyingToType, fromValue));
                }
            }
            else if (underlyingFromType.IsEnum)
            {
                if (underlyingToType.IsIntegerType())
                {
                    return(fromValue => Convert.ChangeType(fromValue, underlyingToType, null));
                }
            }
            else if (typeof(IEnumerable).IsAssignableFrom(fromType))
            {
                return(fromValue =>
                {
                    var listResult = TranslateListWithElements.TryTranslateCollections(
                        fromType, underlyingToType, fromValue);

                    return listResult ?? fromValue;
                });
            }
            else if (underlyingToType.IsValueType)
            {
                return(fromValue => AutoMappingUtils.ChangeValueType(fromValue, underlyingToType));
            }
            else
            {
                return(fromValue =>
                {
                    if (fromValue == null)
                    {
                        return fromValue;
                    }

                    var toValue = toType.CreateInstance();
                    toValue.PopulateWith(fromValue);
                    return toValue;
                });
            }

            return(null);
        }
Example #13
0
        public static T ConvertTo <T>(this object from)
        {
            if (from == null)
            {
                return(default(T));
            }

            var fromType = from.GetType();

            if (fromType == typeof(T))
            {
                return((T)from);
            }

            if (fromType.IsValueType || typeof(T).IsValueType)
            {
                if (!fromType.IsEnum && !typeof(T).IsEnum)
                {
                    if (typeof(T) == typeof(char) && from is string s)
                    {
                        return((T)(s.Length > 0 ? (object)s[0] : null));
                    }
                    if (typeof(T) == typeof(string) && from is char c)
                    {
                        return((T)(object)c.ToString());
                    }

                    var destNumberType = DynamicNumber.GetNumber(typeof(T));
                    var value          = destNumberType?.ConvertFrom(from);
                    if (value != null)
                    {
                        if (typeof(T) == typeof(char))
                        {
                            return((T)(object)value.ToString()[0]);
                        }

                        return((T)value);
                    }

                    if (typeof(T) == typeof(string))
                    {
                        var srcNumberType = DynamicNumber.GetNumber(from.GetType());
                        if (srcNumberType != null)
                        {
                            return((T)(object)srcNumberType.ToString(from));
                        }
                    }
                }

                return((T)ChangeValueType(from, typeof(T)));
            }

            if (typeof(IEnumerable).IsAssignableFrom(typeof(T)))
            {
                var listResult = TranslateListWithElements.TryTranslateCollections(
                    fromType, typeof(T), from);

                return((T)listResult);
            }

            var to = typeof(T).CreateInstance <T>();

            return(to.PopulateWith(from));
        }
        public void Populate(object to, object from,
                             Func <PropertyInfo, bool> propertyInfoPredicate,
                             Func <object, bool> valuePredicate)
        {
            foreach (var assignmentEntry in AssignmentMemberMap)
            {
                var assignmentMember = assignmentEntry.Value;
                var fromMember       = assignmentEntry.Value.From;
                var toMember         = assignmentEntry.Value.To;

                if (fromMember.PropertyInfo != null && propertyInfoPredicate != null)
                {
                    if (!propertyInfoPredicate(fromMember.PropertyInfo))
                    {
                        continue;
                    }
                }

                try
                {
                    var fromValue = assignmentMember.GetValueFn(from);

                    if (valuePredicate != null)
                    {
                        if (!valuePredicate(fromValue))
                        {
                            continue;
                        }
                    }

                    if (fromMember.Type != toMember.Type)
                    {
                        if (fromMember.Type == typeof(string))
                        {
                            fromValue = TypeSerializer.DeserializeFromString((string)fromValue, toMember.Type);
                        }
                        else if (toMember.Type == typeof(string))
                        {
                            fromValue = TypeSerializer.SerializeToString(fromValue);
                        }
                        else if (toMember.Type.IsGeneric() &&
                                 toMember.Type.GenericTypeDefinition() == typeof(Nullable <>))
                        {
                            Type genericArg = toMember.Type.GenericTypeArguments()[0];
                            if (genericArg.IsEnum())
                            {
                                fromValue = Enum.ToObject(genericArg, fromValue);
                            }
                        }
                        else
                        {
                            var listResult = TranslateListWithElements.TryTranslateToGenericICollection(
                                fromMember.Type, toMember.Type, fromValue);

                            if (listResult != null)
                            {
                                fromValue = listResult;
                            }
                        }
                    }

                    var setterFn = assignmentMember.SetValueFn;
                    setterFn(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set properties {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromMember.Type.Name,
                                           ToType.FullName, toMember.Type.Name), ex);
                }
            }
        }
Example #15
0
        public static PropertyGetterDelegate CreateTypeConverter(Type fromType, Type toType)
        {
            if (fromType == toType)
            {
                return(null);
            }

            if (fromType == typeof(string))
            {
                return(fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType));
            }
            if (toType == typeof(string))
            {
                return(TypeSerializer.SerializeToString);
            }
            if (toType.IsEnum() || fromType.IsEnum())
            {
                if (toType.IsEnum() && fromType.IsEnum())
                {
                    return(fromValue => Enum.Parse(toType, fromValue.ToString(), ignoreCase: true));
                }
                if (toType.IsNullableType())
                {
                    var genericArg = toType.GenericTypeArguments()[0];
                    if (genericArg.IsEnum())
                    {
                        return(fromValue => Enum.ToObject(genericArg, fromValue));
                    }
                }
                else if (toType.IsIntegerType())
                {
                    if (fromType.IsNullableType())
                    {
                        var genericArg = fromType.GenericTypeArguments()[0];
                        if (genericArg.IsEnum())
                        {
                            return(fromValue => Enum.ToObject(genericArg, fromValue));
                        }
                    }
                    return(fromValue => Enum.ToObject(fromType, fromValue));
                }
            }
            else if (toType.IsNullableType())
            {
                var toTypeBaseType = toType.GenericTypeArguments()[0];
                if (toTypeBaseType.IsEnum())
                {
                    if (fromType.IsEnum() || (fromType.IsNullableType() && fromType.GenericTypeArguments()[0].IsEnum()))
                    {
                        return(fromValue => Enum.ToObject(toTypeBaseType, fromValue));
                    }
                }
                return(null);
            }
            else if (typeof(IEnumerable).IsAssignableFromType(fromType))
            {
                return(fromValue =>
                {
                    var listResult = TranslateListWithElements.TryTranslateCollections(
                        fromType, toType, fromValue);

                    return listResult ?? fromValue;
                });
            }
            else if (toType.IsValueType())
            {
                return(fromValue => Convert.ChangeType(fromValue, toType, provider: null));
            }
            else
            {
                return(fromValue =>
                {
                    if (fromValue == null)
                    {
                        return fromValue;
                    }

                    var toValue = toType.CreateInstance();
                    toValue.PopulateWith(fromValue);
                    return toValue;
                });
            }

            return(null);
        }
Example #16
0
        public void Populate(object to, object from,
                             Func <PropertyInfo, bool> propertyInfoPredicate,
                             Func <object, bool> valuePredicate)
        {
            foreach (var propertyEntry in PropertyInfoMap)
            {
                var fromPropertyInfo = propertyEntry.Key;
                var toPropertyInfo   = propertyEntry.Value;

                if (propertyInfoPredicate != null)
                {
                    if (!propertyInfoPredicate(fromPropertyInfo))
                    {
                        continue;
                    }
                }

                try
                {
                    var fromValue = fromPropertyInfo.GetValue(from, new object[] { });

                    if (valuePredicate != null)
                    {
                        if (!valuePredicate(fromValue))
                        {
                            continue;
                        }
                    }

                    if (fromPropertyInfo.PropertyType != toPropertyInfo.PropertyType)
                    {
                        if (fromPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.DeserializeFromString((string)fromValue,
                                                                             toPropertyInfo.PropertyType);
                        }
                        else if (toPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.SerializeToString(fromValue);
                        }
                        else
                        {
                            var listResult = TranslateListWithElements.TryTranslateToGenericICollection(
                                fromPropertyInfo.PropertyType, toPropertyInfo.PropertyType, fromValue);

                            if (listResult != null)
                            {
                                fromValue = listResult;
                            }
                        }
                    }

                    var toSetMetodInfo = toPropertyInfo.GetSetMethod();
                    toSetMetodInfo.Invoke(to, new[] { fromValue });
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set properties {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromPropertyInfo.Name,
                                           ToType.FullName, toPropertyInfo.Name), ex);
                }
            }

            foreach (var fieldEntry in FieldInfoMap)
            {
                var fromFieldInfo = fieldEntry.Key;
                var toFieldInfo   = fieldEntry.Value;

                try
                {
                    var fromValue = fromFieldInfo.GetValue(from);
                    toFieldInfo.SetValue(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set fields {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromFieldInfo.Name,
                                           ToType.FullName, toFieldInfo.Name), ex);
                }
            }
        }
        public void Populate(object to, object from,
                             Func <PropertyInfo, bool> propertyInfoPredicate,
                             Func <object, bool> valuePredicate)
        {
            foreach (var propertyEntry in PropertyInfoMap)
            {
                var fromPropertyInfo = propertyEntry.Key;
                var toPropertyInfo   = propertyEntry.Value;

                if (propertyInfoPredicate != null)
                {
                    if (!propertyInfoPredicate(fromPropertyInfo))
                    {
                        continue;
                    }
                }

                try
                {
                    var getterFn = PropertyGetters.GetOrAdd(fromPropertyInfo.Name,
                                                            fromPropertyInfo.GetPropertyGetterFn());
                    var fromValue = getterFn(from);

                    if (valuePredicate != null)
                    {
                        if (!valuePredicate(fromValue))
                        {
                            continue;
                        }
                    }

                    if (fromPropertyInfo.PropertyType != toPropertyInfo.PropertyType)
                    {
                        if (fromPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.DeserializeFromString((string)fromValue,
                                                                             toPropertyInfo.PropertyType);
                        }
                        else if (toPropertyInfo.PropertyType == typeof(string))
                        {
                            fromValue = TypeSerializer.SerializeToString(fromValue);
                        }
                        else if (toPropertyInfo.PropertyType.IsGenericType &&
                                 toPropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                        {
                            Type genericArg = toPropertyInfo.PropertyType.GetGenericArguments()[0];
                            if (genericArg.IsEnum)
                            {
                                fromValue = Enum.ToObject(genericArg, fromValue);
                            }
                        }
                        else
                        {
                            var listResult = TranslateListWithElements.TryTranslateToGenericICollection(
                                fromPropertyInfo.PropertyType, toPropertyInfo.PropertyType, fromValue);

                            if (listResult != null)
                            {
                                fromValue = listResult;
                            }
                        }
                    }

                    var setterFn = PropertySetters.GetOrAdd(toPropertyInfo.Name,
                                                            toPropertyInfo.GetPropertySetterFn());

                    setterFn(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set properties {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromPropertyInfo.Name,
                                           ToType.FullName, toPropertyInfo.Name), ex);
                }
            }

            foreach (var fieldEntry in FieldInfoMap)
            {
                var fromFieldInfo = fieldEntry.Key;
                var toFieldInfo   = fieldEntry.Value;

                try
                {
                    var fromValue = fromFieldInfo.GetValue(from);
                    toFieldInfo.SetValue(to, fromValue);
                }
                catch (Exception ex)
                {
                    Log.Warn(string.Format("Error trying to set fields {0}.{1} > {2}.{3}",
                                           FromType.FullName, fromFieldInfo.Name,
                                           ToType.FullName, toFieldInfo.Name), ex);
                }
            }
        }