CoreTable.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. namespace InABox.Core
  8. {
  9. [Serializable]
  10. public class CoreTable : ICoreTable, ISerializeBinary //: IEnumerable, INotifyCollectionChanged
  11. {
  12. #region Fields
  13. private List<CoreRow>? rows;
  14. private List<CoreColumn> columns = new List<CoreColumn>();
  15. private string tableName;
  16. #endregion
  17. #region Properties
  18. public string TableName { get => tableName; }
  19. public IList<CoreColumn> Columns { get => columns; }
  20. public IList<CoreRow> Rows
  21. {
  22. get
  23. {
  24. rows ??= new List<CoreRow>();
  25. //this.rows.CollectionChanged += OnRowsCollectionChanged;
  26. return rows;
  27. }
  28. }
  29. [field: NonSerialized]
  30. public Dictionary<string, IList<Action<object, object>?>> Setters { get; } = new Dictionary<string, IList<Action<object, object>?>>();
  31. #endregion
  32. public CoreTable() : this("")
  33. {
  34. }
  35. public CoreTable(string tableName): base()
  36. {
  37. this.tableName = tableName;
  38. }
  39. public CoreTable(Type type) : this()
  40. {
  41. LoadColumns(type);
  42. }
  43. public void AddColumn<T>(Expression<Func<T, object>> column)
  44. {
  45. Columns.Add(
  46. new CoreColumn()
  47. {
  48. ColumnName = CoreUtils.GetFullPropertyName(column, "."),
  49. DataType = column.ReturnType
  50. }
  51. );
  52. }
  53. public CoreRow NewRow(bool populate = false)
  54. {
  55. var result = new CoreRow(this);
  56. if (populate)
  57. foreach (var column in Columns)
  58. result[column.ColumnName] = column.DataType.GetDefault();
  59. return result;
  60. }
  61. /*
  62. private void OnRowsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  63. {
  64. switch (e.Action)
  65. {
  66. case NotifyCollectionChangedAction.Add:
  67. this.InternalView.Insert(e.NewStartingIndex, ((DataRow)e.NewItems[0]).RowObject);
  68. break;
  69. case NotifyCollectionChangedAction.Remove:
  70. this.InternalView.RemoveAt(e.OldStartingIndex);
  71. break;
  72. case NotifyCollectionChangedAction.Replace:
  73. this.InternalView.Remove(((DataRow)e.OldItems[0]).RowObject);
  74. this.InternalView.Insert(e.NewStartingIndex, ((DataRow)e.NewItems[0]).RowObject);
  75. break;
  76. case NotifyCollectionChangedAction.Reset:
  77. default:
  78. this.InternalView.Clear();
  79. this.Rows.Select(r => r.RowObject).ToList().ForEach(o => this.InternalView.Add(o));
  80. break;
  81. }
  82. }
  83. private IList InternalView
  84. {
  85. get
  86. {
  87. if (this.internalView == null)
  88. {
  89. this.CreateInternalView();
  90. }
  91. return this.internalView;
  92. }
  93. }
  94. private void CreateInternalView()
  95. {
  96. this.internalView = (IList)Activator.CreateInstance(typeof(ObservableCollection<>).MakeGenericType(this.ElementType));
  97. ((INotifyCollectionChanged)internalView).CollectionChanged += (s, e) => { this.OnCollectionChanged(e); };
  98. }
  99. internal Type ElementType
  100. {
  101. get
  102. {
  103. if (this.elementType == null)
  104. {
  105. this.InitializeElementType();
  106. }
  107. return this.elementType;
  108. }
  109. }
  110. private void InitializeElementType()
  111. {
  112. this.Seal();
  113. this.elementType = DynamicObjectBuilder.GetDynamicObjectBuilderType(this.Columns);
  114. }
  115. private void Seal()
  116. {
  117. this.columns = new ReadOnlyCollection<DataColumn>(this.Columns);
  118. }
  119. public IEnumerator GetEnumerator()
  120. {
  121. return this.InternalView.GetEnumerator();
  122. }
  123. public IList ToList()
  124. {
  125. return this.InternalView;
  126. }
  127. protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  128. {
  129. var handler = this.CollectionChanged;
  130. if (handler != null)
  131. {
  132. handler(this, e);
  133. }
  134. }
  135. */
  136. public void LoadColumns(Type T)
  137. {
  138. var iprops = DatabaseSchema.Properties(T);
  139. foreach (var iprop in iprops)
  140. Columns.Add(new CoreColumn { ColumnName = iprop.Name, DataType = iprop.PropertyType });
  141. }
  142. public void LoadColumns(IColumns columns)
  143. {
  144. foreach (var col in columns.GetColumns())
  145. Columns.Add(new CoreColumn { ColumnName = col.Property, DataType = col.Type });
  146. }
  147. public void LoadColumns(IEnumerable<CoreColumn> columns)
  148. {
  149. Columns.Clear();
  150. foreach (var col in columns)
  151. Columns.Add(new CoreColumn() { ColumnName = col.ColumnName, DataType = col.DataType });
  152. }
  153. public void LoadRows(IEnumerable<object> objects)
  154. {
  155. foreach (var obj in objects)
  156. {
  157. var row = NewRow();
  158. LoadRow(row, obj);
  159. Rows.Add(row);
  160. }
  161. }
  162. public void LoadRows(CoreRow[] rows)
  163. {
  164. foreach (var row in rows)
  165. {
  166. var newrow = NewRow();
  167. LoadRow(newrow, row);
  168. Rows.Add(newrow);
  169. }
  170. }
  171. public void LoadFrom<T1, T2>(CoreTable table, CoreFieldMap<T1, T2> mappings, Action<CoreRow>? customization = null)
  172. {
  173. foreach (var row in table.Rows)
  174. {
  175. var newrow = NewRow();
  176. foreach (var map in mappings.Fields)
  177. newrow.Set(map.To, row.Get(map.From));
  178. customization?.Invoke(newrow);
  179. Rows.Add(newrow);
  180. }
  181. }
  182. public void LoadRow(CoreRow row, object obj)
  183. {
  184. foreach (var col in Columns)
  185. try
  186. {
  187. //var prop = DataModel.Property(obj.GetType(), col.ColumnName);
  188. //if (prop is CustomProperty)
  189. // prop is CustomProperty ? item.UserProperties[key] : CoreUtils.GetPropertyValue(item, key);
  190. var fieldvalue = CoreUtils.GetPropertyValue(obj, col.ColumnName);
  191. row[col.ColumnName] = fieldvalue;
  192. }
  193. catch (Exception e)
  194. {
  195. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  196. }
  197. }
  198. public void LoadRow(CoreRow row, CoreRow from)
  199. {
  200. foreach (var col in Columns)
  201. try
  202. {
  203. if (from.Table.Columns.Any(x => x.ColumnName.Equals(col.ColumnName)))
  204. row[col.ColumnName] = from[col.ColumnName];
  205. }
  206. catch (Exception e)
  207. {
  208. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  209. }
  210. }
  211. public void Filter(Func<CoreRow, bool> predicate)
  212. {
  213. for (var i = Rows.Count - 1; i > -1; i--)
  214. {
  215. var row = Rows[i];
  216. var predresult = predicate.Invoke(row);
  217. if (!predresult)
  218. Rows.Remove(row);
  219. }
  220. }
  221. #region ToDictionary
  222. public IDictionary ToDictionary(string keycol, string displaycol, string sortcol = "")
  223. {
  224. var kc = Columns.FirstOrDefault(x => x.ColumnName.Equals(keycol));
  225. var dc = Columns.FirstOrDefault(x => x.ColumnName.Equals(displaycol));
  226. var dt = typeof(Dictionary<,>).MakeGenericType(kc.DataType, dc.DataType);
  227. var id = (Activator.CreateInstance(dt) as IDictionary)!;
  228. var sorted = string.IsNullOrWhiteSpace(sortcol) ? Rows : Rows.OrderBy(x => x.Get<object>(sortcol)).ToList();
  229. foreach (var row in sorted)
  230. id[row[keycol]] = row[displaycol];
  231. return id;
  232. }
  233. public Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(Expression<Func<T, TKey>> key, Expression<Func<T, TValue>> value,
  234. Expression<Func<T, object>>? sort = null)
  235. {
  236. var result = new Dictionary<TKey, TValue>();
  237. var sorted = sort == null ? Rows : Rows.OrderBy(x => x.Get(sort)).ToList();
  238. foreach (var row in Rows)
  239. result[row.Get(key)] = row.Get(value);
  240. return result;
  241. }
  242. public Dictionary<TKey, string> ToDictionary<T, TKey>(Expression<Func<T, TKey>> key, Expression<Func<T, object>>[] values,
  243. Expression<Func<T, object>>? sort = null)
  244. {
  245. var result = new Dictionary<TKey, string>();
  246. var sorted = sort == null ? Rows : Rows.OrderBy(x => x.Get(sort)).ToList();
  247. foreach (var row in Rows)
  248. {
  249. var display = new List<object>();
  250. foreach (var value in values)
  251. display.Add(row.Get(value));
  252. result[row.Get(key)] = string.Join(" : ", display);
  253. }
  254. return result;
  255. }
  256. public Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(Expression<Func<T, TKey>> key, Func<CoreRow, TValue> value,
  257. Expression<Func<T, object>>? sort = null)
  258. {
  259. var result = new Dictionary<TKey, TValue>();
  260. var sorted = sort == null ? Rows : Rows.OrderBy(x => x.Get(sort)).ToList();
  261. foreach (var row in Rows)
  262. result[row.Get(key)] = value(row);
  263. return result;
  264. }
  265. public void LoadDictionary<T, TKey, TValue>(Dictionary<TKey, TValue> dictionary, Expression<Func<T, TKey>> key,
  266. Expression<Func<T, TValue>> value)
  267. {
  268. foreach (var row in Rows)
  269. dictionary[row.Get(key)] = row.Get(value);
  270. }
  271. public Dictionary<TKey, string> IntoDictionary<T, TKey>(Dictionary<TKey, string> result, Expression<Func<T, TKey>> key,
  272. params Expression<Func<T, object>>[] values)
  273. {
  274. foreach (var row in Rows)
  275. {
  276. var display = new List<object>();
  277. foreach (var value in values)
  278. display.Add(row.Get(value));
  279. result[row.Get(key)] = string.Join(" : ", display);
  280. }
  281. return result;
  282. }
  283. public Dictionary<TKey, TValue> IntoDictionary<T, TKey, TValue>(Dictionary<TKey, TValue> result, Expression<Func<T, TKey>> key,
  284. Func<CoreRow, TValue> value)
  285. {
  286. foreach (var row in Rows)
  287. result[row.Get(key)] = value(row);
  288. return result;
  289. }
  290. #endregion
  291. public DataTable ToDataTable(string name = "", IColumns? additionalColumns = null)
  292. {
  293. var result = new DataTable(name);
  294. foreach (var column in Columns)
  295. result.Columns.Add(column.ColumnName.Replace('.', '_'), column.DataType);
  296. if(additionalColumns != null)
  297. {
  298. foreach (var (column, type) in additionalColumns.AsDictionary())
  299. result.Columns.Add(column.Replace('.', '_'), type);
  300. }
  301. //result.Columns["ID"].Unique = true;
  302. //result.PrimaryKey = new DataColumn[] { result.Columns["ID"] };
  303. foreach (var row in Rows)
  304. {
  305. //result.Rows.Add(row.Values.ToArray());
  306. var newrow = result.NewRow();
  307. newrow.ItemArray = row.Values.ToArray();
  308. result.Rows.Add(newrow);
  309. }
  310. return result;
  311. }
  312. #region ToObjects
  313. public IEnumerable<BaseObject> ToObjects(Type T)
  314. => Rows.Select(x => x.ToObject(T));
  315. public IEnumerable<T> ToObjects<T>() where T : BaseObject, new()
  316. => Rows.Select(x => x.ToObject<T>());
  317. #endregion
  318. #region ToTuples
  319. public IEnumerable<Tuple<T1, T2>> ToTuples<TType, T1, T2>(
  320. Expression<Func<TType, T1>> item1,
  321. Expression<Func<TType, T2>> item2
  322. )
  323. {
  324. return Rows.Select(row =>
  325. new Tuple<T1, T2>
  326. (
  327. row.Get<TType,T1>(item1),
  328. row.Get<TType,T2>(item2)
  329. )
  330. );
  331. }
  332. public IEnumerable<Tuple<T1, T2, T3>> ToTuples<TType, T1, T2, T3>(
  333. Expression<Func<TType, T1>> item1,
  334. Expression<Func<TType, T2>> item2,
  335. Expression<Func<TType, T3>> item3)
  336. {
  337. return Rows.Select(row =>
  338. new Tuple<T1, T2, T3>
  339. (
  340. row.Get<TType,T1>(item1),
  341. row.Get<TType,T2>(item2),
  342. row.Get<TType,T3>(item3)
  343. )
  344. );
  345. }
  346. public IEnumerable<Tuple<T1, T2, T3, T4>> ToTuples<TType, T1, T2, T3, T4>(
  347. Expression<Func<TType, T1>> item1,
  348. Expression<Func<TType, T2>> item2,
  349. Expression<Func<TType, T3>> item3,
  350. Expression<Func<TType, T4>> item4
  351. )
  352. {
  353. return Rows.Select(row =>
  354. new Tuple<T1, T2, T3, T4>
  355. (
  356. row.Get<TType,T1>(item1),
  357. row.Get<TType,T2>(item2),
  358. row.Get<TType,T3>(item3),
  359. row.Get<TType,T4>(item4)
  360. )
  361. );
  362. }
  363. public IEnumerable<Tuple<T1, T2, T3, T4, T5>> ToTuples<TType, T1, T2, T3, T4, T5>(
  364. Expression<Func<TType, T1>> item1,
  365. Expression<Func<TType, T2>> item2,
  366. Expression<Func<TType, T3>> item3,
  367. Expression<Func<TType, T4>> item4,
  368. Expression<Func<TType, T5>> item5
  369. )
  370. {
  371. return Rows.Select(row =>
  372. new Tuple<T1, T2, T3, T4,T5>
  373. (
  374. row.Get<TType,T1>(item1),
  375. row.Get<TType,T2>(item2),
  376. row.Get<TType,T3>(item3),
  377. row.Get<TType,T4>(item4),
  378. row.Get<TType,T5>(item5)
  379. )
  380. );
  381. }
  382. #endregion
  383. public void CopyTo(DataTable table)
  384. {
  385. var columns = new List<string>();
  386. foreach (var column in Columns)
  387. columns.Add(column.ColumnName.Replace('.', '_'));
  388. foreach (var row in Rows)
  389. {
  390. var newrow = table.NewRow();
  391. for (var i = 0; i < columns.Count; i++)
  392. newrow[columns[i]] = row.Values[i];
  393. table.Rows.Add(newrow);
  394. }
  395. }
  396. public void CopyTo(CoreTable table)
  397. {
  398. var columns = new List<string>();
  399. //foreach (var column in Columns)
  400. // columns.Add(column.ColumnName.Replace('.', '_'));
  401. foreach (var row in Rows)
  402. {
  403. var newrow = table.NewRow();
  404. foreach (var column in Columns)
  405. if (table.Columns.Any(x => x.ColumnName.Equals(column.ColumnName)))
  406. newrow[column.ColumnName] = row[column.ColumnName];
  407. //for (int i = 0; i < columns.Count; i++)
  408. // newrow.Set(columns[i], row.Values[i]);
  409. table.Rows.Add(newrow);
  410. }
  411. }
  412. #region Extract Values
  413. public IEnumerable<TValue> ExtractValues<TSource, TValue>(Expression<Func<TSource, TValue>> column, bool distinct = true)
  414. {
  415. var result = Rows.Select(r => r.Get(column));
  416. if (distinct)
  417. result = result.Distinct();
  418. return result;
  419. }
  420. public IEnumerable<TValue> ExtractValues<TValue>(string column, bool distinct = true)
  421. {
  422. var result = Rows.Select(r => r.Get<TValue>(column));
  423. if (distinct)
  424. result = result.Distinct();
  425. return result;
  426. }
  427. #endregion
  428. public CoreTable LoadRow(object obj)
  429. {
  430. var row = NewRow();
  431. LoadRow(row, obj);
  432. Rows.Add(row);
  433. return this;
  434. }
  435. #region ToLookup
  436. public IMutableLookup<TKey, TValue> ToLookup<T, TKey, TValue>(Expression<Func<T, TKey>> key, Expression<Func<T, TValue>> value,
  437. Expression<Func<T, object>>? sort = null)
  438. {
  439. IMutableLookup<TKey, TValue> result = new MutableLookup<TKey, TValue>(
  440. Rows.ToLookup(
  441. r => r.Get(key),
  442. r => r.Get(value)
  443. )
  444. );
  445. return result;
  446. }
  447. public IMutableLookup<TKey, TValue> ToLookup<T, TKey, TValue>(Expression<Func<T, TKey>> key, Func<CoreRow, TValue> value,
  448. Expression<Func<T, object>>? sort = null)
  449. {
  450. IMutableLookup<TKey, TValue> result = new MutableLookup<TKey, TValue>(
  451. Rows.ToLookup(
  452. r => r.Get(key),
  453. r => value(r)
  454. )
  455. );
  456. return result;
  457. }
  458. #endregion
  459. #region Serialize Binary
  460. public void WriteBinary(CoreBinaryWriter writer, bool includeColumns)
  461. {
  462. writer.Write(TableName);
  463. if (includeColumns)
  464. {
  465. foreach (var column in Columns)
  466. {
  467. writer.Write(true);
  468. writer.Write(column.ColumnName);
  469. writer.Write(column.DataType.EntityName());
  470. }
  471. writer.Write(false);
  472. }
  473. writer.Write(Rows.Count);
  474. foreach (var row in Rows)
  475. {
  476. foreach (var col in Columns)
  477. {
  478. var val = row[col.ColumnName];
  479. writer.WriteBinaryValue(col.DataType, val);
  480. }
  481. }
  482. }
  483. public void SerializeBinary(CoreBinaryWriter writer) => WriteBinary(writer, true);
  484. public void ReadBinary(CoreBinaryReader reader, IList<CoreColumn>? columns)
  485. {
  486. tableName = reader.ReadString();
  487. Columns.Clear();
  488. if (columns is null)
  489. {
  490. while (reader.ReadBoolean())
  491. {
  492. var columnName = reader.ReadString();
  493. var dataType = CoreUtils.GetEntity(reader.ReadString());
  494. Columns.Add(new CoreColumn(dataType, columnName));
  495. }
  496. }
  497. else
  498. {
  499. foreach (var column in columns)
  500. {
  501. Columns.Add(column);
  502. }
  503. }
  504. Rows.Clear();
  505. var nRows = reader.ReadInt32();
  506. for (int i = 0; i < nRows; ++i)
  507. {
  508. var row = NewRow();
  509. foreach (var column in Columns)
  510. {
  511. var value = reader.ReadBinaryValue(column.DataType);
  512. row.Values.Add(value);
  513. }
  514. Rows.Add(row);
  515. }
  516. }
  517. public void DeserializeBinary(CoreBinaryReader reader) => ReadBinary(reader, null);
  518. #endregion
  519. }
  520. }