/// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static List <T> MapToList <T>(this IDataReader reader, IJsonSerializer jsonSerializer = null, IXmlSerializer xmlSerializer = null, ICsvSerializer csvSerializer = null) where T : class
        {
            if (reader == null || reader.IsClosed)
            {
                return(new List <T>()
                {
                });
            }



            var accessor = TypeAccessor.Create(typeof(T), true);


            var pocoList = new List <T>();

            // Cache the field names in the reader for use in our while loop for efficiency.
            var readerFieldLookup = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase); // store name and ordinal

            for (var i = 0; i < reader.FieldCount; i++)
            {
                readerFieldLookup.Add(reader.GetName(i), i);
            }
            if (typeof(T) == typeof(string))
            {
                while (reader.Read())
                {
                    pocoList.Add(reader.GetString(0) as T);
                }
                reader.Close();
                reader.Dispose();
                return(pocoList);
            }

            while (reader.Read())
            {
                var clonedPoco = TypeExtension.New <T> .Instance();

                var advanceMembers = ExtFastMember.GetAdvanceMembers(clonedPoco);

                if (advanceMembers.IsNullOrEmpty() && typeof(IDynamicMetaObjectProvider).IsAssignableFrom(typeof(T)))
                {
                    readerFieldLookup.ForEach(delegate(KeyValuePair <string, int> pair)
                    {
                        advanceMembers.Add(new AdvanceMember()
                        {
                            Member = new DynamicMember()
                            {
                                Name = pair.Key
                            }
                        });
                    });
                }
                advanceMembers.Where(p => readerFieldLookup.ContainsKey(p.GetActualMemberName())).ToList().ForEach(delegate(AdvanceMember p)
                {
                    SetPocoProperteyValue(clonedPoco, reader, p, accessor, jsonSerializer, xmlSerializer, csvSerializer);
                });
                pocoList.Add(clonedPoco);
            }
            reader.Close();
            reader.Dispose();
            return(pocoList);
        }
Пример #2
0
        /// <summary>
        /// Builds the SQL parameter list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="poco">The poco.</param>
        /// <returns>List&lt;DbParameter&gt;.</returns>
        public static List <DbParameter> BuildDbParameterList <T>(this IDataSourceDb database, T poco) where T : class
        {
            DataSourceDb db = database is DataSourceDb sourceDb ? sourceDb : new DataSourceDb(database.DBTYPE);

            var list = new List <DbParameter>()
            {
            };

            ExtFastMember.GetAdvanceMembers(poco).ForEach(delegate(AdvanceMember p)
            {
                var validation = DataValidation.IsValidBasedOnSqlColumnAttributes(p);
                if (!validation.Item1)
                {
                    throw new InvalidDataException(string.Join(Environment.NewLine, validation.Item2));
                }

                object parameterValue = DBNull.Value;
                if (p.SqlCustomAttritube.SerializableType != SerializableType.NONE)
                {
                    if (p.Member.Type == typeof(string))
                    {
                        // assuming the string is already serialize and the developer don't know how this library works smh
                        parameterValue = db.ObjectSqlHelper.ConvertToDatabaseValue(p.Member, p.Value);
                    }
                    else
                    {
                        if (p.Value == null)
                        {
                            parameterValue = DBNull.Value;
                        }
                        else
                        {
                            switch (p.SqlCustomAttritube.SerializableType)
                            {
                            case SerializableType.XML:
                                database.XmlSerializer.IsNullThrow(nameof(database.XmlSerializer),
                                                                   new BadCodeException(
                                                                       $"YOU FOOL!!! Your claiming the property {p.Member.Name} in the type {p.Member.Type.FullName} value is in XML Format but your not specifying how to deserialize/serialize it )"));
                                parameterValue = database.XmlSerializer.SerializeToString(p.Value);
                                break;

                            case SerializableType.JSON:
                                database.JsonSerializer.IsNullThrow(nameof(JsonSerializer),
                                                                    new BadCodeException(
                                                                        $"YOU FOOL!!! Your claiming the property {p.Member.Name} in the type {p.Member.Type.FullName} value is in JSON Format but your not specifying how to deserialize/serialize it )"));
                                parameterValue = database.JsonSerializer.SerializeToString(p.Value);
                                break;

                            case SerializableType.CSV:
                                database.CsvSerializer.IsNullThrow(nameof(database.CsvSerializer),
                                                                   new BadCodeException(
                                                                       $"YOU FOOL!!! Your claiming the property {p.Member.Name} in the type {p.Member.Type.FullName} value is in CSV Format but your not specifying how to deserialize/serialize it )"));
                                parameterValue = database.CsvSerializer.SerializeToString(p.Value);
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }

                            //parameterValue = $"'{parameterValue.ToString().Replace("'", @"\'")}'";
                        }
                    }
                }
                else
                {
                    parameterValue = db.ObjectSqlHelper.ConvertToDatabaseValue(p.Member, p.Value);
                }
                // var command = GetNewCommand();

                list.Add(db.GetNewParameter($"@{p.Member.Name}", parameterValue));
            });
            return(list);
        }
