DataTable.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Reflection;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Linq;
  12. namespace InABox.Core
  13. {
  14. // Equivalent to DataColumn
  15. [Serializable]
  16. public class CoreColumn
  17. {
  18. public CoreColumn()
  19. {
  20. DataType = typeof(object);
  21. }
  22. public CoreColumn(string columnName) : this(typeof(object), columnName) { }
  23. public CoreColumn(Type dataType, string columnName)
  24. {
  25. DataType = dataType;
  26. ColumnName = columnName;
  27. }
  28. public Type DataType { get; set; }
  29. public string ColumnName { get; set; }
  30. public override string ToString()
  31. {
  32. return string.Format("{0} ({1})", ColumnName, DataType.EntityName().Split('.').Last());
  33. }
  34. }
  35. [Serializable]
  36. public class CoreRow : ICoreRow
  37. {
  38. #region Fields
  39. [NonSerialized]
  40. private static Dictionary<int, string> _accessedcolumns = new Dictionary<int, string>();
  41. [NonSerialized]
  42. private Dictionary<string, int> _columnindexes = new Dictionary<string, int>();
  43. #endregion
  44. #region Properties
  45. [DoNotSerialize]
  46. [field: NonSerialized]
  47. public CoreTable Table { get; private set; }
  48. public List<object?> Values { get; private set; }
  49. [DoNotSerialize]
  50. public int Index => Table.Rows.IndexOf(this);
  51. #endregion
  52. protected internal CoreRow(CoreTable owner)
  53. {
  54. Table = owner;
  55. Values = new List<object?>();
  56. }
  57. public static CoreRow[] None
  58. {
  59. get { return new CoreRow[] { }; }
  60. }
  61. //private DynamicObject rowObject;
  62. public Dictionary<string, object?> ToDictionary(string[] exclude)
  63. {
  64. var result = new Dictionary<string, object?>();
  65. foreach (var column in Table.Columns.Where(x => !exclude.Contains(x.ColumnName)))
  66. result[column.ColumnName] = this[column.ColumnName];
  67. return result;
  68. }
  69. [DoNotSerialize]
  70. public object? this[string columnName]
  71. {
  72. get =>
  73. //return this.RowObject.GetValue<object>(columnName);
  74. Get<object>(columnName);
  75. set =>
  76. //this.RowObject.SetValue(columnName, value);
  77. Set(columnName, value);
  78. }
  79. public BaseObject ToObject(Type t)
  80. {
  81. var entity = (Activator.CreateInstance(t) as BaseObject)!;
  82. entity.SetObserving(false);
  83. if (!Table.Setters.TryGetValue("", out var setters))
  84. {
  85. setters = new List<Action<object, object>?>();
  86. Table.Setters[""] = setters;
  87. }
  88. var bFirst = !setters.Any();
  89. for (var i = 0; i < Table.Columns.Count; i++)
  90. {
  91. var column = Table.Columns[i].ColumnName;
  92. var value = this[column];
  93. try
  94. {
  95. if (bFirst)
  96. {
  97. var prop = DatabaseSchema.Property(t, column);
  98. setters.Add(prop?.Setter());
  99. }
  100. var setter = setters[i];
  101. if (setter != null && value != null)
  102. setter.Invoke(entity, value);
  103. else
  104. CoreUtils.SetPropertyValue(entity, column, value);
  105. }
  106. catch (Exception e)
  107. {
  108. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  109. }
  110. }
  111. entity.CommitChanges();
  112. entity.SetObserving(true);
  113. return entity;
  114. }
  115. public T ToObject<T>() where T : BaseObject, new()
  116. {
  117. return (ToObject(typeof(T)) as T)!;
  118. }
  119. public T Get<T>(int col, bool usedefault = true)
  120. {
  121. if (col < 0 || col >= Values.Count)
  122. {
  123. if (usedefault)
  124. return CoreUtils.GetDefault<T>();
  125. throw new Exception(string.Format("Column [{0}] does not exist!", col));
  126. }
  127. return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();
  128. }
  129. public T Get<T>(string columnname, bool usedefault = true)
  130. {
  131. var col = GetColumn(columnname);
  132. if (col < 0 || col >= Values.Count)
  133. {
  134. if (usedefault)
  135. return CoreUtils.GetDefault<T>();
  136. throw new Exception(string.Format("Column [{0}] does not exist!", columnname));
  137. }
  138. return Values[col] != null ? (T)CoreUtils.ChangeType(Values[col], typeof(T)) : CoreUtils.GetDefault<T>();
  139. }
  140. public TType Get<TSource, TType>(Expression<Func<TSource, TType>> expression, bool usedefault = true)
  141. {
  142. var colname = GetColName(expression);
  143. //String colname = CoreUtils.GetFullPropertyName(expression, ".");
  144. return Get<TType>(colname, usedefault);
  145. }
  146. public void Set<TSource, TType>(Expression<Func<TSource, TType>> expression, TType value)
  147. {
  148. var colname = GetColName(expression);
  149. //String colname = CoreUtils.GetFullPropertyName(expression, ".");
  150. Set(colname, value);
  151. }
  152. public void Set<T>(int col, T value)
  153. {
  154. while (Values.Count <= col)
  155. Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
  156. Values[col] = value;
  157. }
  158. public void Set<T>(string columnname, T value)
  159. {
  160. var col = GetColumn(columnname);
  161. if (col < 0)
  162. throw new Exception("Column not found: " + columnname);
  163. while (Values.Count <= col)
  164. Values.Add(Table.Columns[Values.Count].DataType.GetDefault());
  165. Values[col] = value;
  166. //this.RowObject.SetValue(columnname, value);
  167. }
  168. public void LoadValues(IEnumerable<object?> values)
  169. {
  170. Values = values.ToList();
  171. }
  172. public T ToObject<TSource, TLink, T>(Expression<Func<TSource, TLink>> property)
  173. where TLink : IEntityLink<T>
  174. where T : BaseObject, new()
  175. {
  176. var entity = new T();
  177. entity.SetObserving(false);
  178. var prefix = CoreUtils.GetFullPropertyName(property, ".");
  179. if (!Table.Setters.TryGetValue(prefix, out var setters))
  180. {
  181. setters = new List<Action<object, object>?>();
  182. Table.Setters[prefix] = setters;
  183. }
  184. var bFirst = !setters.Any();
  185. var cols = Table.Columns.Where(x => x.ColumnName.StartsWith(prefix + ".")).ToArray();
  186. for (var i = 0; i < cols.Length; i++)
  187. {
  188. var column = cols[i].ColumnName;
  189. var prop = column.Substring((prefix + ".").Length);
  190. var value = this[column];
  191. try
  192. {
  193. if (bFirst)
  194. {
  195. var p2 = DatabaseSchema.Property(typeof(T), prop);
  196. setters.Add(p2?.Setter());
  197. }
  198. var setter = setters[i];
  199. if (setter != null && value != null)
  200. setter.Invoke(entity, value);
  201. else
  202. CoreUtils.SetPropertyValue(entity, prop, value);
  203. }
  204. catch (Exception e)
  205. {
  206. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  207. }
  208. }
  209. entity.CommitChanges();
  210. entity.SetObserving(true);
  211. return entity;
  212. }
  213. private string GetColName<TSource, TType>(Expression<Func<TSource, TType>> expression)
  214. {
  215. //int hash = expression.GetHashCode();
  216. //if (_accessedcolumns.ContainsKey(hash))
  217. // return _accessedcolumns[hash];
  218. var colname = CoreUtils.GetFullPropertyName(expression, ".");
  219. //_accessedcolumns[hash] = colname;
  220. return colname;
  221. }
  222. private int GetColumn(string columnname)
  223. {
  224. if (_columnindexes.ContainsKey(columnname))
  225. return _columnindexes[columnname];
  226. for (var i = 0; i < Table.Columns.Count; i++)
  227. if (Table.Columns[i].ColumnName.Equals(columnname))
  228. {
  229. _columnindexes[columnname] = i;
  230. return i;
  231. }
  232. _columnindexes[columnname] = -1;
  233. return -1;
  234. }
  235. }
  236. public class CoreFieldMap<T1, T2>
  237. {
  238. private List<CoreFieldMapPair<T1, T2>> _fields = new List<CoreFieldMapPair<T1, T2>>();
  239. public CoreFieldMapPair<T1, T2>[] Fields => _fields.ToArray();
  240. public CoreFieldMap<T1, T2> Add(Expression<Func<T1, object>> from, Expression<Func<T2, object>> to)
  241. {
  242. _fields.Add(new CoreFieldMapPair<T1, T2>(from, to));
  243. return this;
  244. }
  245. }
  246. public class CoreFieldMapPair<T1, T2>
  247. {
  248. public Expression<Func<T1, object>> From { get; private set; }
  249. public Expression<Func<T2, object>> To { get; private set; }
  250. public CoreFieldMapPair(Expression<Func<T1, object>> from, Expression<Func<T2, object>> to)
  251. {
  252. From = from;
  253. To = to;
  254. }
  255. }
  256. [Serializable]
  257. public class CoreTable : ICoreTable, ISerializeBinary //: IEnumerable, INotifyCollectionChanged
  258. {
  259. #region Fields
  260. private List<CoreRow>? rows;
  261. private List<CoreColumn> columns = new List<CoreColumn>();
  262. private string tableName;
  263. #endregion
  264. #region Properties
  265. public string TableName { get => tableName; }
  266. public IList<CoreColumn> Columns { get => columns; }
  267. public IList<CoreRow> Rows
  268. {
  269. get
  270. {
  271. rows ??= new List<CoreRow>();
  272. //this.rows.CollectionChanged += OnRowsCollectionChanged;
  273. return rows;
  274. }
  275. }
  276. [field: NonSerialized]
  277. public Dictionary<string, IList<Action<object, object>?>> Setters { get; } = new Dictionary<string, IList<Action<object, object>?>>();
  278. #endregion
  279. public CoreTable() : this("")
  280. {
  281. }
  282. public CoreTable(string tableName): base()
  283. {
  284. this.tableName = tableName;
  285. }
  286. public CoreTable(Type type) : this()
  287. {
  288. LoadColumns(type);
  289. }
  290. public void AddColumn<T>(Expression<Func<T, object>> column)
  291. {
  292. Columns.Add(
  293. new CoreColumn()
  294. {
  295. ColumnName = CoreUtils.GetFullPropertyName(column, "."),
  296. DataType = column.ReturnType
  297. }
  298. );
  299. }
  300. public CoreRow NewRow(bool populate = false)
  301. {
  302. var result = new CoreRow(this);
  303. if (populate)
  304. foreach (var column in Columns)
  305. result[column.ColumnName] = column.DataType.GetDefault();
  306. return result;
  307. }
  308. /*
  309. private void OnRowsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  310. {
  311. switch (e.Action)
  312. {
  313. case NotifyCollectionChangedAction.Add:
  314. this.InternalView.Insert(e.NewStartingIndex, ((DataRow)e.NewItems[0]).RowObject);
  315. break;
  316. case NotifyCollectionChangedAction.Remove:
  317. this.InternalView.RemoveAt(e.OldStartingIndex);
  318. break;
  319. case NotifyCollectionChangedAction.Replace:
  320. this.InternalView.Remove(((DataRow)e.OldItems[0]).RowObject);
  321. this.InternalView.Insert(e.NewStartingIndex, ((DataRow)e.NewItems[0]).RowObject);
  322. break;
  323. case NotifyCollectionChangedAction.Reset:
  324. default:
  325. this.InternalView.Clear();
  326. this.Rows.Select(r => r.RowObject).ToList().ForEach(o => this.InternalView.Add(o));
  327. break;
  328. }
  329. }
  330. private IList InternalView
  331. {
  332. get
  333. {
  334. if (this.internalView == null)
  335. {
  336. this.CreateInternalView();
  337. }
  338. return this.internalView;
  339. }
  340. }
  341. private void CreateInternalView()
  342. {
  343. this.internalView = (IList)Activator.CreateInstance(typeof(ObservableCollection<>).MakeGenericType(this.ElementType));
  344. ((INotifyCollectionChanged)internalView).CollectionChanged += (s, e) => { this.OnCollectionChanged(e); };
  345. }
  346. internal Type ElementType
  347. {
  348. get
  349. {
  350. if (this.elementType == null)
  351. {
  352. this.InitializeElementType();
  353. }
  354. return this.elementType;
  355. }
  356. }
  357. private void InitializeElementType()
  358. {
  359. this.Seal();
  360. this.elementType = DynamicObjectBuilder.GetDynamicObjectBuilderType(this.Columns);
  361. }
  362. private void Seal()
  363. {
  364. this.columns = new ReadOnlyCollection<DataColumn>(this.Columns);
  365. }
  366. public IEnumerator GetEnumerator()
  367. {
  368. return this.InternalView.GetEnumerator();
  369. }
  370. public IList ToList()
  371. {
  372. return this.InternalView;
  373. }
  374. protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  375. {
  376. var handler = this.CollectionChanged;
  377. if (handler != null)
  378. {
  379. handler(this, e);
  380. }
  381. }
  382. */
  383. public void LoadColumns(Type T)
  384. {
  385. var iprops = DatabaseSchema.Properties(T);
  386. foreach (var iprop in iprops)
  387. Columns.Add(new CoreColumn { ColumnName = iprop.Name, DataType = iprop.PropertyType });
  388. }
  389. public void LoadColumns(IColumns columns)
  390. {
  391. foreach (var col in columns.GetColumns())
  392. Columns.Add(new CoreColumn { ColumnName = col.Property, DataType = col.Type });
  393. }
  394. public void LoadColumns(IEnumerable<CoreColumn> columns)
  395. {
  396. Columns.Clear();
  397. foreach (var col in columns)
  398. Columns.Add(new CoreColumn() { ColumnName = col.ColumnName, DataType = col.DataType });
  399. }
  400. public void LoadRows(IEnumerable<object> objects)
  401. {
  402. foreach (var obj in objects)
  403. {
  404. var row = NewRow();
  405. LoadRow(row, obj);
  406. Rows.Add(row);
  407. }
  408. }
  409. public void LoadRows(CoreRow[] rows)
  410. {
  411. foreach (var row in rows)
  412. {
  413. var newrow = NewRow();
  414. LoadRow(newrow, row);
  415. Rows.Add(newrow);
  416. }
  417. }
  418. public void LoadFrom<T1, T2>(CoreTable table, CoreFieldMap<T1, T2> mappings, Action<CoreRow>? customization = null)
  419. {
  420. foreach (var row in table.Rows)
  421. {
  422. var newrow = NewRow();
  423. foreach (var map in mappings.Fields)
  424. newrow.Set(map.To, row.Get(map.From));
  425. customization?.Invoke(newrow);
  426. Rows.Add(newrow);
  427. }
  428. }
  429. public void LoadRow(CoreRow row, object obj)
  430. {
  431. foreach (var col in Columns)
  432. try
  433. {
  434. //var prop = DataModel.Property(obj.GetType(), col.ColumnName);
  435. //if (prop is CustomProperty)
  436. // prop is CustomProperty ? item.UserProperties[key] : CoreUtils.GetPropertyValue(item, key);
  437. var fieldvalue = CoreUtils.GetPropertyValue(obj, col.ColumnName);
  438. row[col.ColumnName] = fieldvalue;
  439. }
  440. catch (Exception e)
  441. {
  442. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  443. }
  444. }
  445. public void LoadRow(CoreRow row, CoreRow from)
  446. {
  447. foreach (var col in Columns)
  448. try
  449. {
  450. if (from.Table.Columns.Any(x => x.ColumnName.Equals(col.ColumnName)))
  451. row[col.ColumnName] = from[col.ColumnName];
  452. }
  453. catch (Exception e)
  454. {
  455. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  456. }
  457. }
  458. public void Filter(Func<CoreRow, bool> predicate)
  459. {
  460. for (var i = Rows.Count - 1; i > -1; i--)
  461. {
  462. var row = Rows[i];
  463. var predresult = predicate.Invoke(row);
  464. if (!predresult)
  465. Rows.Remove(row);
  466. }
  467. }
  468. public IDictionary ToDictionary(string keycol, string displaycol, string sortcol = "")
  469. {
  470. var kc = Columns.FirstOrDefault(x => x.ColumnName.Equals(keycol));
  471. var dc = Columns.FirstOrDefault(x => x.ColumnName.Equals(displaycol));
  472. var dt = typeof(Dictionary<,>).MakeGenericType(kc.DataType, dc.DataType);
  473. var id = (Activator.CreateInstance(dt) as IDictionary)!;
  474. var sorted = string.IsNullOrWhiteSpace(sortcol) ? Rows : Rows.OrderBy(x => x.Get<object>(sortcol)).ToList();
  475. foreach (var row in sorted)
  476. id[row[keycol]] = row[displaycol];
  477. return id;
  478. }
  479. public Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(Expression<Func<T, TKey>> key, Expression<Func<T, TValue>> value,
  480. Expression<Func<T, object>>? sort = null)
  481. {
  482. var result = new Dictionary<TKey, TValue>();
  483. var sorted = sort == null ? Rows : Rows.OrderBy(x => x.Get(sort)).ToList();
  484. foreach (var row in Rows)
  485. result[row.Get(key)] = row.Get(value);
  486. return result;
  487. }
  488. public Dictionary<TKey, string> ToDictionary<T, TKey>(Expression<Func<T, TKey>> key, Expression<Func<T, object>>[] values,
  489. Expression<Func<T, object>>? sort = null)
  490. {
  491. var result = new Dictionary<TKey, string>();
  492. var sorted = sort == null ? Rows : Rows.OrderBy(x => x.Get(sort)).ToList();
  493. foreach (var row in Rows)
  494. {
  495. var display = new List<object>();
  496. foreach (var value in values)
  497. display.Add(row.Get(value));
  498. result[row.Get(key)] = string.Join(" : ", display);
  499. }
  500. return result;
  501. }
  502. public Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(Expression<Func<T, TKey>> key, Func<CoreRow, TValue> value,
  503. Expression<Func<T, object>>? sort = null)
  504. {
  505. var result = new Dictionary<TKey, TValue>();
  506. var sorted = sort == null ? Rows : Rows.OrderBy(x => x.Get(sort)).ToList();
  507. foreach (var row in Rows)
  508. result[row.Get(key)] = value(row);
  509. return result;
  510. }
  511. public void LoadDictionary<T, TKey, TValue>(Dictionary<TKey, TValue> dictionary, Expression<Func<T, TKey>> key,
  512. Expression<Func<T, TValue>> value)
  513. {
  514. foreach (var row in Rows) dictionary[row.Get(key)] = row.Get(value);
  515. }
  516. public DataTable ToDataTable(string name = "", IColumns? additionalColumns = null)
  517. {
  518. var result = new DataTable(name);
  519. foreach (var column in Columns)
  520. result.Columns.Add(column.ColumnName.Replace('.', '_'), column.DataType);
  521. if(additionalColumns != null)
  522. {
  523. foreach (var (column, type) in additionalColumns.AsDictionary())
  524. result.Columns.Add(column.Replace('.', '_'), type);
  525. }
  526. //result.Columns["ID"].Unique = true;
  527. //result.PrimaryKey = new DataColumn[] { result.Columns["ID"] };
  528. foreach (var row in Rows)
  529. {
  530. //result.Rows.Add(row.Values.ToArray());
  531. var newrow = result.NewRow();
  532. newrow.ItemArray = row.Values.ToArray();
  533. result.Rows.Add(newrow);
  534. }
  535. return result;
  536. }
  537. public IEnumerable<BaseObject> ToObjects(Type T)
  538. => Rows.Select(x => x.ToObject(T));
  539. public IEnumerable<T> ToObjects<T>() where T : BaseObject, new()
  540. => Rows.Select(x => x.ToObject<T>());
  541. public List<T> ToList<T>() where T : BaseObject, new()
  542. => ToObjects<T>().ToList();
  543. public void CopyTo(DataTable table)
  544. {
  545. var columns = new List<string>();
  546. foreach (var column in Columns)
  547. columns.Add(column.ColumnName.Replace('.', '_'));
  548. foreach (var row in Rows)
  549. {
  550. var newrow = table.NewRow();
  551. for (var i = 0; i < columns.Count; i++)
  552. newrow[columns[i]] = row.Values[i];
  553. table.Rows.Add(newrow);
  554. }
  555. }
  556. public void CopyTo(CoreTable table)
  557. {
  558. var columns = new List<string>();
  559. //foreach (var column in Columns)
  560. // columns.Add(column.ColumnName.Replace('.', '_'));
  561. foreach (var row in Rows)
  562. {
  563. var newrow = table.NewRow();
  564. foreach (var column in Columns)
  565. if (table.Columns.Any(x => x.ColumnName.Equals(column.ColumnName)))
  566. newrow[column.ColumnName] = row[column.ColumnName];
  567. //for (int i = 0; i < columns.Count; i++)
  568. // newrow.Set(columns[i], row.Values[i]);
  569. table.Rows.Add(newrow);
  570. }
  571. }
  572. public IEnumerable<TValue> ExtractValues<TSource, TValue>(Expression<Func<TSource, TValue>> column, bool distinct = true)
  573. {
  574. var result = Rows.Select(r => r.Get(column));
  575. if (distinct)
  576. result = result.Distinct();
  577. return result;
  578. }
  579. public IEnumerable<TValue> ExtractValues<TValue>(string column, bool distinct = true)
  580. {
  581. var result = Rows.Select(r => r.Get<TValue>(column));
  582. if (distinct)
  583. result = result.Distinct();
  584. return result;
  585. }
  586. public CoreTable LoadRow(object obj)
  587. {
  588. var row = NewRow();
  589. LoadRow(row, obj);
  590. Rows.Add(row);
  591. return this;
  592. }
  593. public Dictionary<TKey, string> IntoDictionary<T, TKey>(Dictionary<TKey, string> result, Expression<Func<T, TKey>> key,
  594. params Expression<Func<T, object>>[] values)
  595. {
  596. foreach (var row in Rows)
  597. {
  598. var display = new List<object>();
  599. foreach (var value in values)
  600. display.Add(row.Get(value));
  601. result[row.Get(key)] = string.Join(" : ", display);
  602. }
  603. return result;
  604. }
  605. public Dictionary<TKey, TValue> IntoDictionary<T, TKey, TValue>(Dictionary<TKey, TValue> result, Expression<Func<T, TKey>> key,
  606. Func<CoreRow, TValue> value)
  607. {
  608. foreach (var row in Rows)
  609. result[row.Get(key)] = value(row);
  610. return result;
  611. }
  612. public IMutableLookup<TKey, TValue> ToLookup<T, TKey, TValue>(Expression<Func<T, TKey>> key, Expression<Func<T, TValue>> value,
  613. Expression<Func<T, object>>? sort = null)
  614. {
  615. IMutableLookup<TKey, TValue> result = new MutableLookup<TKey, TValue>(
  616. Rows.ToLookup(
  617. r => r.Get(key),
  618. r => r.Get(value)
  619. )
  620. );
  621. return result;
  622. }
  623. public IMutableLookup<TKey, TValue> ToLookup<T, TKey, TValue>(Expression<Func<T, TKey>> key, Func<CoreRow, TValue> value,
  624. Expression<Func<T, object>>? sort = null)
  625. {
  626. IMutableLookup<TKey, TValue> result = new MutableLookup<TKey, TValue>(
  627. Rows.ToLookup(
  628. r => r.Get(key),
  629. r => value(r)
  630. )
  631. );
  632. return result;
  633. }
  634. #region Serialize Binary
  635. private static void WriteValue(BinaryWriter writer, Type type, object? value)
  636. {
  637. value ??= CoreUtils.GetDefault(type);
  638. if (type == typeof(byte[]) && value is byte[] bArray)
  639. {
  640. writer.Write(bArray.Length);
  641. writer.Write(bArray);
  642. }
  643. else if (type == typeof(byte[]) && value is null)
  644. {
  645. writer.Write(0);
  646. }
  647. else if (type.IsArray && value is Array array)
  648. {
  649. var elementType = type.GetElementType();
  650. writer.Write(array.Length);
  651. foreach (var val1 in array)
  652. {
  653. WriteValue(writer, elementType, val1);
  654. }
  655. }
  656. else if (type.IsArray && value is null)
  657. {
  658. writer.Write(0);
  659. }
  660. else if (type.IsEnum && value is Enum e)
  661. {
  662. var underlyingType = type.GetEnumUnderlyingType();
  663. WriteValue(writer, underlyingType, Convert.ChangeType(e, underlyingType));
  664. }
  665. else if (type == typeof(bool) && value is bool b)
  666. {
  667. writer.Write(b);
  668. }
  669. else if (type == typeof(string) && value is string str)
  670. {
  671. writer.Write(str);
  672. }
  673. else if (type == typeof(string) && value is null)
  674. {
  675. writer.Write("");
  676. }
  677. else if (type == typeof(Guid) && value is Guid guid)
  678. {
  679. writer.Write(guid.ToByteArray());
  680. }
  681. else if (type == typeof(byte) && value is byte i8)
  682. {
  683. writer.Write(i8);
  684. }
  685. else if (type == typeof(Int16) && value is Int16 i16)
  686. {
  687. writer.Write(i16);
  688. }
  689. else if (type == typeof(Int32) && value is Int32 i32)
  690. {
  691. writer.Write(i32);
  692. }
  693. else if (type == typeof(Int64) && value is Int64 i64)
  694. {
  695. writer.Write(i64);
  696. }
  697. else if (type == typeof(float) && value is float f32)
  698. {
  699. writer.Write(f32);
  700. }
  701. else if (type == typeof(double) && value is double f64)
  702. {
  703. writer.Write(f64);
  704. }
  705. else if (type == typeof(DateTime) && value is DateTime date)
  706. {
  707. writer.Write(date.Ticks);
  708. }
  709. else if (type == typeof(TimeSpan) && value is TimeSpan time)
  710. {
  711. writer.Write(time.Ticks);
  712. }
  713. else if (type == typeof(LoggablePropertyAttribute))
  714. {
  715. writer.Write((value as LoggablePropertyAttribute)?.Format ?? "");
  716. }
  717. else if (typeof(IPackable).IsAssignableFrom(type) && value is IPackable pack)
  718. {
  719. pack.Pack(writer);
  720. }
  721. else
  722. {
  723. throw new Exception($"Invalid type; Target DataType is {type} and value DataType is {value?.GetType().ToString() ?? "null"}");
  724. }
  725. }
  726. public void WriteBinary(BinaryWriter writer, bool includeColumns)
  727. {
  728. writer.Write(TableName);
  729. if (includeColumns)
  730. {
  731. foreach (var column in Columns)
  732. {
  733. writer.Write(true);
  734. writer.Write(column.ColumnName);
  735. writer.Write(column.DataType.EntityName());
  736. }
  737. writer.Write(false);
  738. }
  739. writer.Write(Rows.Count);
  740. foreach (var row in Rows)
  741. {
  742. foreach (var col in Columns)
  743. {
  744. var val = row[col.ColumnName];
  745. WriteValue(writer, col.DataType, val);
  746. }
  747. }
  748. }
  749. public void SerializeBinary(BinaryWriter writer) => WriteBinary(writer, true);
  750. private static object? ReadValue(BinaryReader reader, Type type)
  751. {
  752. if (type == typeof(byte[]))
  753. {
  754. var length = reader.ReadInt32();
  755. return reader.ReadBytes(length);
  756. }
  757. else if (type.IsArray)
  758. {
  759. var length = reader.ReadInt32();
  760. var elementType = type.GetElementType();
  761. var array = Array.CreateInstance(elementType, length);
  762. for (int i = 0; i < array.Length; ++i)
  763. {
  764. array.SetValue(ReadValue(reader, elementType), i);
  765. }
  766. return array;
  767. }
  768. else if (type.IsEnum)
  769. {
  770. var val = ReadValue(reader, type.GetEnumUnderlyingType());
  771. return Enum.ToObject(type, val);
  772. }
  773. else if (type == typeof(bool))
  774. {
  775. return reader.ReadBoolean();
  776. }
  777. else if (type == typeof(string))
  778. {
  779. return reader.ReadString();
  780. }
  781. else if (type == typeof(Guid))
  782. {
  783. return new Guid(reader.ReadBytes(16));
  784. }
  785. else if (type == typeof(byte))
  786. {
  787. return reader.ReadByte();
  788. }
  789. else if (type == typeof(Int16))
  790. {
  791. return reader.ReadInt16();
  792. }
  793. else if (type == typeof(Int32))
  794. {
  795. return reader.ReadInt32();
  796. }
  797. else if (type == typeof(Int64))
  798. {
  799. return reader.ReadInt64();
  800. }
  801. else if (type == typeof(float))
  802. {
  803. return reader.ReadSingle();
  804. }
  805. else if (type == typeof(double))
  806. {
  807. return reader.ReadDouble();
  808. }
  809. else if (type == typeof(DateTime))
  810. {
  811. return new DateTime(reader.ReadInt64());
  812. }
  813. else if (type == typeof(TimeSpan))
  814. {
  815. return new TimeSpan(reader.ReadInt64());
  816. }
  817. else if (type == typeof(LoggablePropertyAttribute))
  818. {
  819. String format = reader.ReadString();
  820. return String.IsNullOrWhiteSpace(format)
  821. ? null
  822. : new LoggablePropertyAttribute() { Format = format };
  823. }
  824. else if (typeof(IPackable).IsAssignableFrom(type))
  825. {
  826. var packable = (Activator.CreateInstance(type) as IPackable)!;
  827. packable.Unpack(reader);
  828. return packable;
  829. }
  830. else
  831. {
  832. throw new Exception($"Invalid type; Target DataType is {type}");
  833. }
  834. }
  835. public void ReadBinary(BinaryReader reader, IList<CoreColumn>? columns)
  836. {
  837. tableName = reader.ReadString();
  838. Columns.Clear();
  839. if (columns is null)
  840. {
  841. while (reader.ReadBoolean())
  842. {
  843. var columnName = reader.ReadString();
  844. var dataType = CoreUtils.GetEntity(reader.ReadString());
  845. Columns.Add(new CoreColumn(dataType, columnName));
  846. }
  847. }
  848. else
  849. {
  850. foreach (var column in columns)
  851. {
  852. Columns.Add(column);
  853. }
  854. }
  855. Rows.Clear();
  856. var nRows = reader.ReadInt32();
  857. for (int i = 0; i < nRows; ++i)
  858. {
  859. var row = NewRow();
  860. foreach (var column in Columns)
  861. {
  862. var value = ReadValue(reader, column.DataType);
  863. row.Values.Add(value);
  864. }
  865. Rows.Add(row);
  866. }
  867. }
  868. public void DeserializeBinary(BinaryReader reader) => ReadBinary(reader, null);
  869. #endregion
  870. }
  871. public class CoreTableAdapter<T> : IEnumerable<T> where T : BaseObject, new()
  872. {
  873. private List<T>? _objects;
  874. private readonly CoreTable _table;
  875. public CoreTableAdapter(CoreTable table)
  876. {
  877. _table = table;
  878. }
  879. private List<T> Objects
  880. {
  881. get => _objects ??= _table.Rows.Select(row => row.ToObject<T>()).ToList();
  882. }
  883. public T this[int index] => Objects[index];
  884. public IEnumerator<T> GetEnumerator()
  885. {
  886. return GetObjects();
  887. }
  888. IEnumerator IEnumerable.GetEnumerator()
  889. {
  890. return GetObjects();
  891. }
  892. private IEnumerator<T> GetObjects()
  893. {
  894. return Objects.GetEnumerator();
  895. }
  896. }
  897. public class DataTableJsonConverter : JsonConverter
  898. {
  899. public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
  900. {
  901. if(!(value is CoreTable table))
  902. {
  903. writer.WriteNull();
  904. return;
  905. }
  906. writer.WriteStartObject();
  907. writer.WritePropertyName("Columns");
  908. var cols = new Dictionary<string, string>();
  909. foreach (var column in table.Columns)
  910. cols[column.ColumnName] = column.DataType.EntityName();
  911. serializer.Serialize(writer, cols);
  912. //writer.WriteEndObject();
  913. //writer.WriteStartObject();
  914. writer.WritePropertyName("Rows");
  915. writer.WriteStartArray();
  916. var size = 0;
  917. foreach (var row in table.Rows)
  918. //Console.WriteLine("- Serializing Row #"+row.Index.ToString());
  919. try
  920. {
  921. writer.WriteStartArray();
  922. foreach (var col in table.Columns)
  923. {
  924. var val = row[col.ColumnName];
  925. if (val != null) size += val.ToString().Length;
  926. //Console.WriteLine(String.Format("Serializing Row #{0} Column [{1}] Length={2}", row.Index.ToString(), col.ColumnName, val.ToString().Length));
  927. if (col.DataType.IsArray && val != null)
  928. {
  929. writer.WriteStartArray();
  930. foreach (var val1 in (Array)val)
  931. writer.WriteValue(val1);
  932. writer.WriteEndArray();
  933. }
  934. else if (col.DataType.GetInterfaces().Contains(typeof(IPackableList)))
  935. {
  936. writer.WriteStartArray();
  937. foreach (var val1 in (IList)val)
  938. writer.WriteValue(val1);
  939. writer.WriteEndArray();
  940. }
  941. else
  942. {
  943. writer.WriteValue(val ?? CoreUtils.GetDefault(col.DataType));
  944. }
  945. }
  946. writer.WriteEndArray();
  947. //Console.WriteLine(String.Format("[{0:D8}] Serializing Row #{1}", size, row.Index.ToString()));
  948. }
  949. catch (Exception e)
  950. {
  951. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  952. }
  953. writer.WriteEndArray();
  954. writer.WriteEndObject();
  955. }
  956. public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
  957. {
  958. if (reader.TokenType == JsonToken.Null)
  959. return null;
  960. var result = new CoreTable();
  961. try
  962. {
  963. var json = JObject.Load(reader);
  964. if (json.TryGetValue("Columns", out var columns))
  965. {
  966. foreach (JProperty column in columns.Children())
  967. {
  968. var name = column.Name;
  969. var type = column.Value.ToObject<string>();
  970. result.Columns.Add(new CoreColumn { ColumnName = name, DataType = CoreUtils.GetEntity(type ?? "") });
  971. }
  972. }
  973. if (json.TryGetValue("Rows", out var rows))
  974. {
  975. foreach (JArray row in rows.Children())
  976. if (row.Children().ToArray().Length == result.Columns.Count)
  977. {
  978. var newrow = result.NewRow();
  979. var iCol = 0;
  980. foreach (var cell in row.Children())
  981. {
  982. var column = result.Columns[iCol];
  983. try
  984. {
  985. if (column.DataType.IsArray)
  986. {
  987. newrow[column.ColumnName] = cell.ToObject(column.DataType);
  988. }
  989. else if (column.DataType.GetInterfaces().Contains(typeof(IPackableList)))
  990. {
  991. }
  992. else
  993. {
  994. newrow[column.ColumnName] = cell.ToObject(column.DataType);
  995. }
  996. //if ((column.DataType == typeof(byte[])) && (value != null))
  997. // newrow[column.ColumnName] = Convert.FromBase64String(value.ToString());
  998. //else if (cell is JValue)
  999. // value = ((JValue)cell).Value;
  1000. //else if (cell is JObject)
  1001. // value = ((JObject)cell).ToObject(column.DataType);
  1002. //else if (cell is JArray)
  1003. // value = ((JArray)cell).ToObject(column.DataType);
  1004. //else
  1005. // value = null;
  1006. }
  1007. catch (Exception e)
  1008. {
  1009. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1010. }
  1011. iCol++;
  1012. }
  1013. result.Rows.Add(newrow);
  1014. }
  1015. }
  1016. }
  1017. catch (Exception e)
  1018. {
  1019. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1020. }
  1021. return result;
  1022. //String json = reader.Value.ToString();
  1023. //var table = new CoreTable();
  1024. //Dictionary<String, Object> dict = Serialization.Deserialize<Dictionary<String, Object>>(json);
  1025. //Dictionary<String, String> columns = Serialization.Deserialize<Dictionary<String, String>>(dict["Columns"].ToString());
  1026. //List<List<Object>> rows = Serialization.Deserialize<List<List<Object>>>(dict["Rows"].ToString());
  1027. //String[] keys = columns.Keys.ToArray();
  1028. //foreach (String key in keys)
  1029. // table.Columns.Add(new CoreColumn() { ColumnName = key, DataType = CoreUtils.GetEntity(columns[key]) });
  1030. //foreach (List<Object> row in rows)
  1031. //{
  1032. // CoreRow newrow = table.NewRow();
  1033. // for (int i = 0; i < keys.Count(); i++)
  1034. // {
  1035. // if (row[i] is JObject)
  1036. // newrow[keys[i]] = JsonConvert.DeserializeObject(row[i].ToString(), table.Columns[i].DataType);
  1037. // else if (table.Columns[i].DataType == typeof(byte[]))
  1038. // {
  1039. // if (row[i] != null)
  1040. // newrow.Set(keys[i], Convert.FromBase64String(row[i].ToString()));
  1041. // }
  1042. // else
  1043. // {
  1044. // try
  1045. // {
  1046. // object o = row[i];
  1047. // if (table.Columns[i].DataType != null)
  1048. // o = CoreUtils.ChangeType(o, table.Columns[i].DataType);
  1049. // newrow.Set(keys[i], o);
  1050. // }
  1051. // catch (Exception e)
  1052. // {
  1053. // }
  1054. // }
  1055. // //newrow[keys[i]] = row[i];
  1056. // }
  1057. // table.Rows.Add(newrow);
  1058. //}
  1059. //return table;
  1060. }
  1061. public override bool CanConvert(Type objectType)
  1062. {
  1063. return typeof(CoreTable).GetTypeInfo().IsAssignableFrom(objectType);
  1064. }
  1065. }
  1066. }