PageRenderTime 66ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/mcs/class/System.Data/System.Data/DataTable.cs

https://bitbucket.org/danipen/mono
C# | 3009 lines | 2173 code | 329 blank | 507 comment | 528 complexity | 998048b146804016d6ee20c7946dd11a MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. //
  2. // System.Data.DataTable.cs
  3. //
  4. // Author:
  5. // Franklin Wise <gracenote@earthlink.net>
  6. // Christopher Podurgiel (cpodurgiel@msn.com)
  7. // Daniel Morgan <danmorg@sc.rr.com>
  8. // Rodrigo Moya <rodrigo@ximian.com>
  9. // Tim Coleman (tim@timcoleman.com)
  10. // Ville Palo <vi64pa@koti.soon.fi>
  11. // Sureshkumar T <tsureshkumar@novell.com>
  12. // Konstantin Triger <kostat@mainsoft.com>
  13. //
  14. // (C) Chris Podurgiel
  15. // (C) Ximian, Inc 2002
  16. // Copyright (C) Tim Coleman, 2002-2003
  17. // Copyright (C) Daniel Morgan, 2002-2003
  18. //
  19. //
  20. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  21. //
  22. // Permission is hereby granted, free of charge, to any person obtaining
  23. // a copy of this software and associated documentation files (the
  24. // "Software"), to deal in the Software without restriction, including
  25. // without limitation the rights to use, copy, modify, merge, publish,
  26. // distribute, sublicense, and/or sell copies of the Software, and to
  27. // permit persons to whom the Software is furnished to do so, subject to
  28. // the following conditions:
  29. //
  30. // The above copyright notice and this permission notice shall be
  31. // included in all copies or substantial portions of the Software.
  32. //
  33. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  34. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  35. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  36. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  37. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  38. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  39. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  40. //
  41. using System;
  42. using System.Data.Common;
  43. using System.Collections;
  44. #if NET_2_0
  45. using System.Collections.Generic;
  46. #endif
  47. using System.ComponentModel;
  48. using System.Globalization;
  49. using System.IO;
  50. using System.Runtime.Serialization;
  51. using System.Xml;
  52. using System.Xml.Schema;
  53. using System.Xml.Serialization;
  54. using System.Text.RegularExpressions;
  55. using Mono.Data.SqlExpressions;
  56. namespace System.Data {
  57. //[Designer]
  58. [ToolboxItem (false)]
  59. [DefaultEvent ("RowChanging")]
  60. [DefaultProperty ("TableName")]
  61. [DesignTimeVisible (false)]
  62. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DataTableEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  63. [Serializable]
  64. public partial class DataTable : MarshalByValueComponent, IListSource, ISupportInitialize, ISerializable {
  65. #region Fields
  66. internal DataSet dataSet;
  67. private bool _caseSensitive;
  68. private DataColumnCollection _columnCollection;
  69. private ConstraintCollection _constraintCollection;
  70. // never access it. Use DefaultView.
  71. private DataView _defaultView = null;
  72. private string _displayExpression;
  73. private PropertyCollection _extendedProperties;
  74. private CultureInfo _locale;
  75. private int _minimumCapacity;
  76. private string _nameSpace;
  77. private DataRelationCollection _childRelations;
  78. private DataRelationCollection _parentRelations;
  79. private string _prefix;
  80. private UniqueConstraint _primaryKeyConstraint;
  81. private DataRowCollection _rows;
  82. private ISite _site;
  83. private string _tableName;
  84. internal bool _duringDataLoad;
  85. internal bool _nullConstraintViolationDuringDataLoad;
  86. private bool dataSetPrevEnforceConstraints;
  87. private bool enforceConstraints = true;
  88. private DataRowBuilder _rowBuilder;
  89. private ArrayList _indexes;
  90. private RecordCache _recordCache;
  91. private int _defaultValuesRowIndex = -1;
  92. protected internal bool fInitInProgress;
  93. // If CaseSensitive property is changed once it does not anymore follow owner DataSet's
  94. // CaseSensitive property. So when you lost you virginity it's gone for ever
  95. private bool _virginCaseSensitive = true;
  96. private PropertyDescriptorCollection _propertyDescriptorsCache;
  97. static DataColumn[] _emptyColumnArray = new DataColumn[0];
  98. // Regex to parse the Sort string.
  99. static Regex SortRegex = new Regex ( @"^((\[(?<ColName>.+)\])|(?<ColName>\S+))([ ]+(?<Order>ASC|DESC))?$",
  100. RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);
  101. DataColumn [] _latestPrimaryKeyCols;
  102. #endregion //Fields
  103. /// <summary>
  104. /// Initializes a new instance of the DataTable class with no arguments.
  105. /// </summary>
  106. public DataTable ()
  107. {
  108. dataSet = null;
  109. _columnCollection = new DataColumnCollection(this);
  110. _constraintCollection = new ConstraintCollection(this);
  111. _extendedProperties = new PropertyCollection();
  112. _tableName = "";
  113. _nameSpace = null;
  114. _caseSensitive = false; //default value
  115. _displayExpression = null;
  116. _primaryKeyConstraint = null;
  117. _site = null;
  118. _rows = new DataRowCollection (this);
  119. _indexes = new ArrayList();
  120. _recordCache = new RecordCache(this);
  121. //LAMESPEC: spec says 25 impl does 50
  122. _minimumCapacity = 50;
  123. _childRelations = new DataRelationCollection.DataTableRelationCollection (this);
  124. _parentRelations = new DataRelationCollection.DataTableRelationCollection (this);
  125. }
  126. /// <summary>
  127. /// Intitalizes a new instance of the DataTable class with the specified table name.
  128. /// </summary>
  129. public DataTable (string tableName)
  130. : this ()
  131. {
  132. _tableName = tableName;
  133. }
  134. /// <summary>
  135. /// Initializes a new instance of the DataTable class with the SerializationInfo and the StreamingContext.
  136. /// </summary>
  137. protected DataTable (SerializationInfo info, StreamingContext context)
  138. : this ()
  139. {
  140. #if NET_2_0
  141. SerializationInfoEnumerator e = info.GetEnumerator ();
  142. SerializationFormat serializationFormat = SerializationFormat.Xml;
  143. while (e.MoveNext()) {
  144. if (e.ObjectType == typeof(System.Data.SerializationFormat)) {
  145. serializationFormat = (SerializationFormat) e.Value;
  146. break;
  147. }
  148. }
  149. if (serializationFormat == SerializationFormat.Xml) {
  150. #endif
  151. string schema = info.GetString ("XmlSchema");
  152. string data = info.GetString ("XmlDiffGram");
  153. DataSet ds = new DataSet ();
  154. ds.ReadXmlSchema (new StringReader (schema));
  155. ds.Tables [0].CopyProperties (this);
  156. ds = new DataSet ();
  157. ds.Tables.Add (this);
  158. ds.ReadXml (new StringReader (data), XmlReadMode.DiffGram);
  159. ds.Tables.Remove (this);
  160. /* keeping for a while. With the change above, we shouldn't have to consider
  161. * DataTable mode in schema inference/read.
  162. XmlSchemaMapper mapper = new XmlSchemaMapper (this);
  163. XmlTextReader xtr = new XmlTextReader(new StringReader (schema));
  164. mapper.Read (xtr);
  165. XmlDiffLoader loader = new XmlDiffLoader (this);
  166. xtr = new XmlTextReader(new StringReader (data));
  167. loader.Load (xtr);
  168. */
  169. #if NET_2_0
  170. } else /*if (Tables.RemotingFormat == SerializationFormat.Binary)*/ {
  171. BinaryDeserializeTable (info);
  172. }
  173. #endif
  174. }
  175. /// <summary>
  176. /// Indicates whether string comparisons within the table are case-sensitive.
  177. /// </summary>
  178. #if !NET_2_0
  179. [DataSysDescription ("Indicates whether comparing strings within the table is case sensitive.")]
  180. #endif
  181. public bool CaseSensitive {
  182. get {
  183. if (_virginCaseSensitive && dataSet != null)
  184. return dataSet.CaseSensitive;
  185. else
  186. return _caseSensitive;
  187. }
  188. set {
  189. if (_childRelations.Count > 0 || _parentRelations.Count > 0) {
  190. throw new ArgumentException ("Cannot change CaseSensitive or Locale property. This change would lead to at least one DataRelation or Constraint to have different Locale or CaseSensitive settings between its related tables.");
  191. }
  192. _virginCaseSensitive = false;
  193. _caseSensitive = value;
  194. ResetCaseSensitiveIndexes();
  195. }
  196. }
  197. internal ArrayList Indexes {
  198. get { return _indexes; }
  199. }
  200. internal void ChangedDataColumn (DataRow dr, DataColumn dc, object pv)
  201. {
  202. DataColumnChangeEventArgs e = new DataColumnChangeEventArgs (dr, dc, pv);
  203. OnColumnChanged (e);
  204. }
  205. internal void ChangingDataColumn (DataRow dr, DataColumn dc, object pv)
  206. {
  207. DataColumnChangeEventArgs e = new DataColumnChangeEventArgs (dr, dc, pv);
  208. OnColumnChanging (e);
  209. }
  210. internal void DeletedDataRow (DataRow dr, DataRowAction action)
  211. {
  212. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  213. OnRowDeleted (e);
  214. }
  215. internal void DeletingDataRow (DataRow dr, DataRowAction action)
  216. {
  217. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  218. OnRowDeleting (e);
  219. }
  220. internal void ChangedDataRow (DataRow dr, DataRowAction action)
  221. {
  222. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  223. OnRowChanged (e);
  224. }
  225. internal void ChangingDataRow (DataRow dr, DataRowAction action)
  226. {
  227. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  228. OnRowChanging (e);
  229. }
  230. /// <summary>
  231. /// Gets the collection of child relations for this DataTable.
  232. /// </summary>
  233. [Browsable (false)]
  234. #if !NET_2_0
  235. [DataSysDescription ("Returns the child relations for this table.")]
  236. #endif
  237. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  238. public DataRelationCollection ChildRelations {
  239. get { return _childRelations; }
  240. }
  241. /// <summary>
  242. /// Gets the collection of columns that belong to this table.
  243. /// </summary>
  244. [DataCategory ("Data")]
  245. #if !NET_2_0
  246. [DataSysDescription ("The collection that holds the columns for this table.")]
  247. #endif
  248. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  249. public DataColumnCollection Columns {
  250. get { return _columnCollection; }
  251. }
  252. /// <summary>
  253. /// Gets the collection of constraints maintained by this table.
  254. /// </summary>
  255. [DataCategory ("Data")]
  256. #if !NET_2_0
  257. [DataSysDescription ("The collection that holds the constraints for this table.")]
  258. #endif
  259. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  260. public ConstraintCollection Constraints {
  261. get { return _constraintCollection; }
  262. #if NET_2_0
  263. internal set { _constraintCollection = value; }
  264. #endif
  265. }
  266. /// <summary>
  267. /// Gets the DataSet that this table belongs to.
  268. /// </summary>
  269. [Browsable (false)]
  270. #if !NET_2_0
  271. [DataSysDescription ("Indicates the DataSet to which this table belongs.")]
  272. #endif
  273. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  274. public DataSet DataSet {
  275. get { return dataSet; }
  276. }
  277. /// <summary>
  278. /// Gets a customized view of the table which may
  279. /// include a filtered view, or a cursor position.
  280. /// </summary>
  281. [Browsable (false)]
  282. #if !NET_2_0
  283. [DataSysDescription ("This is the default DataView for the table.")]
  284. #endif
  285. public DataView DefaultView {
  286. get {
  287. if (_defaultView == null) {
  288. lock(this){
  289. if (_defaultView == null){
  290. if (dataSet != null)
  291. _defaultView = dataSet.DefaultViewManager.CreateDataView(this);
  292. else
  293. _defaultView = new DataView(this);
  294. }
  295. }
  296. }
  297. return _defaultView;
  298. }
  299. }
  300. /// <summary>
  301. /// Gets or sets the expression that will return
  302. /// a value used to represent this table in the user interface.
  303. /// </summary>
  304. [DataCategory ("Data")]
  305. #if !NET_2_0
  306. [DataSysDescription ("The expression used to compute the data-bound value of this row.")]
  307. #endif
  308. [DefaultValue ("")]
  309. public string DisplayExpression {
  310. get { return _displayExpression == null ? "" : _displayExpression; }
  311. set { _displayExpression = value; }
  312. }
  313. /// <summary>
  314. /// Gets the collection of customized user information.
  315. /// </summary>
  316. [Browsable (false)]
  317. [DataCategory ("Data")]
  318. #if !NET_2_0
  319. [DataSysDescription ("The collection that holds custom user information.")]
  320. #endif
  321. public PropertyCollection ExtendedProperties {
  322. get { return _extendedProperties; }
  323. }
  324. /// <summary>
  325. /// Gets a value indicating whether there are errors in
  326. /// any of the_rows in any of the tables of the DataSet to
  327. /// which the table belongs.
  328. /// </summary>
  329. [Browsable (false)]
  330. #if !NET_2_0
  331. [DataSysDescription ("Returns whether the table has errors.")]
  332. #endif
  333. public bool HasErrors {
  334. get {
  335. // we can not use the _hasError flag because we do not know when to turn it off!
  336. for (int i = 0; i < _rows.Count; i++) {
  337. if (_rows[i].HasErrors)
  338. return true;
  339. }
  340. return false;
  341. }
  342. }
  343. /// <summary>
  344. /// Gets or sets the locale information used to
  345. /// compare strings within the table.
  346. /// </summary>
  347. #if !NET_2_0
  348. [DataSysDescription ("Indicates a locale under which to compare strings within the table.")]
  349. #endif
  350. public CultureInfo Locale {
  351. get {
  352. // if the locale is null, we check for the DataSet locale
  353. // and if the DataSet is null we return the current culture.
  354. // this way if DataSet locale is changed, only if there is no locale for
  355. // the DataTable it influece the Locale get;
  356. if (_locale != null)
  357. return _locale;
  358. if (DataSet != null)
  359. return DataSet.Locale;
  360. return CultureInfo.CurrentCulture;
  361. }
  362. set {
  363. if (_childRelations.Count > 0 || _parentRelations.Count > 0) {
  364. throw new ArgumentException ("Cannot change CaseSensitive or Locale property. This change would lead to at least one DataRelation or Constraint to have different Locale or CaseSensitive settings between its related tables.");
  365. }
  366. if (_locale == null || !_locale.Equals(value))
  367. _locale = value;
  368. }
  369. }
  370. internal bool LocaleSpecified {
  371. get { return _locale != null; }
  372. }
  373. /// <summary>
  374. /// Gets or sets the initial starting size for this table.
  375. /// </summary>
  376. [DataCategory ("Data")]
  377. #if !NET_2_0
  378. [DataSysDescription ("Indicates an initial starting size for this table.")]
  379. #endif
  380. [DefaultValue (50)]
  381. public int MinimumCapacity {
  382. get { return _minimumCapacity; }
  383. set { _minimumCapacity = value; }
  384. }
  385. /// <summary>
  386. /// Gets or sets the namespace for the XML represenation
  387. /// of the data stored in the DataTable.
  388. /// </summary>
  389. [DataCategory ("Data")]
  390. #if !NET_2_0
  391. [DataSysDescription ("Indicates the XML uri namespace for the elements contained in this table.")]
  392. #endif
  393. public string Namespace {
  394. get {
  395. if (_nameSpace != null)
  396. return _nameSpace;
  397. if (DataSet != null)
  398. return DataSet.Namespace;
  399. return String.Empty;
  400. }
  401. set { _nameSpace = value; }
  402. }
  403. /// <summary>
  404. /// Gets the collection of parent relations for
  405. /// this DataTable.
  406. /// </summary>
  407. [Browsable (false)]
  408. #if !NET_2_0
  409. [DataSysDescription ("Returns the parent relations for this table.")]
  410. #endif
  411. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  412. public DataRelationCollection ParentRelations {
  413. get { return _parentRelations; }
  414. }
  415. /// <summary>
  416. /// Gets or sets the namespace for the XML represenation
  417. /// of the data stored in the DataTable.
  418. /// </summary>
  419. [DataCategory ("Data")]
  420. #if !NET_2_0
  421. [DataSysDescription ("Indicates the Prefix of the namespace used for this table in XML representation.")]
  422. #endif
  423. [DefaultValue ("")]
  424. public string Prefix {
  425. get { return _prefix == null ? "" : _prefix; }
  426. set {
  427. // Prefix cannot contain any special characters other than '_' and ':'
  428. for (int i = 0; i < value.Length; i++) {
  429. if (!(Char.IsLetterOrDigit (value [i])) && (value [i] != '_') && (value [i] != ':'))
  430. throw new DataException ("Prefix '" + value + "' is not valid, because it contains special characters.");
  431. }
  432. _prefix = value;
  433. }
  434. }
  435. /// <summary>
  436. /// Gets or sets an array of columns that function as
  437. /// primary keys for the data table.
  438. /// </summary>
  439. [DataCategory ("Data")]
  440. #if !NET_2_0
  441. [DataSysDescription ("Indicates the column(s) that represent the primary key for this table.")]
  442. #endif
  443. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.PrimaryKeyEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  444. [TypeConverterAttribute ("System.Data.PrimaryKeyTypeConverter, " + Consts.AssemblySystem_Data)]
  445. public DataColumn[] PrimaryKey {
  446. get {
  447. if (_primaryKeyConstraint == null)
  448. return new DataColumn[] {};
  449. return _primaryKeyConstraint.Columns;
  450. }
  451. set {
  452. if (value == null || value.Length == 0) {
  453. if (_primaryKeyConstraint != null) {
  454. _primaryKeyConstraint.SetIsPrimaryKey (false);
  455. Constraints.Remove(_primaryKeyConstraint);
  456. _primaryKeyConstraint = null;
  457. }
  458. return;
  459. }
  460. if (InitInProgress) {
  461. _latestPrimaryKeyCols = value;
  462. return;
  463. }
  464. // first check if value is the same as current PK.
  465. if (_primaryKeyConstraint != null &&
  466. DataColumn.AreColumnSetsTheSame (value, _primaryKeyConstraint.Columns))
  467. return;
  468. //Does constraint exist for these columns
  469. UniqueConstraint uc = UniqueConstraint.GetUniqueConstraintForColumnSet (this.Constraints, (DataColumn[]) value);
  470. //if constraint doesn't exist for columns
  471. //create new unique primary key constraint
  472. if (null == uc) {
  473. foreach (DataColumn Col in (DataColumn []) value) {
  474. if (Col.Table == null)
  475. break;
  476. if (Columns.IndexOf (Col) < 0)
  477. throw new ArgumentException ("PrimaryKey columns do not belong to this table.");
  478. }
  479. // create constraint with primary key indication set to false
  480. // to avoid recursion
  481. uc = new UniqueConstraint ((DataColumn []) value, false);
  482. Constraints.Add (uc);
  483. }
  484. //Remove the existing primary key
  485. if (_primaryKeyConstraint != null) {
  486. _primaryKeyConstraint.SetIsPrimaryKey (false);
  487. Constraints.Remove (_primaryKeyConstraint);
  488. _primaryKeyConstraint = null;
  489. }
  490. //set the constraint as the new primary key
  491. UniqueConstraint.SetAsPrimaryKey (Constraints, uc);
  492. _primaryKeyConstraint = uc;
  493. for (int j = 0; j < uc.Columns.Length; ++j)
  494. uc.Columns [j].AllowDBNull = false;
  495. }
  496. }
  497. internal UniqueConstraint PrimaryKeyConstraint {
  498. get { return _primaryKeyConstraint; }
  499. }
  500. /// <summary>
  501. /// Gets the collection of_rows that belong to this table.
  502. /// </summary>
  503. [Browsable (false)]
  504. #if !NET_2_0
  505. [DataSysDescription ("Indicates the collection that holds the rows of data for this table.")]
  506. #endif
  507. public DataRowCollection Rows {
  508. get { return _rows; }
  509. }
  510. /// <summary>
  511. /// Gets or sets an System.ComponentModel.ISite
  512. /// for the DataTable.
  513. /// </summary>
  514. [Browsable (false)]
  515. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  516. public override ISite Site {
  517. get { return _site; }
  518. set { _site = value; }
  519. }
  520. /// <summary>
  521. /// Gets or sets the name of the the DataTable.
  522. /// </summary>
  523. [DataCategory ("Data")]
  524. #if !NET_2_0
  525. [DataSysDescription ("Indicates the name used to look up this table in the Tables collection of a DataSet.")]
  526. #endif
  527. [DefaultValue ("")]
  528. [RefreshProperties (RefreshProperties.All)]
  529. public string TableName {
  530. get { return _tableName == null ? "" : _tableName; }
  531. set { _tableName = value; }
  532. }
  533. bool IListSource.ContainsListCollection {
  534. // the collection is a DataView
  535. get { return false; }
  536. }
  537. internal RecordCache RecordCache {
  538. get { return _recordCache; }
  539. }
  540. private DataRowBuilder RowBuilder {
  541. get {
  542. // initiate only one row builder.
  543. if (_rowBuilder == null)
  544. _rowBuilder = new DataRowBuilder (this, -1, 0);
  545. else
  546. // new row get id -1.
  547. _rowBuilder._rowId = -1;
  548. return _rowBuilder;
  549. }
  550. }
  551. internal bool EnforceConstraints {
  552. get { return enforceConstraints; }
  553. set {
  554. if (value == enforceConstraints)
  555. return;
  556. if (value) {
  557. // reset indexes since they may be outdated
  558. ResetIndexes();
  559. // assert all constraints
  560. foreach (Constraint constraint in Constraints)
  561. constraint.AssertConstraint ();
  562. AssertNotNullConstraints ();
  563. if (HasErrors)
  564. Constraint.ThrowConstraintException ();
  565. }
  566. enforceConstraints = value;
  567. }
  568. }
  569. internal void AssertNotNullConstraints ()
  570. {
  571. if (_duringDataLoad && !_nullConstraintViolationDuringDataLoad)
  572. return;
  573. bool seen = false;
  574. for (int i = 0; i < Columns.Count; i++) {
  575. DataColumn column = Columns [i];
  576. if (column.AllowDBNull)
  577. continue;
  578. for (int j = 0; j < Rows.Count; j++) {
  579. if (Rows [j].HasVersion (DataRowVersion.Default) && Rows[j].IsNull (column)) {
  580. seen = true;
  581. string errMsg = String.Format ("Column '{0}' does not allow DBNull.Value.",
  582. column.ColumnName);
  583. Rows [j].SetColumnError (i, errMsg);
  584. Rows [j].RowError = errMsg;
  585. }
  586. }
  587. }
  588. _nullConstraintViolationDuringDataLoad = seen;
  589. }
  590. internal bool RowsExist (DataColumn [] columns, DataColumn [] relatedColumns, DataRow row)
  591. {
  592. int curIndex = row.IndexFromVersion (DataRowVersion.Default);
  593. int tmpRecord = RecordCache.NewRecord ();
  594. try {
  595. for (int i = 0; i < relatedColumns.Length; i++)
  596. // according to MSDN: the DataType value for both columns must be identical.
  597. columns [i].DataContainer.CopyValue (relatedColumns [i].DataContainer, curIndex, tmpRecord);
  598. return RowsExist (columns, tmpRecord);
  599. } finally {
  600. RecordCache.DisposeRecord (tmpRecord);
  601. }
  602. }
  603. bool RowsExist (DataColumn [] columns, int index)
  604. {
  605. Index indx = this.FindIndex (columns);
  606. if (indx != null)
  607. return indx.Find (index) != -1;
  608. // we have to perform full-table scan
  609. // check that there is a parent for this row.
  610. foreach (DataRow thisRow in this.Rows) {
  611. if (thisRow.RowState == DataRowState.Deleted)
  612. continue;
  613. // check if the values in the columns are equal
  614. int thisIndex = thisRow.IndexFromVersion (
  615. thisRow.RowState == DataRowState.Modified ? DataRowVersion.Original : DataRowVersion.Current);
  616. bool match = true;
  617. foreach (DataColumn column in columns) {
  618. if (column.DataContainer.CompareValues (thisIndex, index) != 0) {
  619. match = false;
  620. break;
  621. }
  622. }
  623. if (match)
  624. return true;
  625. }
  626. return false;
  627. }
  628. /// <summary>
  629. /// Commits all the changes made to this table since the
  630. /// last time AcceptChanges was called.
  631. /// </summary>
  632. public void AcceptChanges ()
  633. {
  634. //FIXME: Do we need to validate anything here or
  635. //try to catch any errors to deal with them?
  636. // we do not use foreach because if one of the rows is in Delete state
  637. // it will be romeved from Rows and we get an exception.
  638. DataRow myRow;
  639. for (int i = 0; i < Rows.Count; ) {
  640. myRow = Rows [i];
  641. myRow.AcceptChanges ();
  642. // if the row state is Detached it meens that it was removed from row list (Rows)
  643. // so we should not increase 'i'.
  644. if (myRow.RowState != DataRowState.Detached)
  645. i++;
  646. }
  647. _rows.OnListChanged (this, new ListChangedEventArgs (ListChangedType.Reset, -1, -1));
  648. }
  649. /// <summary>
  650. /// Begins the initialization of a DataTable that is used
  651. /// on a form or used by another component. The initialization
  652. /// occurs at runtime.
  653. /// </summary>
  654. public
  655. #if NET_2_0
  656. virtual
  657. #endif
  658. void BeginInit ()
  659. {
  660. InitInProgress = true;
  661. #if NET_2_0
  662. tableInitialized = false;
  663. #endif
  664. }
  665. /// <summary>
  666. /// Turns off notifications, index maintenance, and
  667. /// constraints while loading data.
  668. /// </summary>
  669. public void BeginLoadData ()
  670. {
  671. if (this._duringDataLoad)
  672. return;
  673. //duringDataLoad is important to EndLoadData and
  674. //for not throwing unexpected exceptions.
  675. this._duringDataLoad = true;
  676. this._nullConstraintViolationDuringDataLoad = false;
  677. if (this.dataSet != null) {
  678. //Saving old Enforce constraints state for later
  679. //use in the EndLoadData.
  680. this.dataSetPrevEnforceConstraints = this.dataSet.EnforceConstraints;
  681. this.dataSet.EnforceConstraints = false;
  682. } else {
  683. //if table does not belong to any data set use EnforceConstraints of the table
  684. this.EnforceConstraints = false;
  685. }
  686. return;
  687. }
  688. /// <summary>
  689. /// Clears the DataTable of all data.
  690. /// </summary>
  691. public void Clear ()
  692. {
  693. // Foriegn key constraints are checked in _rows.Clear method
  694. _rows.Clear ();
  695. }
  696. /// <summary>
  697. /// Clones the structure of the DataTable, including
  698. /// all DataTable schemas and constraints.
  699. /// </summary>
  700. public virtual DataTable Clone ()
  701. {
  702. // Use Activator so we can use non-public constructors.
  703. DataTable Copy = (DataTable) Activator.CreateInstance (GetType (), true);
  704. CopyProperties (Copy);
  705. return Copy;
  706. }
  707. /// <summary>
  708. /// Computes the given expression on the current_rows that
  709. /// pass the filter criteria.
  710. /// </summary>
  711. public object Compute (string expression, string filter)
  712. {
  713. // expression is an aggregate function
  714. // filter is an expression used to limit rows
  715. DataRow [] rows = Select (filter);
  716. if (rows == null || rows.Length == 0)
  717. return DBNull.Value;
  718. Parser parser = new Parser (rows);
  719. IExpression expr = parser.Compile (expression);
  720. object obj = expr.Eval (rows [0]);
  721. return obj;
  722. }
  723. /// <summary>
  724. /// Copies both the structure and data for this DataTable.
  725. /// </summary>
  726. public DataTable Copy ()
  727. {
  728. DataTable copy = Clone ();
  729. copy._duringDataLoad = true;
  730. foreach (DataRow row in Rows) {
  731. DataRow newRow = copy.NewNotInitializedRow ();
  732. copy.Rows.AddInternal (newRow);
  733. CopyRow (row, newRow);
  734. }
  735. copy._duringDataLoad = false;
  736. // rebuild copy indexes after loading all rows
  737. copy.ResetIndexes ();
  738. return copy;
  739. }
  740. internal void CopyRow (DataRow fromRow, DataRow toRow)
  741. {
  742. if (fromRow.HasErrors)
  743. fromRow.CopyErrors (toRow);
  744. if (fromRow.HasVersion (DataRowVersion.Original))
  745. toRow.Original = toRow.Table.RecordCache.CopyRecord (this, fromRow.Original, -1);
  746. if (fromRow.HasVersion (DataRowVersion.Current)) {
  747. if (fromRow.Original != fromRow.Current)
  748. toRow.Current = toRow.Table.RecordCache.CopyRecord (this, fromRow.Current, -1);
  749. else
  750. toRow.Current = toRow.Original;
  751. }
  752. }
  753. private void CopyProperties (DataTable Copy)
  754. {
  755. Copy.CaseSensitive = CaseSensitive;
  756. Copy._virginCaseSensitive = _virginCaseSensitive;
  757. // Copy.ChildRelations
  758. // Copy.Constraints
  759. // Copy.Container
  760. // Copy.DefaultView
  761. // Copy.DesignMode
  762. Copy.DisplayExpression = DisplayExpression;
  763. if (ExtendedProperties.Count > 0) {
  764. // Cannot copy extended properties directly as the property does not have a set accessor
  765. Array tgtArray = Array.CreateInstance (typeof (object), ExtendedProperties.Count);
  766. ExtendedProperties.Keys.CopyTo (tgtArray, 0);
  767. for (int i=0; i < ExtendedProperties.Count; i++)
  768. Copy.ExtendedProperties.Add (tgtArray.GetValue (i), ExtendedProperties[tgtArray.GetValue (i)]);
  769. }
  770. Copy._locale = _locale;
  771. Copy.MinimumCapacity = MinimumCapacity;
  772. Copy.Namespace = Namespace;
  773. // Copy.ParentRelations
  774. Copy.Prefix = Prefix;
  775. Copy.Site = Site;
  776. Copy.TableName = TableName;
  777. bool isEmpty = Copy.Columns.Count == 0;
  778. // Copy columns
  779. foreach (DataColumn column in Columns) {
  780. // When cloning a table, the columns may be added in the default constructor.
  781. if (isEmpty || !Copy.Columns.Contains (column.ColumnName))
  782. Copy.Columns.Add (column.Clone ());
  783. }
  784. foreach (DataColumn column in Copy.Columns)
  785. column.CompileExpression ();
  786. CopyConstraints (Copy);
  787. // add primary key to the copy
  788. if (PrimaryKey.Length > 0) {
  789. DataColumn[] pColumns = new DataColumn[PrimaryKey.Length];
  790. for (int i = 0; i < pColumns.Length; i++)
  791. pColumns[i] = Copy.Columns[PrimaryKey[i].ColumnName];
  792. Copy.PrimaryKey = pColumns;
  793. }
  794. }
  795. private void CopyConstraints (DataTable copy)
  796. {
  797. UniqueConstraint origUc;
  798. UniqueConstraint copyUc;
  799. for (int i = 0; i < this.Constraints.Count; i++) {
  800. if (this.Constraints[i] is UniqueConstraint) {
  801. // typed ds can already contain the constraints
  802. if (copy.Constraints.Contains (this.Constraints [i].ConstraintName))
  803. continue;
  804. origUc = (UniqueConstraint) this.Constraints [i];
  805. DataColumn [] columns = new DataColumn [origUc.Columns.Length];
  806. for (int j = 0; j < columns.Length; j++)
  807. columns[j] = copy.Columns [origUc.Columns [j].ColumnName];
  808. copyUc = new UniqueConstraint (origUc.ConstraintName, columns, origUc.IsPrimaryKey);
  809. copy.Constraints.Add (copyUc);
  810. }
  811. }
  812. }
  813. /// <summary>
  814. /// Ends the initialization of a DataTable that is used
  815. /// on a form or used by another component. The
  816. /// initialization occurs at runtime.
  817. /// </summary>
  818. public
  819. #if NET_2_0
  820. virtual
  821. #endif
  822. void EndInit ()
  823. {
  824. InitInProgress = false;
  825. DataTableInitialized ();
  826. FinishInit ();
  827. }
  828. // defined in NET_2_0 profile
  829. partial void DataTableInitialized ();
  830. internal bool InitInProgress {
  831. get { return fInitInProgress; }
  832. set { fInitInProgress = value; }
  833. }
  834. internal void FinishInit ()
  835. {
  836. UniqueConstraint oldPK = _primaryKeyConstraint;
  837. // Columns shud be added 'before' the constraints
  838. Columns.PostAddRange ();
  839. // Add the constraints
  840. _constraintCollection.PostAddRange ();
  841. // ms.net behavior : If a PrimaryKey (UniqueConstraint) is added thru AddRange,
  842. // then it takes precedence over an direct assignment of PrimaryKey
  843. if (_primaryKeyConstraint == oldPK)
  844. PrimaryKey = _latestPrimaryKeyCols;
  845. }
  846. /// <summary>
  847. /// Turns on notifications, index maintenance, and
  848. /// constraints after loading data.
  849. /// </summary>
  850. public void EndLoadData ()
  851. {
  852. if (this._duringDataLoad) {
  853. //Getting back to previous EnforceConstraint state
  854. if (this.dataSet != null)
  855. this.dataSet.InternalEnforceConstraints (this.dataSetPrevEnforceConstraints, true);
  856. else
  857. this.EnforceConstraints = true;
  858. this._duringDataLoad = false;
  859. }
  860. }
  861. /// <summary>
  862. /// Gets a copy of the DataTable that contains all
  863. /// changes made to it since it was loaded or
  864. /// AcceptChanges was last called.
  865. /// </summary>
  866. public DataTable GetChanges ()
  867. {
  868. return GetChanges (DataRowState.Added | DataRowState.Deleted | DataRowState.Modified);
  869. }
  870. /// <summary>
  871. /// Gets a copy of the DataTable containing all
  872. /// changes made to it since it was last loaded, or
  873. /// since AcceptChanges was called, filtered by DataRowState.
  874. /// </summary>
  875. public DataTable GetChanges (DataRowState rowStates)
  876. {
  877. DataTable copyTable = null;
  878. foreach (DataRow row in Rows) {
  879. // The spec says relationship constraints may cause Unchanged parent rows to be included but
  880. // MS .NET 1.1 does not include Unchanged rows even if their child rows are changed.
  881. if (!row.IsRowChanged (rowStates))
  882. continue;
  883. if (copyTable == null)
  884. copyTable = Clone ();
  885. DataRow newRow = copyTable.NewNotInitializedRow ();
  886. // Don't check for ReadOnly, when cloning data to new uninitialized row.
  887. row.CopyValuesToRow (newRow, false);
  888. #if NET_2_0
  889. newRow.XmlRowID = row.XmlRowID;
  890. #endif
  891. copyTable.Rows.AddInternal (newRow);
  892. }
  893. return copyTable;
  894. }
  895. /// <summary>
  896. /// Gets an array of DataRow objects that contain errors.
  897. /// </summary>
  898. public DataRow [] GetErrors ()
  899. {
  900. ArrayList errors = new ArrayList();
  901. for (int i = 0; i < _rows.Count; i++) {
  902. if (_rows[i].HasErrors)
  903. errors.Add (_rows[i]);
  904. }
  905. DataRow[] ret = NewRowArray (errors.Count);
  906. errors.CopyTo (ret, 0);
  907. return ret;
  908. }
  909. /// <summary>
  910. /// This member is only meant to support Mono's infrastructure
  911. /// </summary>
  912. protected virtual DataTable CreateInstance ()
  913. {
  914. return Activator.CreateInstance (this.GetType (), true) as DataTable;
  915. }
  916. /// <summary>
  917. /// This member is only meant to support Mono's infrastructure
  918. /// </summary>
  919. protected virtual Type GetRowType ()
  920. {
  921. return typeof (DataRow);
  922. }
  923. /// <summary>
  924. /// This member is only meant to support Mono's infrastructure
  925. ///
  926. /// Used for Data Binding between System.Web.UI. controls
  927. /// like a DataGrid
  928. /// or
  929. /// System.Windows.Forms controls like a DataGrid
  930. /// </summary>
  931. IList IListSource.GetList ()
  932. {
  933. IList list = (IList) DefaultView;
  934. return list;
  935. }
  936. /// <summary>
  937. /// Copies a DataRow into a DataTable, preserving any
  938. /// property settings, as well as original and current values.
  939. /// </summary>
  940. public void ImportRow (DataRow row)
  941. {
  942. if (row.RowState == DataRowState.Detached)
  943. return;
  944. DataRow newRow = NewNotInitializedRow ();
  945. int original = -1;
  946. if (row.HasVersion (DataRowVersion.Original)) {
  947. original = row.IndexFromVersion (DataRowVersion.Original);
  948. newRow.Original = RecordCache.NewRecord ();
  949. RecordCache.CopyRecord (row.Table, original, newRow.Original);
  950. }
  951. if (row.HasVersion (DataRowVersion.Current)) {
  952. int current = row.IndexFromVersion (DataRowVersion.Current);
  953. if (current == original) {
  954. newRow.Current = newRow.Original;
  955. } else {
  956. newRow.Current = RecordCache.NewRecord ();
  957. RecordCache.CopyRecord (row.Table, current, newRow.Current);
  958. }
  959. }
  960. //Import the row only if RowState is not detached
  961. //Validation for Deleted Rows happens during Accept/RejectChanges
  962. if (row.RowState != DataRowState.Deleted)
  963. newRow.Validate ();
  964. else
  965. AddRowToIndexes (newRow);
  966. Rows.AddInternal(newRow);
  967. if (row.HasErrors)
  968. row.CopyErrors (newRow);
  969. }
  970. internal int DefaultValuesRowIndex {
  971. get { return _defaultValuesRowIndex; }
  972. }
  973. /// <summary>
  974. /// This member is only meant to support Mono's infrastructure
  975. /// </summary>
  976. #if NET_2_0
  977. public virtual
  978. #endif
  979. void
  980. #if !NET_2_0
  981. ISerializable.
  982. #endif
  983. GetObjectData (SerializationInfo info, StreamingContext context)
  984. {
  985. #if NET_2_0
  986. if (RemotingFormat == SerializationFormat.Xml) {
  987. #endif
  988. DataSet dset;
  989. if (dataSet != null)
  990. dset = dataSet;
  991. else {
  992. dset = new DataSet ("tmpDataSet");
  993. dset.Tables.Add (this);
  994. }
  995. StringWriter sw = new StringWriter ();
  996. XmlTextWriter tw = new XmlTextWriter (sw);
  997. tw.Formatting = Formatting.Indented;
  998. dset.WriteIndividualTableContent (tw, this, XmlWriteMode.DiffGram);
  999. tw.Close ();
  1000. StringWriter sw2 = new StringWriter ();
  1001. DataTableCollection tables = new DataTableCollection (dset);
  1002. tables.Add (this);
  1003. XmlSchemaWriter.WriteXmlSchema (dset, new XmlTextWriter (sw2), tables, null);
  1004. sw2.Close ();
  1005. info.AddValue ("XmlSchema", sw2.ToString(), typeof(string));
  1006. info.AddValue ("XmlDiffGram", sw.ToString(), typeof(string));
  1007. #if NET_2_0
  1008. } else /*if (RemotingFormat == SerializationFormat.Binary)*/ {
  1009. BinarySerializeProperty (info);
  1010. if (dataSet == null) {
  1011. for (int i = 0; i < Columns.Count; i++) {
  1012. info.AddValue ("DataTable.DataColumn_" + i + ".Expression",
  1013. Columns[i].Expression);
  1014. }
  1015. BinarySerialize (info, "DataTable_0.");
  1016. }
  1017. }
  1018. #endif
  1019. }
  1020. /// <summary>
  1021. /// Finds and updates a specific row. If no matching row
  1022. /// is found, a new row is created using the given values.
  1023. /// </summary>
  1024. public DataRow LoadDataRow (object [] values, bool fAcceptChanges)
  1025. {
  1026. DataRow row = null;
  1027. if (PrimaryKey.Length == 0) {
  1028. row = Rows.Add (values);
  1029. } else {
  1030. EnsureDefaultValueRowIndex ();
  1031. int newRecord = CreateRecord (values);
  1032. int existingRecord = _primaryKeyConstraint.Index.Find (newRecord);
  1033. if (existingRecord < 0) {
  1034. row = NewRowFromBuilder (RowBuilder);
  1035. row.Proposed = newRecord;
  1036. Rows.AddInternal(row);
  1037. if (!_duringDataLoad)
  1038. AddRowToIndexes (row);
  1039. } else {
  1040. row = RecordCache [existingRecord];
  1041. row.BeginEdit ();
  1042. row.ImportRecord (newRecord);
  1043. row.EndEdit ();
  1044. }
  1045. }
  1046. if (fAcceptChanges)
  1047. row.AcceptChanges ();
  1048. return row;
  1049. }
  1050. internal DataRow LoadDataRow (IDataRecord record, int[] mapping, int length, bool fAcceptChanges)
  1051. {
  1052. DataRow row = null;
  1053. int tmpRecord = this.RecordCache.NewRecord ();
  1054. try {
  1055. RecordCache.ReadIDataRecord (tmpRecord,record,mapping,length);
  1056. if (PrimaryKey.Length != 0) {
  1057. bool hasPrimaryValues = true;
  1058. foreach(DataColumn col in PrimaryKey) {
  1059. if(!(col.Ordinal < mapping.Length)) {
  1060. hasPrimaryValues = false;
  1061. break;
  1062. }
  1063. }
  1064. if (hasPrimaryValues) {
  1065. int existingRecord = _primaryKeyConstraint.Index.Find (tmpRecord);
  1066. if (existingRecord != -1)
  1067. row = RecordCache [existingRecord];
  1068. }
  1069. }
  1070. if (row == null) {
  1071. row = NewNotInitializedRow ();
  1072. row.Proposed = tmpRecord;
  1073. Rows.AddInternal (row);
  1074. } else {
  1075. row.BeginEdit ();
  1076. row.ImportRecord (tmpRecord);
  1077. row.EndEdit ();
  1078. }
  1079. if (fAcceptChanges)
  1080. row.AcceptChanges ();
  1081. } catch {
  1082. this.RecordCache.DisposeRecord (tmpRecord);
  1083. throw;
  1084. }
  1085. return row;
  1086. }
  1087. /// <summary>
  1088. /// Creates a new DataRow with the same schema as the table.
  1089. /// </summary>
  1090. public DataRow NewRow ()
  1091. {
  1092. EnsureDefaultValueRowIndex();
  1093. DataRow newRow = NewRowFromBuilder (RowBuilder);
  1094. newRow.Proposed = CreateRecord (null);
  1095. NewRowAdded (newRow);
  1096. return newRow;
  1097. }
  1098. // defined in the NET_2_0 profile
  1099. partial void NewRowAdded (DataRow dr);
  1100. internal int CreateRecord (object [] values)
  1101. {
  1102. int valCount = values != null ? values.Length : 0;
  1103. if (valCount > Columns.Count)
  1104. throw new ArgumentException ("Input array is longer than the number of columns in this table.");
  1105. int index = RecordCache.NewRecord ();
  1106. try {
  1107. for (int i = 0; i < valCount; i++) {
  1108. object value = values[i];
  1109. if (value == null)
  1110. Columns [i].SetDefaultValue (index);
  1111. else
  1112. Columns [i][index] = values [i];
  1113. }
  1114. for(int i = valCount; i < Columns.Count; i++)
  1115. Columns [i].SetDefaultValue (index);
  1116. return index;
  1117. } catch {
  1118. RecordCache.DisposeRecord (index);
  1119. throw;
  1120. }
  1121. }
  1122. private void EnsureDefaultValueRowIndex ()
  1123. {
  1124. // initialize default values row for the first time
  1125. if (_defaultValuesRowIndex == -1) {
  1126. _defaultValuesRowIndex = RecordCache.NewRecord();
  1127. for (int i = 0; i < Columns.Count; ++i) {
  1128. DataColumn column = Columns [i];
  1129. column.DataContainer [_defaultValuesRowIndex] = column.DefaultValue;
  1130. }
  1131. }
  1132. }
  1133. /// <summary>
  1134. /// This member supports the .NET Framework infrastructure
  1135. /// and is not intended to be used directly from your code.
  1136. /// </summary>
  1137. DataRow [] empty_rows;
  1138. protected internal DataRow [] NewRowArray (int size)
  1139. {
  1140. if (size == 0 && empty_rows != null)
  1141. return empty_rows;
  1142. Type t = GetRowType ();
  1143. /* Avoid reflection if possible */
  1144. DataRow [] rows = t == typeof (DataRow) ? new DataRow [size] : (DataRow []) Array.CreateInstance (t, size);
  1145. if (size == 0)
  1146. empty_rows = rows;
  1147. return rows;
  1148. }
  1149. /// <summary>
  1150. /// Creates a new row from an existing row.
  1151. /// </summary>
  1152. protected virtual DataRow NewRowFromBuilder (DataRowBuilder builder)
  1153. {
  1154. return new DataRow (builder);
  1155. }
  1156. internal DataRow NewNotInitializedRow ()
  1157. {
  1158. EnsureDefaultValueRowIndex ();
  1159. return NewRowFromBuilder (RowBuilder);
  1160. }
  1161. /// <summary>
  1162. /// Rolls back all changes that have been made to the
  1163. /// table since it was loaded, or the last time AcceptChanges
  1164. /// was called.
  1165. /// </summary>
  1166. public void RejectChanges ()
  1167. {
  1168. for (int i = _rows.Count - 1; i >= 0; i--) {
  1169. DataRow row = _rows [i];
  1170. if (row.RowState != DataRowState.Unchanged)
  1171. _rows [i].RejectChanges ();
  1172. }
  1173. }
  1174. /// <summary>
  1175. /// Resets the DataTable to its original state.
  1176. /// </summary>
  1177. public virtual void Reset ()
  1178. {
  1179. Clear ();
  1180. while (ParentRelations.Count > 0) {
  1181. if (dataSet.Relations.Contains (ParentRelations [ParentRelations.Count - 1].RelationName))
  1182. dataSet.Relations.Remove (ParentRelations [ParentRelations.Count - 1]);
  1183. }
  1184. while (ChildRelations.Count > 0) {
  1185. if (dataSet.Relations.Contains (ChildRelations [ChildRelations.Count - 1].RelationName))
  1186. dataSet.Relations.Remove (ChildRelations [ChildRelations.Count - 1]);
  1187. }
  1188. Constraints.Clear ();
  1189. Columns.Clear ();
  1190. }
  1191. /// <summary>
  1192. /// Gets an array of all DataRow objects.
  1193. /// </summary>
  1194. public DataRow[] Select ()
  1195. {
  1196. return Select (String.Empty, String.Empty, DataViewRowState.CurrentRows);
  1197. }
  1198. /// <summary>
  1199. /// Gets an array of all DataRow objects that match
  1200. /// the filter criteria in order of primary key (or
  1201. /// lacking one, order of addition.)
  1202. /// </summary>
  1203. public DataRow[] Select (string filterExpression)
  1204. {
  1205. return Select (filterExpression, String.Empty, DataViewRowState.CurrentRows);
  1206. }
  1207. /// <summary>
  1208. /// Gets an array of all DataRow objects that
  1209. /// match the filter criteria, in the the
  1210. /// specified sort order.
  1211. /// </summary>
  1212. public DataRow[] Select (string filterExpression, string sort)
  1213. {
  1214. return Select (filterExpression, sort, DataViewRowState.CurrentRows);
  1215. }
  1216. /// <summary>
  1217. /// Gets an array of all DataRow objects that match
  1218. /// the filter in the order of the sort, that match
  1219. /// the specified state.
  1220. /// </summary>
  1221. public DataRow [] Select (string filterExpression, string sort, DataViewRowState recordStates)
  1222. {
  1223. if (filterExpression == null)
  1224. filterExpression = String.Empty;
  1225. IExpression filter = null;
  1226. if (filterExpression != String.Empty) {
  1227. Parser parser = new Parser ();
  1228. filter = parser.Compile (filterExpression);
  1229. }
  1230. DataColumn [] columns = _emptyColumnArray;
  1231. ListSortDirection [] sorts = null;
  1232. if (sort != null && !sort.Equals(String.Empty))
  1233. columns = ParseSortString (this, sort, out sorts, false);
  1234. if (Rows.Count == 0)
  1235. return NewRowArray (0);
  1236. //if sort order is not given, sort it in Ascending order of the
  1237. //columns involved in the filter
  1238. if (columns.Length == 0 && filter != null) {
  1239. ArrayList list = new ArrayList ();
  1240. for (int i = 0; i < Columns.Count; ++i) {
  1241. if (!filter.DependsOn (Columns [i]))
  1242. continue;
  1243. list.Add (Columns [i]);
  1244. }
  1245. columns = (DataColumn []) list.ToArray (typeof (DataColumn));
  1246. }
  1247. bool addIndex = true;
  1248. if (filterExpression != String.Empty)
  1249. addIndex = false;
  1250. Index index = GetIndex (columns, sorts, recordStates, filter, false, addIndex);
  1251. int [] records = index.GetAll ();
  1252. DataRow [] dataRows = NewRowArray (index.Size);
  1253. for (int i = 0; i < dataRows.Length; i++)
  1254. dataRows [i] = RecordCache [records [i]];
  1255. return dataRows;
  1256. }
  1257. private void AddIndex (Index index)
  1258. {
  1259. if (_indexes == null)
  1260. _indexes = new ArrayList();
  1261. _indexes.Add (index);
  1262. }
  1263. /// <summary>
  1264. /// Returns index corresponding to columns,sort,row state filter and unique values given.
  1265. /// If such an index not exists, creates a new one.
  1266. /// </summary>
  1267. /// <param name="columns">Columns set of the index to look for.</param>
  1268. /// <param name="sort">Columns sort order of the index to look for.</param>
  1269. /// <param name="rowState">Rpw state filter of the index to look for.</param>
  1270. /// <param name="unique">Uniqueness of the index to look for.</param>
  1271. /// <param name="strict">Indicates whenever the index found should correspond in its uniquness to the value of unique parameter specified.</param>
  1272. /// <param name="reset">Indicates whenever the already existing index should be forced to reset.</param>
  1273. /// <returns></returns>
  1274. internal Index GetIndex (DataColumn[] columns, ListSortDirection[] sort, DataViewRowState rowState, IExpression filter, bool reset)
  1275. {
  1276. return GetIndex (columns, sort, rowState, filter, reset, true);
  1277. }
  1278. internal Index GetIndex (DataColumn[] columns, ListSortDirection[] sort,
  1279. DataViewRowState rowState, IExpression filter,
  1280. bool reset, bool addIndex)
  1281. {
  1282. Index index = FindIndex(columns, sort, rowState, filter);
  1283. if (index == null) {
  1284. index = new Index(new Key (this, columns, sort, rowState, filter));
  1285. if (addIndex)
  1286. AddIndex (index);
  1287. } else if (reset) {
  1288. // reset existing index only if asked for this
  1289. index.Reset ();
  1290. }
  1291. return index;
  1292. }
  1293. internal Index FindIndex (DataColumn[] columns)
  1294. {
  1295. return FindIndex (columns, null, DataViewRowState.None, null);
  1296. }
  1297. internal Index FindIndex (DataColumn[] columns, ListSortDirection[] sort, DataViewRowState rowState, IExpression filter)
  1298. {
  1299. if (Indexes != null) {
  1300. foreach (Index index in Indexes) {
  1301. if (index.Key.Equals (columns,sort,rowState, filter))
  1302. return index;
  1303. }
  1304. }
  1305. return null;
  1306. }
  1307. internal void ResetIndexes ()
  1308. {
  1309. foreach(Index index in Indexes)
  1310. index.Reset ();
  1311. }
  1312. internal void ResetCaseSensitiveIndexes ()
  1313. {
  1314. foreach (Index index in Indexes) {
  1315. bool containsStringcolumns = false;
  1316. foreach(DataColumn column in index.Key.Columns) {
  1317. if (column.DataType == typeof(string)) {
  1318. containsStringcolumns = true;
  1319. break;
  1320. }
  1321. }
  1322. if (!containsStringcolumns && index.Key.HasFilter) {
  1323. foreach (DataColumn column in Columns) {
  1324. if ((column.DataType == DbTypes.TypeOfString) && (index.Key.DependsOn (column))) {
  1325. containsStringcolumns = true;
  1326. break;
  1327. }
  1328. }
  1329. }
  1330. if (containsStringcolumns)
  1331. index.Reset ();
  1332. }
  1333. }
  1334. internal void DropIndex (Index index)
  1335. {
  1336. if (index != null && index.RefCount == 0) {
  1337. _indexes.Remove (index);
  1338. }
  1339. }
  1340. internal void DropReferencedIndexes (DataColumn column)
  1341. {
  1342. if (_indexes != null)
  1343. for (int i = _indexes.Count - 1; i >= 0; i--) {
  1344. Index indx = (Index)_indexes [i];
  1345. if (indx.Key.DependsOn (column))
  1346. _indexes.Remove (indx);
  1347. }
  1348. }
  1349. internal void AddRowToIndexes (DataRow row)
  1350. {
  1351. if (_indexes != null) {
  1352. for (int i = 0; i < _indexes.Count; ++i)
  1353. ((Index)_indexes [i]).Add (row);
  1354. }
  1355. }
  1356. internal void DeleteRowFromIndexes (DataRow row)
  1357. {
  1358. if (_indexes != null) {
  1359. foreach (Index indx in _indexes)
  1360. indx.Delete (row);
  1361. }
  1362. }
  1363. /// <summary>
  1364. /// Gets the TableName and DisplayExpression, if
  1365. /// there is one as a concatenated string.
  1366. /// </summary>
  1367. public override string ToString ()
  1368. {
  1369. //LAMESPEC: spec says concat the two. impl puts a
  1370. //plus sign infront of DisplayExpression
  1371. string retVal = TableName;
  1372. if(DisplayExpression != null && DisplayExpression != "")
  1373. retVal += " + " + DisplayExpression;
  1374. return retVal;
  1375. }
  1376. #region Events
  1377. /// <summary>
  1378. /// Raises the ColumnChanged event.
  1379. /// </summary>
  1380. protected virtual void OnColumnChanged (DataColumnChangeEventArgs e)
  1381. {
  1382. if (null != ColumnChanged)
  1383. ColumnChanged (this, e);
  1384. }
  1385. internal void RaiseOnColumnChanged (DataColumnChangeEventArgs e)
  1386. {
  1387. OnColumnChanged (e);
  1388. }
  1389. /// <summary>
  1390. /// Raises the ColumnChanging event.
  1391. /// </summary>
  1392. protected virtual void OnColumnChanging (DataColumnChangeEventArgs e)
  1393. {
  1394. if (null != ColumnChanging)
  1395. ColumnChanging (this, e);
  1396. }
  1397. internal void RaiseOnColumnChanging (DataColumnChangeEventArgs e)
  1398. {
  1399. OnColumnChanging(e);
  1400. }
  1401. /// <summary>
  1402. /// Raises the PropertyChanging event.
  1403. /// </summary>
  1404. [MonoTODO]
  1405. protected internal virtual void OnPropertyChanging (PropertyChangedEventArgs pcevent)
  1406. {
  1407. //if (null != PropertyChanging)
  1408. //{
  1409. // PropertyChanging (this, pcevent);
  1410. //}
  1411. throw new NotImplementedException ();
  1412. }
  1413. /// <summary>
  1414. /// Notifies the DataTable that a DataColumn is being removed.
  1415. /// </summary>
  1416. protected internal virtual void OnRemoveColumn (DataColumn column)
  1417. {
  1418. DropReferencedIndexes (column);
  1419. }
  1420. /// <summary>
  1421. /// Raises the RowChanged event.
  1422. /// </summary>
  1423. protected virtual void OnRowChanged (DataRowChangeEventArgs e)
  1424. {
  1425. if (null != RowChanged)
  1426. RowChanged (this, e);
  1427. }
  1428. /// <summary>
  1429. /// Raises the RowChanging event.
  1430. /// </summary>
  1431. protected virtual void OnRowChanging (DataRowChangeEventArgs e)
  1432. {
  1433. if (null != RowChanging)
  1434. RowChanging (this, e);
  1435. }
  1436. /// <summary>
  1437. /// Raises the RowDeleted event.
  1438. /// </summary>
  1439. protected virtual void OnRowDeleted (DataRowChangeEventArgs e)
  1440. {
  1441. if (null != RowDeleted)
  1442. RowDeleted (this, e);
  1443. }
  1444. /// <summary>
  1445. /// Raises the RowDeleting event.
  1446. /// </summary>
  1447. protected virtual void OnRowDeleting (DataRowChangeEventArgs e)
  1448. {
  1449. if (null != RowDeleting)
  1450. RowDeleting (this, e);
  1451. }
  1452. /// <summary>
  1453. /// Occurs when after a value has been changed for
  1454. /// the specified DataColumn in a DataRow.
  1455. /// </summary>
  1456. [DataCategory ("Data")]
  1457. #if !NET_2_0
  1458. [DataSysDescription ("Occurs when a value has been changed for this column.")]
  1459. #endif
  1460. public event DataColumnChangeEventHandler ColumnChanged;
  1461. /// <summary>
  1462. /// Occurs when a value is being changed for the specified …

Large files files are truncated, but you can click here to view the full file