DataTable.cs 42 KB

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