DataTable.cs 40 KB

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