using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using Kreta.Core.CustomAttributes; using Kreta.Core.Enum; using Kreta.Core.Exceptions; namespace Kreta.Core.Logic { /// /// Author: Kovács Kornél (DevKornél) Created On: 2019.07. /// public static class DaoLogic { public static object BoolStringToBool(this object value) { if (Equals(value, "T")) { return true; } if (Equals(value, "F")) { return false; } throw new BlException(Enum.BlExceptionType.None); } public static List ToDaoList(this DataSet dataSet) where TDao : class, new() { return dataSet.Tables[0].ToDaoList(); } public static List ToDaoList(this DataTable dataTable) where TDao : class, new() { var response = new List(); foreach (DataRow dataRow in dataTable.Rows) { response.Add(dataRow.ToDao()); } return response; } public static HashSet ToDaoHashSet(this DataSet dataSet) where TDao : class, new() { return dataSet.Tables[0].ToDaoHashSet(); } public static HashSet ToDaoHashSet(this DataTable dataTable) where TDao : class, new() { var response = new HashSet(); foreach (DataRow dataRow in dataTable.Rows) { if (!response.Add(dataRow.ToDao())) { throw new BlException(BlExceptionType.DuplikaltKulcs); } } return response; } public static TDao ToDao(this DataRow dataRow) where TDao : class, new() { PropertyInfo[] properties = typeof(TDao).GetProperties(); var dao = new TDao(); // Case sensitivity miatt van kiszedve külön (A Table.Columns.Contains() nem case-sensitive). IEnumerable dataTableColumns = dataRow.Table.Columns.Cast().Select(c => c.ColumnName); foreach (PropertyInfo property in properties) { if (property.GetCustomAttribute() == null) { string[] columnNames = property.GetCustomAttribute()?.ColumnName ?? new string[] { property.Name }; if (dataTableColumns.Intersect(columnNames).Any()) { foreach (string columnName in columnNames) { if (dataTableColumns.Contains(columnName)) { var propertyValue = ParsePropertyValue(dataRow[columnName], property.PropertyType); if (Nullable.GetUnderlyingType(property.PropertyType) == null && propertyValue == null && property.PropertyType != typeof(string)) { throw new BlException(BlExceptionType.ValtozoErtekeNemLehetNull); } var getterSetter = property.GetSetMethod(); getterSetter.Invoke(dao, new[] { propertyValue }); } } } else { throw new BlException(BlExceptionType.ElvartErtekNemTalalhato); } } } return dao; } private static object ParsePropertyValue(object dataRowValue, Type propertyType) { if (dataRowValue == DBNull.Value) { return null; } if (Nullable.GetUnderlyingType(propertyType) != null) { if (dataRowValue == null) { return null; } propertyType = propertyType.GenericTypeArguments[0]; } if (propertyType == typeof(bool)) { return Logic.DaoLogic.BoolStringToBool(dataRowValue); } return Convert.ChangeType(dataRowValue, propertyType); } } }