DataTableSerializer.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Xml.Serialization;
  5. using System.Data;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Collections;
  9. using EasyDevCore.Common;
  10. namespace EasyDev.Database.EntityTable
  11. {
  12. /// <summary>
  13. ///
  14. /// </summary>
  15. public enum DataTableSerializerSchema
  16. {
  17. /// <summary>
  18. /// The none
  19. /// </summary>
  20. None,
  21. /// <summary>
  22. /// The data table schema
  23. /// </summary>
  24. DataTableSchema,
  25. /// <summary>
  26. /// The column schema
  27. /// </summary>
  28. ColumnSchema
  29. }
  30. /// <summary>
  31. /// Convert DataTable to XML
  32. /// </summary>
  33. [Serializable]
  34. public class DataTableSerializer : IXmlSerializable
  35. {
  36. private DataTable _Table;
  37. private DataTableSerializerSchema _ProxySchema = DataTableSerializerSchema.None;
  38. private bool _ForSynchValues = false;
  39. private bool _OptimumSize = true;
  40. private string _KeyFields = string.Empty;
  41. private string _ColumnNames = string.Empty;
  42. private string _ExceptColumnNames = string.Empty;
  43. /// <summary>
  44. /// use for XmlSerialization
  45. /// </summary>
  46. private DataTableSerializer()
  47. {
  48. }
  49. /// <summary>
  50. /// Initializes a new instance of the <see cref="DataTableSerializer" /> class.
  51. /// </summary>
  52. /// <param name="entities">The entities.</param>
  53. /// <param name="forSynchValues">if set to <c>true</c> [only changed values has been serialize for synchronized].</param>
  54. /// <param name="columnNames">The colum names filter (can be use = for mapping; ex: ColumnName = PropertyName).</param>
  55. /// <param name="exceptColumnNames">The except column names.</param>
  56. /// <param name="keyFields">The key fields.</param>
  57. /// <param name="proxySchema">The proxy schema.</param>
  58. /// <param name="optimumSize">if set to <c>true</c> [optimum size but slower].</param>
  59. public DataTableSerializer(DataTable entities, bool forSynchValues = false, string columnNames = "", string exceptColumnNames = "", string keyFields = "", DataTableSerializerSchema proxySchema = DataTableSerializerSchema.None, bool optimumSize = true)
  60. {
  61. _Table = entities;
  62. _ForSynchValues = forSynchValues;
  63. _ColumnNames = columnNames;
  64. _ExceptColumnNames = exceptColumnNames;
  65. _KeyFields = keyFields;
  66. _OptimumSize = optimumSize;
  67. _ProxySchema = proxySchema;
  68. if (proxySchema == DataTableSerializerSchema.None && entities != null)
  69. {
  70. _ProxySchema = DataTableSerializerSchema.DataTableSchema;
  71. }
  72. }
  73. /// <summary>
  74. /// Gets the table.
  75. /// </summary>
  76. /// <value>The entities.</value>
  77. public virtual DataTable Table
  78. {
  79. get
  80. {
  81. return _Table;
  82. }
  83. }
  84. #region IXmlSerializable Members
  85. /// <summary>
  86. /// This property is reserved, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"></see> to the class instead.
  87. /// </summary>
  88. /// <returns>
  89. /// An <see cref="T:System.Xml.Schema.XmlSchema"></see> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"></see> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"></see> method.
  90. /// </returns>
  91. public System.Xml.Schema.XmlSchema GetSchema()
  92. {
  93. return null;
  94. }
  95. /// <summary>
  96. /// Gets the type of the entity collection.
  97. /// </summary>
  98. /// <returns></returns>
  99. public virtual Type GetDataTableType()
  100. {
  101. return null;
  102. }
  103. /// <summary>
  104. /// Loads the XML only for changes.
  105. /// </summary>
  106. /// <param name="reader">The reader.</param>
  107. /// <param name="optimumSize">if set to <c>true</c> [optimum size].</param>
  108. /// <param name="mapColumns">The map columns.</param>
  109. private void LoadXMLOnlyForSync(System.Xml.XmlReader reader, bool optimumSize, Dictionary<string, int> mapColumns)
  110. {
  111. DataRow row;
  112. DataColumn column;
  113. string rowState;
  114. while (reader.MoveToContent() == System.Xml.XmlNodeType.Element && reader.LocalName == "R")
  115. {
  116. row = Table.NewRow();
  117. rowState = reader.GetAttribute("rowStated");
  118. reader.ReadStartElement();
  119. while (reader.MoveToContent() != System.Xml.XmlNodeType.EndElement)
  120. {
  121. if (reader.LocalName == "CS") //Special columns
  122. {
  123. string[] colNuls = reader.GetAttribute("N").SplitCommaString();
  124. foreach (string col in colNuls)
  125. {
  126. column = Table.Columns[mapColumns["C" + col]];
  127. row[column.Ordinal] = DBNull.Value;
  128. }
  129. if (optimumSize)
  130. {
  131. string[] colZoEs = reader.GetAttribute("E").SplitCommaString();
  132. foreach (string col in colZoEs)
  133. {
  134. column = Table.Columns[mapColumns["C" + col]];
  135. row[column.Ordinal] = GetZeroOrEmptyValue(column.DataType);
  136. }
  137. }
  138. reader.Read();
  139. }
  140. else
  141. {
  142. column = Table.Columns[mapColumns[reader.LocalName]];
  143. row[column.Ordinal] = reader.ReadElementString().StringTo(column.DataType);
  144. }
  145. }
  146. Table.Rows.Add(row);
  147. switch (rowState)
  148. {
  149. case "Modified":
  150. row.AcceptChanges();
  151. row.SetModified();
  152. break;
  153. case "Deleted":
  154. row.Delete();
  155. break;
  156. }
  157. reader.ReadEndElement();
  158. }
  159. }
  160. /// <summary>
  161. /// Loads the XML all rows.
  162. /// </summary>
  163. /// <param name="reader">The reader.</param>
  164. /// <param name="optimumSize">if set to <c>true</c> [optimum size].</param>
  165. /// <param name="mapColumns">The map columns.</param>
  166. private void LoadXMLAllRows(System.Xml.XmlReader reader, bool optimumSize, Dictionary<string, int> mapColumns)
  167. {
  168. DataRow row;
  169. DataColumn column;
  170. while (reader.MoveToContent() == System.Xml.XmlNodeType.Element && reader.LocalName == "R")
  171. {
  172. row = Table.NewRow();
  173. reader.ReadStartElement();
  174. while (reader.MoveToContent() != System.Xml.XmlNodeType.EndElement)
  175. {
  176. if (reader.LocalName == "CS") //Special columns
  177. {
  178. string colNuls = reader.GetAttribute("N");
  179. if (!string.IsNullOrWhiteSpace(colNuls))
  180. {
  181. foreach (string col in colNuls.SplitCommaString())
  182. {
  183. column = Table.Columns[mapColumns["C" + col]];
  184. row[column.Ordinal] = DBNull.Value;
  185. }
  186. }
  187. if (optimumSize)
  188. {
  189. string colZoEs = reader.GetAttribute("E");
  190. if (!string.IsNullOrWhiteSpace(colZoEs))
  191. {
  192. foreach (string col in colZoEs.SplitCommaString())
  193. {
  194. column = Table.Columns[mapColumns["C" + col]];
  195. row[column.Ordinal] = GetZeroOrEmptyValue(column.DataType);
  196. }
  197. }
  198. }
  199. reader.Read();
  200. }
  201. else
  202. {
  203. column = Table.Columns[mapColumns[reader.LocalName]];
  204. row[column.Ordinal] = reader.ReadElementString().StringTo(column.DataType);
  205. }
  206. }
  207. Table.Rows.Add(row);
  208. reader.ReadEndElement();
  209. }
  210. Table.AcceptChanges();
  211. }
  212. /// <summary>
  213. /// Generates an object from its XML representation.
  214. /// </summary>
  215. /// <param name="reader">The <see cref="T:System.Xml.XmlReader"></see> stream from which the object is deserialized.</param>
  216. public void ReadXml(System.Xml.XmlReader reader)
  217. {
  218. bool forSynchValues = false;
  219. bool includeSchema = false;
  220. string type = string.Empty;
  221. string name = string.Empty;
  222. DataColumnCollection schemaColumns = null;
  223. reader.Read();
  224. if (reader.MoveToContent() == System.Xml.XmlNodeType.Element && reader.LocalName == "Option")
  225. {
  226. type = reader.GetAttribute("type");
  227. name = reader.GetAttribute("name");
  228. forSynchValues = reader.GetAttribute("forSynchValues").StringTo(false);
  229. includeSchema = reader.GetAttribute("includeSchema").StringTo(false);
  230. if (Table == null)
  231. {
  232. if (string.IsNullOrEmpty(type) && GetDataTableType() != null)
  233. {
  234. type = GetDataTableType().AssemblyQualifiedName;
  235. }
  236. if (string.IsNullOrEmpty(type))
  237. {
  238. type = typeof(DataTable).AssemblyQualifiedName;
  239. }
  240. _Table = (DataTable)ReflectionHelper.CreateInstance(type);
  241. if (!string.IsNullOrWhiteSpace(name)) _Table.TableName = name;
  242. }
  243. else
  244. {
  245. Table.Clear();
  246. }
  247. string[] extendedProperties = reader.GetAttribute("extendedProperties").Split(new char[] { ',', '|' }, StringSplitOptions.RemoveEmptyEntries);
  248. for (int i = 0; i < extendedProperties.Length; i = i + 2)
  249. {
  250. string attributeName = "extP_" + (i / 2).ToString();
  251. string value = reader.GetAttribute(attributeName);
  252. string typeName = extendedProperties[i + 1];
  253. string propertyName = extendedProperties[i];
  254. Table.ExtendedProperties[propertyName] = value.StringTo(extendedProperties[i + 1]);
  255. }
  256. reader.Read();
  257. }
  258. schemaColumns = Table.Columns;
  259. if (includeSchema)
  260. {
  261. if (reader.MoveToContent() == System.Xml.XmlNodeType.Element && reader.LocalName == "Schema")
  262. {
  263. string schemaType = reader.GetAttribute("type");
  264. if (schemaType == DataTableSerializerSchema.ColumnSchema.ToString())
  265. {
  266. reader.ReadStartElement();
  267. while (reader.MoveToContent() != System.Xml.XmlNodeType.EndElement)
  268. {
  269. DataColumn col = Table.Columns.Add(reader.LocalName, Type.GetType(reader.GetAttribute("type")));
  270. string defaultValue = reader.GetAttribute("defaultValue");
  271. col.DefaultValue = defaultValue == "<DBNull>" ? DBNull.Value : defaultValue.StringTo(col.DataType);
  272. reader.Read();
  273. }
  274. reader.ReadEndElement();
  275. }
  276. else //DataTable schema
  277. {
  278. string schema = reader.ReadInnerXml();
  279. if (!string.IsNullOrEmpty(schema))
  280. {
  281. using (StringReader sr = new StringReader(schema))
  282. {
  283. DataTable tempTable = new DataTable(name ?? "DataTable"); //Use only for get schema
  284. tempTable.ReadXmlSchema(sr);
  285. schemaColumns = tempTable.Columns;
  286. }
  287. using (StringReader sr = new StringReader(schema))
  288. {
  289. Table.ReadXmlSchema(sr);
  290. }
  291. }
  292. }
  293. }
  294. }
  295. Dictionary<string, int> mapColumns = new Dictionary<string, int>();
  296. foreach (DataColumn column in schemaColumns)
  297. {
  298. mapColumns.Add(string.Format("C{0}", column.Ordinal), Table.Columns[column.ColumnName].Ordinal);
  299. }
  300. if (forSynchValues)
  301. {
  302. LoadXMLOnlyForSync(reader, _OptimumSize, mapColumns);
  303. }
  304. else
  305. {
  306. LoadXMLAllRows(reader, _OptimumSize, mapColumns);
  307. }
  308. reader.ReadEndElement();
  309. }
  310. /// <summary>
  311. /// Determines whether [is zero or empty] [the specified value].
  312. /// </summary>
  313. /// <param name="value">The value.</param>
  314. /// <returns>
  315. /// <c>true</c> if [is zero or empty] [the specified value]; otherwise, <c>false</c>.
  316. /// </returns>
  317. protected bool IsZeroOrEmpty(object value)
  318. {
  319. Type type = value.GetType();
  320. if (type == typeof(string))
  321. {
  322. return (string)value == string.Empty;
  323. }
  324. else
  325. {
  326. if (type.IsNumericType())
  327. {
  328. return value.Equals(0);
  329. }
  330. }
  331. return false;
  332. }
  333. /// <summary>
  334. /// Gets the zero or empty value.
  335. /// </summary>
  336. /// <param name="type">The type.</param>
  337. /// <returns></returns>
  338. protected object GetZeroOrEmptyValue(Type type)
  339. {
  340. if (type == typeof(string))
  341. {
  342. return string.Empty;
  343. }
  344. else
  345. {
  346. if (type.IsNumericType())
  347. {
  348. return 0;
  349. }
  350. }
  351. return string.Empty;
  352. }
  353. /// <summary>
  354. /// Creates the XML only for sync values.
  355. /// </summary>
  356. /// <param name="writer">The writer.</param>
  357. private void CreateXMLOnlyForSync(System.Xml.XmlWriter writer)
  358. {
  359. string[] exceptColNames = _ExceptColumnNames.SplitCommaString(trimSpace: true);
  360. string[] colNames = _ColumnNames.SplitCommaString(trimSpace: true);
  361. string[] keyFields = _KeyFields.SplitCommaString(trimSpace: true);
  362. Dictionary<int, string> columns = new Dictionary<int, string>();
  363. Dictionary<int, string> modifiedColumns = new Dictionary<int, string>();
  364. Dictionary<int, string> primaryKeysColumns = new Dictionary<int, string>();
  365. foreach (DataColumn column in Table.Columns)
  366. {
  367. if (string.IsNullOrEmpty(column.Expression) && !column.ReadOnly && (colNames.Length == 0 || Array.IndexOf(colNames, column.ColumnName) > -1)
  368. && (exceptColNames.Length == 0 || Array.IndexOf(exceptColNames, column.ColumnName) == -1))
  369. {
  370. string colName = string.Format("C{0}", column.Ordinal);
  371. columns.Add(column.Ordinal, colName);
  372. }
  373. }
  374. foreach (string columnName in keyFields)
  375. {
  376. int colNo = Table.Columns[columnName].Ordinal;
  377. string colName = string.Format("C{0}", Table.Columns[columnName].Ordinal);
  378. primaryKeysColumns.Add(colNo, colName);
  379. modifiedColumns.Add(colNo, colName);
  380. }
  381. DataView dataView = new DataView(Table, "", "", DataViewRowState.Added | DataViewRowState.Deleted | DataViewRowState.ModifiedCurrent);
  382. DataRow entity;
  383. foreach (DataRowView rowView in dataView)
  384. {
  385. entity = rowView.Row;
  386. writer.WriteStartElement("R");
  387. writer.WriteAttributeString("rowStated", entity.RowState.ToString());
  388. string colNuls = string.Empty;
  389. string colZeroOrEmpty = string.Empty;
  390. switch (entity.RowState)
  391. {
  392. case DataRowState.Added:
  393. foreach (KeyValuePair<int, string> column in columns)
  394. {
  395. if (!entity.IsNull(column.Key))
  396. {
  397. if (_OptimumSize && IsZeroOrEmpty(entity[column.Key]))
  398. {
  399. colZeroOrEmpty += !string.IsNullOrWhiteSpace(colZeroOrEmpty) ? "," + column.Key.ToString() : column.Key.ToString();
  400. }
  401. else
  402. {
  403. writer.WriteElementString(column.Value, entity[column.Key].StringFrom());
  404. }
  405. }
  406. else
  407. {
  408. colNuls += !string.IsNullOrWhiteSpace(colNuls) ? "," + column.Key.ToString() : column.Key.ToString();
  409. }
  410. }
  411. break;
  412. case DataRowState.Deleted:
  413. foreach (KeyValuePair<int, string> column in primaryKeysColumns)
  414. {
  415. writer.WriteElementString(column.Value, entity[column.Key, DataRowVersion.Original].StringFrom());
  416. }
  417. break;
  418. case DataRowState.Modified:
  419. //Saves only columns has value change
  420. if (!entity.IsChanged())
  421. {
  422. continue;
  423. }
  424. foreach (KeyValuePair<int, string> column in columns)
  425. {
  426. if (entity.IsChanged(column.Key))
  427. {
  428. if (!entity.IsNull(column.Key))
  429. {
  430. if (_OptimumSize && IsZeroOrEmpty(entity[column.Key]))
  431. {
  432. colZeroOrEmpty += !string.IsNullOrWhiteSpace(colZeroOrEmpty) ? "," + column.Key.ToString() : column.Key.ToString();
  433. }
  434. else
  435. {
  436. writer.WriteElementString(column.Value, entity[column.Key].StringFrom());
  437. }
  438. }
  439. else
  440. {
  441. colNuls += !string.IsNullOrWhiteSpace(colNuls) ? "," + column.Key.ToString() : column.Key.ToString();
  442. }
  443. }
  444. }
  445. break;
  446. }
  447. bool isNull = !string.IsNullOrWhiteSpace(colNuls);
  448. bool isZeroOrEmpty = !string.IsNullOrWhiteSpace(colZeroOrEmpty);
  449. if (isNull || isZeroOrEmpty)
  450. {
  451. writer.WriteStartElement("CS");
  452. if (isNull) writer.WriteAttributeString("N", colNuls);
  453. if (isZeroOrEmpty) writer.WriteAttributeString("E", colZeroOrEmpty);
  454. writer.WriteEndElement();
  455. }
  456. writer.WriteEndElement();
  457. }
  458. }
  459. /// <summary>
  460. /// Creates the XML all rows.
  461. /// </summary>
  462. /// <param name="writer">The writer.</param>
  463. private void CreateXMLAllRows(System.Xml.XmlWriter writer)
  464. {
  465. string[] exceptColNames = _ExceptColumnNames.SplitCommaString(trimSpace: true);
  466. string[] colNames = _ColumnNames.SplitCommaString(trimSpace: true);
  467. DataView dataView = new DataView(Table, "", "", DataViewRowState.CurrentRows);
  468. DataRow entity;
  469. Dictionary<int, string> columns = new Dictionary<int, string>();
  470. foreach (DataColumn column in Table.Columns)
  471. {
  472. if (string.IsNullOrEmpty(column.Expression) && !column.ReadOnly && (colNames.Length == 0 || Array.IndexOf(colNames, column.ColumnName) > -1)
  473. && (exceptColNames.Length == 0 || Array.IndexOf(exceptColNames, column.ColumnName) == -1))
  474. {
  475. columns.Add(column.Ordinal, string.Format("C{0}", column.Ordinal));
  476. }
  477. }
  478. foreach (DataRowView rowView in dataView)
  479. {
  480. entity = rowView.Row;
  481. writer.WriteStartElement("R");
  482. string colNuls = string.Empty;
  483. string colZeroOrEmpty = string.Empty;
  484. foreach (KeyValuePair<int, string> column in columns)
  485. {
  486. if (!entity.IsNull(column.Key))
  487. {
  488. if (_OptimumSize && IsZeroOrEmpty(entity[column.Key]))
  489. {
  490. colZeroOrEmpty += !string.IsNullOrWhiteSpace(colZeroOrEmpty) ? "," + column.Key.ToString() : column.Key.ToString();
  491. }
  492. else
  493. {
  494. writer.WriteElementString(column.Value, entity[column.Key].StringFrom());
  495. }
  496. }
  497. else
  498. {
  499. colNuls += !string.IsNullOrWhiteSpace(colNuls) ? "," + column.Key.ToString() : column.Key.ToString();
  500. }
  501. }
  502. bool isNull = !string.IsNullOrWhiteSpace(colNuls);
  503. bool isZeroOrEmpty = !string.IsNullOrWhiteSpace(colZeroOrEmpty);
  504. if (isNull || isZeroOrEmpty)
  505. {
  506. writer.WriteStartElement("CS");
  507. if (isNull) writer.WriteAttributeString("N", colNuls);
  508. if (isZeroOrEmpty) writer.WriteAttributeString("E", colZeroOrEmpty);
  509. writer.WriteEndElement();
  510. }
  511. writer.WriteEndElement();
  512. }
  513. }
  514. /// <summary>
  515. /// Converts an object into its XML representation.
  516. /// </summary>
  517. /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"></see> stream to which the object is serialized.</param>
  518. public void WriteXml(System.Xml.XmlWriter writer)
  519. {
  520. writer.WriteStartElement("Option");
  521. writer.WriteAttributeString("name", Table.TableName);
  522. writer.WriteAttributeString("includeSchema", (_ProxySchema != DataTableSerializerSchema.None).ToString());
  523. writer.WriteAttributeString("type", _ProxySchema != DataTableSerializerSchema.None ? string.Empty : Table.GetType().AssemblyQualifiedName);
  524. writer.WriteAttributeString("forSynchValues", _ForSynchValues.ToString());
  525. writer.WriteAttributeString("optimumSize", _OptimumSize.ToString());
  526. string extendedProperites = string.Empty;
  527. int p = 0;
  528. foreach (DictionaryEntry prop in Table.ExtendedProperties)
  529. {
  530. extendedProperites += (!string.IsNullOrWhiteSpace(extendedProperites) ? "," : string.Empty) + prop.Key + "|" + prop.Value.GetType().FullName;
  531. writer.WriteAttributeString("extP_" + p++.ToString(), prop.Value.StringFrom());
  532. }
  533. writer.WriteAttributeString("extendedProperties", extendedProperites);
  534. writer.WriteEndElement();
  535. if (_ProxySchema != DataTableSerializerSchema.None)
  536. {
  537. writer.WriteStartElement("Schema");
  538. if (_ProxySchema == DataTableSerializerSchema.DataTableSchema)
  539. {
  540. Table.WriteXmlSchema(writer);
  541. }
  542. if (_ProxySchema == DataTableSerializerSchema.ColumnSchema)
  543. {
  544. writer.WriteAttributeString("type", _ProxySchema.ToString());
  545. foreach (DataColumn col in Table.Columns)
  546. {
  547. writer.WriteStartElement(col.ColumnName);
  548. writer.WriteAttributeString("type", col.DataType.FullName);
  549. writer.WriteAttributeString("defaultValue", col.DefaultValue == DBNull.Value ? "<DBNull>" : col.DefaultValue.ToString());
  550. writer.WriteEndElement();
  551. }
  552. }
  553. writer.WriteEndElement();
  554. }
  555. if (_ForSynchValues)
  556. {
  557. CreateXMLOnlyForSync(writer);
  558. }
  559. else
  560. {
  561. CreateXMLAllRows(writer);
  562. }
  563. }
  564. #endregion
  565. }
  566. }