-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathDataTable.cs
More file actions
7245 lines (6481 loc) · 287 KB
/
Copy pathDataTable.cs
File metadata and controls
7245 lines (6481 loc) · 287 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Data
{
/// <summary>
/// Represents one table of in-memory data.
/// </summary>
[ToolboxItem(false)]
[DesignTimeVisible(false)]
[DefaultProperty(nameof(TableName))]
[DefaultEvent(nameof(RowChanging))]
[Editor("Microsoft.VSDesigner.Data.Design.DataTableEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[XmlSchemaProvider(nameof(GetDataTableSchema))]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
public class DataTable : MarshalByValueComponent, IListSource, ISupportInitializeNotification, ISerializable, IXmlSerializable
{
private DataSet? _dataSet;
private DataView? _defaultView;
/// <summary>
/// Monotonically increasing number representing the order <see cref="DataRow"/> have been added to <see cref="DataRowCollection"/>.
/// </summary>
/// <remarks>This limits <see cref="DataRowCollection.Add(DataRow)"/> to <see cref="int.MaxValue"/> operations.</remarks>
internal long _nextRowID;
internal readonly DataRowCollection _rowCollection;
// columns
internal readonly DataColumnCollection _columnCollection;
// constraints
private readonly ConstraintCollection _constraintCollection;
//SimpleContent implementation
private int _elementColumnCount;
// relations
internal DataRelationCollection? _parentRelationsCollection;
internal DataRelationCollection? _childRelationsCollection;
// RecordManager
internal readonly RecordManager _recordManager;
// index mgmt
internal readonly List<Index> _indexes;
private List<Index>? _shadowIndexes;
private int _shadowCount;
// props
internal PropertyCollection? _extendedProperties;
private string _tableName = string.Empty;
internal string? _tableNamespace;
private string _tablePrefix = string.Empty;
internal DataExpression? _displayExpression;
internal bool _fNestedInDataset = true;
// globalization stuff
private CultureInfo _culture;
private bool _cultureUserSet;
private CompareInfo? _compareInfo;
private CompareOptions _compareFlags = CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth;
private IFormatProvider? _formatProvider;
private StringComparer? _hashCodeProvider;
private bool _caseSensitive;
private bool _caseSensitiveUserSet;
// XML properties
internal string? _encodedTableName; // For XmlDataDocument only
internal DataColumn? _xmlText; // text values of a complex xml element
internal DataColumn? _colUnique;
internal decimal _minOccurs = 1; // default = 1
internal decimal _maxOccurs = 1; // default = 1
internal bool _repeatableElement;
private object? _typeName;
// primary key info
internal UniqueConstraint? _primaryKey;
internal IndexField[] _primaryIndex = Array.Empty<IndexField>();
private DataColumn[]? _delayedSetPrimaryKey;
// Loading Schema and/or Data related optimization
private Index? _loadIndex;
private Index? _loadIndexwithOriginalAdded;
private Index? _loadIndexwithCurrentDeleted;
private int _suspendIndexEvents;
private bool _savedEnforceConstraints;
private bool _inDataLoad;
private bool _initialLoad;
private bool _enforceConstraints = true;
internal bool _suspendEnforceConstraints;
protected internal bool fInitInProgress;
internal bool _fInLoadDiffgram;
private byte _isTypedDataTable; // 0 == unknown, 1 = yes, 2 = No
private DataRow[]? _emptyDataRowArray;
// Property Descriptor Cache for DataBinding
private PropertyDescriptorCollection? _propertyDescriptorCollectionCache;
// Cache for relation that has this table as nested child table.
private DataRelation[] _nestedParentRelations = Array.Empty<DataRelation>();
// Dependent column list for expression evaluation
internal List<DataColumn>? _dependentColumns;
// events
private bool _mergingData;
private DataRowChangeEventHandler? _onRowChangedDelegate;
private DataRowChangeEventHandler? _onRowChangingDelegate;
private DataRowChangeEventHandler? _onRowDeletingDelegate;
private DataRowChangeEventHandler? _onRowDeletedDelegate;
private DataColumnChangeEventHandler? _onColumnChangedDelegate;
private DataColumnChangeEventHandler? _onColumnChangingDelegate;
private DataTableClearEventHandler? _onTableClearingDelegate;
private DataTableClearEventHandler? _onTableClearedDelegate;
private DataTableNewRowEventHandler? _onTableNewRowDelegate;
private PropertyChangedEventHandler? _onPropertyChangingDelegate;
private EventHandler? _onInitialized;
// misc
private readonly DataRowBuilder _rowBuilder;
private const string KEY_XMLSCHEMA = "XmlSchema";
private const string KEY_XMLDIFFGRAM = "XmlDiffGram";
internal readonly List<DataView> _delayedViews = new List<DataView>();
private readonly List<DataViewListener> _dataViewListeners = new List<DataViewListener>();
internal Hashtable? _rowDiffId;
internal readonly ReaderWriterLockSlim _indexesLock = new ReaderWriterLockSlim();
internal int _ukColumnPositionForInference = -1;
// default remoting format is Xml
private SerializationFormat _remotingFormat = SerializationFormat.Xml;
private static int s_objectTypeCount; // Bid counter
private readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataTable'/> class with no arguments.
/// </summary>
public DataTable()
{
GC.SuppressFinalize(this);
DataCommonEventSource.Log.Trace("<ds.DataTable.DataTable|API> {0}", ObjectID);
_nextRowID = 1;
_recordManager = new RecordManager(this);
_culture = CultureInfo.CurrentCulture;
_columnCollection = new DataColumnCollection(this);
_constraintCollection = new ConstraintCollection(this);
_rowCollection = new DataRowCollection(this);
_indexes = new List<Index>();
_rowBuilder = new DataRowBuilder(this, -1);
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataTable'/> class with the specified table
/// name.
/// </summary>
public DataTable(string? tableName) : this()
{
_tableName = tableName ?? "";
}
public DataTable(string? tableName, string? tableNamespace) : this(tableName)
{
Namespace = tableNamespace;
}
// Deserialize the table from binary/xml stream.
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode",
Justification = "CreateInstance's use of GetType uses only the parameterless constructor. Warnings are about serialization related constructors.")]
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
[Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
protected DataTable(SerializationInfo info, StreamingContext context) : this()
{
bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true;
SerializationFormat remotingFormat = SerializationFormat.Xml;
SerializationInfoEnumerator e = info.GetEnumerator();
while (e.MoveNext())
{
switch (e.Name)
{
case "DataTable.RemotingFormat": //DataTable.RemotingFormat does not exist in V1/V1.1 versions
remotingFormat = (SerializationFormat)e.Value!;
break;
}
}
if (remotingFormat == SerializationFormat.Binary &&
!LocalAppContextSwitches.AllowUnsafeSerializationFormatBinary)
{
throw ExceptionBuilder.SerializationFormatBinaryNotSupported();
}
DeserializeDataTable(info, isSingleTable, remotingFormat);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Binary serialization is unsafe in general and is planned to be obsoleted. We do not want to mark interface or ctors of this class as unsafe as that would show many unnecessary warnings elsewhere.")]
[Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializationFormat remotingFormat = RemotingFormat;
bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true;
SerializeDataTable(info, isSingleTable, remotingFormat);
}
// Serialize the table schema and data.
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
private void SerializeDataTable(SerializationInfo info, bool isSingleTable, SerializationFormat remotingFormat)
{
info.AddValue("DataTable.RemotingVersion", new Version(2, 0));
// SqlHotFix 299, SerializationFormat enumeration types don't exist in V1.1 SP1
if (SerializationFormat.Xml != remotingFormat)
{
info.AddValue("DataTable.RemotingFormat", remotingFormat);
}
if (remotingFormat != SerializationFormat.Xml)
{
//Binary
SerializeTableSchema(info, isSingleTable);
if (isSingleTable)
{
SerializeTableData(info, 0);
}
}
else
{
//XML/V1.0/V1.1
string tempDSNamespace = string.Empty;
bool fCreatedDataSet = false;
if (_dataSet == null)
{
DataSet ds = new DataSet("tmpDataSet");
// if user set values on DataTable, it isn't necessary
// to set them on the DataSet because they won't be inherited
// but it is simpler to set them in both places
// if user did not set values on DataTable, it is required
// to set them on the DataSet so the table will inherit
// the value already on the Datatable
ds.SetLocaleValue(_culture, _cultureUserSet);
ds.CaseSensitive = CaseSensitive;
ds._namespaceURI = Namespace;
Debug.Assert(ds.RemotingFormat == SerializationFormat.Xml, "RemotingFormat must be SerializationFormat.Xml");
ds.Tables.Add(this);
fCreatedDataSet = true;
}
else
{
tempDSNamespace = _dataSet.Namespace;
_dataSet._namespaceURI = Namespace;
}
info.AddValue(KEY_XMLSCHEMA, _dataSet!.GetXmlSchemaForRemoting(this));
info.AddValue(KEY_XMLDIFFGRAM, DataSet.GetRemotingDiffGram(this));
if (fCreatedDataSet)
{
_dataSet.Tables.Remove(this);
}
else
{
_dataSet._namespaceURI = tempDSNamespace;
}
}
}
// Deserialize the table schema and data.
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void DeserializeDataTable(SerializationInfo info, bool isSingleTable, SerializationFormat remotingFormat)
{
if (remotingFormat != SerializationFormat.Xml)
{
//Binary
DeserializeTableSchema(info, isSingleTable);
if (isSingleTable)
{
DeserializeTableData(info, 0);
ResetIndexes();
}
}
else
{
//XML/V1.0/V1.1
string? strSchema = (string?)info.GetValue(KEY_XMLSCHEMA, typeof(string));
string? strData = (string?)info.GetValue(KEY_XMLDIFFGRAM, typeof(string));
if (strSchema != null)
{
DataSet ds = new DataSet();
ds.ReadXmlSchema(new XmlTextReader(new StringReader(strSchema)));
Debug.Assert(ds.Tables.Count == 1, "There should be exactly 1 table here");
DataTable table = ds.Tables[0];
table.CloneTo(this, null, false);
//this is to avoid the cascading rules in the namespace
Namespace = table.Namespace;
if (strData != null)
{
ds.Tables.Remove(ds.Tables[0]);
ds.Tables.Add(this);
ds.ReadXml(new XmlTextReader(new StringReader(strData)), XmlReadMode.DiffGram);
ds.Tables.Remove(this);
}
}
}
}
// Serialize the columns
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void SerializeTableSchema(SerializationInfo info, bool isSingleTable)
{
//DataTable basic properties
info.AddValue("DataTable.TableName", TableName);
info.AddValue("DataTable.Namespace", Namespace);
info.AddValue("DataTable.Prefix", Prefix);
info.AddValue("DataTable.CaseSensitive", _caseSensitive);
info.AddValue("DataTable.caseSensitiveAmbient", !_caseSensitiveUserSet);
info.AddValue("DataTable.LocaleLCID", Locale.LCID);
info.AddValue("DataTable.MinimumCapacity", _recordManager.MinimumCapacity);
//DataTable state internal properties
info.AddValue("DataTable.NestedInDataSet", _fNestedInDataset);
info.AddValue("DataTable.TypeName", TypeName.ToString());
info.AddValue("DataTable.RepeatableElement", _repeatableElement);
//ExtendedProperties
info.AddValue("DataTable.ExtendedProperties", ExtendedProperties);
//Columns
info.AddValue("DataTable.Columns.Count", Columns.Count);
//Check for closure of expression in case of single table.
if (isSingleTable)
{
List<DataTable> list = new List<DataTable>();
list.Add(this);
if (!CheckForClosureOnExpressionTables(list))
{
throw ExceptionBuilder.CanNotRemoteDataTable();
}
}
IFormatProvider formatProvider = CultureInfo.InvariantCulture;
for (int i = 0; i < Columns.Count; i++)
{
//DataColumn basic properties
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnName", i), Columns[i].ColumnName);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.Namespace", i), Columns[i]._columnUri);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.Prefix", i), Columns[i].Prefix);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnMapping", i), Columns[i].ColumnMapping);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AllowDBNull", i), Columns[i].AllowDBNull);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrement", i), Columns[i].AutoIncrement);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementStep", i), Columns[i].AutoIncrementStep);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementSeed", i), Columns[i].AutoIncrementSeed);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.Caption", i), Columns[i].Caption);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DefaultValue", i), Columns[i].DefaultValue);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ReadOnly", i), Columns[i].ReadOnly);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.MaxLength", i), Columns[i].MaxLength);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DataType_AssemblyQualifiedName", i), Columns[i].DataType.AssemblyQualifiedName);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.XmlDataType", i), Columns[i].XmlDataType);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.SimpleType", i), Columns[i].SimpleType);
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DateTimeMode", i), Columns[i].DateTimeMode);
//DataColumn internal state properties
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementCurrent", i), Columns[i].AutoIncrementCurrent);
//Expression
if (isSingleTable)
{
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.Expression", i), Columns[i].Expression);
}
//ExtendedProperties
info.AddValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ExtendedProperties", i), Columns[i]._extendedProperties);
}
//Constraints
if (isSingleTable)
{
SerializeConstraints(info, 0, false);
}
}
// Deserialize all the Columns
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void DeserializeTableSchema(SerializationInfo info, bool isSingleTable)
{
//DataTable basic properties
_tableName = info.GetString("DataTable.TableName")!;
_tableNamespace = info.GetString("DataTable.Namespace");
_tablePrefix = info.GetString("DataTable.Prefix")!;
bool caseSensitive = info.GetBoolean("DataTable.CaseSensitive");
SetCaseSensitiveValue(caseSensitive, true, false);
_caseSensitiveUserSet = !info.GetBoolean("DataTable.caseSensitiveAmbient");
int lcid = (int)info.GetValue("DataTable.LocaleLCID", typeof(int))!;
CultureInfo culture = new CultureInfo(lcid);
SetLocaleValue(culture, true, false);
_cultureUserSet = true;
MinimumCapacity = info.GetInt32("DataTable.MinimumCapacity");
//DataTable state internal properties
_fNestedInDataset = info.GetBoolean("DataTable.NestedInDataSet");
string tName = info.GetString("DataTable.TypeName")!;
_typeName = new XmlQualifiedName(tName);
_repeatableElement = info.GetBoolean("DataTable.RepeatableElement");
//ExtendedProperties
_extendedProperties = (PropertyCollection?)info.GetValue("DataTable.ExtendedProperties", typeof(PropertyCollection));
//Columns
int colCount = info.GetInt32("DataTable.Columns.Count");
string?[] expressions = new string?[colCount];
Debug.Assert(Columns.Count == 0, "There is column in Table");
IFormatProvider formatProvider = CultureInfo.InvariantCulture;
for (int i = 0; i < colCount; i++)
{
DataColumn dc = new DataColumn();
//DataColumn public state properties
dc.ColumnName = info.GetString(string.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnName", i));
dc._columnUri = info.GetString(string.Format(formatProvider, "DataTable.DataColumn_{0}.Namespace", i));
dc.Prefix = info.GetString(string.Format(formatProvider, "DataTable.DataColumn_{0}.Prefix", i));
string typeName = (string)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DataType_AssemblyQualifiedName", i), typeof(string))!;
dc.DataType = Type.GetType(typeName, throwOnError: true);
dc.XmlDataType = (string?)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.XmlDataType", i), typeof(string));
dc.SimpleType = (SimpleType?)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.SimpleType", i), typeof(SimpleType));
dc.ColumnMapping = (MappingType)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ColumnMapping", i), typeof(MappingType))!;
dc.DateTimeMode = (DataSetDateTime)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DateTimeMode", i), typeof(DataSetDateTime))!;
dc.AllowDBNull = info.GetBoolean(string.Format(formatProvider, "DataTable.DataColumn_{0}.AllowDBNull", i));
dc.AutoIncrement = info.GetBoolean(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrement", i));
dc.AutoIncrementStep = info.GetInt64(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementStep", i));
dc.AutoIncrementSeed = info.GetInt64(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementSeed", i));
dc.Caption = info.GetString(string.Format(formatProvider, "DataTable.DataColumn_{0}.Caption", i));
dc.DefaultValue = info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.DefaultValue", i), typeof(object));
dc.ReadOnly = info.GetBoolean(string.Format(formatProvider, "DataTable.DataColumn_{0}.ReadOnly", i));
dc.MaxLength = info.GetInt32(string.Format(formatProvider, "DataTable.DataColumn_{0}.MaxLength", i));
//DataColumn internal state properties
dc.AutoIncrementCurrent = info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.AutoIncrementCurrent", i), typeof(object))!;
//Expression
if (isSingleTable)
{
expressions[i] = info.GetString(string.Format(formatProvider, "DataTable.DataColumn_{0}.Expression", i));
}
//ExtendedProperties
dc._extendedProperties = (PropertyCollection?)info.GetValue(string.Format(formatProvider, "DataTable.DataColumn_{0}.ExtendedProperties", i), typeof(PropertyCollection));
Columns.Add(dc);
}
if (isSingleTable)
{
for (int i = 0; i < colCount; i++)
{
if (expressions[i] != null)
{
Columns[i].Expression = expressions[i];
}
}
}
//Constraints
if (isSingleTable)
{
DeserializeConstraints(info, /*table index */ 0, /* serialize all constraints */false); // since single table, send table index as 0, meanwhile passing
// false for 'allConstraints' means, handle all the constraint related to the table
}
}
// Serialize constraints available on the table - note this function is marked internal because it is called by the DataSet deserializer.
// ***Schema for Serializing ArrayList of Constraints***
// Unique Constraint - ["U"]->[constraintName]->[columnIndexes]->[IsPrimaryKey]->[extendedProperties]
// Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties]
internal void SerializeConstraints(SerializationInfo info, int serIndex, bool allConstraints)
{
if (allConstraints)
{
Debug.Assert(DataSet != null);
}
ArrayList constraintList = new ArrayList();
for (int i = 0; i < Constraints.Count; i++)
{
Constraint c = Constraints[i];
UniqueConstraint? uc = c as UniqueConstraint;
if (uc != null)
{
int[] colInfo = new int[uc.Columns.Length];
for (int j = 0; j < colInfo.Length; j++)
{
colInfo[j] = uc.Columns[j].Ordinal;
}
ArrayList list = new ArrayList();
list.Add("U");
list.Add(uc.ConstraintName);
list.Add(colInfo);
list.Add(uc.IsPrimaryKey);
list.Add(uc.ExtendedProperties);
constraintList.Add(list);
}
else
{
ForeignKeyConstraint? fk = c as ForeignKeyConstraint;
Debug.Assert(fk != null);
bool shouldSerialize = allConstraints || (fk.Table == this && fk.RelatedTable == this);
if (shouldSerialize)
{
int[] parentInfo = new int[fk.RelatedColumns.Length + 1];
parentInfo[0] = allConstraints ? DataSet!.Tables.IndexOf(fk.RelatedTable) : 0;
for (int j = 1; j < parentInfo.Length; j++)
{
parentInfo[j] = fk.RelatedColumns[j - 1].Ordinal;
}
int[] childInfo = new int[fk.Columns.Length + 1];
childInfo[0] = allConstraints ? DataSet!.Tables.IndexOf(fk.Table) : 0; //Since the constraint is on the current table, this is the child table.
for (int j = 1; j < childInfo.Length; j++)
{
childInfo[j] = fk.Columns[j - 1].Ordinal;
}
ArrayList list = new ArrayList();
list.Add("F");
list.Add(fk.ConstraintName);
list.Add(parentInfo);
list.Add(childInfo);
list.Add(new int[] { (int)fk.AcceptRejectRule, (int)fk.UpdateRule, (int)fk.DeleteRule });
list.Add(fk.ExtendedProperties);
constraintList.Add(list);
}
}
}
info.AddValue(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), constraintList);
}
// Deserialize the constraints on the table.
// ***Schema for Serializing ArrayList of Constraints***
// Unique Constraint - ["U"]->[constraintName]->[columnIndexes]->[IsPrimaryKey]->[extendedProperties]
// Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties]
internal void DeserializeConstraints(SerializationInfo info, int serIndex, bool allConstraints)
{
ArrayList constraintList = (ArrayList)info.GetValue(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), typeof(ArrayList))!;
foreach (ArrayList list in constraintList)
{
string con = (string)list[0]!;
if (con.Equals("U"))
{
//Unique Constraints
string constraintName = (string)list[1]!;
int[] keyColumnIndexes = (int[])list[2]!;
bool isPrimaryKey = (bool)list[3]!;
PropertyCollection? extendedProperties = (PropertyCollection?)list[4];
DataColumn[] keyColumns = new DataColumn[keyColumnIndexes.Length];
for (int i = 0; i < keyColumnIndexes.Length; i++)
{
keyColumns[i] = Columns[keyColumnIndexes[i]];
}
//Create the constraint.
UniqueConstraint uc = new UniqueConstraint(constraintName, keyColumns, isPrimaryKey);
uc._extendedProperties = extendedProperties;
//Add the unique constraint and it will in turn set the primary keys also if needed.
Constraints.Add(uc);
}
else
{
//ForeignKeyConstraints
Debug.Assert(con.Equals("F"));
string constraintName = (string)list[1]!;
int[] parentInfo = (int[])list[2]!;
int[] childInfo = (int[])list[3]!;
int[] rules = (int[])list[4]!;
PropertyCollection? extendedProperties = (PropertyCollection?)list[5];
//ParentKey Columns.
DataTable parentTable = (allConstraints == false) ? this : DataSet!.Tables[parentInfo[0]];
DataColumn[] parentkeyColumns = new DataColumn[parentInfo.Length - 1];
for (int i = 0; i < parentkeyColumns.Length; i++)
{
parentkeyColumns[i] = parentTable.Columns[parentInfo[i + 1]];
}
//ChildKey Columns.
DataTable childTable = (allConstraints == false) ? this : DataSet!.Tables[childInfo[0]];
DataColumn[] childkeyColumns = new DataColumn[childInfo.Length - 1];
for (int i = 0; i < childkeyColumns.Length; i++)
{
childkeyColumns[i] = childTable.Columns[childInfo[i + 1]];
}
//Create the Constraint.
ForeignKeyConstraint fk = new ForeignKeyConstraint(constraintName, parentkeyColumns, childkeyColumns);
fk.AcceptRejectRule = (AcceptRejectRule)rules[0];
fk.UpdateRule = (Rule)rules[1];
fk.DeleteRule = (Rule)rules[2];
fk._extendedProperties = extendedProperties;
//Add just the foreign key constraint without creating unique constraint.
Constraints.Add(fk, false);
}
}
}
// Serialize the expressions on the table - Marked internal so that DataSet deserializer can call into this
internal void SerializeExpressionColumns(SerializationInfo info, int serIndex)
{
int colCount = Columns.Count;
for (int i = 0; i < colCount; i++)
{
info.AddValue(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.DataColumn_{1}.Expression", serIndex, i), Columns[i].Expression);
}
}
// Deserialize the expressions on the table - Marked internal so that DataSet deserializer can call into this
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void DeserializeExpressionColumns(SerializationInfo info, int serIndex)
{
int colCount = Columns.Count;
for (int i = 0; i < colCount; i++)
{
string expr = info.GetString(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.DataColumn_{1}.Expression", serIndex, i))!;
if (0 != expr.Length)
{
Columns[i].Expression = expr;
}
}
}
// Serialize all the Rows.
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void SerializeTableData(SerializationInfo info, int serIndex)
{
//Cache all the column count, row count
int colCount = Columns.Count;
int rowCount = Rows.Count;
int modifiedRowCount = 0;
int editRowCount = 0;
//Compute row states and assign the bits accordingly - 00[Unchanged], 01[Added], 10[Modifed], 11[Deleted]
BitArray rowStates = new BitArray(rowCount * 3, false); //All bit flags are set to false on initialization of the BitArray.
for (int i = 0; i < rowCount; i++)
{
int bitIndex = i * 3;
DataRow row = Rows[i];
DataRowState rowState = row.RowState;
switch (rowState)
{
case DataRowState.Unchanged:
//rowStates[bitIndex] = false;
//rowStates[bitIndex + 1] = false;
break;
case DataRowState.Added:
//rowStates[bitIndex] = false;
rowStates[bitIndex + 1] = true;
break;
case DataRowState.Modified:
rowStates[bitIndex] = true;
//rowStates[bitIndex + 1] = false;
modifiedRowCount++;
break;
case DataRowState.Deleted:
rowStates[bitIndex] = true;
rowStates[bitIndex + 1] = true;
break;
default:
throw ExceptionBuilder.InvalidRowState(rowState);
}
if (-1 != row._tempRecord)
{
rowStates[bitIndex + 2] = true;
editRowCount++;
}
}
//Compute the actual storage records that need to be created.
int recordCount = rowCount + modifiedRowCount + editRowCount;
//Create column storages.
ArrayList storeList = new ArrayList();
ArrayList nullbitList = new ArrayList();
if (recordCount > 0)
{
//Create the storage only if have records.
for (int i = 0; i < colCount; i++)
{
object store = Columns[i].GetEmptyColumnStore(recordCount);
storeList.Add(store);
BitArray nullbits = new BitArray(recordCount);
nullbitList.Add(nullbits);
}
}
//Copy values into column storages
int recordsConsumed = 0;
Hashtable rowErrors = new Hashtable();
Hashtable colErrors = new Hashtable();
for (int i = 0; i < rowCount; i++)
{
int recordsPerRow = Rows[i].CopyValuesIntoStore(storeList, nullbitList, recordsConsumed);
GetRowAndColumnErrors(i, rowErrors, colErrors);
recordsConsumed += recordsPerRow;
}
IFormatProvider formatProvider = CultureInfo.InvariantCulture;
//Serialize all the computed values.
info.AddValue(string.Format(formatProvider, "DataTable_{0}.Rows.Count", serIndex), rowCount);
info.AddValue(string.Format(formatProvider, "DataTable_{0}.Records.Count", serIndex), recordCount);
info.AddValue(string.Format(formatProvider, "DataTable_{0}.RowStates", serIndex), rowStates);
info.AddValue(string.Format(formatProvider, "DataTable_{0}.Records", serIndex), storeList);
info.AddValue(string.Format(formatProvider, "DataTable_{0}.NullBits", serIndex), nullbitList);
info.AddValue(string.Format(formatProvider, "DataTable_{0}.RowErrors", serIndex), rowErrors);
info.AddValue(string.Format(formatProvider, "DataTable_{0}.ColumnErrors", serIndex), colErrors);
}
// Deserialize all the Rows.
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void DeserializeTableData(SerializationInfo info, int serIndex)
{
bool enforceConstraintsOrg = _enforceConstraints;
bool inDataLoadOrg = _inDataLoad;
try
{
_enforceConstraints = false;
_inDataLoad = true;
IFormatProvider formatProvider = CultureInfo.InvariantCulture;
int rowCount = info.GetInt32(string.Format(formatProvider, "DataTable_{0}.Rows.Count", serIndex));
int recordCount = info.GetInt32(string.Format(formatProvider, "DataTable_{0}.Records.Count", serIndex));
BitArray rowStates = (BitArray)info.GetValue(string.Format(formatProvider, "DataTable_{0}.RowStates", serIndex), typeof(BitArray))!;
ArrayList storeList = (ArrayList)info.GetValue(string.Format(formatProvider, "DataTable_{0}.Records", serIndex), typeof(ArrayList))!;
ArrayList nullbitList = (ArrayList)info.GetValue(string.Format(formatProvider, "DataTable_{0}.NullBits", serIndex), typeof(ArrayList))!;
Hashtable rowErrors = (Hashtable)info.GetValue(string.Format(formatProvider, "DataTable_{0}.RowErrors", serIndex), typeof(Hashtable))!;
rowErrors.OnDeserialization(this); //OnDeSerialization must be called since the hashtable gets deserialized after the whole graph gets deserialized
Hashtable colErrors = (Hashtable)info.GetValue(string.Format(formatProvider, "DataTable_{0}.ColumnErrors", serIndex), typeof(Hashtable))!;
colErrors.OnDeserialization(this); //OnDeSerialization must be called since the hashtable gets deserialized after the whole graph gets deserialized
if (recordCount <= 0)
{
//No need for deserialization of the storage and errors if there are no records.
return;
}
//Point the record manager storage to the deserialized values.
for (int i = 0; i < Columns.Count; i++)
{
Columns[i].SetStorage(storeList[i]!, (BitArray)nullbitList[i]!);
}
//Create rows and set the records appropriately.
int recordIndex = 0;
DataRow[] rowArr = new DataRow[recordCount];
for (int i = 0; i < rowCount; i++)
{
//Create a new row which sets old and new records to -1.
DataRow row = NewEmptyRow();
rowArr[recordIndex] = row;
int bitIndex = i * 3;
switch (ConvertToRowState(rowStates, bitIndex))
{
case DataRowState.Unchanged:
row._oldRecord = recordIndex;
row._newRecord = recordIndex;
recordIndex += 1;
break;
case DataRowState.Added:
row._oldRecord = -1;
row._newRecord = recordIndex;
recordIndex += 1;
break;
case DataRowState.Modified:
row._oldRecord = recordIndex;
row._newRecord = recordIndex + 1;
rowArr[recordIndex + 1] = row;
recordIndex += 2;
break;
case DataRowState.Deleted:
row._oldRecord = recordIndex;
row._newRecord = -1;
recordIndex += 1;
break;
}
if (rowStates[bitIndex + 2])
{
row._tempRecord = recordIndex;
rowArr[recordIndex] = row;
recordIndex += 1;
}
else
{
row._tempRecord = -1;
}
Rows.ArrayAdd(row);
row.rowID = _nextRowID;
_nextRowID++;
ConvertToRowError(i, rowErrors, colErrors);
}
_recordManager.SetRowCache(rowArr);
ResetIndexes();
}
finally
{
_enforceConstraints = enforceConstraintsOrg;
_inDataLoad = inDataLoadOrg;
}
}
// Constructs the RowState from the two bits in the bitarray.
private static DataRowState ConvertToRowState(BitArray bitStates, int bitIndex)
{
Debug.Assert(bitStates != null);
Debug.Assert(bitStates.Length > bitIndex);
bool b1 = bitStates[bitIndex];
bool b2 = bitStates[bitIndex + 1];
if (!b1 && !b2)
{
return DataRowState.Unchanged;
}
else if (!b1 && b2)
{
return DataRowState.Added;
}
else if (b1 && !b2)
{
return DataRowState.Modified;
}
else if (b1 && b2)
{
return DataRowState.Deleted;
}
else
{
throw ExceptionBuilder.InvalidRowBitPattern();
}
}
// Get the error on the row and columns - Marked internal so that DataSet deserializer can call into this
internal void GetRowAndColumnErrors(int rowIndex, Hashtable rowErrors, Hashtable colErrors)
{
Debug.Assert(Rows.Count > rowIndex);
Debug.Assert(rowErrors != null);
Debug.Assert(colErrors != null);
DataRow row = Rows[rowIndex];
if (row.HasErrors)
{
rowErrors.Add(rowIndex, row.RowError);
DataColumn[] dcArr = row.GetColumnsInError();
if (dcArr.Length > 0)
{
int[] columnsInError = new int[dcArr.Length];
string[] columnErrors = new string[dcArr.Length];
for (int i = 0; i < dcArr.Length; i++)
{
columnsInError[i] = dcArr[i].Ordinal;
columnErrors[i] = row.GetColumnError(dcArr[i]);
}
ArrayList list = new ArrayList();
list.Add(columnsInError);
list.Add(columnErrors);
colErrors.Add(rowIndex, list);
}
}
}
// Set the row and columns in error..
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
private void ConvertToRowError(int rowIndex, Hashtable rowErrors, Hashtable colErrors)
{
Debug.Assert(Rows.Count > rowIndex);
Debug.Assert(rowErrors != null);
Debug.Assert(colErrors != null);
DataRow row = Rows[rowIndex];
if (rowErrors.ContainsKey(rowIndex))
{
row.RowError = (string)rowErrors[rowIndex]!;
}
if (colErrors.ContainsKey(rowIndex))
{
ArrayList list = (ArrayList)colErrors[rowIndex]!;
int[] columnsInError = (int[])list[0]!;
string[] columnErrors = (string[])list[1]!;
Debug.Assert(columnsInError.Length == columnErrors.Length);
for (int i = 0; i < columnsInError.Length; i++)
{
row.SetColumnError(columnsInError[i], columnErrors[i]);
}
}
}
/// <summary>
/// Indicates whether string comparisons within the table are case-sensitive.
/// </summary>
public bool CaseSensitive
{
get { return _caseSensitive; }
set
{
if (_caseSensitive != value)
{
bool oldValue = _caseSensitive;
bool oldUserSet = _caseSensitiveUserSet;
_caseSensitive = value;
_caseSensitiveUserSet = true;
if (DataSet != null && !DataSet.ValidateCaseConstraint())
{
_caseSensitive = oldValue;
_caseSensitiveUserSet = oldUserSet;
throw ExceptionBuilder.CannotChangeCaseLocale();
}
SetCaseSensitiveValue(value, true, true);
}
_caseSensitiveUserSet = true;
}
}
internal bool AreIndexEventsSuspended => 0 < _suspendIndexEvents;
internal void RestoreIndexEvents(bool forceReset)
{
DataCommonEventSource.Log.Trace("<ds.DataTable.RestoreIndexEvents|Info> {0}, {1}", ObjectID, _suspendIndexEvents);
if (0 < _suspendIndexEvents)
{
_suspendIndexEvents--;
if (0 == _suspendIndexEvents)
{
Exception? first = null;
SetShadowIndexes();
try
{
// the length of shadowIndexes will not change
// but the array instance may change during
// events during Index.Reset
int numIndexes = _shadowIndexes!.Count;
for (int i = 0; i < numIndexes; i++)
{
Index ndx = _shadowIndexes[i]; // shadowindexes may change, see ShadowIndexCopy()
try
{
if (forceReset || ndx.HasRemoteAggregate)
{
ndx.Reset(); // resets & fires