DataTable.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065
  1. //
  2. // System.Data.DataTable.cs
  3. //
  4. // Author:
  5. // Franklin Wise <[email protected]>
  6. // Christopher Podurgiel ([email protected])
  7. // Daniel Morgan <[email protected]>
  8. // Rodrigo Moya <[email protected]>
  9. // Tim Coleman ([email protected])
  10. // Ville Palo <[email protected]>
  11. // Sureshkumar T <[email protected]>
  12. // Konstantin Triger <[email protected]>
  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. using System.ComponentModel;
  45. using System.Globalization;
  46. using System.IO;
  47. using System.Runtime.Serialization;
  48. using System.Xml;
  49. using System.Xml.Schema;
  50. using System.Text.RegularExpressions;
  51. using Mono.Data.SqlExpressions;
  52. namespace System.Data {
  53. //[Designer]
  54. [ToolboxItem (false)]
  55. [DefaultEvent ("RowChanging")]
  56. [DefaultProperty ("TableName")]
  57. [DesignTimeVisible (false)]
  58. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DataTableEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  59. [Serializable]
  60. public class DataTable : MarshalByValueComponent, IListSource, ISupportInitialize, ISerializable
  61. {
  62. #region Fields
  63. internal DataSet dataSet;
  64. private bool _caseSensitive;
  65. private DataColumnCollection _columnCollection;
  66. private ConstraintCollection _constraintCollection;
  67. // never access it. Use DefaultView.
  68. private DataView _defaultView = null;
  69. private string _displayExpression;
  70. private PropertyCollection _extendedProperties;
  71. private bool _hasErrors;
  72. private CultureInfo _locale;
  73. private int _minimumCapacity;
  74. private string _nameSpace;
  75. private DataRelationCollection _childRelations;
  76. private DataRelationCollection _parentRelations;
  77. private string _prefix;
  78. private UniqueConstraint _primaryKeyConstraint;
  79. private DataRowCollection _rows;
  80. private ISite _site;
  81. private string _tableName;
  82. private bool _containsListCollection;
  83. private string _encodedTableName;
  84. internal bool _duringDataLoad;
  85. internal bool _nullConstraintViolationDuringDataLoad;
  86. private bool dataSetPrevEnforceConstraints;
  87. private bool dataTablePrevEnforceConstraints;
  88. private bool enforceConstraints = true;
  89. private DataRowBuilder _rowBuilder;
  90. private ArrayList _indexes;
  91. private RecordCache _recordCache;
  92. private int _defaultValuesRowIndex = -1;
  93. protected internal bool initInProgress;
  94. // If CaseSensitive property is changed once it does not anymore follow owner DataSet's
  95. // CaseSensitive property. So when you lost you virginity it's gone for ever
  96. private bool _virginCaseSensitive = true;
  97. private PropertyDescriptorCollection _propertyDescriptorsCache;
  98. static DataColumn[] _emptyColumnArray = new DataColumn[0];
  99. // Regex to parse the Sort string.
  100. static Regex SortRegex = new Regex ( @"^((\[(?<ColName>.+)\])|(?<ColName>\S+))([ ]+(?<Order>ASC|DESC))?$",
  101. RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);
  102. DataColumn[] _latestPrimaryKeyCols;
  103. #endregion //Fields
  104. /// <summary>
  105. /// Initializes a new instance of the DataTable class with no arguments.
  106. /// </summary>
  107. public DataTable ()
  108. {
  109. dataSet = null;
  110. _columnCollection = new DataColumnCollection(this);
  111. _constraintCollection = new ConstraintCollection(this);
  112. _extendedProperties = new PropertyCollection();
  113. _tableName = "";
  114. _nameSpace = null;
  115. _caseSensitive = false; //default value
  116. _displayExpression = null;
  117. _primaryKeyConstraint = null;
  118. _site = null;
  119. _rows = new DataRowCollection (this);
  120. _indexes = new ArrayList();
  121. _recordCache = new RecordCache(this);
  122. //LAMESPEC: spec says 25 impl does 50
  123. _minimumCapacity = 50;
  124. _childRelations = new DataRelationCollection.DataTableRelationCollection (this);
  125. _parentRelations = new DataRelationCollection.DataTableRelationCollection (this);
  126. }
  127. /// <summary>
  128. /// Intitalizes a new instance of the DataTable class with the specified table name.
  129. /// </summary>
  130. public DataTable (string tableName) : 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. [MonoTODO]
  138. protected DataTable (SerializationInfo info, StreamingContext context)
  139. : this ()
  140. {
  141. string schema = info.GetString ("XmlSchema");
  142. string data = info.GetString ("XmlDiffGram");
  143. DataSet ds = new DataSet ();
  144. ds.ReadXmlSchema (new StringReader (schema));
  145. ds.Tables [0].CopyProperties (this);
  146. ds = new DataSet ();
  147. ds.Tables.Add (this);
  148. ds.ReadXml (new StringReader (data), XmlReadMode.DiffGram);
  149. ds.Tables.Remove (this);
  150. /* keeping for a while. With the change above, we shouldn't have to consider
  151. * DataTable mode in schema inference/read.
  152. XmlSchemaMapper mapper = new XmlSchemaMapper (this);
  153. XmlTextReader xtr = new XmlTextReader(new StringReader (schema));
  154. mapper.Read (xtr);
  155. XmlDiffLoader loader = new XmlDiffLoader (this);
  156. xtr = new XmlTextReader(new StringReader (data));
  157. loader.Load (xtr);
  158. */
  159. }
  160. #if NET_2_0
  161. public DataTable (string tableName, string tbNamespace)
  162. : this (tableName)
  163. {
  164. _nameSpace = tbNamespace;
  165. }
  166. #endif
  167. /// <summary>
  168. /// Indicates whether string comparisons within the table are case-sensitive.
  169. /// </summary>
  170. #if !NET_2_0
  171. [DataSysDescription ("Indicates whether comparing strings within the table is case sensitive.")]
  172. #endif
  173. public bool CaseSensitive {
  174. get {
  175. if (_virginCaseSensitive && dataSet != null)
  176. return dataSet.CaseSensitive;
  177. else
  178. return _caseSensitive;
  179. }
  180. set {
  181. if (_childRelations.Count > 0 || _parentRelations.Count > 0) {
  182. 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.");
  183. }
  184. _virginCaseSensitive = false;
  185. _caseSensitive = value;
  186. ResetCaseSensitiveIndexes();
  187. }
  188. }
  189. internal ArrayList Indexes{
  190. get { return _indexes; }
  191. }
  192. internal void ChangedDataColumn (DataRow dr, DataColumn dc, object pv)
  193. {
  194. DataColumnChangeEventArgs e = new DataColumnChangeEventArgs (dr, dc, pv);
  195. OnColumnChanged(e);
  196. }
  197. internal void ChangingDataColumn (DataRow dr, DataColumn dc, object pv)
  198. {
  199. DataColumnChangeEventArgs e = new DataColumnChangeEventArgs (dr, dc, pv);
  200. OnColumnChanging (e);
  201. }
  202. internal void DeletedDataRow (DataRow dr, DataRowAction action)
  203. {
  204. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  205. OnRowDeleted (e);
  206. }
  207. internal void DeletingDataRow (DataRow dr, DataRowAction action)
  208. {
  209. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  210. OnRowDeleting(e);
  211. }
  212. internal void ChangedDataRow (DataRow dr, DataRowAction action)
  213. {
  214. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  215. OnRowChanged (e);
  216. }
  217. internal void ChangingDataRow (DataRow dr, DataRowAction action)
  218. {
  219. DataRowChangeEventArgs e = new DataRowChangeEventArgs (dr, action);
  220. OnRowChanging (e);
  221. }
  222. /// <summary>
  223. /// Gets the collection of child relations for this DataTable.
  224. /// </summary>
  225. [Browsable (false)]
  226. #if !NET_2_0
  227. [DataSysDescription ("Returns the child relations for this table.")]
  228. #endif
  229. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  230. public DataRelationCollection ChildRelations {
  231. get {
  232. return _childRelations;
  233. }
  234. }
  235. /// <summary>
  236. /// Gets the collection of columns that belong to this table.
  237. /// </summary>
  238. [DataCategory ("Data")]
  239. #if !NET_2_0
  240. [DataSysDescription ("The collection that holds the columns for this table.")]
  241. #endif
  242. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  243. public DataColumnCollection Columns {
  244. get { return _columnCollection; }
  245. }
  246. /// <summary>
  247. /// Gets the collection of constraints maintained by this table.
  248. /// </summary>
  249. [DataCategory ("Data")]
  250. #if !NET_2_0
  251. [DataSysDescription ("The collection that holds the constraints for this table.")]
  252. #endif
  253. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  254. public ConstraintCollection Constraints {
  255. get { return _constraintCollection; }
  256. }
  257. /// <summary>
  258. /// Gets the DataSet that this table belongs to.
  259. /// </summary>
  260. [Browsable (false)]
  261. #if !NET_2_0
  262. [DataSysDescription ("Indicates the DataSet to which this table belongs.")]
  263. #endif
  264. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  265. public DataSet DataSet {
  266. get { return dataSet; }
  267. }
  268. /// <summary>
  269. /// Gets a customized view of the table which may
  270. /// include a filtered view, or a cursor position.
  271. /// </summary>
  272. [MonoTODO]
  273. [Browsable (false)]
  274. #if !NET_2_0
  275. [DataSysDescription ("This is the default DataView for the table.")]
  276. #endif
  277. public DataView DefaultView {
  278. get {
  279. if (_defaultView == null) {
  280. lock(this){
  281. if (_defaultView == null){
  282. if (dataSet != null)
  283. _defaultView = dataSet.DefaultViewManager.CreateDataView(this);
  284. else
  285. _defaultView = new DataView(this);
  286. }
  287. }
  288. }
  289. return _defaultView;
  290. }
  291. }
  292. /// <summary>
  293. /// Gets or sets the expression that will return
  294. /// a value used to represent this table in the user interface.
  295. /// </summary>
  296. [DataCategory ("Data")]
  297. #if !NET_2_0
  298. [DataSysDescription ("The expression used to compute the data-bound value of this row.")]
  299. #endif
  300. [DefaultValue ("")]
  301. public string DisplayExpression {
  302. get { return _displayExpression == null ? "" : _displayExpression; }
  303. set { _displayExpression = value; }
  304. }
  305. /// <summary>
  306. /// Gets the collection of customized user information.
  307. /// </summary>
  308. [Browsable (false)]
  309. [DataCategory ("Data")]
  310. #if !NET_2_0
  311. [DataSysDescription ("The collection that holds custom user information.")]
  312. #endif
  313. public PropertyCollection ExtendedProperties {
  314. get { return _extendedProperties; }
  315. }
  316. /// <summary>
  317. /// Gets a value indicating whether there are errors in
  318. /// any of the_rows in any of the tables of the DataSet to
  319. /// which the table belongs.
  320. /// </summary>
  321. [Browsable (false)]
  322. #if !NET_2_0
  323. [DataSysDescription ("Returns whether the table has errors.")]
  324. #endif
  325. public bool HasErrors {
  326. get {
  327. // we can not use the _hasError flag because we do not know when to turn it off!
  328. for (int i = 0; i < _rows.Count; i++)
  329. {
  330. if (_rows[i].HasErrors)
  331. return true;
  332. }
  333. return false;
  334. }
  335. }
  336. /// <summary>
  337. /// Gets or sets the locale information used to
  338. /// compare strings within the table.
  339. /// </summary>
  340. #if !NET_2_0
  341. [DataSysDescription ("Indicates a locale under which to compare strings within the table.")]
  342. #endif
  343. public CultureInfo Locale {
  344. get {
  345. // if the locale is null, we check for the DataSet locale
  346. // and if the DataSet is null we return the current culture.
  347. // this way if DataSet locale is changed, only if there is no locale for
  348. // the DataTable it influece the Locale get;
  349. if (_locale != null)
  350. return _locale;
  351. if (DataSet != null)
  352. return DataSet.Locale;
  353. return CultureInfo.CurrentCulture;
  354. }
  355. set {
  356. if (_childRelations.Count > 0 || _parentRelations.Count > 0) {
  357. 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.");
  358. }
  359. if (_locale == null || !_locale.Equals(value))
  360. _locale = value;
  361. }
  362. }
  363. /// <summary>
  364. /// Gets or sets the initial starting size for this table.
  365. /// </summary>
  366. [DataCategory ("Data")]
  367. #if !NET_2_0
  368. [DataSysDescription ("Indicates an initial starting size for this table.")]
  369. #endif
  370. [DefaultValue (50)]
  371. public int MinimumCapacity {
  372. get { return _minimumCapacity; }
  373. set { _minimumCapacity = value; }
  374. }
  375. /// <summary>
  376. /// Gets or sets the namespace for the XML represenation
  377. /// of the data stored in the DataTable.
  378. /// </summary>
  379. [DataCategory ("Data")]
  380. #if !NET_2_0
  381. [DataSysDescription ("Indicates the XML uri namespace for the elements contained in this table.")]
  382. #endif
  383. public string Namespace {
  384. get
  385. {
  386. if (_nameSpace != null)
  387. {
  388. return _nameSpace;
  389. }
  390. if (DataSet != null)
  391. {
  392. return DataSet.Namespace;
  393. }
  394. return String.Empty;
  395. }
  396. set { _nameSpace = value; }
  397. }
  398. /// <summary>
  399. /// Gets the collection of parent relations for
  400. /// this DataTable.
  401. /// </summary>
  402. [Browsable (false)]
  403. #if !NET_2_0
  404. [DataSysDescription ("Returns the parent relations for this table.")]
  405. #endif
  406. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  407. public DataRelationCollection ParentRelations {
  408. get {
  409. return _parentRelations;
  410. }
  411. }
  412. /// <summary>
  413. /// Gets or sets the namespace for the XML represenation
  414. /// of the data stored in the DataTable.
  415. /// </summary>
  416. [DataCategory ("Data")]
  417. #if !NET_2_0
  418. [DataSysDescription ("Indicates the Prefix of the namespace used for this table in XML representation.")]
  419. #endif
  420. [DefaultValue ("")]
  421. public string Prefix {
  422. get { return _prefix == null ? "" : _prefix; }
  423. set {
  424. // Prefix cannot contain any special characters other than '_' and ':'
  425. for (int i = 0; i < value.Length; i++) {
  426. if (!(Char.IsLetterOrDigit (value [i])) && (value [i] != '_') && (value [i] != ':'))
  427. throw new DataException ("Prefix '" + value + "' is not valid, because it contains special characters.");
  428. }
  429. _prefix = value;
  430. }
  431. }
  432. /// <summary>
  433. /// Gets or sets an array of columns that function as
  434. /// primary keys for the data table.
  435. /// </summary>
  436. [DataCategory ("Data")]
  437. #if !NET_2_0
  438. [DataSysDescription ("Indicates the column(s) that represent the primary key for this table.")]
  439. #endif
  440. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.PrimaryKeyEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  441. [TypeConverterAttribute ("System.Data.PrimaryKeyTypeConverter, " + Consts.AssemblySystem_Data)]
  442. public DataColumn[] PrimaryKey {
  443. get {
  444. if (_primaryKeyConstraint == null) {
  445. return new DataColumn[] {};
  446. }
  447. return _primaryKeyConstraint.Columns;
  448. }
  449. set {
  450. if (value == null || value.Length == 0) {
  451. if (_primaryKeyConstraint != null) {
  452. Constraints.Remove(_primaryKeyConstraint);
  453. _primaryKeyConstraint = null;
  454. }
  455. return;
  456. }
  457. if (InitInProgress) {
  458. _latestPrimaryKeyCols = value;
  459. return;
  460. }
  461. // first check if value is the same as current PK.
  462. if (_primaryKeyConstraint!= null && DataColumn.AreColumnSetsTheSame(value, _primaryKeyConstraint.Columns))
  463. return;
  464. //Does constraint exist for these columns
  465. UniqueConstraint uc = UniqueConstraint.GetUniqueConstraintForColumnSet(this.Constraints, (DataColumn[]) value);
  466. //if constraint doesn't exist for columns
  467. //create new unique primary key constraint
  468. if (null == uc) {
  469. foreach (DataColumn Col in (DataColumn[]) value) {
  470. if (Col.Table == null)
  471. break;
  472. if (Columns.IndexOf (Col) < 0)
  473. throw new ArgumentException ("PrimaryKey columns do not belong to this table.");
  474. }
  475. // create constraint with primary key indication set to false
  476. // to avoid recursion
  477. uc = new UniqueConstraint( (DataColumn[]) value, false);
  478. Constraints.Add (uc);
  479. }
  480. //Remove the existing primary key
  481. if (_primaryKeyConstraint != null) {
  482. Constraints.Remove(_primaryKeyConstraint);
  483. _primaryKeyConstraint = null;
  484. }
  485. //set the constraint as the new primary key
  486. UniqueConstraint.SetAsPrimaryKey(this.Constraints, uc);
  487. _primaryKeyConstraint = uc;
  488. for (int j=0; j < uc.Columns.Length; ++j)
  489. uc.Columns[j].AllowDBNull = false;
  490. }
  491. }
  492. internal UniqueConstraint PrimaryKeyConstraint {
  493. get{
  494. return _primaryKeyConstraint;
  495. }
  496. }
  497. /// <summary>
  498. /// Gets the collection of_rows that belong to this table.
  499. /// </summary>
  500. [Browsable (false)]
  501. #if !NET_2_0
  502. [DataSysDescription ("Indicates the collection that holds the rows of data for this table.")]
  503. #endif
  504. public DataRowCollection Rows {
  505. get { return _rows; }
  506. }
  507. /// <summary>
  508. /// Gets or sets an System.ComponentModel.ISite
  509. /// for the DataTable.
  510. /// </summary>
  511. [Browsable (false)]
  512. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  513. public override ISite Site {
  514. get { return _site; }
  515. set { _site = value; }
  516. }
  517. /// <summary>
  518. /// Gets or sets the name of the the DataTable.
  519. /// </summary>
  520. [DataCategory ("Data")]
  521. #if !NET_2_0
  522. [DataSysDescription ("Indicates the name used to look up this table in the Tables collection of a DataSet.")]
  523. #endif
  524. [DefaultValue ("")]
  525. [RefreshProperties (RefreshProperties.All)]
  526. public string TableName {
  527. get { return _tableName == null ? "" : _tableName; }
  528. set { _tableName = value; }
  529. }
  530. bool IListSource.ContainsListCollection {
  531. get {
  532. // the collection is a DataView
  533. return false;
  534. }
  535. }
  536. internal RecordCache RecordCache {
  537. get {
  538. return _recordCache;
  539. }
  540. }
  541. private DataRowBuilder RowBuilder
  542. {
  543. get
  544. {
  545. // initiate only one row builder.
  546. if (_rowBuilder == null)
  547. _rowBuilder = new DataRowBuilder (this, -1, 0);
  548. else
  549. // new row get id -1.
  550. _rowBuilder._rowId = -1;
  551. return _rowBuilder;
  552. }
  553. }
  554. internal bool EnforceConstraints {
  555. get { return enforceConstraints; }
  556. set {
  557. if (value != enforceConstraints) {
  558. if (value) {
  559. // reset indexes since they may be outdated
  560. ResetIndexes();
  561. bool violatesConstraints = false;
  562. //FIXME: use index for AllowDBNull
  563. for (int i = 0; i < Columns.Count; i++) {
  564. DataColumn column = Columns[i];
  565. if (!column.AllowDBNull) {
  566. for (int j = 0; j < Rows.Count; j++){
  567. if (Rows[j].IsNull(column)) {
  568. violatesConstraints = true;
  569. Rows[j].RowError = String.Format("Column '{0}' does not allow DBNull.Value.", column.ColumnName);
  570. }
  571. }
  572. }
  573. }
  574. if (violatesConstraints)
  575. Constraint.ThrowConstraintException();
  576. // assert all constraints
  577. foreach (Constraint constraint in Constraints) {
  578. constraint.AssertConstraint();
  579. }
  580. }
  581. enforceConstraints = value;
  582. }
  583. }
  584. }
  585. internal bool RowsExist(DataColumn[] columns, DataColumn[] relatedColumns,DataRow row)
  586. {
  587. int curIndex = row.IndexFromVersion(DataRowVersion.Default);
  588. int tmpRecord = RecordCache.NewRecord();
  589. try {
  590. for (int i = 0; i < relatedColumns.Length; i++) {
  591. // according to MSDN: the DataType value for both columns must be identical.
  592. columns[i].DataContainer.CopyValue(relatedColumns[i].DataContainer, curIndex, tmpRecord);
  593. }
  594. return RowsExist(columns, tmpRecord);
  595. }
  596. finally {
  597. RecordCache.DisposeRecord(tmpRecord);
  598. }
  599. }
  600. bool RowsExist(DataColumn[] columns, int index)
  601. {
  602. bool rowsExist = false;
  603. Index indx = this.FindIndex(columns);
  604. if (indx != null) { // lookup for a row in index
  605. rowsExist = (indx.Find(index) != -1);
  606. }
  607. else {
  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. bool match = true;
  613. // check if the values in the columns are equal
  614. int thisIndex = thisRow.IndexFromVersion(DataRowVersion.Current);
  615. foreach (DataColumn column in columns) {
  616. if (column.DataContainer.CompareValues(thisIndex, index) != 0) {
  617. match = false;
  618. break;
  619. }
  620. }
  621. if (match) {// there is a row with columns values equals to those supplied.
  622. rowsExist = true;
  623. break;
  624. }
  625. }
  626. }
  627. }
  628. return rowsExist;
  629. }
  630. /// <summary>
  631. /// Commits all the changes made to this table since the
  632. /// last time AcceptChanges was called.
  633. /// </summary>
  634. public void AcceptChanges ()
  635. {
  636. //FIXME: Do we need to validate anything here or
  637. //try to catch any errors to deal with them?
  638. // we do not use foreach because if one of the rows is in Delete state
  639. // it will be romeved from Rows and we get an exception.
  640. DataRow myRow;
  641. for (int i = 0; i < Rows.Count; )
  642. {
  643. myRow = Rows[i];
  644. myRow.AcceptChanges();
  645. // if the row state is Detached it meens that it was removed from row list (Rows)
  646. // so we should not increase 'i'.
  647. if (myRow.RowState != DataRowState.Detached)
  648. i++;
  649. }
  650. }
  651. /// <summary>
  652. /// Begins the initialization of a DataTable that is used
  653. /// on a form or used by another component. The initialization
  654. /// occurs at runtime.
  655. /// </summary>
  656. public virtual void BeginInit ()
  657. {
  658. InitInProgress = true;
  659. }
  660. /// <summary>
  661. /// Turns off notifications, index maintenance, and
  662. /// constraints while loading data.
  663. /// </summary>
  664. [MonoTODO]
  665. public void BeginLoadData ()
  666. {
  667. if (!this._duringDataLoad)
  668. {
  669. //duringDataLoad is important to EndLoadData and
  670. //for not throwing unexpected exceptions.
  671. this._duringDataLoad = true;
  672. this._nullConstraintViolationDuringDataLoad = false;
  673. if (this.dataSet != null)
  674. {
  675. //Saving old Enforce constraints state for later
  676. //use in the EndLoadData.
  677. this.dataSetPrevEnforceConstraints = this.dataSet.EnforceConstraints;
  678. this.dataSet.EnforceConstraints = false;
  679. }
  680. else {
  681. //if table does not belong to any data set use EnforceConstraints of the table
  682. this.EnforceConstraints = false;
  683. }
  684. }
  685. return;
  686. }
  687. /// <summary>
  688. /// Clears the DataTable of all data.
  689. /// </summary>
  690. public void Clear () {
  691. // Foriegn key constraints are checked in _rows.Clear method
  692. _rows.Clear ();
  693. foreach(Index index in Indexes)
  694. index.Reset();
  695. #if NET_2_0
  696. OnTableCleared (new DataTableClearEventArgs (this));
  697. #endif // NET_2_0
  698. }
  699. /// <summary>
  700. /// Clones the structure of the DataTable, including
  701. /// all DataTable schemas and constraints.
  702. /// </summary>
  703. public virtual DataTable Clone ()
  704. {
  705. // Use Activator so we can use non-public constructors.
  706. DataTable Copy = (DataTable) Activator.CreateInstance(GetType(), true);
  707. CopyProperties (Copy);
  708. return Copy;
  709. }
  710. /// <summary>
  711. /// Computes the given expression on the current_rows that
  712. /// pass the filter criteria.
  713. /// </summary>
  714. [MonoTODO]
  715. public object Compute (string expression, string filter)
  716. {
  717. // expression is an aggregate function
  718. // filter is an expression used to limit rows
  719. DataRow[] rows = Select(filter);
  720. if (rows == null || rows.Length == 0)
  721. return DBNull.Value;
  722. Parser parser = new Parser (rows);
  723. IExpression expr = parser.Compile (expression);
  724. object obj = expr.Eval (rows[0]);
  725. return obj;
  726. }
  727. /// <summary>
  728. /// Copies both the structure and data for this DataTable.
  729. /// </summary>
  730. public DataTable Copy ()
  731. {
  732. DataTable copy = Clone();
  733. copy._duringDataLoad = true;
  734. foreach (DataRow row in Rows) {
  735. DataRow newRow = copy.NewNotInitializedRow();
  736. copy.Rows.AddInternal(newRow);
  737. CopyRow(row,newRow);
  738. }
  739. copy._duringDataLoad = false;
  740. // rebuild copy indexes after loading all rows
  741. copy.ResetIndexes();
  742. return copy;
  743. }
  744. internal void CopyRow(DataRow fromRow,DataRow toRow)
  745. {
  746. if (fromRow.HasErrors) {
  747. fromRow.CopyErrors(toRow);
  748. }
  749. if (fromRow.HasVersion(DataRowVersion.Original)) {
  750. toRow.Original = toRow.Table.RecordCache.CopyRecord(this,fromRow.Original,-1);
  751. }
  752. if (fromRow.HasVersion(DataRowVersion.Current)) {
  753. if (fromRow.Original != fromRow.Current) {
  754. toRow.Current = toRow.Table.RecordCache.CopyRecord(this,fromRow.Current,-1);
  755. }
  756. else {
  757. toRow.Current = toRow.Original;
  758. }
  759. }
  760. }
  761. private void CopyProperties (DataTable Copy)
  762. {
  763. Copy.CaseSensitive = CaseSensitive;
  764. Copy._virginCaseSensitive = _virginCaseSensitive;
  765. // Copy.ChildRelations
  766. // Copy.Constraints
  767. // Copy.Container
  768. // Copy.DefaultView
  769. // Copy.DesignMode
  770. Copy.DisplayExpression = DisplayExpression;
  771. if(ExtendedProperties.Count > 0) {
  772. // Cannot copy extended properties directly as the property does not have a set accessor
  773. Array tgtArray = Array.CreateInstance( typeof (object), ExtendedProperties.Count);
  774. ExtendedProperties.Keys.CopyTo (tgtArray, 0);
  775. for (int i=0; i < ExtendedProperties.Count; i++)
  776. Copy.ExtendedProperties.Add (tgtArray.GetValue (i), ExtendedProperties[tgtArray.GetValue (i)]);
  777. }
  778. Copy.Locale = Locale;
  779. Copy.MinimumCapacity = MinimumCapacity;
  780. Copy.Namespace = Namespace;
  781. // Copy.ParentRelations
  782. Copy.Prefix = Prefix;
  783. Copy.Site = Site;
  784. Copy.TableName = TableName;
  785. bool isEmpty = Copy.Columns.Count == 0;
  786. // Copy columns
  787. foreach (DataColumn column in Columns) {
  788. // When cloning a table, the columns may be added in the default constructor.
  789. if (isEmpty || !Copy.Columns.Contains(column.ColumnName)) {
  790. Copy.Columns.Add (column.Clone());
  791. }
  792. }
  793. CopyConstraints(Copy);
  794. // add primary key to the copy
  795. if (PrimaryKey.Length > 0) {
  796. DataColumn[] pColumns = new DataColumn[PrimaryKey.Length];
  797. for (int i = 0; i < pColumns.Length; i++)
  798. pColumns[i] = Copy.Columns[PrimaryKey[i].ColumnName];
  799. Copy.PrimaryKey = pColumns;
  800. }
  801. }
  802. private void CopyConstraints(DataTable copy)
  803. {
  804. UniqueConstraint origUc;
  805. UniqueConstraint copyUc;
  806. for (int i = 0; i < this.Constraints.Count; i++)
  807. {
  808. if (this.Constraints[i] is UniqueConstraint)
  809. {
  810. // typed ds can already contain the constraints
  811. if (copy.Constraints.Contains (this.Constraints [i].ConstraintName))
  812. continue;
  813. origUc = (UniqueConstraint)this.Constraints[i];
  814. DataColumn[] columns = new DataColumn[origUc.Columns.Length];
  815. for (int j = 0; j < columns.Length; j++)
  816. columns[j] = copy.Columns[origUc.Columns[j].ColumnName];
  817. copyUc = new UniqueConstraint(origUc.ConstraintName, columns, origUc.IsPrimaryKey);
  818. copy.Constraints.Add(copyUc);
  819. }
  820. }
  821. }
  822. /// <summary>
  823. /// Ends the initialization of a DataTable that is used
  824. /// on a form or used by another component. The
  825. /// initialization occurs at runtime.
  826. /// </summary>
  827. [MonoTODO]
  828. public virtual void EndInit ()
  829. {
  830. InitInProgress = false;
  831. FinishInit ();
  832. }
  833. internal bool InitInProgress {
  834. get { return initInProgress; }
  835. set { initInProgress = value; }
  836. }
  837. internal void FinishInit ()
  838. {
  839. UniqueConstraint oldPK = _primaryKeyConstraint;
  840. // Columns shud be added 'before' the constraints
  841. Columns.PostAddRange ();
  842. // Add the constraints
  843. _constraintCollection.PostAddRange ();
  844. // ms.net behavior : If a PrimaryKey (UniqueConstraint) is added thru AddRange,
  845. // then it takes precedence over an direct assignment of PrimaryKey
  846. if (_primaryKeyConstraint == oldPK)
  847. PrimaryKey = _latestPrimaryKeyCols;
  848. }
  849. /// <summary>
  850. /// Turns on notifications, index maintenance, and
  851. /// constraints after loading data.
  852. /// </summary>
  853. public void EndLoadData()
  854. {
  855. if (this._duringDataLoad) {
  856. if(this._nullConstraintViolationDuringDataLoad) {
  857. this._nullConstraintViolationDuringDataLoad = false;
  858. throw new ConstraintException ("Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.");
  859. }
  860. if (this.dataSet !=null) {
  861. //Getting back to previous EnforceConstraint state
  862. this.dataSet.InternalEnforceConstraints(this.dataSetPrevEnforceConstraints,true);
  863. }
  864. else {
  865. //Getting back to the table's previous EnforceConstraint state
  866. this.EnforceConstraints = true;
  867. }
  868. //Returning from loading mode, raising exceptions as usual
  869. this._duringDataLoad = false;
  870. }
  871. }
  872. /// <summary>
  873. /// Gets a copy of the DataTable that contains all
  874. /// changes made to it since it was loaded or
  875. /// AcceptChanges was last called.
  876. /// </summary>
  877. public DataTable GetChanges()
  878. {
  879. return GetChanges(DataRowState.Added | DataRowState.Deleted | DataRowState.Modified);
  880. }
  881. /// <summary>
  882. /// Gets a copy of the DataTable containing all
  883. /// changes made to it since it was last loaded, or
  884. /// since AcceptChanges was called, filtered by DataRowState.
  885. /// </summary>
  886. public DataTable GetChanges(DataRowState rowStates)
  887. {
  888. DataTable copyTable = null;
  889. IEnumerator rowEnumerator = Rows.GetEnumerator();
  890. while (rowEnumerator.MoveNext()) {
  891. DataRow row = (DataRow)rowEnumerator.Current;
  892. // The spec says relationship constraints may cause Unchanged parent rows to be included but
  893. // MS .NET 1.1 does not include Unchanged rows even if their child rows are changed.
  894. if (row.IsRowChanged(rowStates)) {
  895. if (copyTable == null)
  896. copyTable = Clone();
  897. DataRow newRow = copyTable.NewNotInitializedRow();
  898. row.CopyValuesToRow(newRow);
  899. copyTable.Rows.AddInternal (newRow);
  900. }
  901. }
  902. return copyTable;
  903. }
  904. #if NET_2_0
  905. [MonoTODO]
  906. public DataTableReader GetDataReader ()
  907. {
  908. throw new NotImplementedException ();
  909. }
  910. #endif
  911. /// <summary>
  912. /// Gets an array of DataRow objects that contain errors.
  913. /// </summary>
  914. public DataRow[] GetErrors ()
  915. {
  916. ArrayList errors = new ArrayList();
  917. for (int i = 0; i < _rows.Count; i++)
  918. {
  919. if (_rows[i].HasErrors)
  920. errors.Add(_rows[i]);
  921. }
  922. DataRow[] ret = NewRowArray(errors.Count);
  923. errors.CopyTo(ret, 0);
  924. return ret;
  925. }
  926. /// <summary>
  927. /// This member is only meant to support Mono's infrastructure
  928. /// </summary>
  929. protected virtual DataTable CreateInstance ()
  930. {
  931. return Activator.CreateInstance (this.GetType (), true) as DataTable;
  932. }
  933. /// <summary>
  934. /// This member is only meant to support Mono's infrastructure
  935. /// </summary>
  936. protected virtual Type GetRowType ()
  937. {
  938. return typeof (DataRow);
  939. }
  940. /// <summary>
  941. /// This member is only meant to support Mono's infrastructure
  942. ///
  943. /// Used for Data Binding between System.Web.UI. controls
  944. /// like a DataGrid
  945. /// or
  946. /// System.Windows.Forms controls like a DataGrid
  947. /// </summary>
  948. IList IListSource.GetList ()
  949. {
  950. IList list = (IList) DefaultView;
  951. return list;
  952. }
  953. /// <summary>
  954. /// Copies a DataRow into a DataTable, preserving any
  955. /// property settings, as well as original and current values.
  956. /// </summary>
  957. public void ImportRow (DataRow row)
  958. {
  959. if (row.RowState == DataRowState.Detached)
  960. return;
  961. DataRow newRow = NewNotInitializedRow();
  962. int original = -1;
  963. if (row.HasVersion(DataRowVersion.Original)) {
  964. original = row.IndexFromVersion(DataRowVersion.Original);
  965. newRow.Original = RecordCache.NewRecord();
  966. RecordCache.CopyRecord(row.Table,original,newRow.Original);
  967. }
  968. if (row.HasVersion(DataRowVersion.Current)) {
  969. int current = row.IndexFromVersion(DataRowVersion.Current);
  970. if (current == original)
  971. newRow.Current = newRow.Original;
  972. else {
  973. newRow.Current = RecordCache.NewRecord();
  974. RecordCache.CopyRecord(row.Table,current,newRow.Current);
  975. }
  976. }
  977. //Import the row only if RowState is not detached
  978. //Validation for Deleted Rows happens during Accept/RejectChanges
  979. if (row.RowState != DataRowState.Deleted)
  980. newRow.Validate();
  981. else
  982. AddRowToIndexes (newRow);
  983. Rows.AddInternal(newRow);
  984. if (row.HasErrors) {
  985. row.CopyErrors(newRow);
  986. }
  987. }
  988. internal int DefaultValuesRowIndex
  989. {
  990. get {
  991. return _defaultValuesRowIndex;
  992. }
  993. }
  994. /// <summary>
  995. /// This member is only meant to support Mono's infrastructure
  996. /// </summary>
  997. void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
  998. {
  999. DataSet dset;
  1000. if (dataSet != null)
  1001. dset = dataSet;
  1002. else {
  1003. dset = new DataSet ("tmpDataSet");
  1004. dset.Tables.Add (this);
  1005. }
  1006. StringWriter sw = new StringWriter ();
  1007. XmlTextWriter tw = new XmlTextWriter (sw);
  1008. tw.Formatting = Formatting.Indented;
  1009. dset.WriteIndividualTableContent (tw, this, XmlWriteMode.DiffGram);
  1010. tw.Close ();
  1011. StringWriter sw2 = new StringWriter ();
  1012. DataTableCollection tables = new DataTableCollection (dset);
  1013. tables.Add (this);
  1014. XmlSchemaWriter.WriteXmlSchema (dset, new XmlTextWriter (sw2), tables, null);
  1015. sw2.Close ();
  1016. info.AddValue ("XmlSchema", sw2.ToString(), typeof(string));
  1017. info.AddValue ("XmlDiffGram", sw.ToString(), typeof(string));
  1018. }
  1019. #if NET_2_0
  1020. /// <summary>
  1021. /// Loads the table with the values from the reader
  1022. /// </summary>
  1023. public void Load (IDataReader reader)
  1024. {
  1025. Load (reader, LoadOption.PreserveChanges);
  1026. }
  1027. /// <summary>
  1028. /// Loads the table with the values from the reader and the pattern
  1029. /// of the changes to the existing rows or the new rows are based on
  1030. /// the LoadOption passed.
  1031. /// </summary>
  1032. public void Load (IDataReader reader, LoadOption loadOption)
  1033. {
  1034. bool prevEnforceConstr = this.EnforceConstraints;
  1035. try {
  1036. this.EnforceConstraints = false;
  1037. int [] mapping = DbDataAdapter.BuildSchema (reader, this, SchemaType.Mapped,
  1038. MissingSchemaAction.AddWithKey,
  1039. MissingMappingAction.Passthrough,
  1040. new DataTableMappingCollection ());
  1041. DbDataAdapter.FillFromReader (this,
  1042. reader,
  1043. 0, // start from
  1044. 0, // all records
  1045. mapping,
  1046. loadOption);
  1047. } finally {
  1048. this.EnforceConstraints = prevEnforceConstr;
  1049. }
  1050. }
  1051. #endif
  1052. /// <summary>
  1053. /// Finds and updates a specific row. If no matching row
  1054. /// is found, a new row is created using the given values.
  1055. /// </summary>
  1056. public DataRow LoadDataRow (object[] values, bool fAcceptChanges)
  1057. {
  1058. DataRow row = null;
  1059. if (PrimaryKey.Length == 0) {
  1060. row = Rows.Add (values);
  1061. if (fAcceptChanges)
  1062. row.AcceptChanges ();
  1063. }
  1064. else {
  1065. int newRecord = CreateRecord(values);
  1066. int existingRecord = _primaryKeyConstraint.Index.Find(newRecord);
  1067. if (existingRecord < 0) {
  1068. row = NewRowFromBuilder (RowBuilder);
  1069. row.Proposed = newRecord;
  1070. Rows.AddInternal(row);
  1071. }
  1072. else {
  1073. row = RecordCache[existingRecord];
  1074. row.BeginEdit();
  1075. row.ImportRecord(newRecord);
  1076. row.EndEdit();
  1077. }
  1078. if (fAcceptChanges)
  1079. row.AcceptChanges ();
  1080. }
  1081. return row;
  1082. }
  1083. internal DataRow LoadDataRow(IDataRecord record, int[] mapping, int length, bool fAcceptChanges)
  1084. {
  1085. DataRow row = null;
  1086. int tmpRecord = this.RecordCache.NewRecord();
  1087. try {
  1088. RecordCache.ReadIDataRecord(tmpRecord,record,mapping,length);
  1089. if (PrimaryKey.Length != 0) {
  1090. bool hasPrimaryValues = true;
  1091. foreach(DataColumn col in PrimaryKey) {
  1092. if(!(col.Ordinal < mapping.Length)) {
  1093. hasPrimaryValues = false;
  1094. break;
  1095. }
  1096. }
  1097. if (hasPrimaryValues) {
  1098. // find the row in the table.
  1099. row = Rows.Find(tmpRecord);
  1100. }
  1101. }
  1102. bool shouldUpdateIndex = false;
  1103. if (row == null) {
  1104. row = NewNotInitializedRow();
  1105. row.ImportRecord(tmpRecord);
  1106. Rows.AddInternal (row);
  1107. shouldUpdateIndex = true;
  1108. }
  1109. else {
  1110. // Proposed = tmpRecord
  1111. row.ImportRecord(tmpRecord);
  1112. }
  1113. if (fAcceptChanges) {
  1114. row.AcceptChanges();
  1115. }
  1116. if (shouldUpdateIndex && !fAcceptChanges) {
  1117. AddRowToIndexes(row);
  1118. }
  1119. }
  1120. catch(Exception e) {
  1121. this.RecordCache.DisposeRecord(tmpRecord);
  1122. throw e;
  1123. }
  1124. return row;
  1125. }
  1126. #if NET_2_0
  1127. /// <summary>
  1128. /// Loads the given values into an existing row if matches or creates
  1129. /// the new row popluated with the values.
  1130. /// </summary>
  1131. /// <remarks>
  1132. /// This method searches for the values using primary keys and it first
  1133. /// searches using the original values of the rows and if not found, it
  1134. /// searches using the current version of the row.
  1135. /// </remarks>
  1136. public DataRow LoadDataRow (object [] values, LoadOption loadOption)
  1137. {
  1138. DataRow row = null;
  1139. // Find Data DataRow
  1140. if (this.PrimaryKey.Length > 0) {
  1141. object [] keys = new object [PrimaryKey.Length];
  1142. for (int i=0; i < PrimaryKey.Length; i++)
  1143. keys [i] = values [PrimaryKey [i].Ordinal];
  1144. row = Rows.Find(keys, DataViewRowState.OriginalRows);
  1145. if (row == null)
  1146. row = Rows.Find (keys);
  1147. }
  1148. // If not found, add new row
  1149. if (row == null
  1150. || (row.RowState == DataRowState.Deleted
  1151. && loadOption == LoadOption.Upsert)) {
  1152. row = NewNotInitializedRow ();
  1153. row.ImportRecord (CreateRecord(values));
  1154. row.Validate(); // this adds to index ;-)
  1155. if (loadOption == LoadOption.OverwriteChanges ||
  1156. loadOption == LoadOption.PreserveChanges) {
  1157. Rows.AddInternal(row);
  1158. ChangingDataRow (row, DataRowAction.ChangeCurrentAndOriginal);
  1159. row.Original = row.Current;
  1160. ChangedDataRow (row, DataRowAction.ChangeCurrentAndOriginal);
  1161. } else
  1162. Rows.AddInternal(row);
  1163. return row;
  1164. }
  1165. if (row.RowState == DataRowState.Deleted
  1166. && loadOption == LoadOption.OverwriteChanges)
  1167. row.RejectChanges ();
  1168. row.Load (values, loadOption);
  1169. return row;
  1170. }
  1171. [MonoTODO]
  1172. public void Merge (DataTable table)
  1173. {
  1174. throw new NotImplementedException ();
  1175. }
  1176. [MonoTODO]
  1177. public void Merge (DataTable table, bool preserveChanges)
  1178. {
  1179. throw new NotImplementedException ();
  1180. }
  1181. [MonoTODO]
  1182. public void Merge (DataTable table, bool preserveChanges, MissingSchemaAction missingSchemaAction)
  1183. {
  1184. throw new NotImplementedException ();
  1185. }
  1186. #endif
  1187. /// <summary>
  1188. /// Creates a new DataRow with the same schema as the table.
  1189. /// </summary>
  1190. public DataRow NewRow ()
  1191. {
  1192. EnsureDefaultValueRowIndex();
  1193. DataRow newRow = NewRowFromBuilder (RowBuilder);
  1194. newRow.Proposed = CreateRecord(null);
  1195. return newRow;
  1196. }
  1197. internal int CreateRecord(object[] values) {
  1198. int valCount = values != null ? values.Length : 0;
  1199. if (valCount > Columns.Count)
  1200. throw new ArgumentException("Input array is longer than the number of columns in this table.");
  1201. int index = RecordCache.NewRecord();
  1202. try {
  1203. for (int i = 0; i < valCount; i++) {
  1204. object value = values[i];
  1205. if (value == null)
  1206. Columns[i].SetDefaultValue(index);
  1207. else
  1208. Columns[i][index] = values[i];
  1209. }
  1210. for(int i = valCount; i < Columns.Count; i++) {
  1211. Columns[i].SetDefaultValue(index);
  1212. }
  1213. return index;
  1214. }
  1215. catch {
  1216. RecordCache.DisposeRecord(index);
  1217. throw;
  1218. }
  1219. }
  1220. private void EnsureDefaultValueRowIndex()
  1221. {
  1222. // initialize default values row for the first time
  1223. if ( _defaultValuesRowIndex == -1 ) {
  1224. _defaultValuesRowIndex = RecordCache.NewRecord();
  1225. foreach(DataColumn column in Columns) {
  1226. column.DataContainer[_defaultValuesRowIndex] = column.DefaultValue;
  1227. }
  1228. }
  1229. }
  1230. #if NET_2_0
  1231. internal int CompareRecords(int x, int y) {
  1232. for (int col = 0; col < Columns.Count; col++) {
  1233. int res = Columns[col].DataContainer.CompareValues (x, y);
  1234. if (res != 0)
  1235. return res;
  1236. }
  1237. return 0;
  1238. }
  1239. #endif
  1240. /// <summary>
  1241. /// This member supports the .NET Framework infrastructure
  1242. /// and is not intended to be used directly from your code.
  1243. /// </summary>
  1244. protected internal DataRow[] NewRowArray (int size)
  1245. {
  1246. return (DataRow[]) Array.CreateInstance (GetRowType (), size);
  1247. }
  1248. /// <summary>
  1249. /// Creates a new row from an existing row.
  1250. /// </summary>
  1251. protected virtual DataRow NewRowFromBuilder (DataRowBuilder builder)
  1252. {
  1253. return new DataRow (builder);
  1254. }
  1255. internal DataRow NewNotInitializedRow()
  1256. {
  1257. EnsureDefaultValueRowIndex();
  1258. return NewRowFromBuilder (RowBuilder);
  1259. }
  1260. #if NET_2_0
  1261. [MonoTODO]
  1262. XmlReadMode ReadXml (Stream stream)
  1263. {
  1264. throw new NotImplementedException ();
  1265. }
  1266. public void ReadXmlSchema (Stream stream)
  1267. {
  1268. ReadXmlSchema (new XmlTextReader (stream));
  1269. }
  1270. public void ReadXmlSchema (TextReader reader)
  1271. {
  1272. ReadXmlSchema (new XmlTextReader (reader));
  1273. }
  1274. public void ReadXmlSchema (string fileName)
  1275. {
  1276. XmlTextReader reader = null;
  1277. try {
  1278. reader = new XmlTextReader (fileName);
  1279. ReadXmlSchema (reader);
  1280. } finally {
  1281. if (reader != null)
  1282. reader.Close ();
  1283. }
  1284. }
  1285. public void ReadXmlSchema (XmlReader reader)
  1286. {
  1287. DataSet ds = new DataSet ();
  1288. new XmlSchemaDataImporter (ds, reader).Process ();
  1289. DataTable target = null;
  1290. if (TableName == String.Empty) {
  1291. if (ds.Tables.Count > 0)
  1292. target = ds.Tables [0];
  1293. }
  1294. else {
  1295. target = ds.Tables [TableName];
  1296. if (target == null)
  1297. throw new ArgumentException (String.Format ("DataTable '{0}' does not match to any DataTable in source.", TableName));
  1298. }
  1299. if (target != null)
  1300. target.CopyProperties (this);
  1301. }
  1302. #endif
  1303. /// <summary>
  1304. /// Rolls back all changes that have been made to the
  1305. /// table since it was loaded, or the last time AcceptChanges
  1306. /// was called.
  1307. /// </summary>
  1308. public void RejectChanges ()
  1309. {
  1310. for (int i = _rows.Count - 1; i >= 0; i--) {
  1311. DataRow row = _rows [i];
  1312. if (row.RowState != DataRowState.Unchanged)
  1313. _rows [i].RejectChanges ();
  1314. }
  1315. }
  1316. /// <summary>
  1317. /// Resets the DataTable to its original state.
  1318. /// </summary>
  1319. public virtual void Reset ()
  1320. {
  1321. Clear();
  1322. while (ParentRelations.Count > 0)
  1323. {
  1324. if (dataSet.Relations.Contains(ParentRelations[ParentRelations.Count - 1].RelationName))
  1325. dataSet.Relations.Remove(ParentRelations[ParentRelations.Count - 1]);
  1326. }
  1327. while (ChildRelations.Count > 0)
  1328. {
  1329. if (dataSet.Relations.Contains(ChildRelations[ChildRelations.Count - 1].RelationName))
  1330. dataSet.Relations.Remove(ChildRelations[ChildRelations.Count - 1]);
  1331. }
  1332. Constraints.Clear();
  1333. Columns.Clear();
  1334. }
  1335. /// <summary>
  1336. /// Gets an array of all DataRow objects.
  1337. /// </summary>
  1338. public DataRow[] Select ()
  1339. {
  1340. return Select(String.Empty, String.Empty, DataViewRowState.CurrentRows);
  1341. }
  1342. /// <summary>
  1343. /// Gets an array of all DataRow objects that match
  1344. /// the filter criteria in order of primary key (or
  1345. /// lacking one, order of addition.)
  1346. /// </summary>
  1347. public DataRow[] Select (string filterExpression)
  1348. {
  1349. return Select(filterExpression, String.Empty, DataViewRowState.CurrentRows);
  1350. }
  1351. /// <summary>
  1352. /// Gets an array of all DataRow objects that
  1353. /// match the filter criteria, in the the
  1354. /// specified sort order.
  1355. /// </summary>
  1356. public DataRow[] Select (string filterExpression, string sort)
  1357. {
  1358. return Select(filterExpression, sort, DataViewRowState.CurrentRows);
  1359. }
  1360. /// <summary>
  1361. /// Gets an array of all DataRow objects that match
  1362. /// the filter in the order of the sort, that match
  1363. /// the specified state.
  1364. /// </summary>
  1365. [MonoTODO]
  1366. public DataRow[] Select(string filterExpression, string sort, DataViewRowState recordStates)
  1367. {
  1368. if (filterExpression == null)
  1369. filterExpression = String.Empty;
  1370. DataColumn[] columns = _emptyColumnArray;
  1371. ListSortDirection[] sorts = null;
  1372. if (sort != null && !sort.Equals(String.Empty))
  1373. columns = ParseSortString (this, sort, out sorts, false);
  1374. IExpression filter = null;
  1375. if (filterExpression != String.Empty) {
  1376. Parser parser = new Parser ();
  1377. filter = parser.Compile (filterExpression);
  1378. }
  1379. Index index = GetIndex(columns, sorts, recordStates, filter, false);
  1380. int[] records = index.GetAll();
  1381. DataRow[] dataRows = NewRowArray(index.Size);
  1382. for (int i = 0; i < dataRows.Length; i++)
  1383. dataRows[i] = RecordCache[records[i]];
  1384. return dataRows;
  1385. }
  1386. private void AddIndex (Index index)
  1387. {
  1388. if (_indexes == null) {
  1389. _indexes = new ArrayList();
  1390. }
  1391. _indexes.Add (index);
  1392. }
  1393. /// <summary>
  1394. /// Returns index corresponding to columns,sort,row state filter and unique values given.
  1395. /// If such an index not exists, creates a new one.
  1396. /// </summary>
  1397. /// <param name="columns">Columns set of the index to look for.</param>
  1398. /// <param name="sort">Columns sort order of the index to look for.</param>
  1399. /// <param name="rowState">Rpw state filter of the index to look for.</param>
  1400. /// <param name="unique">Uniqueness of the index to look for.</param>
  1401. /// <param name="strict">Indicates whenever the index found should correspond in its uniquness to the value of unique parameter specified.</param>
  1402. /// <param name="reset">Indicates whenever the already existing index should be forced to reset.</param>
  1403. /// <returns></returns>
  1404. internal Index GetIndex(DataColumn[] columns, ListSortDirection[] sort, DataViewRowState rowState, IExpression filter, bool reset)
  1405. {
  1406. Index index = FindIndex(columns,sort,rowState,filter);
  1407. if (index == null ) {
  1408. index = new Index(new Key(this,columns,sort,rowState,filter));
  1409. AddIndex(index);
  1410. }
  1411. else if (reset) {
  1412. // reset existing index only if asked for this
  1413. index.Reset();
  1414. }
  1415. return index;
  1416. }
  1417. internal Index FindIndex(DataColumn[] columns)
  1418. {
  1419. return FindIndex(columns,null,DataViewRowState.None, null);
  1420. }
  1421. internal Index FindIndex(DataColumn[] columns, ListSortDirection[] sort, DataViewRowState rowState, IExpression filter)
  1422. {
  1423. if (Indexes != null) {
  1424. foreach (Index index in Indexes) {
  1425. if (index.Key.Equals(columns,sort,rowState, filter)) {
  1426. return index;
  1427. }
  1428. }
  1429. }
  1430. return null;
  1431. }
  1432. internal void ResetIndexes()
  1433. {
  1434. foreach(Index index in Indexes) {
  1435. index.Reset();
  1436. }
  1437. }
  1438. internal void ResetCaseSensitiveIndexes()
  1439. {
  1440. foreach(Index index in Indexes) {
  1441. bool containsStringcolumns = false;
  1442. foreach(DataColumn column in index.Key.Columns) {
  1443. if (column.DataType == typeof(string)) {
  1444. containsStringcolumns = true;
  1445. break;
  1446. }
  1447. }
  1448. if (!containsStringcolumns && index.Key.HasFilter)
  1449. foreach (DataColumn column in Columns)
  1450. if ((column.DataType == DbTypes.TypeOfString) && (index.Key.DependsOn (column))) {
  1451. containsStringcolumns = true;
  1452. break;
  1453. }
  1454. if (containsStringcolumns) {
  1455. index.Reset();
  1456. }
  1457. }
  1458. }
  1459. internal void DropIndex(Index index)
  1460. {
  1461. if (index != null && index.RefCount == 0) {
  1462. _indexes.Remove(index);
  1463. }
  1464. }
  1465. internal void DropReferencedIndexes (DataColumn column)
  1466. {
  1467. if (_indexes != null)
  1468. for (int i = _indexes.Count - 1; i >= 0; i--) {
  1469. Index indx = (Index)_indexes [i];
  1470. if (indx.Key.DependsOn (column))
  1471. _indexes.Remove (indx);
  1472. }
  1473. }
  1474. internal void AddRowToIndexes (DataRow row) {
  1475. if (_indexes != null) {
  1476. foreach (Index indx in _indexes) {
  1477. indx.Add (row);
  1478. }
  1479. }
  1480. }
  1481. internal void DeleteRowFromIndexes (DataRow row)
  1482. {
  1483. if (_indexes != null) {
  1484. foreach (Index indx in _indexes) {
  1485. indx.Delete (row);
  1486. }
  1487. }
  1488. }
  1489. /// <summary>
  1490. /// Gets the TableName and DisplayExpression, if
  1491. /// there is one as a concatenated string.
  1492. /// </summary>
  1493. public override string ToString()
  1494. {
  1495. //LAMESPEC: spec says concat the two. impl puts a
  1496. //plus sign infront of DisplayExpression
  1497. string retVal = TableName;
  1498. if(DisplayExpression != null && DisplayExpression != "")
  1499. retVal += " + " + DisplayExpression;
  1500. return retVal;
  1501. }
  1502. #if NET_2_0
  1503. private XmlWriterSettings GetWriterSettings ()
  1504. {
  1505. XmlWriterSettings s = new XmlWriterSettings ();
  1506. s.Indent = true;
  1507. return s;
  1508. }
  1509. public void WriteXml (Stream stream)
  1510. {
  1511. WriteXml (stream, XmlWriteMode.IgnoreSchema);
  1512. }
  1513. public void WriteXml (TextWriter writer)
  1514. {
  1515. WriteXml (writer, XmlWriteMode.IgnoreSchema);
  1516. }
  1517. public void WriteXml (XmlWriter writer)
  1518. {
  1519. WriteXml (writer, XmlWriteMode.IgnoreSchema);
  1520. }
  1521. public void WriteXml (string fileName)
  1522. {
  1523. WriteXml (fileName, XmlWriteMode.IgnoreSchema);
  1524. }
  1525. public void WriteXml (Stream stream, XmlWriteMode mode)
  1526. {
  1527. WriteXml (XmlWriter.Create (stream, GetWriterSettings ()), mode);
  1528. }
  1529. public void WriteXml (TextWriter writer, XmlWriteMode mode)
  1530. {
  1531. WriteXml (XmlWriter.Create (writer, GetWriterSettings ()), mode);
  1532. }
  1533. [MonoTODO]
  1534. public void WriteXml (XmlWriter writer, XmlWriteMode mode)
  1535. {
  1536. throw new NotImplementedException ();
  1537. }
  1538. public void WriteXml (string fileName, XmlWriteMode mode)
  1539. {
  1540. XmlWriter xw = null;
  1541. try {
  1542. xw = XmlWriter.Create (fileName, GetWriterSettings ());
  1543. WriteXml (xw, mode);
  1544. } finally {
  1545. if (xw != null)
  1546. xw.Close ();
  1547. }
  1548. }
  1549. public void WriteXmlSchema (Stream stream)
  1550. {
  1551. WriteXmlSchema (XmlWriter.Create (stream, GetWriterSettings ()));
  1552. }
  1553. public void WriteXmlSchema (TextWriter writer)
  1554. {
  1555. WriteXmlSchema (XmlWriter.Create (writer, GetWriterSettings ()));
  1556. }
  1557. public void WriteXmlSchema (XmlWriter writer)
  1558. {
  1559. DataSet ds = DataSet;
  1560. DataSet tmp = null;
  1561. try {
  1562. if (ds == null) {
  1563. tmp = ds = new DataSet ();
  1564. ds.Tables.Add (this);
  1565. }
  1566. DataTableCollection col = new DataTableCollection (ds);
  1567. col.Add (this);
  1568. XmlSchemaWriter.WriteXmlSchema (ds, writer, col, null);
  1569. } finally {
  1570. if (tmp != null)
  1571. ds.Tables.Remove (this);
  1572. }
  1573. }
  1574. public void WriteXmlSchema (string fileName)
  1575. {
  1576. XmlWriter xw = null;
  1577. try {
  1578. xw = XmlWriter.Create (fileName, GetWriterSettings ());
  1579. WriteXmlSchema (xw);
  1580. } finally {
  1581. if (xw != null)
  1582. xw.Close ();
  1583. }
  1584. }
  1585. #endif
  1586. #region Events
  1587. /// <summary>
  1588. /// Raises the ColumnChanged event.
  1589. /// </summary>
  1590. protected virtual void OnColumnChanged (DataColumnChangeEventArgs e) {
  1591. if (null != ColumnChanged) {
  1592. ColumnChanged (this, e);
  1593. }
  1594. }
  1595. internal void RaiseOnColumnChanged (DataColumnChangeEventArgs e) {
  1596. OnColumnChanged(e);
  1597. }
  1598. #if NET_2_0
  1599. /// <summary>
  1600. /// Raises TableCleared Event and delegates to subscribers
  1601. /// </summary>
  1602. protected virtual void OnTableCleared (DataTableClearEventArgs e) {
  1603. if (TableCleared != null)
  1604. TableCleared (this, e);
  1605. }
  1606. #endif // NET_2_0
  1607. /// <summary>
  1608. /// Raises the ColumnChanging event.
  1609. /// </summary>
  1610. protected virtual void OnColumnChanging (DataColumnChangeEventArgs e) {
  1611. if (null != ColumnChanging) {
  1612. ColumnChanging (this, e);
  1613. }
  1614. }
  1615. internal void RaiseOnColumnChanging (DataColumnChangeEventArgs e) {
  1616. OnColumnChanging(e);
  1617. }
  1618. /// <summary>
  1619. /// Raises the PropertyChanging event.
  1620. /// </summary>
  1621. [MonoTODO]
  1622. protected internal virtual void OnPropertyChanging (PropertyChangedEventArgs pcevent) {
  1623. // if (null != PropertyChanging)
  1624. // {
  1625. // PropertyChanging (this, e);
  1626. // }
  1627. }
  1628. /// <summary>
  1629. /// Notifies the DataTable that a DataColumn is being removed.
  1630. /// </summary>
  1631. protected internal virtual void OnRemoveColumn (DataColumn column) {
  1632. DropReferencedIndexes (column);
  1633. }
  1634. /// <summary>
  1635. /// Raises the RowChanged event.
  1636. /// </summary>
  1637. protected virtual void OnRowChanged (DataRowChangeEventArgs e) {
  1638. if (null != RowChanged) {
  1639. RowChanged(this, e);
  1640. }
  1641. }
  1642. /// <summary>
  1643. /// Raises the RowChanging event.
  1644. /// </summary>
  1645. protected virtual void OnRowChanging (DataRowChangeEventArgs e) {
  1646. if (null != RowChanging) {
  1647. RowChanging(this, e);
  1648. }
  1649. }
  1650. /// <summary>
  1651. /// Raises the RowDeleted event.
  1652. /// </summary>
  1653. protected virtual void OnRowDeleted (DataRowChangeEventArgs e) {
  1654. if (null != RowDeleted) {
  1655. RowDeleted(this, e);
  1656. }
  1657. }
  1658. /// <summary>
  1659. /// Raises the RowDeleting event.
  1660. /// </summary>
  1661. protected virtual void OnRowDeleting (DataRowChangeEventArgs e) {
  1662. if (null != RowDeleting) {
  1663. RowDeleting(this, e);
  1664. }
  1665. }
  1666. /// <summary>
  1667. /// Occurs when after a value has been changed for
  1668. /// the specified DataColumn in a DataRow.
  1669. /// </summary>
  1670. [DataCategory ("Data")]
  1671. #if !NET_2_0
  1672. [DataSysDescription ("Occurs when a value has been changed for this column.")]
  1673. #endif
  1674. public event DataColumnChangeEventHandler ColumnChanged;
  1675. /// <summary>
  1676. /// Occurs when a value is being changed for the specified
  1677. /// DataColumn in a DataRow.
  1678. /// </summary>
  1679. [DataCategory ("Data")]
  1680. #if !NET_2_0
  1681. [DataSysDescription ("Occurs when a value has been submitted for this column. The user can modify the proposed value and should throw an exception to cancel the edit.")]
  1682. #endif
  1683. public event DataColumnChangeEventHandler ColumnChanging;
  1684. /// <summary>
  1685. /// Occurs after a DataRow has been changed successfully.
  1686. /// </summary>
  1687. [DataCategory ("Data")]
  1688. #if !NET_2_0
  1689. [DataSysDescription ("Occurs after a row in the table has been successfully edited.")]
  1690. #endif
  1691. public event DataRowChangeEventHandler RowChanged;
  1692. /// <summary>
  1693. /// Occurs when a DataRow is changing.
  1694. /// </summary>
  1695. [DataCategory ("Data")]
  1696. #if !NET_2_0
  1697. [DataSysDescription ("Occurs when the row is being changed so that the event handler can modify or cancel the change. The user can modify values in the row and should throw an exception to cancel the edit.")]
  1698. #endif
  1699. public event DataRowChangeEventHandler RowChanging;
  1700. /// <summary>
  1701. /// Occurs after a row in the table has been deleted.
  1702. /// </summary>
  1703. [DataCategory ("Data")]
  1704. #if !NET_2_0
  1705. [DataSysDescription ("Occurs after a row in the table has been successfully deleted.")]
  1706. #endif
  1707. public event DataRowChangeEventHandler RowDeleted;
  1708. /// <summary>
  1709. /// Occurs before a row in the table is about to be deleted.
  1710. /// </summary>
  1711. [DataCategory ("Data")]
  1712. #if !NET_2_0
  1713. [DataSysDescription ("Occurs when a row in the table marked for deletion. Throw an exception to cancel the deletion.")]
  1714. #endif
  1715. public event DataRowChangeEventHandler RowDeleting;
  1716. #if NET_2_0
  1717. /// <summary>
  1718. /// Occurs after the Clear method is called on the datatable.
  1719. /// </summary>
  1720. [DataCategory ("Data")]
  1721. #if !NET_2_0
  1722. [DataSysDescription ("Occurs when the rows in a table is cleared . Throw an exception to cancel the deletion.")]
  1723. #endif
  1724. public event DataTableClearEventHandler TableCleared;
  1725. #endif // NET_2_0
  1726. #endregion // Events
  1727. /// <summary>
  1728. /// Removes all UniqueConstraints
  1729. /// </summary>
  1730. private void RemoveUniqueConstraints ()
  1731. {
  1732. foreach (Constraint Cons in Constraints) {
  1733. if (Cons is UniqueConstraint) {
  1734. Constraints.Remove (Cons);
  1735. break;
  1736. }
  1737. }
  1738. UniqueConstraint.SetAsPrimaryKey(this.Constraints, null);
  1739. }
  1740. internal static DataColumn[] ParseSortString (DataTable table, string sort, out ListSortDirection[] sortDirections, bool rejectNoResult)
  1741. {
  1742. DataColumn[] sortColumns = _emptyColumnArray;
  1743. sortDirections = null;
  1744. ArrayList columns = null;
  1745. ArrayList sorts = null;
  1746. if (sort != null && !sort.Equals ("")) {
  1747. columns = new ArrayList ();
  1748. sorts = new ArrayList();
  1749. string[] columnExpression = sort.Trim ().Split (new char[1] {','});
  1750. for (int c = 0; c < columnExpression.Length; c++) {
  1751. string rawColumnName = columnExpression[c].Trim ();
  1752. Match match = SortRegex.Match (rawColumnName);
  1753. CaptureCollection cc = match.Groups["ColName"].Captures ;
  1754. if (cc.Count == 0)
  1755. throw new IndexOutOfRangeException ("Could not find column: " + rawColumnName);
  1756. string columnName = cc[0].Value;
  1757. DataColumn dc = table.Columns[columnName];
  1758. if (dc == null){
  1759. try {
  1760. dc = table.Columns[Int32.Parse (columnName)];
  1761. } catch (FormatException) {
  1762. throw new IndexOutOfRangeException("Cannot find column " + columnName);
  1763. }
  1764. }
  1765. columns.Add (dc);
  1766. cc = match.Groups["Order"].Captures;
  1767. if (cc.Count == 0 || String.Compare (cc[0].Value, "ASC", true) == 0)
  1768. sorts.Add(ListSortDirection.Ascending);
  1769. else
  1770. sorts.Add (ListSortDirection.Descending);
  1771. }
  1772. sortColumns = (DataColumn[]) columns.ToArray (typeof (DataColumn));
  1773. sortDirections = new ListSortDirection[sorts.Count];
  1774. for (int i = 0; i < sortDirections.Length; i++)
  1775. sortDirections[i] = (ListSortDirection)sorts[i];
  1776. }
  1777. if (rejectNoResult) {
  1778. if (sortColumns == null)
  1779. throw new SystemException ("sort expression result is null");
  1780. if (sortColumns.Length == 0)
  1781. throw new SystemException("sort expression result is 0");
  1782. }
  1783. return sortColumns;
  1784. }
  1785. private void UpdatePropertyDescriptorsCache()
  1786. {
  1787. PropertyDescriptor[] descriptors = new PropertyDescriptor[Columns.Count + ChildRelations.Count];
  1788. int index = 0;
  1789. foreach(DataColumn col in Columns) {
  1790. descriptors[index++] = new DataColumnPropertyDescriptor(col);
  1791. }
  1792. foreach(DataRelation rel in ChildRelations) {
  1793. descriptors[index++] = new DataRelationPropertyDescriptor(rel);
  1794. }
  1795. _propertyDescriptorsCache = new PropertyDescriptorCollection(descriptors);
  1796. }
  1797. internal PropertyDescriptorCollection GetPropertyDescriptorCollection()
  1798. {
  1799. if (_propertyDescriptorsCache == null) {
  1800. UpdatePropertyDescriptorsCache();
  1801. }
  1802. return _propertyDescriptorsCache;
  1803. }
  1804. internal void ResetPropertyDescriptorsCache() {
  1805. _propertyDescriptorsCache = null;
  1806. }
  1807. }
  1808. }