Пример #3
0
        /// <summary>
        /// Maps Json to a list of T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="throwOnError"> if true return empty list on exception during parsing json</param>
        /// <returns></returns>
        public static List <T> JsonToList <T>(this string json, bool throwOnError, JsonSerializer serializer = null, bool validateData = false) where T : class
        {
            serializer = serializer ?? new JsonSerializer();
            if (throwOnError)
            {
                var token = JToken.Parse(json);
                if (token is JArray array)
                {
                    if (validateData)
                    {
                        var members = ExtFastMember.GetAdvanceMembers <T>().Where(b => (b.SqlCustomAttritube.PrimaryKey == true && b.SqlCustomAttritube.AutoIncrementBy != null) || b.SqlCustomAttritube.Nullable == false).ToList();
                        if (members.Count <= 0)
                        {
                            return(token.ToObject <List <T> >(serializer));
                        }
                        array.ForEach(delegate(JToken jToken)
                        {
                            members.ForEach(delegate(AdvanceMember m)
                            {
                                if (jToken[m.Member.Name] == null)
                                {
                                    if (m.SqlCustomAttritube.AutoIncrementBy == null && m.SqlCustomAttritube.StartIncrementAt == null && m.SqlCustomAttritube.TSQLDefaultValue == null) // IDENTITY SHOULDN'T MATTER IF THEY EXIST BECAUSE THE DATABASE CREATES THEM
                                    {
                                        throw new InvalidDataException($"The Field {m.Member.Name} Is Missing");
                                    }
                                }
                            });
                        });
                    }

                    return(token.ToObject <List <T> >(serializer));
                }
                else
                {
                    if (validateData)
                    {
                        var members = ExtFastMember.GetAdvanceMembers <T>().Where(b => (b.SqlCustomAttritube.PrimaryKey == true && b.SqlCustomAttritube.AutoIncrementBy != null) || b.SqlCustomAttritube.Nullable == false).ToList();
                        if (members.Count <= 0)
                        {
                            return(token.ToObject <List <T> >(serializer));
                        }


                        members.ForEach(delegate(AdvanceMember m)
                        {
                            if (token[m.Member.Name] == null)
                            {
                                if (m.SqlCustomAttritube.AutoIncrementBy == null && m.SqlCustomAttritube.StartIncrementAt == null && m.SqlCustomAttritube.TSQLDefaultValue == null) // IDENTITY SHOULDN'T MATTER IF THEY EXIST BECAUSE THE DATABASE CREATES THEM
                                {
                                    throw new InvalidDataException($"The Field {m.Member.Name} Is Missing");
                                }
                            }
                        });
                    }
                    return(new List <T>()
                    {
                        token.ToObject <T>(serializer)
                    });
                }
            }
            if (string.IsNullOrEmpty(json))
            {
                return new List <T>()
                       {
                       }
            }
            ;
            try
            {
                var token = JToken.Parse(json);

                return(token is JArray?token.ToObject <List <T> >(serializer) : new List <T>()
                {
                    token.ToObject <T>(serializer)
                });
            }
            catch (Exception)
            {
                return(new List <T>()
                {
                });
            }
        }