CoreRow.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. namespace InABox.Core
  6. {
  7. [Serializable]
  8. public class CoreRow : ICoreRow
  9. {
  10. #region Fields
  11. [NonSerialized]
  12. private static Dictionary<int, string> _accessedcolumns = new Dictionary<int, string>();
  13. [NonSerialized]
  14. private Dictionary<string, int> _columnindexes = new Dictionary<string, int>();
  15. #endregion
  16. #region Properties
  17. [DoNotSerialize]
  18. [field: NonSerialized]
  19. public CoreTable Table { get; private set; }
  20. public List<object?> Values { get; private set; }
  21. [DoNotSerialize]
  22. public int Index => Table.Rows.IndexOf(this);
  23. #endregion
  24. protected internal CoreRow(CoreTable owner)
  25. {
  26. Table = owner;
  27. Values = new List<object?>();
  28. }
  29. public static CoreRow[] None
  30. {
  31. get { return new CoreRow[] { }; }
  32. }
  33. //private DynamicObject rowObject;
  34. public Dictionary<string, object?> ToDictionary(string[]? exclude = null)
  35. {
  36. var result = new Dictionary<string, object?>();
  37. var columns = exclude == null
  38. ? Table.Columns
  39. : Table.Columns.Where(x => !exclude.Contains(x.ColumnName));
  40. foreach (var column in columns)
  41. result[column.ColumnName] = this[column.ColumnName];
  42. return result;
  43. }
  44. [DoNotSerialize]
  45. public object? this[string columnName]
  46. {
  47. get =>
  48. //return this.RowObject.GetValue<object>(columnName);
  49. Get<object>(columnName);
  50. set =>
  51. //this.RowObject.SetValue(columnName, value);
  52. Set(columnName, value);
  53. }
  54. /// <summary>
  55. /// Fill an object with the data from this row.
  56. /// </summary>
  57. /// <remarks>
  58. /// If <paramref name="overrideExisting"/> is <see langword="true"/>, then the data in the row will override the data in <paramref name="obj"/>,
  59. /// even if that column has previously been loaded (i.e., it is in <see cref="BaseObject.LoadedColumns"/>).
  60. /// </remarks>
  61. /// <param name="t">The type of <paramref name="obj"/>.</param>
  62. /// <param name="obj">The object to fill.</param>
  63. /// <param name="overrideExisting">Override any data which already exists in <paramref name="obj"/>.</param>
  64. public void FillObject(Type t, BaseObject obj, bool overrideExisting = false)
  65. {
  66. obj.SetObserving(false);
  67. if (!Table.Setters.TryGetValue("", out var setters))
  68. {
  69. setters = new List<Action<object, object>?>();
  70. Table.Setters[""] = setters;
  71. }
  72. var bFirst = !setters.Any();
  73. for (var i = 0; i < Table.Columns.Count; i++)
  74. {
  75. var column = Table.Columns[i].ColumnName;
  76. var value = i > -1 && i < Values.Count
  77. ? Values[i]
  78. : CoreUtils.GetDefault(Table.Columns[i].DataType);
  79. try
  80. {
  81. if (obj.LoadedColumns.Add(column) || overrideExisting)
  82. {
  83. if (bFirst)
  84. {
  85. var prop = DatabaseSchema.Property(t, column);
  86. setters.Add(prop?.Setter());
  87. }
  88. var setter = setters[i];
  89. if (setter != null && value != null)
  90. setter.Invoke(obj, value);
  91. else
  92. CoreUtils.SetPropertyValue(obj, column, value);
  93. }
  94. }
  95. catch (Exception e)
  96. {
  97. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  98. }
  99. }
  100. obj.CommitChanges();
  101. obj.SetObserving(true);
  102. }
  103. /// <summary>
  104. /// Fill an object with the data from this row.
  105. /// </summary>
  106. /// <remarks>
  107. /// If <paramref name="overrideExisting"/> is <see langword="true"/>, then the data in the row will override the data in <paramref name="obj"/>,
  108. /// even if that column has previously been loaded (i.e., it is in <see cref="BaseObject.LoadedColumns"/>).
  109. /// </remarks>
  110. /// <param name="obj">The object to fill.</param>
  111. /// <param name="overrideExisting">Override any data which already exists in <paramref name="obj"/>.</param>
  112. public void FillObject<T>(T obj, bool overrideExisting = false) where T : BaseObject
  113. {
  114. FillObject(typeof(T), obj, overrideExisting: overrideExisting);
  115. }
  116. public BaseObject ToObject(Type t)
  117. {
  118. var entity = (Activator.CreateInstance(t) as BaseObject)!;
  119. FillObject(t, entity, overrideExisting: true);
  120. return entity;
  121. }
  122. public T ToObject<T>() where T : BaseObject, new()
  123. {
  124. return (ToObject(typeof(T)) as T)!;
  125. }
  126. public T Get<T>(int col, bool usedefault = true)
  127. {
  128. if (col < 0 || col >= Values.Count)
  129. {
  130. if (usedefault)
  131. return CoreUtils.GetDefault<T>();
  132. throw new Exception(string.Format("Column [{0}] does not exist!", col));
  133. }
  134. return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();
  135. }
  136. public T Get<T>(string columnname, bool usedefault = true)
  137. {
  138. var col = GetColumn(columnname);
  139. if (col < 0 || col >= Values.Count)
  140. {
  141. if (usedefault)
  142. return CoreUtils.GetDefault<T>();
  143. throw new Exception(string.Format("Column [{0}] does not exist!", columnname));
  144. }
  145. return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();
  146. }
  147. public TType Get<TSource, TType>(Expression<Func<TSource, TType>> expression, bool usedefault = true)
  148. {
  149. var colname = GetColName(expression);
  150. //String colname = CoreUtils.GetFullPropertyName(expression, ".");
  151. return Get<TType>(colname, usedefault);
  152. }
  153. public void Set<TSource, TType>(Expression<Func<TSource, TType>> expression, TType value)
  154. {
  155. var colname = GetColName(expression);
  156. //String colname = CoreUtils.GetFullPropertyName(expression, ".");
  157. Set(colname, value);
  158. }
  159. public void Set<T>(int col, T value)
  160. {
  161. while (Values.Count <= col)
  162. Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
  163. Values[col] = value;
  164. }
  165. public void Set<T>(string columnname, T value)
  166. {
  167. var col = GetColumn(columnname);
  168. if (col < 0)
  169. throw new Exception("Column not found: " + columnname);
  170. while (Values.Count <= col)
  171. Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
  172. Values[col] = value;
  173. //this.RowObject.SetValue(columnname, value);
  174. }
  175. public void LoadValues(IEnumerable<object?> values)
  176. {
  177. Values = values.ToList();
  178. }
  179. public T ToObject<TSource, TLink, T>(Expression<Func<TSource, TLink>> property)
  180. where TLink : IEntityLink<T>
  181. where T : BaseObject, new()
  182. {
  183. var entity = new T();
  184. entity.SetObserving(false);
  185. var prefix = CoreUtils.GetFullPropertyName(property, ".");
  186. if (!Table.Setters.TryGetValue(prefix, out var setters))
  187. {
  188. setters = new List<Action<object, object>?>();
  189. Table.Setters[prefix] = setters;
  190. }
  191. var bFirst = !setters.Any();
  192. var cols = Table.Columns.Where(x => x.ColumnName.StartsWith(prefix + ".")).ToArray();
  193. for (var i = 0; i < cols.Length; i++)
  194. {
  195. var column = cols[i].ColumnName;
  196. var prop = column.Substring((prefix + ".").Length);
  197. var value = this[column];
  198. try
  199. {
  200. if (bFirst)
  201. {
  202. var p2 = DatabaseSchema.Property(typeof(T), prop);
  203. setters.Add(p2?.Setter());
  204. }
  205. var setter = setters[i];
  206. if (setter != null && value != null)
  207. setter.Invoke(entity, value);
  208. else
  209. CoreUtils.SetPropertyValue(entity, prop, value);
  210. }
  211. catch (Exception e)
  212. {
  213. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  214. }
  215. }
  216. entity.CommitChanges();
  217. entity.SetObserving(true);
  218. return entity;
  219. }
  220. private string GetColName<TSource, TType>(Expression<Func<TSource, TType>> expression)
  221. {
  222. //int hash = expression.GetHashCode();
  223. //if (_accessedcolumns.ContainsKey(hash))
  224. // return _accessedcolumns[hash];
  225. var colname = CoreUtils.GetFullPropertyName(expression, ".");
  226. //_accessedcolumns[hash] = colname;
  227. return colname;
  228. }
  229. private int GetColumn(string columnname)
  230. {
  231. if (_columnindexes.ContainsKey(columnname))
  232. return _columnindexes[columnname];
  233. for (var i = 0; i < Table.Columns.Count; i++)
  234. if (Table.Columns[i].ColumnName.Equals(columnname))
  235. {
  236. _columnindexes[columnname] = i;
  237. return i;
  238. }
  239. _columnindexes[columnname] = -1;
  240. return -1;
  241. }
  242. }
  243. public static class CoreRowExtensions
  244. {
  245. public static IEnumerable<T> ToObjects<T>(this IEnumerable<CoreRow> rows)
  246. where T : BaseObject, new()
  247. {
  248. return rows.Select(x => x.ToObject<T>());
  249. }
  250. }
  251. }