CoreRow.cs 12 KB

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