Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DataColumn.cs « Data « System « System.Data « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cacc19d4e390ba307fdc4c72c0eca677310d172b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
//------------------------------------------------------------------------------
// <copyright file="DataColumn.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------

namespace System.Data {
    using System;
    using System.Xml;
    using System.Data.Common;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Collections;
    using System.Globalization;
    using System.Data.SqlTypes;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    using System.Runtime.CompilerServices;

    /// <devdoc>
    ///    <para>
    ///       Represents one column of data in a <see cref='System.Data.DataTable'/>.
    ///    </para>
    /// </devdoc>
    [
    ToolboxItem(false),
    DesignTimeVisible(false),
    DefaultProperty("ColumnName"),
    Editor("Microsoft.VSDesigner.Data.Design.DataColumnEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
    ]
 public class DataColumn : MarshalByValueComponent {

        // properties
        private bool allowNull = true;
        private string caption = null;
        private string _columnName = null;
        private Type dataType = null;
        private StorageType _storageType;
        internal object defaultValue = DBNull.Value;             // DefaultValue Converter
        private DataSetDateTime _dateTimeMode = DataSetDateTime.UnspecifiedLocal;
        private DataExpression expression = null;
        private int maxLength = -1;
        private int _ordinal = -1;
        private bool readOnly = false;
        internal Index sortIndex = null;
        internal DataTable table = null;
        private bool unique = false;
        internal MappingType columnMapping = MappingType.Element;
        internal int _hashCode;

        internal int errors;
        private bool isSqlType = false;
        private bool implementsINullable = false;
        private bool implementsIChangeTracking = false;
        private bool implementsIRevertibleChangeTracking = false;
        private bool implementsIXMLSerializable = false;

        private bool defaultValueIsNull = true;

        // list of columns whose expression consume values from this column
        internal List<DataColumn> dependentColumns = null;

        // collections
        internal PropertyCollection extendedProperties = null;

        // events
        private PropertyChangedEventHandler onPropertyChangingDelegate = null;

        // state
        private DataStorage _storage;

        /// <summary>represents current value to return, usage pattern is .get_Current then MoveAfter</summary>
        private AutoIncrementValue autoInc;

        //
        // The _columnClass member is the class for the unfoliated virtual nodes in the XML.
        //
        internal string _columnUri = null;
        private string _columnPrefix = "";
        internal string encodedColumnName = null;

        // 
        internal string dttype = "";        // The type specified in dt:type attribute
        internal SimpleType simpleType = null;

        private static int _objectTypeCount; // Bid counter
        private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of a <see cref='System.Data.DataColumn'/>
        ///       class.
        ///    </para>
        /// </devdoc>
        public DataColumn() : this(null, typeof(string), null, MappingType.Element) {
        }

        /// <devdoc>
        ///    <para>
        ///       Inititalizes a new instance of the <see cref='System.Data.DataColumn'/> class
        ///       using the specified column name.
        ///    </para>
        /// </devdoc>
        public DataColumn(string columnName) : this(columnName, typeof(string), null, MappingType.Element) {
        }

        /// <devdoc>
        ///    <para>
        ///       Inititalizes a new instance of the <see cref='System.Data.DataColumn'/> class
        ///       using the specified column name and data type.
        ///    </para>
        /// </devdoc>
        public DataColumn(string columnName, Type dataType) : this(columnName, dataType, null, MappingType.Element) {
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance
        ///       of the <see cref='System.Data.DataColumn'/> class
        ///       using the specified name, data type, and expression.
        ///    </para>
        /// </devdoc>
        public DataColumn(string columnName, Type dataType, string expr) : this(columnName, dataType, expr, MappingType.Element) {
        }

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Data.DataColumn'/> class
        ///       using
        ///       the specified name, data type, expression, and value that determines whether the
        ///       column is an attribute.
        ///    </para>
        /// </devdoc>
        public DataColumn(string columnName, Type dataType, string expr, MappingType type) {
            GC.SuppressFinalize(this);
            Bid.Trace("<ds.DataColumn.DataColumn|API> %d#, columnName='%ls', expr='%ls', type=%d{ds.MappingType}\n",
                          ObjectID, columnName, expr, (int)type);

            if (dataType == null) {
                throw ExceptionBuilder.ArgumentNull("dataType");
            }

            StorageType typeCode = DataStorage.GetStorageType(dataType);
            if (DataStorage.ImplementsINullableValue(typeCode, dataType)) {
                throw ExceptionBuilder.ColumnTypeNotSupported();
            }
            _columnName = columnName ?? string.Empty;

            SimpleType stype = SimpleType.CreateSimpleType(typeCode, dataType);
            if (null != stype) {
                this.SimpleType = stype;
            }
            UpdateColumnType(dataType, typeCode);

            if ((null != expr) && (0 < expr.Length)) {
                // @perfnote: its a performance hit to set Expression to the empty str when we know it will come out null
                this.Expression = expr;
            }
            this.columnMapping = type;
        }


        private void UpdateColumnType(Type type, StorageType typeCode) {
            dataType = type;
            _storageType = typeCode;
            if (StorageType.DateTime != typeCode) { // revert _dateTimeMode back to default, when column type is changed
                _dateTimeMode = DataSetDateTime.UnspecifiedLocal;
            }
            DataStorage.ImplementsInterfaces(
                                typeCode, type,
                                out isSqlType,
                                out implementsINullable,
                                out implementsIXMLSerializable,
                                out implementsIChangeTracking,
                                out implementsIRevertibleChangeTracking);

            if (!isSqlType && implementsINullable) {
                SqlUdtStorage.GetStaticNullForUdtType(type);
            }
        }

        // PUBLIC PROPERTIES

        /// <devdoc>
        ///    <para>
        ///       Gets or sets a value indicating whether null
        ///       values are
        ///       allowed in this column for rows belonging to the table.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue(true),
        ResDescriptionAttribute(Res.DataColumnAllowNullDescr)
        ]
        public bool AllowDBNull {
            get {
                return allowNull;
            }
            set {
                IntPtr hscp;
                Bid.ScopeEnter(out hscp, "<ds.DataColumn.set_AllowDBNull|API> %d#, %d{bool}\n", ObjectID, value);
                try {
                    if (allowNull != value) {
                        if (table != null) {
                            if (!value && table.EnforceConstraints)
                                CheckNotAllowNull();
                        }
                        this.allowNull = value;
                    }
                    // 
                }
                finally {
                    Bid.ScopeLeave(ref hscp);
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or
        ///       sets a value indicating whether the column automatically increments the value of the column for new
        ///       rows added to the table.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        RefreshProperties(RefreshProperties.All),
        DefaultValue(false),
        ResDescriptionAttribute(Res.DataColumnAutoIncrementDescr)
        ]
        public bool AutoIncrement {
            get {
                return ((null != autoInc) && (autoInc.Auto));
            }
            set {
                Bid.Trace("<ds.DataColumn.set_AutoIncrement|API> %d#, %d{bool}\n", ObjectID, value);
                if (this.AutoIncrement != value) {
                    if (value) {
                        if (expression != null) {
                            throw ExceptionBuilder.AutoIncrementAndExpression();
                        }
                        //                        if (defaultValue != null && defaultValue != DBNull.Value) {
                        if (!DefaultValueIsNull) {
                            throw ExceptionBuilder.AutoIncrementAndDefaultValue();
                        }
                        if (!IsAutoIncrementType(DataType)) {
                            if (HasData) {
                                throw ExceptionBuilder.AutoIncrementCannotSetIfHasData(DataType.Name);
                            }
                            DataType = typeof(int);
                        }
                    }

                    this.AutoInc.Auto = value;
                }
            }
        }

        internal object AutoIncrementCurrent {
            get { return ((null != this.autoInc) ? this.autoInc.Current : this.AutoIncrementSeed); }
            set {
                if ((System.Numerics.BigInteger)this.AutoIncrementSeed != BigIntegerStorage.ConvertToBigInteger(value, this.FormatProvider)) {
                    this.AutoInc.SetCurrent(value, this.FormatProvider);
                }
            }
        }

        internal AutoIncrementValue AutoInc {
            get {
                return (this.autoInc ?? (this.autoInc = ((this.DataType == typeof(System.Numerics.BigInteger)) 
                                                         ? (AutoIncrementValue)new AutoIncrementBigInteger()
                                                         : new AutoIncrementInt64())));
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       or sets the starting value for a column that has its
        ///    <see cref='System.Data.DataColumn.AutoIncrement'/> property
        ///       set to <see langword='true'/>
        ///       .
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue((Int64)0),
        ResDescriptionAttribute(Res.DataColumnAutoIncrementSeedDescr)
        ]
        public Int64 AutoIncrementSeed {
            get {
                return ((null != this.autoInc) ? this.autoInc.Seed : 0L);
            }
            set {
                Bid.Trace("<ds.DataColumn.set_AutoIncrementSeed|API> %d#, %I64d\n", ObjectID, value);
                if (this.AutoIncrementSeed != value) {
                    this.AutoInc.Seed = value;
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the increment used by a column with its <see cref='System.Data.DataColumn.AutoIncrement'/>
        ///       property set to <see langword='true'/>
        ///       .
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue((Int64)1),
        ResDescriptionAttribute(Res.DataColumnAutoIncrementStepDescr)
        ]
        public Int64 AutoIncrementStep {
            get {
                return ((null != this.autoInc) ? this.autoInc.Step : 1L);
            }
            set {
                Bid.Trace("<ds.DataColumn.set_AutoIncrementStep|API> %d#, %I64d\n", ObjectID, value);
                if (this.AutoIncrementStep != value) {
                    this.AutoInc.Step = value;
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets
        ///       the caption for this column.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.DataColumnCaptionDescr)
        ]
        public string Caption {
            get {
                return (caption != null) ? caption : _columnName;
            }
            set {
                if (value == null)
                    value = "";

                if (caption == null || String.Compare(caption, value, true, Locale) != 0) {
                    caption = value;
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Resets the <see cref='System.Data.DataColumn.Caption'/> property to its previous value, or
        ///       to <see langword='null'/> .
        ///    </para>
        /// </devdoc>
        private void ResetCaption() {
            if (caption != null) {
                caption = null;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets a value indicating whether the <see cref='System.Data.DataColumn.Caption'/> has been explicitly set.
        ///    </para>
        /// </devdoc>
        private bool ShouldSerializeCaption() {
            return (caption != null);
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the name of the column within the <see cref='System.Data.DataColumnCollection'/>.
        ///    </para>
        /// </devdoc>
        [
        RefreshProperties(RefreshProperties.All),
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue(""),
        ResDescriptionAttribute(Res.DataColumnColumnNameDescr)
        ]
        public string ColumnName {
            get {
                return _columnName;
            }
            set {
                IntPtr hscp;
                Bid.ScopeEnter(out hscp, "<ds.DataColumn.set_ColumnName|API> %d#, '%ls'\n", ObjectID, value);
                try {
                    if (value == null) {
                        value = "";
                    }

                    if (String.Compare(_columnName, value, true, Locale) != 0) {
                        if (table != null) {
                            if (value.Length == 0)
                                throw ExceptionBuilder.ColumnNameRequired();

                            table.Columns.RegisterColumnName(value, this);
                            if (_columnName.Length != 0)
                                table.Columns.UnregisterName(_columnName);
                        }

                        RaisePropertyChanging("ColumnName");
                        _columnName = value;
                        encodedColumnName = null;
                        if (table != null) {
                            table.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
                        }
                    }
                    else if (_columnName != value) {
                        RaisePropertyChanging("ColumnName");
                        _columnName = value;
                        encodedColumnName = null;
                        if (table != null) {
                            table.Columns.OnColumnPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
                        }
                    }
                }
                finally {
                    Bid.ScopeLeave(ref hscp);
                }
            }
        }

        internal string EncodedColumnName {
            get {
                if (this.encodedColumnName == null) {
                    this.encodedColumnName = XmlConvert.EncodeLocalName(this.ColumnName);
                }
                Debug.Assert(this.encodedColumnName != null && this.encodedColumnName.Length != 0);
                return this.encodedColumnName;
            }
        }

        internal IFormatProvider FormatProvider {
            get {
                // used for formating/parsing not comparing
                return ((null != table) ? table.FormatProvider : CultureInfo.CurrentCulture);
            }
        }

        internal CultureInfo Locale {
            get {
                // used for comparing not formating/parsing
                return ((null != table) ? table.Locale : CultureInfo.CurrentCulture);
            }
        }

        internal int ObjectID {
            get {
                return _objectID;
            }
        }

        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue(""),
        ResDescriptionAttribute(Res.DataColumnPrefixDescr)
        ]
        public string Prefix {
            get { return _columnPrefix; }
            set {
                if (value == null)
                    value = "";
                Bid.Trace("<ds.DataColumn.set_Prefix|API> %d#, '%ls'\n", ObjectID, value);

                if ((XmlConvert.DecodeName(value) == value) && (XmlConvert.EncodeName(value) != value))
                    throw ExceptionBuilder.InvalidPrefix(value);

                _columnPrefix = value;

            }
        }

        // Return the field value as a string. If the field value is NULL, then NULL is return.
        // If the column type is string and it's value is empty, then the empty string is returned.
        // If the column type is not string, or the column type is string and the value is not empty string, then a non-empty string is returned
        // This method does not throw any formatting exceptions, since we can always format the field value to a string.
        internal string GetColumnValueAsString(DataRow row, DataRowVersion version) {

            object objValue = this[row.GetRecordFromVersion(version)];

            if (DataStorage.IsObjectNull(objValue)) {
                return null;
            }

            string value = ConvertObjectToXml(objValue);
            Debug.Assert(value != null);

            return value;
        }

        /// <devdoc>
        /// Whether this column computes values.
        /// </devdoc>
        internal bool Computed {
            get {
                return this.expression != null;
            }
        }

        /// <devdoc>
        /// The internal expression object that computes the values.
        /// </devdoc>
        internal DataExpression DataExpression {
            get {
                return this.expression;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       The type
        ///       of data stored in thecolumn.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue(typeof(string)),
        RefreshProperties(RefreshProperties.All),
        TypeConverter(typeof(ColumnTypeConverter)),
        ResDescriptionAttribute(Res.DataColumnDataTypeDescr)
        ]
        public Type DataType {
            get {
                return dataType;
            }
            set {
                if (dataType != value) {
                    if (HasData) {
                        throw ExceptionBuilder.CantChangeDataType();
                    }
                    if (value == null) {
                        throw ExceptionBuilder.NullDataType();
                    }
                    StorageType typeCode = DataStorage.GetStorageType(value);
                    if (DataStorage.ImplementsINullableValue(typeCode, value)) {
                        throw ExceptionBuilder.ColumnTypeNotSupported();
                    }
                    if (table != null && IsInRelation()) {
                        throw ExceptionBuilder.ColumnsTypeMismatch();
                    }
                    if (typeCode == StorageType.BigInteger && this.expression != null)
                    {
                        throw ExprException.UnsupportedDataType(value);
                    }

                    // If the DefualtValue is different from the Column DataType, we will coerce the value to the DataType
                    if (!DefaultValueIsNull) {
                        try {
                            if (this.defaultValue is System.Numerics.BigInteger) {
                                this.defaultValue = BigIntegerStorage.ConvertFromBigInteger((System.Numerics.BigInteger)this.defaultValue, value, this.FormatProvider);
                            }
                            else if (typeof(System.Numerics.BigInteger) == value) {
                                this.defaultValue = BigIntegerStorage.ConvertToBigInteger(this.defaultValue, this.FormatProvider);
                            }
                            else if (typeof(string) == value) { // since string types can be null in value! DO NOT REMOVE THIS 
                                defaultValue = DefaultValue.ToString();
                            }
                            else if (typeof(SqlString) == value) { // since string types can be null in value! DO NOT REMOVE THIS 
                                defaultValue = SqlConvert.ConvertToSqlString(DefaultValue);
                            }
                            else if (typeof(object) != value) {
                                DefaultValue = SqlConvert.ChangeTypeForDefaultValue(DefaultValue, value, FormatProvider);
                            }
                        }
                        catch (InvalidCastException ex) {
                            throw ExceptionBuilder.DefaultValueDataType(ColumnName, DefaultValue.GetType(), value, ex);
                        }
                        catch (FormatException ex) {
                            throw ExceptionBuilder.DefaultValueDataType(ColumnName, DefaultValue.GetType(), value, ex);
                        }
                    }

                    if (this.ColumnMapping == MappingType.SimpleContent)
                        if (value == typeof(Char))
                            throw ExceptionBuilder.CannotSetSimpleContentType(ColumnName, value);

                    SimpleType = SimpleType.CreateSimpleType(typeCode, value);
                    if (StorageType.String == typeCode) {
                        maxLength = -1;
                    }
                    UpdateColumnType(value, typeCode);
                    XmlDataType = null;

                    if (AutoIncrement) {
                        if (!IsAutoIncrementType(value)) {
                            AutoIncrement = false;
                        }

                        if (null != this.autoInc) {
                            // if you already have data you can't change the data type
                            // if you don't have data - you wouldn't have incremented AutoIncrementCurrent.
                            AutoIncrementValue inc = this.autoInc;
                            this.autoInc = null;
                            this.AutoInc.Auto = inc.Auto; // recreate with correct datatype
                            this.AutoInc.Seed = inc.Seed;
                            this.AutoInc.Step = inc.Step;
                            if (this.autoInc.DataType == inc.DataType) {
                                this.autoInc.Current = inc.Current;
                            }
                            else if (inc.DataType == typeof(Int64)) {
                                this.AutoInc.Current = (System.Numerics.BigInteger)(long)inc.Current;
                            }
                            else {
                                this.AutoInc.Current = checked((long)(System.Numerics.BigInteger)inc.Current);
                            }
                        }
                    }
                }
            }
        }

        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue(DataSetDateTime.UnspecifiedLocal),
        RefreshProperties(RefreshProperties.All),
        ResDescriptionAttribute(Res.DataColumnDateTimeModeDescr)
        ]
        public DataSetDateTime DateTimeMode {
            get {
                return _dateTimeMode;
            }
            set {
                if (_dateTimeMode != value) {
                    if (DataType != typeof(DateTime) && value != DataSetDateTime.UnspecifiedLocal) { //Check for column being DateTime. If the column is not DateTime make sure the value that is being is only the default[UnspecifiedLocal].
                        throw ExceptionBuilder.CannotSetDateTimeModeForNonDateTimeColumns();
                    }
                    switch (value) {
                    case DataSetDateTime.Utc:
                    case DataSetDateTime.Local:
                        if (HasData) {
                            throw ExceptionBuilder.CantChangeDateTimeMode(_dateTimeMode, value);
                        }
                        break;
                    case DataSetDateTime.Unspecified:
                    case DataSetDateTime.UnspecifiedLocal:
                        if (_dateTimeMode == DataSetDateTime.Unspecified || _dateTimeMode == DataSetDateTime.UnspecifiedLocal) {
                            break;
                        }
                        if (HasData) {
                            throw ExceptionBuilder.CantChangeDateTimeMode(_dateTimeMode, value);
                        }
                        break;
                    default:
                        throw ExceptionBuilder.InvalidDateTimeMode(value);
                    }
                    _dateTimeMode = value;
                }
            }
        }

        /// <devdoc>
        ///    <para>Gets or sets the default value for the
        ///       column when creating new rows.</para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.DataColumnDefaultValueDescr),
        TypeConverter(typeof(DefaultValueTypeConverter))
        ]
        public object DefaultValue {
            get {
                Debug.Assert(defaultValue != null, "It should not have been set to null.");
                if (defaultValue == DBNull.Value && this.implementsINullable) { // for perf I dont access property
                    if (_storage != null)
                        defaultValue = _storage.NullValue;
                    else if (this.isSqlType)
                            defaultValue = SqlConvert.ChangeTypeForDefaultValue(defaultValue, this.dataType, FormatProvider);
                    else if (this.implementsINullable) {
                        System.Reflection.PropertyInfo propInfo = this.dataType.GetProperty("Null", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                        if (propInfo != null)
                            defaultValue = propInfo.GetValue(null, null);
                    }
                }

                return defaultValue;
            }
            set {
                Bid.Trace("<ds.DataColumn.set_DefaultValue|API> %d#\n", ObjectID);
                if (defaultValue == null || !DefaultValue.Equals(value)) {
                    if (AutoIncrement) {
                        throw ExceptionBuilder.DefaultValueAndAutoIncrement();
                    }

                    object newDefaultValue = (value == null) ? DBNull.Value : value;
                    if (newDefaultValue != DBNull.Value && DataType != typeof(Object)) {
                        // If the DefualtValue is different from the Column DataType, we will coerce the value to the DataType
                        try {
                            newDefaultValue = SqlConvert.ChangeTypeForDefaultValue(newDefaultValue, DataType, FormatProvider);
                        }
                        catch (InvalidCastException ex) {
                            throw ExceptionBuilder.DefaultValueColumnDataType(ColumnName, newDefaultValue.GetType(), DataType, ex);
                        }
                    }
                    defaultValue = newDefaultValue;
                    // SQL BU Defect Tracking 401640:  should not assign any value until conversion is successful.
                    defaultValueIsNull = ((newDefaultValue == DBNull.Value) || (this.ImplementsINullable && DataStorage.IsObjectSqlNull(newDefaultValue))) ? true : false;
                }
            }
        }

        internal bool DefaultValueIsNull {
            get {
                return defaultValueIsNull;
            }
        }

        internal void BindExpression() {
            this.DataExpression.Bind(this.table);
        }

        /// <devdoc>
        ///    <para>Gets
        ///       or sets the expresssion used to either filter rows, calculate the column's
        ///       value, or create an aggregate column.</para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        RefreshProperties(RefreshProperties.All),
        DefaultValue(""),
        ResDescriptionAttribute(Res.DataColumnExpressionDescr)
        ]
        public string Expression {
            get {
                return (this.expression == null ? "" : this.expression.Expression);
            }
            set {
                IntPtr hscp;
                Bid.ScopeEnter(out hscp, "<ds.DataColumn.set_Expression|API> %d#, '%ls'\n", ObjectID, value);

                if (value == null) {
                    value = "";
                }

                try {
                    DataExpression newExpression = null;
                    if (value.Length > 0) {
                        DataExpression testExpression = new DataExpression(this.table, value, this.dataType);
                        if (testExpression.HasValue) {
                            newExpression = testExpression;
                        }
                    }

                    if (expression == null && newExpression != null) {
                        if (AutoIncrement || Unique) {
                            throw ExceptionBuilder.ExpressionAndUnique();
                        }

                        // We need to make sure the column is not involved in any Constriants
                        if (table != null) {
                            for (int i = 0; i < table.Constraints.Count; i++) {
                                if (table.Constraints[i].ContainsColumn(this)) {
                                    throw ExceptionBuilder.ExpressionAndConstraint(this, table.Constraints[i]);
                                }
                            }
                        }

                        bool oldReadOnly = ReadOnly;
                        try {
                            ReadOnly = true;
                        }
                        catch (ReadOnlyException e) {
                            ExceptionBuilder.TraceExceptionForCapture(e);
                            ReadOnly = oldReadOnly;
                            throw ExceptionBuilder.ExpressionAndReadOnly();
                        }
                    }

                    // re-calculate the evaluation queue
                    if (this.table != null) {
                        if (newExpression != null && newExpression.DependsOn(this)) {
                            throw ExceptionBuilder.ExpressionCircular();
                        }
                        HandleDependentColumnList(expression, newExpression);
                        //hold onto oldExpression in case of error applying new Expression.
                        DataExpression oldExpression = this.expression;
                        this.expression = newExpression;

                        // because the column is attached to a table we need to re-calc values
                        try {
                            if (newExpression == null) {
                                for (int i = 0; i < table.RecordCapacity; i++) {
                                    InitializeRecord(i);
                                }
                            }
                            else {
                                this.table.EvaluateExpressions(this);
                            }
                            // SQLBU 501916: DataTable internal index is corrupted:'5'
                            this.table.ResetInternalIndexes(this);
                            this.table.EvaluateDependentExpressions(this);
                        }
                        catch (Exception e1) {
                            // 
                            if (!ADP.IsCatchableExceptionType(e1)) {
                                throw;
                            }
                            ExceptionBuilder.TraceExceptionForCapture(e1);
                            try {
                                // in the case of error we need to set the column expression to the old value
                                this.expression = oldExpression;
                                HandleDependentColumnList(newExpression, expression);
                                if (oldExpression == null) {
                                    for (int i = 0; i < table.RecordCapacity; i++) {
                                        InitializeRecord(i);
                                    }
                                }
                                else {
                                    this.table.EvaluateExpressions(this);
                                }
                                this.table.ResetInternalIndexes(this);
                                this.table.EvaluateDependentExpressions(this);
                            }
                            catch (Exception e2) {
                                // 
                                if (!ADP.IsCatchableExceptionType(e2)) {
                                    throw;
                                }
                                ExceptionBuilder.TraceExceptionWithoutRethrow(e2);
                            }
                            throw;
                        }
                    }
                    else {
                        //if column is not attached to a table, just set.
                        this.expression = newExpression;
                    }
                }
                finally {
                    Bid.ScopeLeave(ref hscp);
                }
            }
        }

        /// <devdoc>
        ///    <para>Gets the collection of custom user information.</para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        Browsable(false),
        ResDescriptionAttribute(Res.ExtendedPropertiesDescr)
        ]
        public PropertyCollection ExtendedProperties {
            get {
                if (extendedProperties == null) {
                    extendedProperties = new PropertyCollection();
                }
                return extendedProperties;
            }
        }

        /// <devdoc>
        /// Indicates whether this column is now storing data.
        /// </devdoc>
        internal bool HasData {
            get {
                return (_storage != null);
            }
        }

        internal bool ImplementsINullable {
            get {
                return implementsINullable;
            }
        }

        internal bool ImplementsIChangeTracking {
            get {
                return implementsIChangeTracking;
            }
        }

        internal bool ImplementsIRevertibleChangeTracking {
            get {
                return implementsIRevertibleChangeTracking;
            }
        }

        internal bool IsCloneable {
            get {
                Debug.Assert(null != _storage, "no storage");
                return _storage.IsCloneable;
            }
        }

        internal bool IsStringType {
            get {
                Debug.Assert(null != _storage, "no storage");
                return _storage.IsStringType;
            }
        }

        internal bool IsValueType {
            get {
                Debug.Assert(null != _storage, "no storage");
                return _storage.IsValueType;
            }
        }

        internal bool IsSqlType {
            get {
                return isSqlType;
            }
        }

        private void SetMaxLengthSimpleType() {
            if (this.simpleType != null) {
                Debug.Assert(this.simpleType.CanHaveMaxLength(), "expected simpleType to be string");

                this.simpleType.MaxLength = maxLength;
                // check if we reset the simpleType back to plain string
                if (this.simpleType.IsPlainString()) {
                    this.simpleType = null;
                }
                else {
                    // Named Simple Type's Name should not be null
                    if (this.simpleType.Name != null && this.dttype != null) {
                        // if MaxLength is changed, we need to make  namedsimpletype annonymous simpletype
                        this.simpleType.ConvertToAnnonymousSimpleType();
                        this.dttype = null;
                    }
                }
            }
            else if (-1 < maxLength) {
                this.SimpleType = SimpleType.CreateLimitedStringType(maxLength);
            }
        }
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.DataColumnMaxLengthDescr),
        DefaultValue(-1)
        ]
        public int MaxLength {
            get {
                return maxLength;
            }
            set {
                IntPtr hscp;
                Bid.ScopeEnter(out hscp, "<ds.DataColumn.set_MaxLength|API> %d#, %d\n", ObjectID, value);

                try {
                    if (maxLength != value) {
                        if (this.ColumnMapping == MappingType.SimpleContent) {
                            throw ExceptionBuilder.CannotSetMaxLength2(this);
                        }
                        if ((DataType != typeof(string)) && (DataType != typeof(SqlString))) {
                            throw ExceptionBuilder.HasToBeStringType(this);
                        }
                        int oldValue = maxLength;
                        maxLength = Math.Max(value, -1);

                        if (((oldValue < 0) || (value < oldValue)) && (null != table) && table.EnforceConstraints) {
                            if (!CheckMaxLength()) {
                                maxLength = oldValue;
                                throw ExceptionBuilder.CannotSetMaxLength(this, value);
                            }
                        }
                        SetMaxLengthSimpleType();
                    }
                }
                finally {
                    Bid.ScopeLeave(ref hscp);
                }
            }
        }

        [
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.DataColumnNamespaceDescr)
        ]
        public string Namespace {
            get {
                if (_columnUri == null) {
                    if (Table != null && columnMapping != MappingType.Attribute) {
                        return Table.Namespace;
                    }
                    return "";
                }
                return _columnUri;
            }
            set {
                Bid.Trace("<ds.DataColumn.set_Namespace|API> %d#, '%ls'\n", ObjectID, value);

                if (_columnUri != value) {
                    if (columnMapping != MappingType.SimpleContent) {
                        RaisePropertyChanging("Namespace");
                        _columnUri = value;
                    }
                    else if (value != this.Namespace) {
                        throw ExceptionBuilder.CannotChangeNamespace(this.ColumnName);
                    }
                }
            }
        }

        private bool ShouldSerializeNamespace() {
            return (_columnUri != null);
        }

        private void ResetNamespace() {
            this.Namespace = null;
        }

        /// <devdoc>
        ///    <para>
        ///       Gets the position of the column in the <see cref='System.Data.DataColumnCollection'/>
        ///       collection.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.DataColumnOrdinalDescr)
        ]
        public int Ordinal {
            get {
                return _ordinal;
            }
        }

        public void SetOrdinal(int ordinal) {
            if (_ordinal == -1) {
                throw ExceptionBuilder.ColumnNotInAnyTable();
            }

            if (this._ordinal != ordinal) {
                table.Columns.MoveTo(this, ordinal);
            }
        }

        internal void SetOrdinalInternal(int ordinal) {
            // 
            if (this._ordinal != ordinal) {
                if (Unique && this._ordinal != -1 && ordinal == -1) {
                    UniqueConstraint key = table.Constraints.FindKeyConstraint(this);
                    if (key != null)
                        table.Constraints.Remove(key);
                }
                // SQLBU 429176: remove the sortIndex when DataColumn is removed
                if ((null != sortIndex) && (-1 == ordinal)) {
                    Debug.Assert(2 <= sortIndex.RefCount, "bad sortIndex refcount");
                    sortIndex.RemoveRef();
                    sortIndex.RemoveRef(); // second should remove it from index collection
                    sortIndex = null;
                }
                int originalOrdinal = this._ordinal;
                this._ordinal = ordinal;
                if (originalOrdinal == -1 && this._ordinal != -1) {
                    if (Unique) {
                        UniqueConstraint key = new UniqueConstraint(this);
                        table.Constraints.Add(key);
                    }
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets a value
        ///       indicating whether the column allows changes once a row has been added to the table.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue(false),
        ResDescriptionAttribute(Res.DataColumnReadOnlyDescr)
        ]
        public bool ReadOnly {
            get {
                return readOnly;
            }
            set {
                Bid.Trace("<ds.DataColumn.set_ReadOnly|API> %d#, %d{bool}\n", ObjectID, value);
                if (readOnly != value) {
                    if (!value && expression != null) {
                        throw ExceptionBuilder.ReadOnlyAndExpression();
                    }
                    this.readOnly = value;
                }
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)] // don't have debugger view expand this
        private Index SortIndex {
            get {
                if (sortIndex == null) {
                    IndexField[] indexDesc = new IndexField[] { new IndexField(this, false) };
                    sortIndex = table.GetIndex(indexDesc, DataViewRowState.CurrentRows, (IFilter)null);
                    sortIndex.AddRef();
                }
                return sortIndex;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets the <see cref='System.Data.DataTable'/> to which the column belongs to.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.DataColumnDataTableDescr)
        ]
        public DataTable Table {
            get {
                return table;
            }
        }

        /// <devdoc>
        /// Internal mechanism for changing the table pointer.
        /// </devdoc>
        internal void SetTable(DataTable table) {
            if (this.table != table) {
                if (this.Computed)
                    if ((table == null) ||
                        (!table.fInitInProgress && ((table.DataSet == null) || (!table.DataSet.fIsSchemaLoading && !table.DataSet.fInitInProgress)))) {
                        // We need to re-bind all expression columns.
                        this.DataExpression.Bind(table);
                    }

                if (Unique && this.table != null) {
                    UniqueConstraint constraint = table.Constraints.FindKeyConstraint(this);
                    if (constraint != null)
                        table.Constraints.CanRemove(constraint, true);
                }
                this.table = table;
                _storage = null; // empty out storage for reuse.
            }
        }

        private DataRow GetDataRow(int index) {
            return table.recordManager[index];
        }

        /// <devdoc>
        /// This is how data is pushed in and out of the column.
        /// </devdoc>
        internal object this[int record] {
            get {
                table.recordManager.VerifyRecord(record);
                Debug.Assert(null != _storage, "null storage");
                return _storage.Get(record);
            }
            set {
                try {
                    table.recordManager.VerifyRecord(record);
                    Debug.Assert(null != _storage, "no storage");
                    Debug.Assert(null != value, "setting null, expecting dbnull");
                    _storage.Set(record, value);
                    Debug.Assert(null != this.table, "storage with no DataTable on column");
                }
                catch (Exception e) {
                    ExceptionBuilder.TraceExceptionForCapture(e);
                    throw ExceptionBuilder.SetFailed(value, this, DataType, e);
                }

                if (AutoIncrement) {
                    if (!_storage.IsNull(record)) {
                        this.AutoInc.SetCurrentAndIncrement(_storage.Get(record));
                    }
                }
                if (Computed) {// if and only if it is Expression column, we will cache LastChangedColumn, otherwise DO NOT
                    DataRow dr = GetDataRow(record);
                    if (dr != null) {
                        // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we wont have datarow)
                        dr.LastChangedColumn = this;
                    }
                }
            }
        }

        internal void InitializeRecord(int record) {
            Debug.Assert(null != _storage, "no storage");
            _storage.Set(record, DefaultValue);
        }

        internal void SetValue(int record, object value) { // just silently set the value
            try {
                Debug.Assert(null != value, "setting null, expecting dbnull");
                Debug.Assert(null != this.table, "storage with no DataTable on column");
                Debug.Assert(null != _storage, "no storage");
                _storage.Set(record, value);
            }
            catch (Exception e) {
                ExceptionBuilder.TraceExceptionForCapture(e);
                throw ExceptionBuilder.SetFailed(value, this, DataType, e);
            }

            DataRow dr = GetDataRow(record);
            if (dr != null) {  // at initialization time (datatable.NewRow(), we would fill the storage with default value, but at that time we wont have datarow)
                dr.LastChangedColumn = this;
            }
        }

        internal void FreeRecord(int record) {
            Debug.Assert(null != _storage, "no storage");
            _storage.Set(record, _storage.NullValue);
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets a value indicating whether the values in each row of the column must be unique.
        ///    </para>
        /// </devdoc>
        [
        ResCategoryAttribute(Res.DataCategory_Data),
        DefaultValue(false),
        ResDescriptionAttribute(Res.DataColumnUniqueDescr),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public bool Unique {
            get {
                return unique;
            }
            set {
                IntPtr hscp;
                Bid.ScopeEnter(out hscp, "<ds.DataColumn.set_Unique|API> %d#, %d{bool}\n", ObjectID, value);
                try {
                    if (unique != value) {
                        if (value && expression != null) {
                            throw ExceptionBuilder.UniqueAndExpression();
                        }
                        UniqueConstraint oldConstraint = null;
                        if (table != null) {
                            if (value)
                                CheckUnique();
                            else {
                                for (System.Collections.IEnumerator e = Table.Constraints.GetEnumerator(); e.MoveNext(); ) {
                                    UniqueConstraint o = (e.Current as UniqueConstraint);
                                    if ((null != o) && (o.ColumnsReference.Length == 1) && (o.ColumnsReference[0] == this))
                                        oldConstraint = o;
                                }
                                Debug.Assert(oldConstraint != null, "Should have found a column to remove from the collection.");
                                table.Constraints.CanRemove(oldConstraint, true);
                            }
                        }

                        this.unique = value;

                        if (table != null) {
                            if (value) {
                                // This should not fail due to a duplicate constraint. unique would have
                                // already been true if there was an existed UniqueConstraint for this column

                                UniqueConstraint constraint = new UniqueConstraint(this);
                                Debug.Assert(table.Constraints.FindKeyConstraint(this) == null, "Should not be a duplication constraint in collection");
                                table.Constraints.Add(constraint);
                            }
                            else
                            {
                                table.Constraints.Remove(oldConstraint);
                                // 
                            }
                        }
                    }
                }
                finally {
                    Bid.ScopeLeave(ref hscp);
                }
            }
        }


        // FxCop Rule; getter not used!  WebData 101301; so changing from Property to method
        internal void InternalUnique(bool value) {
            this.unique = value;
        }

        internal string XmlDataType {
            get {
                return dttype;
            }
            set {
                dttype = value;
            }
        }

        internal SimpleType SimpleType {
            get {
                return simpleType;
            }
            set {
                simpleType = value;
                // there is a change, since we are supporting hierarchy(bacause of Names Simple Type) old check (just one leel base check) is wrong
                if (value != null && value.CanHaveMaxLength())
                    maxLength = simpleType.MaxLength;// this is temp solution, since we dont let simple content to have
                //maxlength set but for simple type we want to set it, after coming to decision about it , we should
                // use MaxLength property
            }
        }

        /// <devdoc>
        /// <para>Gets the <see cref='System.Data.MappingType'/> of the column.</para>
        /// </devdoc>
        [
        DefaultValue(MappingType.Element),
        ResDescriptionAttribute(Res.DataColumnMappingDescr)
        ]
        public virtual MappingType ColumnMapping {
            get {
                return columnMapping;
            }
            set {
                Bid.Trace("<ds.DataColumn.set_ColumnMapping|API> %d#, %d{ds.MappingType}\n", ObjectID, (int)value);
                if (value != columnMapping) {

                    if (value == MappingType.SimpleContent && table != null) {
                        int threshold = 0;
                        if (columnMapping == MappingType.Element)
                            threshold = 1;
                        if (this.dataType == typeof(Char))
                            throw ExceptionBuilder.CannotSetSimpleContent(ColumnName, this.dataType);

                        if (table.XmlText != null && table.XmlText != this)
                            throw ExceptionBuilder.CannotAddColumn3();
                        if (table.ElementColumnCount > threshold)
                            throw ExceptionBuilder.CannotAddColumn4(this.ColumnName);
                    }

                    RaisePropertyChanging("ColumnMapping");

                    if (table != null) {
                        if (columnMapping == MappingType.SimpleContent)
                            table.xmlText = null;

                        if (value == MappingType.Element)
                            table.ElementColumnCount++;
                        else if (columnMapping == MappingType.Element)
                            table.ElementColumnCount--;
                    }

                    columnMapping = value;
                    if (value == MappingType.SimpleContent) {
                        _columnUri = null;
                        if (table != null) {
                            table.XmlText = this;
                        }
                        this.SimpleType = null;
                    }
                }
            }
        }

        internal event PropertyChangedEventHandler PropertyChanging {
            add {
                onPropertyChangingDelegate += value;
            }
            remove {
                onPropertyChangingDelegate -= value;
            }
        }

        internal void CheckColumnConstraint(DataRow row, DataRowAction action) {
            if (table.UpdatingCurrent(row, action)) {
                CheckNullable(row);
                CheckMaxLength(row);
            }
        }

        internal bool CheckMaxLength() {
            if ((0 <= maxLength) && (null != Table) && (0 < Table.Rows.Count)) {
                Debug.Assert(IsStringType, "not a String or SqlString column");
                foreach (DataRow dr in Table.Rows) {
                    if (dr.HasVersion(DataRowVersion.Current)) {
                        if (maxLength < GetStringLength(dr.GetCurrentRecordNo())) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        internal void CheckMaxLength(DataRow dr) {
            if (0 <= maxLength) {
                Debug.Assert(IsStringType, "not a String or SqlString column");
                if (maxLength < GetStringLength(dr.GetDefaultRecord())) {
                    throw ExceptionBuilder.LongerThanMaxLength(this);
                }
            }
        }

        internal protected void CheckNotAllowNull() {
            if (_storage == null)
                return;

            if (sortIndex != null) {
                if (sortIndex.IsKeyInIndex(_storage.NullValue)) {// here we do use strong typed NULL for Sql types
                    throw ExceptionBuilder.NullKeyValues(ColumnName);
                }
            }
            else { // since we do not have index, we so sequential search
                foreach (DataRow dr in this.table.Rows) {
                    if (dr.RowState == DataRowState.Deleted)
                        continue;
                    if (!implementsINullable) {
                        if (dr[this] == DBNull.Value) {
                            throw ExceptionBuilder.NullKeyValues(ColumnName);
                        }
                    }
                    else {
                        if (DataStorage.IsObjectNull(dr[this])) {
                            throw ExceptionBuilder.NullKeyValues(ColumnName);
                        }
                    }
                }
            }
        }

        internal void CheckNullable(DataRow row) {
            if (!AllowDBNull) {
                Debug.Assert(null != _storage, "no storage");
                if (_storage.IsNull(row.GetDefaultRecord())) {
                    throw ExceptionBuilder.NullValues(ColumnName);
                }
            }
        }

        protected void CheckUnique() {
            if (!SortIndex.CheckUnique()) {
                // Throws an exception and the name of any column if its Unique property set to
                // True and non-unique values are found in the column.
                throw ExceptionBuilder.NonUniqueValues(ColumnName);
            }
        }

        internal int Compare(int record1, int record2) {
            Debug.Assert(null != _storage, "null storage");
            return _storage.Compare(record1, record2);
        }

        internal bool CompareValueTo(int record1, object value, bool checkType) {
            // this method is used to make sure value and exact type match.
            int valuesMatch = CompareValueTo(record1, value);
            // if values match according to storage, do extra checks for exact compare
            if (valuesMatch == 0) {
                Type leftType = value.GetType();
                Type rightType = _storage.Get(record1).GetType();
                // if strings, then do exact character by character check
                if (leftType == typeof(System.String) && rightType == typeof(System.String)) {
                    return String.CompareOrdinal((string)_storage.Get(record1), (string)value) == 0 ? true : false;
                }
                // make sure same type
                else if (leftType == rightType) {
                    return true;
                }
            }
            return false;
        }

        internal int CompareValueTo(int record1, object value) {
            Debug.Assert(null != _storage, "null storage");
            return _storage.CompareValueTo(record1, value);
        }

        internal object ConvertValue(object value) {
            Debug.Assert(null != _storage, "null storage");
            return _storage.ConvertValue(value);
        }

        internal void Copy(int srcRecordNo, int dstRecordNo) {
            Debug.Assert(null != _storage, "null storage");
            _storage.Copy(srcRecordNo, dstRecordNo);
        }

        // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
        [MethodImpl(MethodImplOptions.NoInlining)] 
        internal DataColumn Clone() {
            DataColumn clone = (DataColumn)Activator.CreateInstance(this.GetType());
            // set All properties
            //            clone.columnMapping = columnMapping;

            clone.SimpleType = SimpleType;

            clone.allowNull = allowNull;
            if (null != this.autoInc) {
                clone.autoInc = this.autoInc.Clone();
            }
            clone.caption = caption;
            clone.ColumnName = ColumnName;
            clone._columnUri = _columnUri;
            clone._columnPrefix = _columnPrefix;
            clone.DataType = DataType;
            clone.defaultValue = defaultValue;
            clone.defaultValueIsNull = ((defaultValue == DBNull.Value) || (clone.ImplementsINullable && DataStorage.IsObjectSqlNull(defaultValue))) ? true : false;
            clone.columnMapping = columnMapping;// clone column Mapping since we dont let MaxLength to be set throu API
            // 
            clone.readOnly = readOnly;
            clone.MaxLength = MaxLength;
            clone.dttype = dttype;
            clone._dateTimeMode = _dateTimeMode;


            // so if we have set it, we should continue preserving the information

            // ...Extended Properties
            if (this.extendedProperties != null) {
                foreach (Object key in this.extendedProperties.Keys) {
                    clone.ExtendedProperties[key] = this.extendedProperties[key];
                }
            }

            return clone;
        }

        /// <devdoc>
        ///    <para>Finds a relation that this column is the sole child of or null.</para>
        /// </devdoc>
        internal DataRelation FindParentRelation() {
            DataRelation[] parentRelations = new DataRelation[Table.ParentRelations.Count];
            Table.ParentRelations.CopyTo(parentRelations, 0);

            for (int i = 0; i < parentRelations.Length; i++) {
                DataRelation relation = parentRelations[i];
                DataKey key = relation.ChildKey;
                if (key.ColumnsReference.Length == 1 && key.ColumnsReference[0] == this) {
                    return relation;
                }
            }
            // should we throw an exception?
            return null;
        }


        internal object GetAggregateValue(int[] records, AggregateType kind) {
            if (_storage == null) {
                if (kind == AggregateType.Count)
                    return 0;
                else
                    return DBNull.Value;
            }
            return _storage.Aggregate(records, kind);
        }

        private int GetStringLength(int record) {
            Debug.Assert(null != _storage, "no storage");
            return _storage.GetStringLength(record);
        }

        internal void Init(int record) {
            if (AutoIncrement) {
                object value = this.autoInc.Current;
                this.autoInc.MoveAfter();
                Debug.Assert(null != _storage, "no storage");
                _storage.Set(record, value);
            }
            else
                this[record] = defaultValue;
        }

        internal static bool IsAutoIncrementType(Type dataType) {
            return ((dataType == typeof(Int32)) || (dataType == typeof(Int64)) || (dataType == typeof(Int16)) || (dataType == typeof(Decimal)) || (dataType == typeof(System.Numerics.BigInteger)) ||
                   (dataType == typeof(SqlInt32)) || (dataType == typeof(SqlInt64)) || (dataType == typeof(SqlInt16)) || (dataType == typeof(SqlDecimal)));
        }

        private bool IsColumnMappingValid(StorageType typeCode, MappingType mapping) {
            if ((mapping != MappingType.Element) && DataStorage.IsTypeCustomType(typeCode)) {
                return false;
            }
            return true;
        }

        internal bool IsCustomType {
            get {
                if (null != _storage)
                    return _storage.IsCustomDefinedType;
                return DataStorage.IsTypeCustomType(DataType);
            }
        }

        internal bool IsValueCustomTypeInstance(object value) {
            // if instance is not a storage supported type (built in or SQL types)
            return (DataStorage.IsTypeCustomType(value.GetType()) && !(value is Type));
        }

        internal bool ImplementsIXMLSerializable {
            get {
                return implementsIXMLSerializable;
            }
        }

        internal bool IsNull(int record) {
            Debug.Assert(null != _storage, "no storage");
            return _storage.IsNull(record);
        }

        /// <devdoc>
        ///      Returns true if this column is a part of a Parent or Child key for a relation.
        /// </devdoc>
        internal bool IsInRelation() {
            DataKey key;
            DataRelationCollection rels = table.ParentRelations;

            Debug.Assert(rels != null, "Invalid ParentRelations");
            for (int i = 0; i < rels.Count; i++) {
                key = rels[i].ChildKey;
                Debug.Assert(key.HasValue, "Invalid child key (null)");
                if (key.ContainsColumn(this)) {
                    return true;
                }
            }
            rels = table.ChildRelations;
            Debug.Assert(rels != null, "Invalid ChildRelations");
            for (int i = 0; i < rels.Count; i++) {
                key = rels[i].ParentKey;
                Debug.Assert(key.HasValue, "Invalid parent key (null)");
                if (key.ContainsColumn(this)) {
                    return true;
                }
            }
            return false;
        }

        internal bool IsMaxLengthViolated() {
            if (MaxLength < 0)
                return true;

            bool error = false;
            object value;
            string errorText = null;

            foreach (DataRow dr in Table.Rows) {
                if (dr.HasVersion(DataRowVersion.Current)) {
                    value = dr[this];
                    if (!this.isSqlType) {
                        if (value != null && value != DBNull.Value && ((string)value).Length > MaxLength) {
                            if (errorText == null) {
                                errorText = ExceptionBuilder.MaxLengthViolationText(this.ColumnName);
                            }
                            dr.RowError = errorText;
                            dr.SetColumnError(this, errorText);
                            error = true;
                        }
                    }
                    else {
                        if (!DataStorage.IsObjectNull(value) && ((SqlString)value).Value.Length > MaxLength) {
                            if (errorText == null) {
                                errorText = ExceptionBuilder.MaxLengthViolationText(this.ColumnName);
                            }
                            dr.RowError = errorText;
                            dr.SetColumnError(this, errorText);
                            error = true;
                        }
                    }
                }
            }
            return error;
        }

        internal bool IsNotAllowDBNullViolated() {//
            Index index = this.SortIndex;
            DataRow[] rows = index.GetRows(index.FindRecords(DBNull.Value));
            for (int i = 0; i < rows.Length; i++) {
                string errorText = ExceptionBuilder.NotAllowDBNullViolationText(this.ColumnName);
                rows[i].RowError = errorText;
                rows[i].SetColumnError(this, errorText);
            }
            return (rows.Length > 0);
        }

        internal void FinishInitInProgress() {
            if (this.Computed)
                BindExpression();
        }

        protected virtual void OnPropertyChanging(PropertyChangedEventArgs pcevent) {
            if (onPropertyChangingDelegate != null)
                onPropertyChangingDelegate(this, pcevent);
        }

        protected internal void RaisePropertyChanging(string name) {
            OnPropertyChanging(new PropertyChangedEventArgs(name));
        }

        private void InsureStorage() {
            if (_storage == null) {
                _storage = DataStorage.CreateStorage(this, dataType, _storageType);
            }
        }

        internal void SetCapacity(int capacity) {
            InsureStorage();
            _storage.SetCapacity(capacity);
        }

        private bool ShouldSerializeDefaultValue() {
            return (!DefaultValueIsNull);
        }

        internal void OnSetDataSet() {
        }

        // Returns the <see cref='System.Data.DataColumn.Expression'/> of the column, if one exists.
        public override string ToString() {
            if (this.expression == null)
                return this.ColumnName;
            else
                return this.ColumnName + " + " + this.Expression;

        }


        internal object ConvertXmlToObject(string s) {
            Debug.Assert(s != null, "Caller is resposible for missing element/attribure case");
            InsureStorage();
            return _storage.ConvertXmlToObject(s);
        }

        internal object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute xmlAttrib) {
            InsureStorage();
            return _storage.ConvertXmlToObject(xmlReader, xmlAttrib);
        }


        internal string ConvertObjectToXml(object value) {
            Debug.Assert(value != null && (value != DBNull.Value), "Caller is resposible for checking on DBNull");
            InsureStorage();
            return _storage.ConvertObjectToXml(value);
        }

        internal void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) {
            Debug.Assert(value != null && (value != DBNull.Value), "Caller is resposible for checking on DBNull");
            InsureStorage();
            _storage.ConvertObjectToXml(value, xmlWriter, xmlAttrib);
        }

        internal object GetEmptyColumnStore(int recordCount) {
            InsureStorage();
            return _storage.GetEmptyStorageInternal(recordCount);
        }

        internal void CopyValueIntoStore(int record, object store, BitArray nullbits, int storeIndex) {
            Debug.Assert(null != _storage, "no storage");
            _storage.CopyValueInternal(record, store, nullbits, storeIndex);
        }

        internal void SetStorage(object store, BitArray nullbits) {
            InsureStorage();
            _storage.SetStorageInternal(store, nullbits);
        }

        internal void AddDependentColumn(DataColumn expressionColumn) {
            if (dependentColumns == null) {
                dependentColumns = new List<DataColumn>();
            }
            Debug.Assert(!dependentColumns.Contains(expressionColumn), "duplicate column - expected to be unique");
            dependentColumns.Add(expressionColumn);
            this.table.AddDependentColumn(expressionColumn);
        }

        internal void RemoveDependentColumn(DataColumn expressionColumn) {
            if (dependentColumns != null && dependentColumns.Contains(expressionColumn)) {
                dependentColumns.Remove(expressionColumn);
            }
            this.table.RemoveDependentColumn(expressionColumn);
        }

        internal void HandleDependentColumnList(DataExpression oldExpression, DataExpression newExpression) {
            DataColumn[] dependency;
            // remove this column from the dependentColumn list of the columns this column depends on.
            if (oldExpression != null) {
                dependency = oldExpression.GetDependency();
                foreach (DataColumn col in dependency) {
                    Debug.Assert(null != col, "null datacolumn in expression dependencies");
                    col.RemoveDependentColumn(this);
                    if (col.table != this.table) {
                        this.table.RemoveDependentColumn(this);
                    }
                }
                this.table.RemoveDependentColumn(this);
            }

            if (newExpression != null) {
                // get the list of columns that this expression depends on
                dependency = newExpression.GetDependency();
                // add this column to dependent column list of each column this column depends on
                foreach (DataColumn col in dependency) {
                    col.AddDependentColumn(this);
                    if (col.table != this.table) {
                        this.table.AddDependentColumn(this);
                    }
                }
                this.table.AddDependentColumn(this);
            }
        }
    }

    internal abstract class AutoIncrementValue {
        private bool auto;

        internal bool Auto {
            get { return this.auto; }
            set { this.auto = value; }
        }
        internal abstract object Current { get; set; }
        internal abstract long Seed { get; set; }
        internal abstract long Step { get; set; }
        internal abstract Type DataType { get; }

        internal abstract void SetCurrent(object value, IFormatProvider formatProvider);
        internal abstract void SetCurrentAndIncrement(object value);
        internal abstract void MoveAfter();

        internal AutoIncrementValue Clone() {
            AutoIncrementValue clone = (this is AutoIncrementInt64) ? (AutoIncrementValue)new AutoIncrementInt64() : (AutoIncrementValue)new AutoIncrementBigInteger();
            clone.Auto = this.Auto;
            clone.Seed = this.Seed;
            clone.Step = this.Step;
            clone.Current = this.Current;
            return clone;
        }
    }

    /// <summary>the auto stepped value with Int64 representation</summary>
    /// <remarks>use unchecked behavior for Dev10 Bug 568510</remarks>
    internal sealed class AutoIncrementInt64 : AutoIncrementValue {
        /// <summary>the last returned auto incremented value</summary>
        private System.Int64 current;

        /// <summary>the initial value use to set current</summary>
        private System.Int64 seed;

        /// <summary>the value by which to offset the next value</summary>
        private System.Int64 step = 1;

        /// <summary>Gets and sets the current auto incremented value to use</summary>
        internal override object Current {
            get { return this.current; }
            set { this.current = (Int64)value; }
        }

        internal override Type DataType { get { return typeof(System.Int64); } }

        /// <summary>Get and sets the initial seed value.</summary>
        internal override long Seed {
            get { return this.seed; }
            set {
                if ((this.current == this.seed) || this.BoundaryCheck(value)) {
                    this.current = value;
                }
                this.seed = value;
            }
        }

        /// <summary>Get and sets the stepping value.</summary>
        /// <exception cref="ArugmentException">if value is 0</exception>
        internal override long Step {
            get { return this.step; }
            set {
                if (0 == value) {
                    throw ExceptionBuilder.AutoIncrementSeed();
                }
                if (this.step != value) {
                    if (this.current != this.Seed) {
                        this.current = unchecked(this.current - this.step + value);
                    }
                    this.step = value;
                }
            }
        }

        internal override void MoveAfter() {
            this.current = unchecked(this.current + this.step);
        }

        internal override void SetCurrent(object value, IFormatProvider formatProvider) {
            this.current = Convert.ToInt64(value, formatProvider);
        }

        internal override void SetCurrentAndIncrement(object value) {
            Debug.Assert(null != value && DataColumn.IsAutoIncrementType(value.GetType()) && !(value is System.Numerics.BigInteger), "unexpected value for autoincrement");
            System.Int64 v = (Int64)SqlConvert.ChangeType2(value, StorageType.Int64, typeof(Int64), CultureInfo.InvariantCulture);
            if (this.BoundaryCheck(v)) {
                this.current = unchecked(v + this.step);
            }
        }

        private bool BoundaryCheck(System.Numerics.BigInteger value) {
            return (((this.step < 0) && (value <= this.current)) || ((0 < this.step) && (this.current <= value)));
        }
    }

    /// <summary>the auto stepped value with BigInteger representation</summary>
    internal sealed class AutoIncrementBigInteger : AutoIncrementValue {
        /// <summary>the current auto incremented value to use</summary>
        private System.Numerics.BigInteger current;

        /// <summary>the initial value use to set current</summary>
        private System.Int64 seed;

        /// <summary>the value by which to offset the next value</summary>
        private System.Numerics.BigInteger step = 1;

        /// <summary>Gets and sets the current auto incremented value to use</summary>
        internal override object Current {
            get { return this.current; }
            set { this.current = (System.Numerics.BigInteger)value; }
        }

        internal override Type DataType { get { return typeof(System.Numerics.BigInteger); } }

        /// <summary>Get and sets the initial seed value.</summary>
        internal override long Seed {
            get { return this.seed; }
            set {
                if ((this.current == this.seed) || this.BoundaryCheck(value)) {
                    this.current = value;
                }
                this.seed = value;
            }
        }

        /// <summary>Get and sets the stepping value.</summary>
        /// <exception cref="ArugmentException">if value is 0</exception>
        internal override long Step {
            get { return (long)this.step; }
            set {
                if (0 == value) {
                    throw ExceptionBuilder.AutoIncrementSeed();
                }
                if (this.step != value) {
                    if (this.current != this.Seed) {
                        this.current = checked(this.current - this.step + value);
                    }
                    this.step = value;
                }
            }
        }

        internal override void MoveAfter() {
            this.current = checked(this.current + this.step);
        }

        internal override void SetCurrent(object value, IFormatProvider formatProvider) {
            this.current = BigIntegerStorage.ConvertToBigInteger(value, formatProvider);
        }

        internal override void SetCurrentAndIncrement(object value) {
            System.Numerics.BigInteger v = (System.Numerics.BigInteger)value;
            if (this.BoundaryCheck(v)) {
                this.current = v + this.step;
            }
        }

        private bool BoundaryCheck(System.Numerics.BigInteger value) {
            return (((this.step < 0) && (value <= this.current)) || ((0 < this.step) && (this.current <= value)));
        }
    }
}