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

SqlDataReader.cs « SqlClient « Data « System « System.Data « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8e04c42254201997009d8e392d25ddbcad7d4f57 (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
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
//------------------------------------------------------------------------------
// <copyright file="SqlDataReader.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.SqlClient {
    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Data;
    using System.Data.Sql;
    using System.Data.SqlTypes;
    using System.Data.Common;
    using System.Data.ProviderBase;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Threading;
    using System.Xml;
    
    using Microsoft.SqlServer.Server;
    using System.Threading.Tasks;

    public class SqlDataReader : DbDataReader, IDataReader {

        private enum ALTROWSTATUS {
            Null = 0,           // default and after Done
            AltRow,             // after calling NextResult and the first AltRow is available for read
            Done,               // after consuming the value (GetValue -> GetValueInternal)
        }

        internal class SharedState { // parameters needed to execute cleanup from parser
            internal int _nextColumnHeaderToRead;
            internal int _nextColumnDataToRead;
            internal long _columnDataBytesRemaining;
            internal bool _dataReady; // ready to ProcessRow
        }

        internal SharedState _sharedState = new SharedState();

        private TdsParser                      _parser;                 // TODO: Probably don't need this, since it's on the stateObj
        private TdsParserStateObject           _stateObj;
        private SqlCommand                     _command;
        private SqlConnection                  _connection;
        private int                            _defaultLCID;
        private bool                           _haltRead;               // bool to denote whether we have read first row for single row behavior
        private bool                           _metaDataConsumed;
        private bool                           _browseModeInfoConsumed;
        private bool                           _isClosed;
        private bool                           _isInitialized;          // Webdata 104560
        private bool                           _hasRows;
        private ALTROWSTATUS                   _altRowStatus;
        private int                            _recordsAffected = -1;
        private long                           _defaultTimeoutMilliseconds;
        private SqlConnectionString.TypeSystem _typeSystem;

        // SQLStatistics support
        private SqlStatistics   _statistics;
        private SqlBuffer[]     _data;         // row buffer, filled in by ReadColumnData()
        private SqlStreamingXml _streamingXml; // Used by Getchars on an Xml column for sequential access

        // buffers and metadata
        private _SqlMetaDataSet           _metaData;                 // current metaData for the stream, it is lazily loaded
        private _SqlMetaDataSetCollection _altMetaDataSetCollection;
        private FieldNameLookup           _fieldNameLookup;
        private CommandBehavior           _commandBehavior;

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

        // context
        // undone: we may still want to do this...it's nice to pass in an lpvoid (essentially) and just have the reader keep the state
        // private object _context = null; // this is never looked at by the stream object.  It is used by upper layers who wish
        // to remain stateless

        // metadata (no explicit table, use 'Table')
        private MultiPartTableName[] _tableNames = null;
        private string               _resetOptionsString;

        private int    _lastColumnWithDataChunkRead;
        private long   _columnDataBytesRead;       // last byte read by user
        private long   _columnDataCharsRead;       // last char read by user
        private char[] _columnDataChars;
        private int    _columnDataCharsIndex;      // Column index that is currently loaded in _columnDataChars 

        private Task _currentTask;
        private Snapshot _snapshot;
        private CancellationTokenSource _cancelAsyncOnCloseTokenSource;
        private CancellationToken _cancelAsyncOnCloseToken;

        // Used for checking if the Type parameter provided to GetValue<T> is an INullable
        internal static readonly Type _typeofINullable = typeof(INullable);
        private static readonly Type _typeofSqlString = typeof(SqlString);

        private SqlSequentialStream _currentStream;
        private SqlSequentialTextReader _currentTextReader;
        
        internal SqlDataReader(SqlCommand command, CommandBehavior behavior)
        {
            SqlConnection.VerifyExecutePermission();
            
            _command = command;
            _commandBehavior = behavior;
            if (_command != null) {
                _defaultTimeoutMilliseconds = (long)command.CommandTimeout * 1000L;
                _connection = command.Connection;
                if (_connection != null) {
                    _statistics = _connection.Statistics;
                    _typeSystem = _connection.TypeSystem;
                }
            }
            _sharedState._dataReady = false;
            _metaDataConsumed = false;
            _hasRows = false;
            _browseModeInfoConsumed = false;
            _currentStream = null;
            _currentTextReader = null;
            _cancelAsyncOnCloseTokenSource = new CancellationTokenSource();
            _cancelAsyncOnCloseToken = _cancelAsyncOnCloseTokenSource.Token;
            _columnDataCharsIndex = -1;
        }
        
        internal bool BrowseModeInfoConsumed {
            set {
                _browseModeInfoConsumed = value;
            }
        }

        internal SqlCommand Command {
            get {
                return _command;
            }
        }

        protected SqlConnection Connection {
            get {
                return _connection;
            }
        }

        override public int Depth {
            get {
                if (this.IsClosed) {
                    throw ADP.DataReaderClosed("Depth");
                }

                return 0;
            }
        }

        // fields/attributes collection
        override public int FieldCount {
            get {
                if (this.IsClosed) {
                    throw ADP.DataReaderClosed("FieldCount");
                }
                if (_currentTask != null) {
                    throw ADP.AsyncOperationPending();
                }

                if (MetaData == null) {
                    return 0;
                }

                return _metaData.Length;
            }
        }

        override public bool HasRows {
            get {
                if (this.IsClosed) {
                    throw ADP.DataReaderClosed("HasRows");
                }
                if (_currentTask != null) {
                    throw ADP.AsyncOperationPending();
                }

                return _hasRows;
            }
        }

        override public bool IsClosed {
            get {
                return _isClosed;
            }
        }

        internal bool IsInitialized {
            get {
                return _isInitialized;
            }
            set {
                Debug.Assert(value, "attempting to uninitialize a data reader?");
                _isInitialized = value;
            }
        }

        // NOTE: For PLP values this indicates the amount of data left in the current chunk (or 0 if there are no more chunks left)
        internal long ColumnDataBytesRemaining() {
            // If there are an unknown (-1) number of bytes left for a PLP, read its size
            if (-1 == _sharedState._columnDataBytesRemaining) {
                _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
            }

            return _sharedState._columnDataBytesRemaining;
        }

        internal _SqlMetaDataSet MetaData {
            get {
                if (IsClosed) {
                    throw ADP.DataReaderClosed("MetaData");
                }
                // metaData comes in pieces: colmetadata, tabname, colinfo, etc
                // if we have any metaData, return it.  If we have none,
                // then fetch it
                if (_metaData == null && !_metaDataConsumed) {
                    if (_currentTask != null) {
                        throw SQL.PendingBeginXXXExists();
                    }

                    RuntimeHelpers.PrepareConstrainedRegions();
                    try {
#if DEBUG
                        TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                        RuntimeHelpers.PrepareConstrainedRegions();
                        try {
                            tdsReliabilitySection.Start();
#else
                        {
#endif //DEBUG

                            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
                            if (!TryConsumeMetaData())
                            {
                                throw SQL.SynchronousCallMayNotPend();
                            }
                        }
#if DEBUG
                        finally {
                            tdsReliabilitySection.Stop();
                        }
#endif //DEBUG
                    }
                    catch (System.OutOfMemoryException e) {
                        _isClosed = true;
                        if (null != _connection) {
                            _connection.Abort(e);
                        }
                        throw;
                    }
                    catch (System.StackOverflowException e) {
                        _isClosed = true;
                        if (null != _connection) {
                            _connection.Abort(e);
                        }
                        throw;
                    }
                    catch (System.Threading.ThreadAbortException e)  {
                        _isClosed = true;
                        if (null != _connection) {
                            _connection.Abort(e);
                        }
                        throw;
                    }
                }
                return _metaData;
            }
        }

        internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() {
            SmiExtendedMetaData[] metaDataReturn = null;
            _SqlMetaDataSet metaData = this.MetaData;

            if ( null != metaData && 0 < metaData.Length ) {
                metaDataReturn = new SmiExtendedMetaData[metaData.visibleColumns];

                for( int index=0; index < metaData.Length; index++ ) {
                    _SqlMetaData colMetaData = metaData[index];

                    if ( !colMetaData.isHidden ) {
                        SqlCollation collation = colMetaData.collation;

                        string typeSpecificNamePart1 = null;
                        string typeSpecificNamePart2 = null;
                        string typeSpecificNamePart3 = null;

                        if (SqlDbType.Xml == colMetaData.type) {
                            typeSpecificNamePart1 = colMetaData.xmlSchemaCollectionDatabase;
                            typeSpecificNamePart2 = colMetaData.xmlSchemaCollectionOwningSchema;
                            typeSpecificNamePart3 = colMetaData.xmlSchemaCollectionName;
                        }
                        else if (SqlDbType.Udt == colMetaData.type) {
                            Connection.CheckGetExtendedUDTInfo(colMetaData, true);    // SQLBUDT #370593 ensure that colMetaData.udtType is set

                            typeSpecificNamePart1 = colMetaData.udtDatabaseName;
                            typeSpecificNamePart2 = colMetaData.udtSchemaName;
                            typeSpecificNamePart3 = colMetaData.udtTypeName;
                        }

                        int length = colMetaData.length;
                        if ( length > TdsEnums.MAXSIZE ) {
                            length = (int) SmiMetaData.UnlimitedMaxLengthIndicator;
                        }
                        else if (SqlDbType.NChar == colMetaData.type
                                ||SqlDbType.NVarChar == colMetaData.type) {
                            length /= ADP.CharSize;
                        }

                        metaDataReturn[index] = new SmiQueryMetaData( 
                                                        colMetaData.type, 
                                                        length,
                                                        colMetaData.precision, 
                                                        colMetaData.scale, 
                                                        (null != collation) ? collation.LCID : _defaultLCID,
                                                        (null != collation) ? collation.SqlCompareOptions : SqlCompareOptions.None,
                                                        colMetaData.udtType, 
                                                        false,  // isMultiValued
                                                        null,   // fieldmetadata
                                                        null,   // extended properties
                                                        colMetaData.column, 
                                                        typeSpecificNamePart1, 
                                                        typeSpecificNamePart2, 
                                                        typeSpecificNamePart3,
                                                        colMetaData.isNullable,
                                                        colMetaData.serverName,
                                                        colMetaData.catalogName,
                                                        colMetaData.schemaName,
                                                        colMetaData.tableName,
                                                        colMetaData.baseColumn,
                                                        colMetaData.isKey,
                                                        colMetaData.isIdentity,
                                                        0==colMetaData.updatability,
                                                        colMetaData.isExpression,
                                                        colMetaData.isDifferentName,
                                                        colMetaData.isHidden
                                                        );
                    }
                }
            }

            return metaDataReturn;
        }

        override public int RecordsAffected {
            get {
                if (null != _command)
                    return _command.InternalRecordsAffected;

                // cached locally for after Close() when command is nulled out
                return _recordsAffected;
            }
        }

        internal string ResetOptionsString {
            set {
                _resetOptionsString = value;
            }
        }

        private SqlStatistics Statistics {
            get {
                return _statistics;
            }
        }

        internal MultiPartTableName[] TableNames {
            get {
                return _tableNames;
            }
            set {
                _tableNames = value;
            }
        }

        override public int VisibleFieldCount {
            get {
                if (this.IsClosed) {
                    throw ADP.DataReaderClosed("VisibleFieldCount");
                }
                _SqlMetaDataSet md = this.MetaData;
                if (md == null) {
                    return 0;
                }
                return (md.visibleColumns);
            }
        }

        // this operator
        override public object this[int i] {
            get {
                return GetValue(i);
            }
        }

        override public object this[string name] {
            get {
                return GetValue(GetOrdinal(name));
            }
        }

        internal void Bind(TdsParserStateObject stateObj) {
            Debug.Assert(null != stateObj, "null stateobject");

            Debug.Assert(null == _snapshot, "Should not change during execution of asynchronous command");

            stateObj.Owner = this;
            _stateObj    = stateObj;
            _parser      = stateObj.Parser;
            _defaultLCID = _parser.DefaultLCID;
        }

        // Fills in a schema table with meta data information.  This function should only really be called by
        // 

        internal DataTable BuildSchemaTable() {
            _SqlMetaDataSet md = this.MetaData;
            Debug.Assert(null != md, "BuildSchemaTable - unexpected null metadata information");

            DataTable schemaTable = new DataTable("SchemaTable");
            schemaTable.Locale = CultureInfo.InvariantCulture;
            schemaTable.MinimumCapacity = md.Length;

            DataColumn ColumnName                       = new DataColumn(SchemaTableColumn.ColumnName,                       typeof(System.String));
            DataColumn Ordinal                          = new DataColumn(SchemaTableColumn.ColumnOrdinal,                    typeof(System.Int32));
            DataColumn Size                             = new DataColumn(SchemaTableColumn.ColumnSize,                       typeof(System.Int32));
            DataColumn Precision                        = new DataColumn(SchemaTableColumn.NumericPrecision,                 typeof(System.Int16));
            DataColumn Scale                            = new DataColumn(SchemaTableColumn.NumericScale,                     typeof(System.Int16));

            DataColumn DataType                         = new DataColumn(SchemaTableColumn.DataType,                         typeof(System.Type));
            DataColumn ProviderSpecificDataType         = new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type));
            DataColumn NonVersionedProviderType         = new DataColumn(SchemaTableColumn.NonVersionedProviderType,         typeof(System.Int32));
            DataColumn ProviderType                     = new DataColumn(SchemaTableColumn.ProviderType,                     typeof(System.Int32));

            DataColumn IsLong                           = new DataColumn(SchemaTableColumn.IsLong,                           typeof(System.Boolean));
            DataColumn AllowDBNull                      = new DataColumn(SchemaTableColumn.AllowDBNull,                      typeof(System.Boolean));
            DataColumn IsReadOnly                       = new DataColumn(SchemaTableOptionalColumn.IsReadOnly,               typeof(System.Boolean));
            DataColumn IsRowVersion                     = new DataColumn(SchemaTableOptionalColumn.IsRowVersion,             typeof(System.Boolean));

            DataColumn IsUnique                         = new DataColumn(SchemaTableColumn.IsUnique,                         typeof(System.Boolean));
            DataColumn IsKey                            = new DataColumn(SchemaTableColumn.IsKey,                            typeof(System.Boolean));
            DataColumn IsAutoIncrement                  = new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement,          typeof(System.Boolean));
            DataColumn IsHidden                         = new DataColumn(SchemaTableOptionalColumn.IsHidden,                 typeof(System.Boolean));

            DataColumn BaseCatalogName                  = new DataColumn(SchemaTableOptionalColumn.BaseCatalogName,          typeof(System.String));
            DataColumn BaseSchemaName                   = new DataColumn(SchemaTableColumn.BaseSchemaName,                   typeof(System.String));
            DataColumn BaseTableName                    = new DataColumn(SchemaTableColumn.BaseTableName,                    typeof(System.String));
            DataColumn BaseColumnName                   = new DataColumn(SchemaTableColumn.BaseColumnName,                   typeof(System.String));

            // unique to SqlClient
            DataColumn BaseServerName                   = new DataColumn(SchemaTableOptionalColumn.BaseServerName,           typeof(System.String));
            DataColumn IsAliased                        = new DataColumn(SchemaTableColumn.IsAliased,                        typeof(System.Boolean));
            DataColumn IsExpression                     = new DataColumn(SchemaTableColumn.IsExpression,                     typeof(System.Boolean));
            DataColumn IsIdentity                       = new DataColumn("IsIdentity",                                       typeof(System.Boolean));
            DataColumn DataTypeName                     = new DataColumn("DataTypeName",                                     typeof(System.String));
            DataColumn UdtAssemblyQualifiedName         = new DataColumn("UdtAssemblyQualifiedName",                         typeof(System.String));
            // Xml metadata specific
            DataColumn XmlSchemaCollectionDatabase      = new DataColumn("XmlSchemaCollectionDatabase",                      typeof(System.String));
            DataColumn XmlSchemaCollectionOwningSchema  = new DataColumn("XmlSchemaCollectionOwningSchema",                  typeof(System.String));
            DataColumn XmlSchemaCollectionName          = new DataColumn("XmlSchemaCollectionName",                          typeof(System.String));
            // SparseColumnSet
            DataColumn IsColumnSet                      = new DataColumn("IsColumnSet",                                      typeof(System.Boolean));

            Ordinal.DefaultValue = 0;
            IsLong.DefaultValue = false;

            DataColumnCollection columns = schemaTable.Columns;

            // must maintain order for backward compatibility
            columns.Add(ColumnName);
            columns.Add(Ordinal);
            columns.Add(Size);
            columns.Add(Precision);
            columns.Add(Scale);
            columns.Add(IsUnique);
            columns.Add(IsKey);
            columns.Add(BaseServerName);
            columns.Add(BaseCatalogName);
            columns.Add(BaseColumnName);
            columns.Add(BaseSchemaName);
            columns.Add(BaseTableName);
            columns.Add(DataType);
            columns.Add(AllowDBNull);
            columns.Add(ProviderType);
            columns.Add(IsAliased);
            columns.Add(IsExpression);
            columns.Add(IsIdentity);
            columns.Add(IsAutoIncrement);
            columns.Add(IsRowVersion);
            columns.Add(IsHidden);
            columns.Add(IsLong);
            columns.Add(IsReadOnly);
            columns.Add(ProviderSpecificDataType);
            columns.Add(DataTypeName);
            columns.Add(XmlSchemaCollectionDatabase);
            columns.Add(XmlSchemaCollectionOwningSchema);
            columns.Add(XmlSchemaCollectionName);
            columns.Add(UdtAssemblyQualifiedName);
            columns.Add(NonVersionedProviderType);
            columns.Add(IsColumnSet);

            for (int i = 0; i < md.Length; i++) {
                _SqlMetaData col = md[i];
                DataRow schemaRow = schemaTable.NewRow();

                schemaRow[ColumnName] = col.column;
                schemaRow[Ordinal]    = col.ordinal;
                //
                // be sure to return character count for string types, byte count otherwise
                // col.length is always byte count so for unicode types, half the length
                //
                // For MAX and XML datatypes, we get 0x7fffffff from the server. Do not divide this.
                if (col.cipherMD != null) {
                    Debug.Assert(col.baseTI != null && col.baseTI.metaType != null, "col.baseTI and col.baseTI.metaType should not be null.");
                    schemaRow[Size] = (col.baseTI.metaType.IsSizeInCharacters && (col.baseTI.length != 0x7fffffff)) ? (col.baseTI.length / 2) : col.baseTI.length;
                }
                else {
                    schemaRow[Size] = (col.metaType.IsSizeInCharacters && (col.length != 0x7fffffff)) ? (col.length / 2) : col.length;
                }

                schemaRow[DataType]                 = GetFieldTypeInternal(col);
                schemaRow[ProviderSpecificDataType] = GetProviderSpecificFieldTypeInternal(col);
                schemaRow[NonVersionedProviderType] = (int) (col.cipherMD != null ? col.baseTI.type : col.type); // SqlDbType enum value - does not change with TypeSystem.
                schemaRow[DataTypeName]             = GetDataTypeNameInternal(col);

                if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType) {
                    schemaRow[ProviderType] = SqlDbType.NVarChar;
                    switch (col.type) {
                        case SqlDbType.Date:
                            schemaRow[Size] = TdsEnums.WHIDBEY_DATE_LENGTH;
                            break;
                        case SqlDbType.Time:
                            Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for Time column: " + col.scale);
                            schemaRow[Size] = TdsEnums.WHIDBEY_TIME_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
                            break;
                        case SqlDbType.DateTime2:
                            Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for DateTime2 column: " + col.scale);
                            schemaRow[Size] = TdsEnums.WHIDBEY_DATETIME2_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
                            break;
                        case SqlDbType.DateTimeOffset:
                            Debug.Assert(TdsEnums.UNKNOWN_PRECISION_SCALE == col.scale || (0 <= col.scale && col.scale <= 7), "Invalid scale for DateTimeOffset column: " + col.scale);
                            schemaRow[Size] = TdsEnums.WHIDBEY_DATETIMEOFFSET_LENGTH[TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale ? col.scale : col.metaType.Scale];
                            break;
                    }
                }
                else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsLargeUdt) {
                    if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
                        schemaRow[ProviderType] = SqlDbType.VarBinary;
                    }
                    else {
                        // TypeSystem.SQLServer2000
                        schemaRow[ProviderType] = SqlDbType.Image;
                    }
                }
                else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
                    // TypeSystem.SQLServer2005 and above

                    // SqlDbType enum value - always the actual type for SQLServer2005.
                    schemaRow[ProviderType] = (int) (col.cipherMD != null ? col.baseTI.type : col.type);

                    if (col.type == SqlDbType.Udt) { // Additional metadata for UDTs.
                        Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
                        schemaRow[UdtAssemblyQualifiedName] = col.udtAssemblyQualifiedName;
                    }
                    else if (col.type == SqlDbType.Xml) { // Additional metadata for Xml.
                        Debug.Assert(Connection.IsYukonOrNewer, "Invalid DataType (Xml) for the column");
                        schemaRow[XmlSchemaCollectionDatabase]     = col.xmlSchemaCollectionDatabase;
                        schemaRow[XmlSchemaCollectionOwningSchema] = col.xmlSchemaCollectionOwningSchema;
                        schemaRow[XmlSchemaCollectionName]         = col.xmlSchemaCollectionName;
                    }
                }
                else {
                    // TypeSystem.SQLServer2000
            
                    // SqlDbType enum value - variable for certain types when SQLServer2000.
                    schemaRow[ProviderType] = GetVersionedMetaType(col.metaType).SqlDbType; 
                }
    
                if (col.cipherMD != null) {
                    Debug.Assert(col.baseTI != null, @"col.baseTI should not be null.");
                    if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.baseTI.precision) {
                        schemaRow[Precision] = col.baseTI.precision;
                    }
                    else {
                        schemaRow[Precision] = col.baseTI.metaType.Precision;
                    }
                }
                else if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.precision) {
                    schemaRow[Precision] = col.precision;
                }
                else {
                    schemaRow[Precision] = col.metaType.Precision;
                }

                if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && col.IsNewKatmaiDateTimeType) {
                    schemaRow[Scale] = MetaType.MetaNVarChar.Scale;
                }
                else if (col.cipherMD != null) {
                    Debug.Assert(col.baseTI != null, @"col.baseTI should not be null.");
                    if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.baseTI.scale) {
                        schemaRow[Scale] = col.baseTI.scale;
                    }
                    else {
                        schemaRow[Scale] = col.baseTI.metaType.Scale;
                    }
                }
                else if (TdsEnums.UNKNOWN_PRECISION_SCALE != col.scale) {
                    schemaRow[Scale] = col.scale;
                }
                else {
                    schemaRow[Scale] = col.metaType.Scale;
                }

                schemaRow[AllowDBNull] = col.isNullable;

                // If no ColInfo token received, do not set value, leave as null.
                if (_browseModeInfoConsumed) {
                    schemaRow[IsAliased]    = col.isDifferentName;
                    schemaRow[IsKey]        = col.isKey;
                    schemaRow[IsHidden]     = col.isHidden;
                    schemaRow[IsExpression] = col.isExpression;
                }

                schemaRow[IsIdentity] = col.isIdentity;
                schemaRow[IsAutoIncrement] = col.isIdentity;

                if (col.cipherMD != null) {
                    Debug.Assert(col.baseTI != null, @"col.baseTI should not be null.");
                    Debug.Assert(col.baseTI.metaType != null, @"col.baseTI.metaType should not be null.");
                    schemaRow[IsLong] = col.baseTI.metaType.IsLong;
                }
                else {
                    schemaRow[IsLong] = col.metaType.IsLong;
                }

                // mark unique for timestamp columns
                if (SqlDbType.Timestamp == col.type) {
                    schemaRow[IsUnique] = true;
                    schemaRow[IsRowVersion] = true;
                }
                else {
                    schemaRow[IsUnique] = false;
                    schemaRow[IsRowVersion] = false;
                }

                schemaRow[IsReadOnly] = (0 == col.updatability);
                schemaRow[IsColumnSet] = col.isColumnSet;

                if (!ADP.IsEmpty(col.serverName)) {
                    schemaRow[BaseServerName] = col.serverName;
                }
                if (!ADP.IsEmpty(col.catalogName)) {
                    schemaRow[BaseCatalogName] = col.catalogName;
                }
                if (!ADP.IsEmpty(col.schemaName)) {
                    schemaRow[BaseSchemaName] = col.schemaName;
                }
                if (!ADP.IsEmpty(col.tableName)) {
                    schemaRow[BaseTableName] = col.tableName;
                }
                if (!ADP.IsEmpty(col.baseColumn)) {
                    schemaRow[BaseColumnName] = col.baseColumn;
                }
                else if (!ADP.IsEmpty(col.column)) {
                    schemaRow[BaseColumnName] = col.column;
                }

                schemaTable.Rows.Add(schemaRow);
                schemaRow.AcceptChanges();
            }

            // mark all columns as readonly
            foreach(DataColumn column in columns) {
                column.ReadOnly = true; // MDAC 70943
            }

            return schemaTable;
        }

        internal void Cancel(int objectID) {
            TdsParserStateObject stateObj = _stateObj;
            if (null != stateObj) {
                stateObj.Cancel(objectID);
            }
        }

        // wipe any data off the wire from a partial read
        // and reset all pointers for sequential access
        private bool TryCleanPartialRead() {
            AssertReaderState(requireData: true, permitAsync: true);

            // VSTS DEVDIV2 380446: It is possible that read attempt we are cleaning after ended with partially 
            // processed header (if it falls between network packets). In this case the first thing to do is to 
            // finish reading the header, otherwise code will start treating unread header as TDS payload.
            if (_stateObj._partialHeaderBytesRead > 0) {
                if (!_stateObj.TryProcessHeader()) {
                    return false;
                }
            }

            // following cases for sequential read
            // i. user called read but didn't fetch anything
            // iia. user called read and fetched a subset of the columns
            // iib. user called read and fetched a subset of the column data

            // Wipe out any Streams or TextReaders
            if (-1 != _lastColumnWithDataChunkRead) {
                CloseActiveSequentialStreamAndTextReader();
            }

            // i. user called read but didn't fetch anything
            if (0 == _sharedState._nextColumnHeaderToRead) {
                if (!_stateObj.Parser.TrySkipRow(_metaData, _stateObj)) {
                    return false;
                }
            }
            else {

                // iia.  if we still have bytes left from a partially read column, skip
                if (!TryResetBlobState()) {
                    return false;
                }

                // iib.
                // now read the remaining values off the wire for this row
                if (!_stateObj.Parser.TrySkipRow(_metaData, _sharedState._nextColumnHeaderToRead, _stateObj)) {
                    return false;
                }
            }

#if DEBUG
                if (_stateObj._pendingData) {
                    byte token;
                    if (!_stateObj.TryPeekByte(out token)) {
                        return false;
                    }

                    Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("Invalid token after performing CleanPartialRead: {0,-2:X2}", token));
                }
#endif            
            _sharedState._dataReady = false;

            return true;
        }

        private void CleanPartialReadReliable() {
            AssertReaderState(requireData: true, permitAsync: false);
            
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    bool result = TryCleanPartialRead();
                    Debug.Assert(result, "Should not pend on sync call");
                    Debug.Assert(!_sharedState._dataReady, "_dataReady should be cleared");
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                if (_connection != null) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                if (_connection != null) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                if (_connection != null) {
                    _connection.Abort(e);
                }
                throw;
            }
        }

        override public void Close() {
            SqlStatistics statistics = null;
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.Close|API> %d#", ObjectID);
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                TdsParserStateObject stateObj = _stateObj;

                // Request that the current task is stopped
                _cancelAsyncOnCloseTokenSource.Cancel();
                var currentTask = _currentTask;
                if ((currentTask != null) && (!currentTask.IsCompleted)) {
                    try {
                        // Wait for the task to complete
                        ((IAsyncResult)currentTask).AsyncWaitHandle.WaitOne();

                        // Ensure that we've finished reading any pending data
                        var networkPacketTaskSource = stateObj._networkPacketTaskSource;
                        if (networkPacketTaskSource != null) {
                            ((IAsyncResult)networkPacketTaskSource.Task).AsyncWaitHandle.WaitOne();
                        }
                    }
                    catch (Exception) {
                        // If we receive any exceptions while waiting, something has gone horribly wrong and we need to doom the connection and fast-fail the reader
                        _connection.InnerConnection.DoomThisConnection();
                        _isClosed = true;

                        if (stateObj != null) {
                            lock (stateObj) {
                                _stateObj = null;
                                _command = null;
                                _connection = null;
                            }
                        }

                        throw;
                    }
                }
                
                // Close down any active Streams and TextReaders (this will also wait for them to finish their async tasks)
                // NOTE: This must be done outside of the lock on the stateObj otherwise it will deadlock with CleanupAfterAsyncInvocation
                CloseActiveSequentialStreamAndTextReader();

                if (stateObj != null) {

                    // protect against concurrent close and cancel
                    lock (stateObj) {
                        
                        if (_stateObj != null ) {  // reader not closed while we waited for the lock

                            // TryCloseInternal will clear out the snapshot when it is done
                            if (_snapshot != null) {
#if DEBUG
                                // The stack trace for replays will differ since they weren't captured during close                                
                                stateObj._permitReplayStackTraceToDiffer = true;
#endif
                                PrepareForAsyncContinuation();
                            }

                            SetTimeout(_defaultTimeoutMilliseconds);

                            // Close can be called from async methods in error cases, 
                            // in which case we need to switch to syncOverAsync
                            stateObj._syncOverAsync = true;

                            if (!TryCloseInternal(true /*closeReader*/)) {
                                throw SQL.SynchronousCallMayNotPend();
                            }

                            // DO NOT USE stateObj after this point - it has been returned to the TdsParser's session pool and potentially handed out to another thread
                        }
                    }
                }
            }
            finally {
                SqlStatistics.StopTimer(statistics);
                Bid.ScopeLeave(ref hscp);
            }
        }

        private bool TryCloseInternal(bool closeReader) {
            TdsParser parser = _parser;
            TdsParserStateObject stateObj = _stateObj;
            bool closeConnection = (IsCommandBehavior(CommandBehavior.CloseConnection));
            bool aborting = false;
            bool cleanDataFailed = false;
            
            RuntimeHelpers.PrepareConstrainedRegions();            
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    if ((!_isClosed) && (parser != null) && (stateObj != null) && (stateObj._pendingData)) {

                        // It is possible for this to be called during connection close on a
                        // broken connection, so check state first.
                        if (parser.State == TdsParserState.OpenLoggedIn) {
                            // if user called read but didn't fetch any values, skip the row
                            // same applies after NextResult on ALTROW because NextResult starts rowconsumption in that case ...

                            Debug.Assert(SniContext.Snix_Read==stateObj.SniContext, String.Format((IFormatProvider)null, "The SniContext should be Snix_Read but it actually is {0}", stateObj.SniContext));

                            if (_altRowStatus == ALTROWSTATUS.AltRow) {
                                _sharedState._dataReady = true;      // set _sharedState._dataReady to not confuse CleanPartialRead
                            }
                            _stateObj._internalTimeout = false;
                            if (_sharedState._dataReady) {
                                cleanDataFailed = true;
                                if (TryCleanPartialRead()) {
                                    cleanDataFailed = false;
                                }
                                else {
                                    return false;
                                }
                            }
#if DEBUG
                            else {
                                byte token;
                                if (!_stateObj.TryPeekByte(out token)) {
                                    return false;
                                }

                                Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("DataReady is false, but next token is invalid: {0,-2:X2}", token));
                            }
#endif


                            bool ignored;
                            if (!parser.TryRun(RunBehavior.Clean, _command, this, null, stateObj, out ignored)) {
                                return false;
                            }
                        }
                    }

                    RestoreServerSettings(parser, stateObj);
                    return true;
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                aborting = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                aborting = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                aborting = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            finally {
                if (aborting) {
                    _isClosed = true;
                    _command = null; // we are done at this point, don't allow navigation to the connection
                    _connection = null;
                    _statistics = null;
                    _stateObj = null;
                    _parser = null;
                }
                else if (closeReader) {
                    bool wasClosed = _isClosed;
                    _isClosed = true;
                    _parser = null;
                    _stateObj = null;
                    _data = null;

                    if (_snapshot != null) {
                        CleanupAfterAsyncInvocationInternal(stateObj);
                    }

                    // SQLBUDT #284712 - Note the order here is extremely important:
                    //
                    // (1) First, we remove the reader from the reference collection
                    //     to prevent it from being forced closed by the parser if
                    //     any future work occurs.
                    //
                    // (2) Next, we ensure that cancellation can no longer happen by
                    //     calling CloseSession.

                    if (Connection != null) {
                        Connection.RemoveWeakReference(this);  // This doesn't catch everything -- the connection may be closed, but it prevents dead readers from clogging the collection
                    }


                    RuntimeHelpers.PrepareConstrainedRegions();
                    try {
#if DEBUG
                        TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                        RuntimeHelpers.PrepareConstrainedRegions();
                        try {
                            tdsReliabilitySection.Start();
#else
                        {
#endif //DEBUG
                            // IsClosed may be true if CloseReaderFromConnection was called - in which case, the session has already been closed
                            if ((!wasClosed) && (null != stateObj)) {
                                if (!cleanDataFailed) {
                                    stateObj.CloseSession();
                                }
                                else {
                                    if (parser != null) {
                                        parser.State = TdsParserState.Broken; // We failed while draining data, so TDS pointer can be between tokens - cannot recover
                                        parser.PutSession(stateObj);
                                        parser.Connection.BreakConnection();
                                    }
                                }
                            }

                            // DO NOT USE stateObj after this point - it has been returned to the TdsParser's session pool and potentially handed out to another thread
                        }
#if DEBUG
                        finally {
                            tdsReliabilitySection.Stop();
                        }
#endif //DEBUG
                    }
                    catch (System.OutOfMemoryException e) {
                        if (null != _connection) {
                            _connection.Abort(e);
                        }
                        throw;
                    }
                    catch (System.StackOverflowException e) {
                        if (null != _connection) {
                            _connection.Abort(e);
                        }
                        throw;
                    }
                    catch (System.Threading.ThreadAbortException e)  {
                        if (null != _connection) {
                            _connection.Abort(e);
                        }
                        throw;
                    }

                    // do not retry here
                    bool result = TrySetMetaData(null, false);
                    Debug.Assert(result, "Should not pend a synchronous request");
                    _fieldNameLookup = null;

                    // if the user calls ExecuteReader(CommandBehavior.CloseConnection)
                    // then we close down the connection when we are done reading results
                    if (closeConnection) {
                        if (Connection != null) {
                            Connection.Close();
                        }
                    }
                    if (_command != null) {
                        // cache recordsaffected to be returnable after DataReader.Close();
                        _recordsAffected = _command.InternalRecordsAffected;
                    }

                    _command = null; // we are done at this point, don't allow navigation to the connection
                    _connection = null;
                    _statistics = null;
                }
            }
        }

        virtual internal void CloseReaderFromConnection() {
            var parser = _parser;
            Debug.Assert(parser == null || parser.State != TdsParserState.OpenNotLoggedIn, "Reader on a connection that is not logged in");
            if ((parser != null) && (parser.State == TdsParserState.OpenLoggedIn)) {
                // Connection is ok - proper cleanup
                // NOTE: This is NOT thread-safe
                Close();
            }
            else {
                // Connection is broken - quick cleanup
                // NOTE: This MUST be thread-safe as a broken connection can happen at any time

                var stateObj = _stateObj;
                _isClosed = true;
                // Request that the current task is stopped
                _cancelAsyncOnCloseTokenSource.Cancel();
                if (stateObj != null) {
                    var networkPacketTaskSource = stateObj._networkPacketTaskSource;
                    if (networkPacketTaskSource != null) {
                        // If the connection is closed or broken, this will never complete
                        networkPacketTaskSource.TrySetException(ADP.ClosedConnectionError());
                    }
                    if (_snapshot != null) {
                        // CleanWire will do cleanup - so we don't really care about the snapshot
                        CleanupAfterAsyncInvocationInternal(stateObj, resetNetworkPacketTaskSource: false);
                    }
                    // Switch to [....] to prepare for cleanwire
                    stateObj._syncOverAsync = true;
                    // Remove owner (this will allow the stateObj to be disposed after the connection is closed)
                    stateObj.RemoveOwner();
                }
            }
        }

        private bool TryConsumeMetaData() {
            // warning:  Don't check the MetaData property within this function
            // warning:  as it will be a reentrant call
            while (_parser != null && _stateObj != null && _stateObj._pendingData && !_metaDataConsumed) {
                if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed) {
                    // Happened for DEVDIV2:180509	(SqlDataReader.ConsumeMetaData Hangs In 100% CPU Loop Forever When TdsParser._state == TdsParserState.Broken)
                    // during request for DTC address. 
                    // NOTE: We doom connection for TdsParserState.Closed since it indicates that it is in some abnormal and unstable state, probably as a result of
                    // closing from another thread. In general, TdsParserState.Closed does not necessitate dooming the connection.
                    if (_parser.Connection != null)
                        _parser.Connection.DoomThisConnection();                     
                    throw SQL.ConnectionDoomed();
                }
                bool ignored;
                if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
                    return false;
                }
                Debug.Assert(!ignored, "Parser read a row token while trying to read metadata");
            }

            // we hide hidden columns from the user so build an internal map
            // that compacts all hidden columns from the array
            if (null != _metaData) {

                if (_snapshot != null && object.ReferenceEquals(_snapshot._metadata, _metaData)) {
                    _metaData = (_SqlMetaDataSet)_metaData.Clone();
                }

                _metaData.visibleColumns = 0;

                Debug.Assert(null == _metaData.indexMap, "non-null metaData indexmap");
                int[] indexMap = new int[_metaData.Length];
                for (int i = 0; i < indexMap.Length; ++i) {
                    indexMap[i] = _metaData.visibleColumns;

                    if (!(_metaData[i].isHidden)) {
                        _metaData.visibleColumns++;
                    }
                }
                _metaData.indexMap = indexMap;
            }

            return true;
        }

        override public string GetDataTypeName(int i) {
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                CheckMetaDataIsReady(columnIndex: i);

                return GetDataTypeNameInternal(_metaData[i]);
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        private string GetDataTypeNameInternal(_SqlMetaData metaData) {
            string dataTypeName = null;

            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
                dataTypeName = MetaType.MetaNVarChar.TypeName;
            }
            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
                if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
                    dataTypeName = MetaType.MetaMaxVarBinary.TypeName;
                }
                else {
                    // TypeSystem.SQLServer2000
                    dataTypeName = MetaType.MetaImage.TypeName;
                }
            }
            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
                // TypeSystem.SQLServer2005 and above

                if (metaData.type == SqlDbType.Udt) {
                    Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
                    dataTypeName = metaData.udtDatabaseName + "." + metaData.udtSchemaName + "." + metaData.udtTypeName;
                }
                else { // For all other types, including Xml - use data in MetaType.
                        if (metaData.cipherMD != null) {
                            Debug.Assert(metaData.baseTI != null && metaData.baseTI.metaType != null, "metaData.baseTI and metaData.baseTI.metaType should not be null.");
                            dataTypeName = metaData.baseTI.metaType.TypeName;
                        }
                        else {
                            dataTypeName = metaData.metaType.TypeName;  
                        }
                }
            }
            else {
                // TypeSystem.SQLServer2000

                    dataTypeName = GetVersionedMetaType(metaData.metaType).TypeName;
            }

            return dataTypeName;
        }

        virtual internal SqlBuffer.StorageType GetVariantInternalStorageType(int i) {
            Debug.Assert(null != _data, "Attempting to get variant internal storage type");
            Debug.Assert(i < _data.Length, "Reading beyond data length?");

            return _data[i].VariantInternalStorageType;
        }

        override public IEnumerator GetEnumerator() {
            return new DbEnumerator(this, IsCommandBehavior(CommandBehavior.CloseConnection));
        }
        
        override public Type GetFieldType(int i) {
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                CheckMetaDataIsReady(columnIndex: i);

                return GetFieldTypeInternal(_metaData[i]);
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        private Type GetFieldTypeInternal(_SqlMetaData metaData) {
            Type fieldType = null;

            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
                // Return katmai types as string
                fieldType = MetaType.MetaNVarChar.ClassType;
            }
            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
                if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
                    fieldType = MetaType.MetaMaxVarBinary.ClassType;
                }
                else {
                    // TypeSystem.SQLServer2000
                    fieldType = MetaType.MetaImage.ClassType;
                }
            }
            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
                // TypeSystem.SQLServer2005 and above

                if (metaData.type == SqlDbType.Udt) {
                    Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
                    Connection.CheckGetExtendedUDTInfo(metaData, false);
                    fieldType = metaData.udtType;
                }
                else { // For all other types, including Xml - use data in MetaType.
                    if (metaData.cipherMD != null) {
                        Debug.Assert(metaData.baseTI != null && metaData.baseTI.metaType != null, "metaData.baseTI and metaData.baseTI.metaType should not be null.");
                        fieldType = metaData.baseTI.metaType.ClassType;
                    }
                    else {
                        fieldType = metaData.metaType.ClassType; // Com+ type.
                    }
                }
            }
            else {
                // TypeSystem.SQLServer2000
        
                fieldType = GetVersionedMetaType(metaData.metaType).ClassType; // Com+ type.
            }    
            
            return fieldType;
        }

        virtual internal int GetLocaleId(int i) {
            _SqlMetaData sqlMetaData = MetaData[i];
            int lcid;

            if (sqlMetaData.cipherMD != null) {
                // If this column is encrypted, get the collation from baseTI
                //
                if (sqlMetaData.baseTI.collation != null) {
                    lcid = sqlMetaData.baseTI.collation.LCID;
                }
                else {
                    lcid = 0;
                }
            }
            else {
                if (sqlMetaData.collation != null) {
                    lcid = sqlMetaData.collation.LCID;
                }
                else {
                    lcid = 0;
                }
            }

            return lcid;
        }
        
        override public string GetName(int i) {
            CheckMetaDataIsReady(columnIndex: i);

            Debug.Assert(null != _metaData[i].column, "MDAC 66681");
            return _metaData[i].column;
        }

        override public Type GetProviderSpecificFieldType(int i) {
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                CheckMetaDataIsReady(columnIndex: i);

                return GetProviderSpecificFieldTypeInternal(_metaData[i]);
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        private Type GetProviderSpecificFieldTypeInternal(_SqlMetaData metaData) {
            Type providerSpecificFieldType = null;

            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
                providerSpecificFieldType = MetaType.MetaNVarChar.SqlType;
            }
            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
                if (_typeSystem == SqlConnectionString.TypeSystem.SQLServer2005) {
                    providerSpecificFieldType = MetaType.MetaMaxVarBinary.SqlType;
                }
                else {
                    // TypeSystem.SQLServer2000
                    providerSpecificFieldType = MetaType.MetaImage.SqlType;
                }
            }
            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
                // TypeSystem.SQLServer2005 and above

                if (metaData.type == SqlDbType.Udt) {
                    Debug.Assert(Connection.IsYukonOrNewer, "Invalid Column type received from the server");
                    Connection.CheckGetExtendedUDTInfo(metaData, false);
                    providerSpecificFieldType = metaData.udtType;
                }
                else {
                    // For all other types, including Xml - use data in MetaType.
                    if (metaData.cipherMD != null) {
                        Debug.Assert(metaData.baseTI != null && metaData.baseTI.metaType != null,
                            "metaData.baseTI and metaData.baseTI.metaType should not be null.");
                        providerSpecificFieldType = metaData.baseTI.metaType.SqlType; // SqlType type.
                    }
                    else {
                        providerSpecificFieldType = metaData.metaType.SqlType; // SqlType type.
                    }
                }
            }
            else {
                // TypeSystem.SQLServer2000
        
                providerSpecificFieldType = GetVersionedMetaType(metaData.metaType).SqlType; // SqlType type.
            }

            return providerSpecificFieldType;
        }
    
        // named field access
        override public int GetOrdinal(string name) {
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                if (null == _fieldNameLookup) {
                    CheckMetaDataIsReady();
                    _fieldNameLookup = new FieldNameLookup(this, _defaultLCID);
                }
                return _fieldNameLookup.GetOrdinal(name); // MDAC 71470
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        override public object GetProviderSpecificValue(int i) {
            return GetSqlValue(i);
        }

        override public int GetProviderSpecificValues(object[] values) {
            return GetSqlValues(values);
        }

        override public DataTable GetSchemaTable() {
            SqlStatistics statistics = null;
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.GetSchemaTable|API> %d#", ObjectID);
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                if (null == _metaData || null == _metaData.schemaTable) {
                    if (null != this.MetaData) {

                        _metaData.schemaTable = BuildSchemaTable();
                        Debug.Assert(null != _metaData.schemaTable, "No schema information yet!");
                        // filter table?
                    }
                }
                if (null != _metaData) {
                    return _metaData.schemaTable;
                }
                return null;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
                Bid.ScopeLeave(ref hscp);
            }
        }

        override public bool GetBoolean(int i) {
            ReadColumn(i);
            return _data[i].Boolean;
        }

        virtual public XmlReader GetXmlReader(int i) {
            // NOTE: sql_variant can not contain a XML data type: http://msdn.microsoft.com/en-us/library/ms173829.aspx
            // If this ever changes, the following code should be changed to be like GetStream\GetTextReader
            CheckDataIsReady(columnIndex: i, methodName: "GetXmlReader");

            MetaType mt = _metaData[i].metaType;

            // XmlReader only allowed on XML types
            if (mt.SqlDbType != SqlDbType.Xml) {
                throw SQL.XmlReaderNotSupportOnColumnType(_metaData[i].column);
            }

            if (IsCommandBehavior(CommandBehavior.SequentialAccess)) {
                // Wrap the sequential stream in an XmlReader
                _currentStream = new SqlSequentialStream(this, i);
                _lastColumnWithDataChunkRead = i;
                return SqlXml.CreateSqlXmlReader(_currentStream, closeInput: true);
            }
            else {
                // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlBinary) rather than calling anther Get*() method
                ReadColumn(i);

                if (_data[i].IsNull) {
                    // A 'null' stream
                    return SqlXml.CreateSqlXmlReader(new MemoryStream(new byte[0], writable: false), closeInput: true);
                }
                else {
                    // Grab already read data    
                    return _data[i].SqlXml.CreateReader();
                }                
            }
        }

        override public Stream GetStream(int i) {
            CheckDataIsReady(columnIndex: i, methodName: "GetStream");

            // Streaming is not supported on encrypted columns.
            if (_metaData[i] != null && _metaData[i].cipherMD != null) {
                throw SQL.StreamNotSupportOnEncryptedColumn(_metaData[i].column);
            }

            // Stream is only for Binary, Image, VarBinary, Udt and Xml types
            // NOTE: IsBinType also includes Timestamp for some reason...
            MetaType mt = _metaData[i].metaType;
            if (((!mt.IsBinType) || (mt.SqlDbType == SqlDbType.Timestamp)) && (mt.SqlDbType != SqlDbType.Variant)) {
                throw SQL.StreamNotSupportOnColumnType(_metaData[i].column);
            }

            // For non-variant types with sequential access, we support proper streaming
            if ((mt.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess))) {
                _currentStream = new SqlSequentialStream(this, i);
                _lastColumnWithDataChunkRead = i;
                return _currentStream;
            }
            else {
                // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlBinary) rather than calling anther Get*() method
                ReadColumn(i);

                byte[] data;
                if (_data[i].IsNull) {
                    // A 'null' stream
                    data = new byte[0];
                }
                else {
                    // Grab already read data    
                    data = _data[i].SqlBinary.Value;
                }

                // If non-sequential then we just have a read-only MemoryStream
                return new MemoryStream(data, writable: false);
            }
        }

        override public byte GetByte(int i) {
            ReadColumn(i);
            return _data[i].Byte;
        }

        override public long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) {
            SqlStatistics statistics = null;
            long  cbBytes = 0;

            CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true, methodName: "GetBytes");

            // don't allow get bytes on non-long or non-binary columns
            MetaType mt = _metaData[i].metaType;
            if (!(mt.IsLong || mt.IsBinType) || (SqlDbType.Xml == mt.SqlDbType)) {
                throw SQL.NonBlobColumn(_metaData[i].column);
            }
                      
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                SetTimeout(_defaultTimeoutMilliseconds);
                cbBytes = GetBytesInternal(i, dataIndex, buffer, bufferIndex, length);
                _lastColumnWithDataChunkRead = i;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
            return cbBytes;
        }

        // Used (indirectly) by SqlCommand.CompleteXmlReader
        virtual internal long GetBytesInternal(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }

            long value;
            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            bool result = TryGetBytesInternal(i, dataIndex, buffer, bufferIndex, length, out value);
            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
            return value;
        }

        private bool TryGetBytesInternal(int i, long dataIndex, byte[] buffer, int bufferIndex, int length, out long remaining) {
            remaining = 0;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    int cbytes = 0;
                    AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);

                    // sequential reading
                    if (IsCommandBehavior(CommandBehavior.SequentialAccess)) {
                        Debug.Assert(!HasActiveStreamOrTextReaderOnColumn(i), "Column has an active Stream or TextReader");

                        if (_metaData[i] != null && _metaData[i].cipherMD != null) {
                            throw SQL.SequentialAccessNotSupportedOnEncryptedColumn(_metaData[i].column);
                        }

                        if (_sharedState._nextColumnHeaderToRead <= i) {
                            if (!TryReadColumnHeader(i)) {
                                return false;
                            }
                        }

                        // If data is null, ReadColumnHeader sets the data.IsNull bit.
                        if (_data[i] != null && _data[i].IsNull) {
                            throw new SqlNullValueException();
                        }    

                        // If there are an unknown (-1) number of bytes left for a PLP, read its size
                        if ((-1 == _sharedState._columnDataBytesRemaining) && (_metaData[i].metaType.IsPlp)) {
                            ulong left;
                            if (!_parser.TryPlpBytesLeft(_stateObj, out left)) {
                                return false;
                            }
                            _sharedState._columnDataBytesRemaining = (long)left;
                        }

                        if (0 == _sharedState._columnDataBytesRemaining) {
                            return true; // We've read this column to the end
                        }

                        // if no buffer is passed in, return the number total of bytes, or -1
                        if (null == buffer) {
                            if (_metaData[i].metaType.IsPlp) {
                                remaining = (long) _parser.PlpBytesTotalLength(_stateObj);
                                return true;
                            }
                            remaining = _sharedState._columnDataBytesRemaining;
                            return true;
                        }
                        
                        if (dataIndex < 0)
                            throw ADP.NegativeParameter("dataIndex");
                        
                        if (dataIndex < _columnDataBytesRead) {
                            throw ADP.NonSeqByteAccess(dataIndex, _columnDataBytesRead, ADP.GetBytes);
                        }

                        // if the dataIndex is not equal to bytes read, then we have to skip bytes
                        long cb = dataIndex - _columnDataBytesRead;

                        // if dataIndex is outside of the data range, return 0
                        if ((cb > _sharedState._columnDataBytesRemaining) && !_metaData[i].metaType.IsPlp) {
                            return true;
                        }
                        
                        // if bad buffer index, throw
                        if (bufferIndex < 0 || bufferIndex >= buffer.Length)
                            throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");

                        // if there is not enough room in the buffer for data
                        if (length + bufferIndex > buffer.Length)
                            throw ADP.InvalidBufferSizeOrIndex(length, bufferIndex);

                        if (length < 0)
                            throw ADP.InvalidDataLength(length);

                        // Skip if needed
                        if (cb > 0) {
                            if (_metaData[i].metaType.IsPlp) {
                                    ulong skipped;
                                    if (!_parser.TrySkipPlpValue((ulong) cb, _stateObj, out skipped)) {
                                        return false;
                                    }
                                    _columnDataBytesRead += (long) skipped;
                            }
                            else {
                                if (!_stateObj.TrySkipLongBytes(cb)) {
                                    return false;
                                }
                                _columnDataBytesRead += cb;
                                _sharedState._columnDataBytesRemaining -= cb;
                            }
                        }

                        int bytesRead;
                        bool result = TryGetBytesInternalSequential(i, buffer, bufferIndex, length, out bytesRead);
                        remaining = (int)bytesRead;
                        return result;
                    }

                    // random access now!
                    // note that since we are caching in an array, and arrays aren't 64 bit ready yet,
                    // we need can cast to int if the dataIndex is in range
                    if (dataIndex < 0)
                        throw ADP.NegativeParameter("dataIndex");
                    
                    if (dataIndex > Int32.MaxValue) {
                        throw ADP.InvalidSourceBufferIndex(cbytes, dataIndex, "dataIndex");
                    }
                    
                    int ndataIndex = (int)dataIndex;
                    byte[] data;

                    // WebData 99342 - in the non-sequential case, we need to support
                    //                 the use of GetBytes on string data columns, but
                    //                 GetSqlBinary isn't supposed to.  What we end up
                    //                 doing isn't exactly pretty, but it does work.
                    if (_metaData[i].metaType.IsBinType) {
                        data = GetSqlBinary(i).Value;
                    }
                    else {
                        Debug.Assert(_metaData[i].metaType.IsLong, "non long type?");
                        Debug.Assert(_metaData[i].metaType.IsCharType, "non-char type?");

                        SqlString temp = GetSqlString(i);
                        if (_metaData[i].metaType.IsNCharType) {
                            data = temp.GetUnicodeBytes();
                        }
                        else {
                            data = temp.GetNonUnicodeBytes();
                        }
                    }

                    cbytes = data.Length;

                    // if no buffer is passed in, return the number of characters we have
                    if (null == buffer) {
                        remaining = cbytes;
                        return true;
                    }

                    // if dataIndex is outside of data range, return 0
                    if (ndataIndex < 0 || ndataIndex >= cbytes) {
                        return true;
                    }
                    try {
                        if (ndataIndex < cbytes) {
                            // help the user out in the case where there's less data than requested
                            if ((ndataIndex + length) > cbytes)
                                cbytes = cbytes - ndataIndex;
                            else
                                cbytes = length;
                        }

                        Array.Copy(data, ndataIndex, buffer, bufferIndex, cbytes);
                    }
                    catch (Exception e) {
                        // 
                        if (!ADP.IsCatchableExceptionType(e)) {
                            throw;
                        }
                        cbytes = data.Length;

                        if (length < 0)
                            throw ADP.InvalidDataLength(length);

                        // if bad buffer index, throw
                        if (bufferIndex < 0 || bufferIndex >= buffer.Length)
                            throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");

                        // if there is not enough room in the buffer for data
                        if (cbytes + bufferIndex > buffer.Length)
                            throw ADP.InvalidBufferSizeOrIndex(cbytes, bufferIndex);

                        throw;
                    }

                    remaining = cbytes;
                    return true;
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
        }

        internal int GetBytesInternalSequential(int i, byte[] buffer, int index, int length, long? timeoutMilliseconds = null) {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }

            int value;
            SqlStatistics statistics = null;
            Debug.Assert(_stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                SetTimeout(timeoutMilliseconds ?? _defaultTimeoutMilliseconds);

                bool result = TryReadColumnHeader(i);
                if (!result) { throw SQL.SynchronousCallMayNotPend(); }

                result = TryGetBytesInternalSequential(i, buffer, index, length, out value);
                if (!result) { throw SQL.SynchronousCallMayNotPend(); }
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
            
            return value;
        }

        // This is meant to be called from other internal methods once we are at the column to read
        // NOTE: This method must be retriable WITHOUT replaying a snapshot
        // Every time you call this method increment the index and decrease length by the value of bytesRead
        internal bool TryGetBytesInternalSequential(int i, byte[] buffer, int index, int length, out int bytesRead) {
            AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
            Debug.Assert(_sharedState._nextColumnHeaderToRead == i + 1 && _sharedState._nextColumnDataToRead == i, "Non sequential access");
            Debug.Assert(buffer != null, "Null buffer");
            Debug.Assert(index >= 0, "Invalid index");
            Debug.Assert(length >= 0, "Invalid length");
            Debug.Assert(index + length <= buffer.Length, "Buffer too small");
            
            bytesRead = 0;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#endif //DEBUG
                    if ((_sharedState._columnDataBytesRemaining == 0) || (length == 0)) {
                        // No data left or nothing requested, return 0
                        bytesRead = 0;
                        return true;
                    }
                    else {
                        // if plp columns, do partial reads. Don't read the entire value in one shot.
                        if (_metaData[i].metaType.IsPlp) {
                            // Read in data
                            bool result = _stateObj.TryReadPlpBytes(ref buffer, index, length, out bytesRead);
                            _columnDataBytesRead += bytesRead;
                            if (!result) {
                                return false;
                            }

                            // Query for number of bytes left
                            ulong left;
                            if (!_parser.TryPlpBytesLeft(_stateObj, out left)) {
                                _sharedState._columnDataBytesRemaining = -1;
                                return false;
                            }
                            _sharedState._columnDataBytesRemaining = (long)left;
                            return true;
                        }
                        else {
                            // Read data (not exceeding the total amount of data available)
                            int bytesToRead = (int)Math.Min((long)length, _sharedState._columnDataBytesRemaining);
                            bool result = _stateObj.TryReadByteArray(buffer, index, bytesToRead, out bytesRead);
                            _columnDataBytesRead += bytesRead;
                            _sharedState._columnDataBytesRemaining -= bytesRead;
                            return result;
                        }
                    }
#if DEBUG
                }
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
        }

        override public TextReader GetTextReader(int i) {
            CheckDataIsReady(columnIndex: i, methodName: "GetTextReader");
            
            // Xml type is not supported
            MetaType mt = null;

            if (_metaData[i].cipherMD != null) {
                Debug.Assert(_metaData[i].baseTI != null, "_metaData[i].baseTI should not be null.");
                mt = _metaData[i].baseTI.metaType;
            }
            else {
                mt = _metaData[i].metaType;
            }

            Debug.Assert(mt != null, @"mt should not be null.");

            if (((!mt.IsCharType) && (mt.SqlDbType != SqlDbType.Variant)) || (mt.SqlDbType == SqlDbType.Xml)) {
                throw SQL.TextReaderNotSupportOnColumnType(_metaData[i].column);
            }

            // For non-variant types with sequential access, we support proper streaming
            if ((mt.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess))) {
                if (_metaData[i].cipherMD != null) {
                    throw SQL.SequentialAccessNotSupportedOnEncryptedColumn(_metaData[i].column);
                }

                System.Text.Encoding encoding;
                if (mt.IsNCharType)
                {
                    // NChar types always use unicode
                    encoding = SqlUnicodeEncoding.SqlUnicodeEncodingInstance;
                }
                else
                {
                    encoding = _metaData[i].encoding;
                }
                        
                _currentTextReader = new SqlSequentialTextReader(this, i, encoding);
                _lastColumnWithDataChunkRead = i;
                return _currentTextReader;
            }
            else {
                // Need to call ReadColumn, since we want to access the internal data structures (i.e. SqlString) rather than calling anther Get*() method
                ReadColumn(i);

                string data;
                if (_data[i].IsNull) {
                    // A 'null' stream
                    data = string.Empty;
                }
                else {
                    // Grab already read data    
                    data = _data[i].SqlString.Value;
                }

                // We've already read the data, so just wrap it in a StringReader
                return new StringReader(data);
            }
        }

        [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] // MDAC 69508
        override public char GetChar(int i) {
            throw ADP.NotSupported();
        }

        override public long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) {
            SqlStatistics statistics = null;

            CheckMetaDataIsReady(columnIndex: i);

            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }

            MetaType mt = null;
            if (_metaData[i].cipherMD != null) {
                Debug.Assert(_metaData[i].baseTI != null, @"_metaData[i].baseTI should not be null.");
                mt = _metaData[i].baseTI.metaType;
            }
            else {
                mt = _metaData[i].metaType;
            }

            Debug.Assert(mt != null, "mt should not be null.");

            SqlDbType sqlDbType;
            if (_metaData[i].cipherMD != null) {
                Debug.Assert(_metaData[i].baseTI != null, @"_metaData[i].baseTI should not be null.");
                sqlDbType = _metaData[i].baseTI.type;
            }
            else {
                sqlDbType = _metaData[i].type;
            }
            
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                SetTimeout(_defaultTimeoutMilliseconds);
                if ((mt.IsPlp) &&
                    (IsCommandBehavior(CommandBehavior.SequentialAccess)) ) {
                    if (length < 0) {
                        throw ADP.InvalidDataLength(length);
                    }

                    if (_metaData[i].cipherMD != null) {
                        throw SQL.SequentialAccessNotSupportedOnEncryptedColumn(_metaData[i].column);
                    }

                    // if bad buffer index, throw
                    if ((bufferIndex < 0) || (buffer != null && bufferIndex >= buffer.Length)) {
                        throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
                    }
                    
                    // if there is not enough room in the buffer for data
                    if (buffer != null && (length + bufferIndex > buffer.Length)) {
                        throw ADP.InvalidBufferSizeOrIndex(length, bufferIndex);
                    }
                    long charsRead = 0;
                    if ( sqlDbType == SqlDbType.Xml ) {
                        try {
                            CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true, methodName: "GetChars");
                        }
                        catch (Exception ex) {
                            // Dev11 Bug #315513: Exception type breaking change from 4.0 RTM when calling GetChars on null xml
                            // We need to wrap all exceptions inside a TargetInvocationException to simulate calling CreateSqlReader via MethodInfo.Invoke
                            if (ADP.IsCatchableExceptionType(ex)) {
                                throw new TargetInvocationException(ex);
                            }
                            else {
                                throw;
                            }
                        }
                        charsRead = GetStreamingXmlChars(i, dataIndex, buffer, bufferIndex, length);
                    }
                    else {
                        CheckDataIsReady(columnIndex: i, allowPartiallyReadColumn: true, methodName: "GetChars");
                        charsRead = GetCharsFromPlpData(i, dataIndex, buffer, bufferIndex, length);
                    }
                    _lastColumnWithDataChunkRead = i;
                    return charsRead;
                }

                // Did we start reading this value yet?
                if ((_sharedState._nextColumnDataToRead == (i+1)) && (_sharedState._nextColumnHeaderToRead == (i+1)) && (_columnDataChars != null) && (IsCommandBehavior(CommandBehavior.SequentialAccess)) && (dataIndex < _columnDataCharsRead)) {
                    // Don't allow re-read of same chars in sequential access mode
                    throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, ADP.GetChars);
                }

                if (_columnDataCharsIndex != i) {
                    // if the object doesn't contain a char[] then the user will get an exception
                    string s = GetSqlString(i).Value;

                    _columnDataChars = s.ToCharArray();
                    _columnDataCharsRead = 0;
                    _columnDataCharsIndex = i;
                }

                int cchars = _columnDataChars.Length;

                // note that since we are caching in an array, and arrays aren't 64 bit ready yet,
                // we need can cast to int if the dataIndex is in range
                if (dataIndex > Int32.MaxValue) {
                    throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex");
                }
                int ndataIndex = (int)dataIndex;

                // if no buffer is passed in, return the number of characters we have
                if (null == buffer)
                    return cchars;

                // if dataIndex outside of data range, return 0
                if (ndataIndex < 0 || ndataIndex >= cchars)
                    return 0;

                try {
                    if (ndataIndex < cchars) {
                        // help the user out in the case where there's less data than requested
                        if ((ndataIndex + length) > cchars)
                            cchars = cchars - ndataIndex;
                        else
                            cchars = length;
                    }

                    Array.Copy(_columnDataChars, ndataIndex, buffer, bufferIndex, cchars);
                    _columnDataCharsRead += cchars;
                }
                catch (Exception e) {
                    // 
                    if (!ADP.IsCatchableExceptionType(e)) {
                        throw;
                    }
                    cchars = _columnDataChars.Length;

                    if (length < 0)
                       throw ADP.InvalidDataLength(length);

                    // if bad buffer index, throw
                    if (bufferIndex < 0 || bufferIndex >= buffer.Length)
                        throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");

                    // if there is not enough room in the buffer for data
                    if (cchars + bufferIndex > buffer.Length)
                        throw ADP.InvalidBufferSizeOrIndex(cchars, bufferIndex);

                    throw;
                }

                return cchars;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int bufferIndex, int length) {
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    long cch;

                    AssertReaderState(requireData: true, permitAsync: false, columnIndex: i, enforceSequentialAccess: true);
                    Debug.Assert(!HasActiveStreamOrTextReaderOnColumn(i), "Column has active Stream or TextReader");
                    // don't allow get bytes on non-long or non-binary columns
                    Debug.Assert(_metaData[i].metaType.IsPlp, "GetCharsFromPlpData called on a non-plp column!");
                    // Must be sequential reading
                    Debug.Assert (IsCommandBehavior(CommandBehavior.SequentialAccess), "GetCharsFromPlpData called for non-Sequential access");
                    
                    if (!_metaData[i].metaType.IsCharType) {
                        throw SQL.NonCharColumn(_metaData[i].column);
                    }
                    
                    if (_sharedState._nextColumnHeaderToRead <= i) {
                        ReadColumnHeader(i);
                    }
                    
                    // If data is null, ReadColumnHeader sets the data.IsNull bit.
                    if (_data[i] != null && _data[i].IsNull) {
                        throw new SqlNullValueException();
                    }    

                    if (dataIndex < _columnDataCharsRead) {
                        // Don't allow re-read of same chars in sequential access mode
                        throw ADP.NonSeqByteAccess(dataIndex, _columnDataCharsRead, ADP.GetChars);
                    }
                    
                    // If we start reading the new column, either dataIndex is 0 or 
                    // _columnDataCharsRead is 0 and dataIndex > _columnDataCharsRead is true below.
                    // In both cases we will clean decoder
                    if (dataIndex == 0) 
                        _stateObj._plpdecoder = null;

                    bool isUnicode = _metaData[i].metaType.IsNCharType;

                    // If there are an unknown (-1) number of bytes left for a PLP, read its size
                    if (-1 == _sharedState._columnDataBytesRemaining) {
                        _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
                    }

                    if (0 == _sharedState._columnDataBytesRemaining) {
                        _stateObj._plpdecoder = null;
                        return 0; // We've read this column to the end
                    }

                    // if no buffer is passed in, return the total number of characters or -1
                    // 
                    if (null == buffer) {
                        cch = (long) _parser.PlpBytesTotalLength(_stateObj);
                        return (isUnicode && (cch > 0)) ? cch >> 1 : cch;
                    }
                    if (dataIndex > _columnDataCharsRead) {
                        // Skip chars

                        // Clean decoder state: we do not reset it, but destroy to ensure
                        // that we do not start decoding the column with decoder from the old one                                                       
                        _stateObj._plpdecoder = null; 

                        // 

                        cch = dataIndex - _columnDataCharsRead;
                        cch = isUnicode ? (cch << 1 ) : cch;
                        cch = (long) _parser.SkipPlpValue((ulong)(cch), _stateObj);
                        _columnDataBytesRead += cch;
                        _columnDataCharsRead += (isUnicode && (cch > 0)) ? cch >> 1 : cch;
                    }
                    cch = length;
                    
                    if (isUnicode) {
                        cch = (long) _parser.ReadPlpUnicodeChars(ref buffer, bufferIndex, length, _stateObj);
                        _columnDataBytesRead += (cch << 1);
                    }
                    else {
                        cch = (long) _parser.ReadPlpAnsiChars(ref buffer, bufferIndex, length, _metaData[i], _stateObj);
                        _columnDataBytesRead += cch << 1;
                    }
                    _columnDataCharsRead += cch;
                    _sharedState._columnDataBytesRemaining = (long)_parser.PlpBytesLeft(_stateObj);
                    return cch;
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
        }

        internal long GetStreamingXmlChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) {
           SqlStreamingXml localSXml = null;
           if ((_streamingXml != null) && ( _streamingXml.ColumnOrdinal != i)) {
                _streamingXml.Close();
                _streamingXml = null;
           }
            if (_streamingXml == null) {
                localSXml = new SqlStreamingXml(i, this);
            }
            else {
                localSXml = _streamingXml;
            }
            long cnt = localSXml.GetChars(dataIndex, buffer, bufferIndex, length);
            if (_streamingXml == null) {
                // Data is read through GetBytesInternal which may dispose _streamingXml if it has to advance the column ordinal.
                // Therefore save the new SqlStreamingXml class after the read succeeds.
                _streamingXml = localSXml;
            }
            return cnt;            
        }

        [ EditorBrowsableAttribute(EditorBrowsableState.Never) ] // MDAC 69508
        IDataReader IDataRecord.GetData(int i) {
            throw ADP.NotSupported();
        }

        override public DateTime GetDateTime(int i) {
            ReadColumn(i);

            DateTime dt = _data[i].DateTime;
            // This accessor can be called for regular DateTime column. In this case we should not throw
            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType) {
                // TypeSystem.SQLServer2005 or less

                // If the above succeeds, then we received a valid DateTime instance, now we need to force
                // an InvalidCastException since DateTime is not exposed with the version knob in this setting.
                // To do so, we simply force the exception by casting the string representation of the value
                // To DateTime.
                object temp = (object) _data[i].String;
                dt = (DateTime) temp;
            }

            return dt;
        }

        override public Decimal GetDecimal(int i) {
            ReadColumn(i);
            return _data[i].Decimal;
        }

        override public double GetDouble(int i) {
            ReadColumn(i);
            return _data[i].Double;
        }

        override public float GetFloat(int i) {
            ReadColumn(i);
            return _data[i].Single;
        }

        override public Guid GetGuid(int i) {
            ReadColumn(i);
            return _data[i].SqlGuid.Value;
        }

        override public Int16 GetInt16(int i) {
            ReadColumn(i);
            return _data[i].Int16;
        }

        override public Int32 GetInt32(int i) {
            ReadColumn(i);
            return _data[i].Int32;
        }

        override public Int64 GetInt64(int i) {
            ReadColumn(i);
            return _data[i].Int64;
        }

        virtual public SqlBoolean GetSqlBoolean(int i) {
            ReadColumn(i);
            return _data[i].SqlBoolean;
        }

        virtual public SqlBinary GetSqlBinary(int i) {
            ReadColumn(i, setTimeout: true, allowPartiallyReadColumn: true);
            return _data[i].SqlBinary;
        }

        virtual public SqlByte GetSqlByte(int i) {
            ReadColumn(i);
            return _data[i].SqlByte;
        }

        virtual public SqlBytes GetSqlBytes(int i) {
            ReadColumn(i);
            SqlBinary data = _data[i].SqlBinary;
            return new SqlBytes(data);
        }

        virtual public SqlChars GetSqlChars(int i) {
            ReadColumn(i);
            SqlString data;            
            // Convert Katmai types to string
            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType)
            {
                data = _data[i].KatmaiDateTimeSqlString;
            } else {
                data = _data[i].SqlString;
            }
            return new SqlChars(data);
        }

        virtual public SqlDateTime GetSqlDateTime(int i) {
            ReadColumn(i);
            return _data[i].SqlDateTime;
        }

        virtual public SqlDecimal GetSqlDecimal(int i) {
            ReadColumn(i);
            return _data[i].SqlDecimal;
        }

        virtual public SqlGuid GetSqlGuid(int i) {
            ReadColumn(i);
            return _data[i].SqlGuid;
        }

        virtual public SqlDouble GetSqlDouble(int i) {
            ReadColumn(i);
            return _data[i].SqlDouble;
        }

        virtual public SqlInt16 GetSqlInt16(int i) {
            ReadColumn(i);
            return _data[i].SqlInt16;
        }

        virtual public SqlInt32 GetSqlInt32(int i) {
            ReadColumn(i);
            return _data[i].SqlInt32;
        }

        virtual public SqlInt64 GetSqlInt64(int i) {
            ReadColumn(i);
            return _data[i].SqlInt64;
        }

        virtual public SqlMoney GetSqlMoney(int i) {
            ReadColumn(i);
            return _data[i].SqlMoney;
        }

        virtual public SqlSingle GetSqlSingle(int i) {
            ReadColumn(i);
            return _data[i].SqlSingle;
        }

        // 
        virtual public SqlString GetSqlString(int i) {
            ReadColumn(i);

            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType) {
                return _data[i].KatmaiDateTimeSqlString;
            }

            return _data[i].SqlString;
        }

        virtual public SqlXml GetSqlXml(int i){
            ReadColumn(i);
            SqlXml sx = null;

            if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
                // TypeSystem.SQLServer2005

                sx = _data[i].IsNull ? SqlXml.Null : _data[i].SqlCachedBuffer.ToSqlXml();
            }
            else {
                // TypeSystem.SQLServer2000

                // First, attempt to obtain SqlXml value.  If not SqlXml, we will throw the appropriate
                // cast exception.
                sx = _data[i].IsNull ? SqlXml.Null : _data[i].SqlCachedBuffer.ToSqlXml();

                // If the above succeeds, then we received a valid SqlXml instance, now we need to force
                // an InvalidCastException since SqlXml is not exposed with the version knob in this setting.
                // To do so, we simply force the exception by casting the string representation of the value
                // To SqlXml.
                object temp = (object) _data[i].String;
                sx = (SqlXml) temp;
            }            

            return sx;
        }

        virtual public object GetSqlValue(int i) {
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);

                SetTimeout(_defaultTimeoutMilliseconds);
                return GetSqlValueInternal(i);
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        private object GetSqlValueInternal(int i) {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }

            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            bool result = TryReadColumn(i, setTimeout: false);
            if (!result) { throw SQL.SynchronousCallMayNotPend(); }

            return GetSqlValueFromSqlBufferInternal(_data[i], _metaData[i]);
        }

        // NOTE: This method is called by the fast-paths in Async methods and, therefore, should be resilient to the DataReader being closed
        //       Always make sure to take reference copies of anything set to null in TryCloseInternal()
        private object GetSqlValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData) {
            // Dev11 Bug #336820, Dev10 Bug #479607 (SqlClient: IsDBNull always returns false for timestamp datatype)
            // Due to a bug in TdsParser.GetNullSqlValue, Timestamps' IsNull is not correctly set - so we need to bypass the following check
            Debug.Assert(!data.IsEmpty || data.IsNull || metaData.type == SqlDbType.Timestamp, "Data has been read, but the buffer is empty");

            // Convert Katmai types to string
            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
                return data.KatmaiDateTimeSqlString;
            }
            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
                return data.SqlValue;
            }
            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
                // TypeSystem.SQLServer2005

                if (metaData.type == SqlDbType.Udt) {
                    var connection = _connection;
                    if (connection != null) {
                        connection.CheckGetExtendedUDTInfo(metaData, true);
                        return connection.GetUdtValue(data.Value, metaData, false);
                    }
                    else {
                        throw ADP.DataReaderClosed("GetSqlValueFromSqlBufferInternal");
                    }
                }
                else {
                    return data.SqlValue;
                }
            }
            else {
                // TypeSystem.SQLServer2000

                if (metaData.type == SqlDbType.Xml) {
                    return data.SqlString;
                }
                else {
                    return data.SqlValue;
                }
            }
        }

        virtual public int GetSqlValues(object[] values){
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);
                CheckDataIsReady();
                if (null == values) {
                    throw ADP.ArgumentNull("values");
                }

                SetTimeout(_defaultTimeoutMilliseconds);

                int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns;

                for (int i = 0; i < copyLen; i++) {
                    values[_metaData.indexMap[i]] = GetSqlValueInternal(i);
                }
                return copyLen;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        override public string GetString(int i) {
            ReadColumn(i);

            // Convert katmai value to string if type system knob is 2005 or earlier
            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && _metaData[i].IsNewKatmaiDateTimeType) {
                return _data[i].KatmaiDateTimeString;
            }

            return _data[i].String;
        }
        
        override public T GetFieldValue<T>(int i) {
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);

                SetTimeout(_defaultTimeoutMilliseconds);
                return GetFieldValueInternal<T>(i);
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        override public object GetValue(int i) {
            SqlStatistics statistics = null;
            try {
                statistics = SqlStatistics.StartTimer(Statistics);

                SetTimeout(_defaultTimeoutMilliseconds);
                return GetValueInternal(i);
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        virtual public TimeSpan GetTimeSpan(int i) {
            ReadColumn(i);

            TimeSpan t = _data[i].Time;

            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005) {
                // TypeSystem.SQLServer2005 or less

                // If the above succeeds, then we received a valid TimeSpan instance, now we need to force
                // an InvalidCastException since TimeSpan is not exposed with the version knob in this setting.
                // To do so, we simply force the exception by casting the string representation of the value
                // To TimeSpan.
                object temp = (object) _data[i].String;
                t = (TimeSpan) temp;
            }

            return t;
        }

        virtual public DateTimeOffset GetDateTimeOffset(int i) {
            ReadColumn(i);

            DateTimeOffset dto = _data[i].DateTimeOffset;

            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005) {
                // TypeSystem.SQLServer2005 or less

                // If the above succeeds, then we received a valid DateTimeOffset instance, now we need to force
                // an InvalidCastException since DateTime is not exposed with the version knob in this setting.
                // To do so, we simply force the exception by casting the string representation of the value
                // To DateTimeOffset.
                object temp = (object) _data[i].String;
                dto = (DateTimeOffset) temp;
            }

            return dto;
        }

        private object GetValueInternal(int i) {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }

            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            bool result = TryReadColumn(i, setTimeout: false);
            if (!result) { throw SQL.SynchronousCallMayNotPend(); }

            return GetValueFromSqlBufferInternal(_data[i], _metaData[i]);
        }

        // NOTE: This method is called by the fast-paths in Async methods and, therefore, should be resilient to the DataReader being closed
        //       Always make sure to take reference copies of anything set to null in TryCloseInternal()
        private object GetValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData) {
            // Dev11 Bug #336820, Dev10 Bug #479607 (SqlClient: IsDBNull always returns false for timestamp datatype)
            // Due to a bug in TdsParser.GetNullSqlValue, Timestamps' IsNull is not correctly set - so we need to bypass the following check
            Debug.Assert(!data.IsEmpty || data.IsNull || metaData.type == SqlDbType.Timestamp, "Data has been read, but the buffer is empty");

            if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsNewKatmaiDateTimeType) {
                if (data.IsNull) {
                    return DBNull.Value;
                }
                else {
                    return data.KatmaiDateTimeString;
                }
            }
            else if (_typeSystem <= SqlConnectionString.TypeSystem.SQLServer2005 && metaData.IsLargeUdt) {
                return data.Value;
            }
            else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000) {
                // TypeSystem.SQLServer2005

                if (metaData.type != SqlDbType.Udt) {
                    return data.Value;
                }
                else {
                    var connection = _connection;
                    if (connection != null) {
                        connection.CheckGetExtendedUDTInfo(metaData, true);
                        return connection.GetUdtValue(data.Value, metaData, true);
                    }
                    else {
                        throw ADP.DataReaderClosed("GetValueFromSqlBufferInternal");
                    }
                }
            }
            else {
                // TypeSystem.SQLServer2000
                return data.Value;
            }
        }

        private T GetFieldValueInternal<T>(int i) {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }

            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            bool result = TryReadColumn(i, setTimeout: false);
            if (!result) { throw SQL.SynchronousCallMayNotPend(); }

            return GetFieldValueFromSqlBufferInternal<T>(_data[i], _metaData[i]);
        }

        private T GetFieldValueFromSqlBufferInternal<T>(SqlBuffer data, _SqlMetaData metaData) {
            Type typeofT = typeof(T);
            if (_typeofINullable.IsAssignableFrom(typeofT)) {
                // If its a SQL Type or Nullable UDT
                object rawValue = GetSqlValueFromSqlBufferInternal(data, metaData);

                // Special case: User wants SqlString, but we have a SqlXml
                // SqlXml can not be typecast into a SqlString, but we need to support SqlString on XML Types - so do a manual conversion
                if (typeofT == _typeofSqlString) {
                    SqlXml xmlValue = rawValue as SqlXml;
                    if (xmlValue != null) {
                        if (xmlValue.IsNull) {
                            rawValue = SqlString.Null;
                        }
                        else {
                            rawValue = new SqlString(xmlValue.Value);
                        }
                    }
                }

                return (T)rawValue;
            }
            else {
                // Otherwise Its a CLR or non-Nullable UDT
                try {
                    return (T)GetValueFromSqlBufferInternal(data, metaData);
                }
                catch (InvalidCastException) {
                    if (data.IsNull) {
                        // If the value was actually null, then we should throw a SqlNullValue instead
                        throw SQL.SqlNullValue();
                    }
                    else {
                        // Legitmate InvalidCast, rethrow
                        throw;
                    }
                }
            }
        }

        override public int GetValues(object[] values) {
            SqlStatistics statistics = null;
            bool sequentialAccess = IsCommandBehavior(CommandBehavior.SequentialAccess);

            try {
                statistics = SqlStatistics.StartTimer(Statistics);

                if (null == values) {
                    throw ADP.ArgumentNull("values");
                }

                CheckMetaDataIsReady();

                int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns;
                int maximumColumn = copyLen - 1;

                SetTimeout(_defaultTimeoutMilliseconds);

                // Temporarily disable sequential access
                _commandBehavior &= ~CommandBehavior.SequentialAccess;

                // Read in all of the columns in one TryReadColumn call
                bool result = TryReadColumn(maximumColumn, setTimeout: false);
                if (!result) { throw SQL.SynchronousCallMayNotPend(); }

                for (int i = 0; i < copyLen; i++) {
                    // Get the usable, TypeSystem-compatible value from the iternal buffer
                    values[_metaData.indexMap[i]] = GetValueFromSqlBufferInternal(_data[i], _metaData[i]);

                    // If this is sequential access, then we need to wipe the internal buffer
                    if ((sequentialAccess) && (i < maximumColumn)) {
                        _data[i].Clear();                        
                    }
                }

                return copyLen;
            }
            finally {
                // Restore sequential access
                if (sequentialAccess) {
                    _commandBehavior |= CommandBehavior.SequentialAccess;
                }

                SqlStatistics.StopTimer(statistics);
            }
        }

        private MetaType GetVersionedMetaType(MetaType actualMetaType) {
            Debug.Assert(_typeSystem == SqlConnectionString.TypeSystem.SQLServer2000, "Should not be in this function under anything else but SQLServer2000");

            MetaType metaType = null;

            if      (actualMetaType == MetaType.MetaUdt) {
                metaType = MetaType.MetaVarBinary;
            }
            else if (actualMetaType == MetaType.MetaXml) {
                metaType = MetaType.MetaNText;
            }
            else if (actualMetaType == MetaType.MetaMaxVarBinary) {
                metaType = MetaType.MetaImage;
            }
            else if (actualMetaType == MetaType.MetaMaxVarChar) {
                metaType = MetaType.MetaText;
            }
            else if (actualMetaType == MetaType.MetaMaxNVarChar) {
                metaType = MetaType.MetaNText;
            }
            else {
                metaType = actualMetaType;
            }

            return metaType;
        }

        private bool TryHasMoreResults(out bool moreResults) {
            if(null != _parser) {
                bool moreRows;
                if (!TryHasMoreRows(out moreRows)) {
                    moreResults = false;
                    return false;
                }
                if(moreRows) {
                    // When does this happen?  This is only called from NextResult(), which loops until Read() false.
                    moreResults = false;
                    return true;
                }

                Debug.Assert(null != _command, "unexpected null command from the data reader!");

                while(_stateObj._pendingData) {
                    byte token;
                    if (!_stateObj.TryPeekByte(out token)) {
                        moreResults = false;
                        return false;
                    }

                    switch(token) {
                        case TdsEnums.SQLALTROW:
                            if(_altRowStatus == ALTROWSTATUS.Null) {
                                // cache the regular metadata
                                _altMetaDataSetCollection.metaDataSet = _metaData;
                                _metaData = null;
                            }
                            else {
                                Debug.Assert(_altRowStatus == ALTROWSTATUS.Done, "invalid AltRowStatus");
                            }
                            _altRowStatus = ALTROWSTATUS.AltRow;
                            _hasRows = true;
                            moreResults = true;
                            return true;
                        case TdsEnums.SQLROW:
                        case TdsEnums.SQLNBCROW:
                            // always happens if there is a row following an altrow
                            moreResults = true;
                            return true;
                        
                        // VSTFDEVDIV 926281: DONEINPROC case is missing here; we have decided to reject this bug as it would result in breaking change
                        // from Orcas RTM/SP1 and Dev10 RTM. See the bug for more details.
                        // case TdsEnums.DONEINPROC:
                        case TdsEnums.SQLDONE:
                            Debug.Assert(_altRowStatus == ALTROWSTATUS.Done || _altRowStatus == ALTROWSTATUS.Null, "invalid AltRowStatus");
                            _altRowStatus = ALTROWSTATUS.Null;
                            _metaData = null;
                            _altMetaDataSetCollection = null;
                            moreResults = true;
                            return true;
                        case TdsEnums.SQLCOLMETADATA:
                            moreResults = true;
                            return true;
                    }

                    // Dev11 Bug 316483:Hang on SqlDataReader::TryHasMoreResults using MARS
                    // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=316483
                    // TryRun() will immediately return if the TdsParser is closed\broken, causing us to enter an infinite loop
                    // Instead, we will throw a closed connection exception
                    if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed) {
                        throw ADP.ClosedConnectionError();
                    }

                    bool ignored;
                    if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
                        moreResults = false;
                        return false;
                    }
                }
            }
            moreResults = false;
            return true;
        }

        private bool TryHasMoreRows(out bool moreRows) {
            if (null != _parser) {
                if (_sharedState._dataReady) {
                    moreRows = true;
                    return true;
                }

                // NextResult: previous call to NextResult started to process the altrowpackage, can't peek anymore
                // Read: Read prepared for final processing of altrow package, No more Rows until NextResult ...
                // Done: Done processing the altrow, no more rows until NextResult ...
                switch (_altRowStatus) {
                    case ALTROWSTATUS.AltRow:
                        moreRows = true;
                        return true;
                    case ALTROWSTATUS.Done:
                        moreRows = false;
                        return true;
                }
                if (_stateObj._pendingData) {
                    // Consume error's, info's, done's on HasMoreRows, so user obtains error on Read.
                    // Previous bug where Read() would return false with error on the wire in the case
                    // of metadata and error immediately following.  See MDAC 78285 and 75225.

                    // 







                    // process any done, doneproc and doneinproc token streams and
                    // any order, error or info token preceeding the first done, doneproc or doneinproc token stream
                    byte b;
                    if (!_stateObj.TryPeekByte(out b)) {
                        moreRows = false;
                        return false;
                    }
                    bool ParsedDoneToken = false;

                    while ( b == TdsEnums.SQLDONE ||
                            b == TdsEnums.SQLDONEPROC   ||
                            b == TdsEnums.SQLDONEINPROC ||
                            !ParsedDoneToken && (
                                b == TdsEnums.SQLSESSIONSTATE ||
                                b == TdsEnums.SQLENVCHANGE ||
                                b == TdsEnums.SQLORDER  ||
                                b == TdsEnums.SQLERROR  ||
                                b == TdsEnums.SQLINFO ) ) {

                        if (b == TdsEnums.SQLDONE ||
                            b == TdsEnums.SQLDONEPROC   ||
                            b == TdsEnums.SQLDONEINPROC) {
                            ParsedDoneToken = true;
                        }

                        // Dev11 Bug 316483:Hang on SqlDataReader::TryHasMoreResults using MARS
                        // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=316483
                        // TryRun() will immediately return if the TdsParser is closed\broken, causing us to enter an infinite loop
                        // Instead, we will throw a closed connection exception
                        if (_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed) {
                            throw ADP.ClosedConnectionError();
                        }

                        bool ignored;
                        if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
                            moreRows = false;
                            return false;
                        }
                        if ( _stateObj._pendingData) {
                            if (!_stateObj.TryPeekByte(out b)) {
                                moreRows = false;
                                return false;
                            }
                        }
                        else {
                            break;
                        }
                    }

                    // Only return true when we are positioned on a row token.
                    if (IsRowToken(b)) {
                        moreRows = true;
                        return true;
                    }
                }
            }
            moreRows = false;
            return true;
        }
        
        private bool IsRowToken(byte token) {
            return TdsEnums.SQLROW == token || TdsEnums.SQLNBCROW == token;
        }

        override public bool IsDBNull(int i) {
            if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) && ((_sharedState._nextColumnHeaderToRead > i + 1) || (_lastColumnWithDataChunkRead > i))) {
                // Bug 447026 : A breaking change in System.Data .NET 4.5 for calling IsDBNull on commands in SequentialAccess mode
                // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=447026
                // In .Net 4.0 and previous, it was possible to read a previous column using IsDBNull when in sequential mode
                // However, since it had already gone past the column, the current IsNull value is simply returned

                // To replicate this behavior we will skip CheckHeaderIsReady\ReadColumnHeader and instead just check that the reader is ready and the column is valid
                CheckMetaDataIsReady(columnIndex: i);
            }
            else {
                CheckHeaderIsReady(columnIndex: i, methodName: "IsDBNull");
            
                SetTimeout(_defaultTimeoutMilliseconds);

                ReadColumnHeader(i);    // header data only
            }

            return _data[i].IsNull;
        }

        protected internal bool IsCommandBehavior(CommandBehavior condition) {
            return (condition == (condition & _commandBehavior));
        }

        override public bool NextResult() {
            if (_currentTask != null) {
                throw SQL.PendingBeginXXXExists();
            }

            bool more;
            bool result;

            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            result = TryNextResult(out more);

            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
            return more;
        }

        // recordset is automatically positioned on the first result set
        private bool TryNextResult(out bool more) {
            SqlStatistics statistics = null;
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.NextResult|API> %d#", ObjectID);

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    statistics = SqlStatistics.StartTimer(Statistics);

                    SetTimeout(_defaultTimeoutMilliseconds);
                    
                    if (IsClosed) {
                        throw ADP.DataReaderClosed("NextResult");
                    }
                    _fieldNameLookup = null;

                    bool success = false; // WebData 100390
                    _hasRows = false; // reset HasRows

                    // if we are specifically only processing a single result, then read all the results off the wire and detach
                    if (IsCommandBehavior(CommandBehavior.SingleResult)) {
                        if (!TryCloseInternal(false /*closeReader*/)) {
                            more = false;
                            return false;
                        }

                        // In the case of not closing the reader, null out the metadata AFTER
                        // CloseInternal finishes - since CloseInternal may go to the wire
                        // and use the metadata.
                        ClearMetaData();
                        more = success;
                        return true;
                    }

                    if (null != _parser) {
                        // if there are more rows, then skip them, the user wants the next result
                        bool moreRows = true;
                        while (moreRows) { 
                            if (!TryReadInternal(false, out moreRows)) { // don't reset set the timeout value
                                more = false;
                                return false;
                            }
                        }
                    }

                    // we may be done, so continue only if we have not detached ourselves from the parser
                    if (null != _parser) {
                        bool moreResults;
                        if (!TryHasMoreResults(out moreResults)) {
                            more = false;
                            return false;
                        }
                        if (moreResults) {
                            _metaDataConsumed = false;
                            _browseModeInfoConsumed = false;

                            switch (_altRowStatus) {
                                case ALTROWSTATUS.AltRow:
                                    int altRowId;
                                    if (!_parser.TryGetAltRowId(_stateObj, out altRowId)) {
                                        more = false;
                                        return false;
                                    }
                                    _SqlMetaDataSet altMetaDataSet = _altMetaDataSetCollection.GetAltMetaData(altRowId);
                                    if (altMetaDataSet != null) {
                                        _metaData = altMetaDataSet;
                                    }
                                    Debug.Assert ((_metaData != null), "Can't match up altrowmetadata");
                                    break;
                                case ALTROWSTATUS.Done:
                                    // restore the row-metaData
                                    _metaData = _altMetaDataSetCollection.metaDataSet;
                                    Debug.Assert (_altRowStatus == ALTROWSTATUS.Done, "invalid AltRowStatus");
                                    _altRowStatus = ALTROWSTATUS.Null;
                                    break;
                                default:
                                    if (!TryConsumeMetaData()) {
                                        more = false;
                                        return false;
                                    }
                                    if (_metaData == null) {
                                        more = false;
                                        return true;
                                    }
                                    break;
                            }

                            success = true;
                        }
                        else {
                            // detach the parser from this reader now
                            if (!TryCloseInternal(false /*closeReader*/)) {
                                more = false;
                                return false;
                            }

                            // In the case of not closing the reader, null out the metadata AFTER
                            // CloseInternal finishes - since CloseInternal may go to the wire
                            // and use the metadata.
                            if (!TrySetMetaData(null, false)) {
                                more = false;
                                return false;
                            }
                        }
                    }
                    else {
                        // Clear state in case of Read calling CloseInternal() then user calls NextResult()
                        // MDAC 81986.  Or, also the case where the Read() above will do essentially the same
                        // thing.
                        ClearMetaData();
                    }

                    more = success;
                    return true;
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
                Bid.ScopeLeave(ref hscp);
            }
        }

        // user must call Read() to position on the first row
        override public bool Read() {
            if (_currentTask != null) {
                throw SQL.PendingBeginXXXExists();
            }

            bool more;
            bool result;

            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            result = TryReadInternal(true, out more);

            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
            return more;
        }

        // user must call Read() to position on the first row
        private bool TryReadInternal(bool setTimeout, out bool more) {
            SqlStatistics statistics = null;
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.Read|API> %d#", ObjectID);

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    statistics = SqlStatistics.StartTimer(Statistics);

                    if (null != _parser) {
                        if (setTimeout) {
                            SetTimeout(_defaultTimeoutMilliseconds);
                        }
                        if (_sharedState._dataReady) {
                            if (!TryCleanPartialRead()) {
                                more = false;
                                return false;
                            }
                        }
                        
                        // clear out our buffers
                        SqlBuffer.Clear(_data);

                        _sharedState._nextColumnHeaderToRead = 0;
                        _sharedState._nextColumnDataToRead = 0;
                        _sharedState._columnDataBytesRemaining = -1; // unknown
                        _lastColumnWithDataChunkRead = -1;

                        if (!_haltRead) {
                            bool moreRows;
                            if (!TryHasMoreRows(out moreRows)) {
                                more = false;
                                return false;
                            }
                            if (moreRows) {
                                // read the row from the backend (unless it's an altrow were the marker is already inside the altrow ...)
                                while (_stateObj._pendingData) {
                                    if (_altRowStatus != ALTROWSTATUS.AltRow) {
                                        // if this is an ordinary row we let the run method consume the ROW token
                                        if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out _sharedState._dataReady)) {
                                            more = false;
                                            return false;
                                        }
                                        if (_sharedState._dataReady) {
                                            break;
                                        }
                                    }
                                    else {
                                        // ALTROW token and AltrowId are already consumed ...
                                        Debug.Assert (_altRowStatus == ALTROWSTATUS.AltRow, "invalid AltRowStatus");
                                        _altRowStatus = ALTROWSTATUS.Done;
                                        _sharedState._dataReady = true;
                                        break;
                                    }
                                }
                                if (_sharedState._dataReady) {
                                    _haltRead = IsCommandBehavior(CommandBehavior.SingleRow);
                                    more = true;
                                    return true;
                                }
                            }

                            if (!_stateObj._pendingData) {
                                if (!TryCloseInternal(false /*closeReader*/)) {
                                    more = false;
                                    return false;
                                }
                            }
                        }
                        else {
                            // if we did not get a row and halt is true, clean off rows of result
                            // success must be false - or else we could have just read off row and set
                            // halt to true
                            bool moreRows;
                            if (!TryHasMoreRows(out moreRows)) {
                                more = false;
                                return false;
                            }
                            while (moreRows) {
                                // if we are in SingleRow mode, and we've read the first row,
                                // read the rest of the rows, if any
                                while (_stateObj._pendingData && !_sharedState._dataReady) {
                                    if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out _sharedState._dataReady)) {
                                        more = false;
                                        return false;
                                    }
                                }

                                if (_sharedState._dataReady) {
                                    if (!TryCleanPartialRead()) {
                                        more = false;
                                        return false;
                                    }
                                }

                                // clear out our buffers
                                SqlBuffer.Clear(_data);

                                _sharedState._nextColumnHeaderToRead = 0;

                                if (!TryHasMoreRows(out moreRows)) {
                                    more = false;
                                    return false;
                                }
                            }

                            // reset haltRead
                            _haltRead = false;
                         }
                    }
                    else if (IsClosed) {
                        throw ADP.DataReaderClosed("Read");
                    }
                    more = false;

#if DEBUG
                    if ((!_sharedState._dataReady) && (_stateObj._pendingData)) {
                        byte token;
                        if (!_stateObj.TryPeekByte(out token)) {
                            return false;
                        }

                        Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("DataReady is false, but next token is invalid: {0,-2:X2}", token));
                    }
#endif

                    return true;
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                SqlConnection con = _connection;
                if (con != null) {
                    con.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                SqlConnection con = _connection;
                if (con != null) {
                    con.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
               _isClosed = true;
                SqlConnection con = _connection;
                if (con != null) {
                    con.Abort(e);
                }
                throw;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
                Bid.ScopeLeave(ref hscp);
            }
        }

        private void ReadColumn(int i, bool setTimeout = true, bool allowPartiallyReadColumn = false) {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }

            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            bool result = TryReadColumn(i, setTimeout, allowPartiallyReadColumn);
            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
        }

        private bool TryReadColumn(int i, bool setTimeout, bool allowPartiallyReadColumn = false) {
            CheckDataIsReady(columnIndex: i, permitAsync: true, allowPartiallyReadColumn: allowPartiallyReadColumn);
            
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large");
                    Debug.Assert(_sharedState._nextColumnDataToRead <= _metaData.Length, "_sharedState._nextColumnDataToRead too large");

                    if (setTimeout) {
                        SetTimeout(_defaultTimeoutMilliseconds);
                    }
                    
                    if (!TryReadColumnInternal(i, readHeaderOnly: false)) {
                        return false;
                    }
                    
                    Debug.Assert(null != _data[i], " data buffer is null?");
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }

            return true;
        }

        private bool TryReadColumnData() {
            // If we've already read the value (because it was NULL) we don't
            // bother to read here.
            if (!_data[_sharedState._nextColumnDataToRead].IsNull) {
                _SqlMetaData columnMetaData = _metaData[_sharedState._nextColumnDataToRead];

                if (!_parser.TryReadSqlValue(_data[_sharedState._nextColumnDataToRead], columnMetaData, (int)_sharedState._columnDataBytesRemaining, _stateObj,
                                             _command != null ? _command.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting,
                                             columnMetaData.column)) { // will read UDTs as VARBINARY.
                    return false;
                }
                _sharedState._columnDataBytesRemaining = 0;
            }
            _sharedState._nextColumnDataToRead++;
            return true;
        }

        private void ReadColumnHeader(int i) {
            Debug.Assert(_stateObj == null || _stateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
            bool result = TryReadColumnHeader(i);
            if (!result) { throw SQL.SynchronousCallMayNotPend(); }
        }

        private bool TryReadColumnHeader(int i) {
            if (!_sharedState._dataReady) {
                throw SQL.InvalidRead();
            }
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#endif //DEBUG
                    return TryReadColumnInternal(i, readHeaderOnly: true);
#if DEBUG
                }
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.StackOverflowException e) {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
            catch (System.Threading.ThreadAbortException e)  {
                _isClosed = true;
                if (null != _connection) {
                    _connection.Abort(e);
                }
                throw;
            }
        }

        private bool TryReadColumnInternal(int i, bool readHeaderOnly = false) {
            AssertReaderState(requireData: true, permitAsync: true, columnIndex: i);

            // Check if we've already read the header already
            if (i < _sharedState._nextColumnHeaderToRead) {
                // Read the header, but we need to read the data
                if ((i == _sharedState._nextColumnDataToRead) && (!readHeaderOnly)) {
                    return TryReadColumnData();
                }
                // Else we've already read the data, or we're reading the header only
                else {
                    // Ensure that, if we've read past the column, then we did store its data
                    Debug.Assert(i == _sharedState._nextColumnDataToRead ||                                                          // Either we haven't read the column yet
                        ((i + 1 < _sharedState._nextColumnDataToRead) && (IsCommandBehavior(CommandBehavior.SequentialAccess))) ||   // Or we're in sequential mode and we've read way past the column (i.e. it was not the last column we read)
                        (!_data[i].IsEmpty || _data[i].IsNull) ||                                                       // Or we should have data stored for the column (unless the column was null)
                        (_metaData[i].type == SqlDbType.Timestamp),                                                     // Or Dev11 Bug #336820, Dev10 Bug #479607 (SqlClient: IsDBNull always returns false for timestamp datatype)
                                                                                                                        //    Due to a bug in TdsParser.GetNullSqlValue, Timestamps' IsNull is not correctly set - so we need to bypass the check
                        "Gone past column, be we have no data stored for it");
                    return true;
                }
            }

            Debug.Assert(_data[i].IsEmpty || _data[i].IsNull, "re-reading column value?");
            
            // If we're in sequential access mode, we can safely clear out any
            // data from the previous column.
            bool isSequentialAccess = IsCommandBehavior(CommandBehavior.SequentialAccess);
            if (isSequentialAccess) {
                if (0 < _sharedState._nextColumnDataToRead) {
                    _data[_sharedState._nextColumnDataToRead - 1].Clear();
                }

                // Only wipe out the blob objects if they aren't for a 'future' column (i.e. we haven't read up to them yet)
                if ((_lastColumnWithDataChunkRead > -1) && (i > _lastColumnWithDataChunkRead)) {
                    CloseActiveSequentialStreamAndTextReader();
                }
            }
            else if (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead) {
                // We read the header but not the column for the previous column
                if (!TryReadColumnData()) {
                    return false;
                }
                Debug.Assert(_sharedState._nextColumnDataToRead == _sharedState._nextColumnHeaderToRead);
            }

            // if we still have bytes left from the previous blob read, clear the wire and reset
            if (!TryResetBlobState()) {
                return false;
            }

            do {
                _SqlMetaData columnMetaData = _metaData[_sharedState._nextColumnHeaderToRead];

                if ((isSequentialAccess) && (_sharedState._nextColumnHeaderToRead < i)) {
                    // SkipValue is no-op if the column appears in NBC bitmask
                    // if not, it skips regular and PLP types
                    if (!_parser.TrySkipValue(columnMetaData, _sharedState._nextColumnHeaderToRead, _stateObj)) {
                        return false;
                    }

                    _sharedState._nextColumnDataToRead = _sharedState._nextColumnHeaderToRead;
                    _sharedState._nextColumnHeaderToRead++;
                }
                else {
                    bool isNull;
                    ulong dataLength;
                    if (!_parser.TryProcessColumnHeader(columnMetaData, _stateObj, _sharedState._nextColumnHeaderToRead, out isNull, out dataLength)) {
                        return false;
                    }

                    _sharedState._nextColumnDataToRead = _sharedState._nextColumnHeaderToRead;
                    _sharedState._nextColumnHeaderToRead++;  // We read this one

                    if (isNull && columnMetaData.type != SqlDbType.Timestamp /* Maintain behavior for known bug (Dev10 479607) rejected as breaking change - See comments in GetNullSqlValue for timestamp */)
                    {
                        TdsParser.GetNullSqlValue(_data[_sharedState._nextColumnDataToRead], 
                            columnMetaData,
                            _command != null ? _command.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting,
                            _parser.Connection);
                        
                        if (!readHeaderOnly) {
                            _sharedState._nextColumnDataToRead++;
                        }                        
                    }
                    else {
                        if ((i > _sharedState._nextColumnDataToRead) || (!readHeaderOnly)) {
                            // If we're not in sequential access mode, we have to
                            // save the data we skip over so that the consumer
                            // can read it out of order
                            if (!_parser.TryReadSqlValue(_data[_sharedState._nextColumnDataToRead], columnMetaData, (int)dataLength, _stateObj,
                                                         _command != null ? _command.ColumnEncryptionSetting : SqlCommandColumnEncryptionSetting.UseConnectionSetting,
                                                         columnMetaData.column)) { // will read UDTs as VARBINARY.
                                return false;
                            }
                            _sharedState._nextColumnDataToRead++;
                        }
                        else {
                            _sharedState._columnDataBytesRemaining = (long)dataLength;
                        }
                    }
                }

                if (_snapshot != null) {
                    // reset snapshot to save memory use.  We can safely do that here because all SqlDataReader values are stable.
                    // The retry logic can use the current values to get back to the right state.
                    _snapshot = null;
                    PrepareAsyncInvocation(useSnapshot: true);
                }
            } while (_sharedState._nextColumnHeaderToRead <= i);

            return true;
        }

        // Estimates if there is enough data available to read the number of columns requested
        private bool WillHaveEnoughData(int targetColumn, bool headerOnly = false) {
            AssertReaderState(requireData: true, permitAsync: true, columnIndex: targetColumn);
                       
            if ((_lastColumnWithDataChunkRead == _sharedState._nextColumnDataToRead) && (_metaData[_lastColumnWithDataChunkRead].metaType.IsPlp)) {
                // In the middle of reading a Plp - no idea how much is left
                return false;
            }

            int bytesRemaining = Math.Min(checked(_stateObj._inBytesRead - _stateObj._inBytesUsed), _stateObj._inBytesPacket);

            // There are some parts of our code that peeks at the next token after doing its read
            // So we will make sure that there is always a spare byte for it to look at
            bytesRemaining--;
            
            if ((targetColumn >= _sharedState._nextColumnDataToRead) && (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead)) {
                if (_sharedState._columnDataBytesRemaining > bytesRemaining) {
                    // The current column needs more data than we currently have
                    // NOTE: Since the Long data types (TEXT, IMAGE, NTEXT) can have a size of Int32.MaxValue we cannot simply subtract
                    // _columnDataBytesRemaining from bytesRemaining and then compare it to zero as this may lead to an overflow
                    return false;
                }
                else {
                    // Already read the header, so subtract actual data size
                    bytesRemaining = checked(bytesRemaining - (int)_sharedState._columnDataBytesRemaining);
                }
            }
            
            // For each column that we need to read, subtract the size of its header and the size of its data
            int currentColumn = _sharedState._nextColumnHeaderToRead;
            while ((bytesRemaining >= 0) && (currentColumn <= targetColumn)) {
                // Check NBC first
                if (!_stateObj.IsNullCompressionBitSet(currentColumn)) {

                    // NOTE: This is mostly duplicated from TryProcessColumnHeaderNoNBC and TryGetTokenLength
                    var metaType = _metaData[currentColumn].metaType;                    
                    if ((metaType.IsLong) || (metaType.IsPlp) || (metaType.SqlDbType == SqlDbType.Udt) || (metaType.SqlDbType == SqlDbType.Structured)) {
                        // Plp, Udt and TVP types have an unknownable size - so return that the estimate failed
                        return false;
                    }            
                    int maxHeaderSize;
                    byte typeAndMask = (byte)(_metaData[currentColumn].tdsType & TdsEnums.SQLLenMask);
                    if ((typeAndMask == TdsEnums.SQLVarLen) || (typeAndMask == TdsEnums.SQLVarCnt)) {
                        if (0 != (_metaData[currentColumn].tdsType & 0x80)) {
                            // UInt16 represents size
                            maxHeaderSize = 2;
                        }
                        else if (0 == (_metaData[currentColumn].tdsType & 0x0c)) {
                            // UInt32 represents size
                            maxHeaderSize = 4;
                        }
                        else {
                            // Byte represents size
                            maxHeaderSize = 1;
                        }
                    }
                    else
                    {
                        maxHeaderSize = 0;
                    }

                    bytesRemaining = checked(bytesRemaining - maxHeaderSize);
                    if ((currentColumn < targetColumn) || (!headerOnly)) {
                        bytesRemaining = checked(bytesRemaining - _metaData[currentColumn].length);
                    }
                }

                currentColumn++;
            }

            return (bytesRemaining >= 0);
        }

        // clean remainder bytes for the column off the wire
        private bool TryResetBlobState() {
            Debug.Assert(null != _stateObj, "null state object"); // _parser may be null at this point
            AssertReaderState(requireData: true, permitAsync: true);
            Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large");

            // If we haven't already entirely read the column
            if (_sharedState._nextColumnDataToRead < _sharedState._nextColumnHeaderToRead) {
                if ((_sharedState._nextColumnHeaderToRead > 0) && (_metaData[_sharedState._nextColumnHeaderToRead - 1].metaType.IsPlp)) {
                    if (_stateObj._longlen != 0) {
                        ulong ignored;
                        if (!_stateObj.Parser.TrySkipPlpValue(UInt64.MaxValue, _stateObj, out ignored)) {
                            return false;
                        }
                    }
                    if (_streamingXml != null) {
                        SqlStreamingXml localSXml = _streamingXml;
                        _streamingXml = null;
                        localSXml.Close();
                    }
                }
                else if (0 < _sharedState._columnDataBytesRemaining) {
                    if (!_stateObj.TrySkipLongBytes(_sharedState._columnDataBytesRemaining)) {
                        return false;
                    }
                }
            }
#if DEBUG
            else {
                Debug.Assert((_sharedState._columnDataBytesRemaining == 0 || _sharedState._columnDataBytesRemaining == -1) && _stateObj._longlen == 0, "Haven't read header yet, but column is partially read?");
            }
#endif

            _sharedState._columnDataBytesRemaining = 0;
            _columnDataBytesRead = 0;
            _columnDataCharsRead = 0;
            _columnDataChars = null;
            _columnDataCharsIndex = -1;
            _stateObj._plpdecoder = null;

            return true;
        }

        private void CloseActiveSequentialStreamAndTextReader() {
            if (_currentStream != null) {
                _currentStream.SetClosed();
                _currentStream = null;
            }
            if (_currentTextReader != null) {
                _currentTextReader.SetClosed();
                _currentStream = null;
            }
        }

        private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateObj) {
            // turn off any set options
            if (null != parser && null != _resetOptionsString) {
                // It is possible for this to be called during connection close on a
                // broken connection, so check state first.
                if (parser.State == TdsParserState.OpenLoggedIn) {
                    Bid.CorrelationTrace("<sc.SqlDataReader.RestoreServerSettings|Info|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
                    Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true);
                    Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
                    
                    // must execute this one synchronously as we can't retry
                    parser.Run(RunBehavior.UntilDone, _command, this, null, stateObj);
                }
                _resetOptionsString = null;
            }
        }

        internal bool TrySetAltMetaDataSet(_SqlMetaDataSet metaDataSet, bool metaDataConsumed) {
            if (_altMetaDataSetCollection == null) {
                _altMetaDataSetCollection = new _SqlMetaDataSetCollection();
            } 
            else if (_snapshot != null && object.ReferenceEquals(_snapshot._altMetaDataSetCollection, _altMetaDataSetCollection)) {
                _altMetaDataSetCollection = (_SqlMetaDataSetCollection)_altMetaDataSetCollection.Clone();
            }
            _altMetaDataSetCollection.SetAltMetaData(metaDataSet);
            _metaDataConsumed = metaDataConsumed;
            if (_metaDataConsumed && null != _parser) {
                byte b;
                if (!_stateObj.TryPeekByte(out b)) {
                    return false;
                }
                if (TdsEnums.SQLORDER == b) {
                    bool ignored;
                    if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, this, null, _stateObj, out ignored)) {
                        return false;
                    }
                    if (!_stateObj.TryPeekByte(out b)) {
                        return false;
                    }
                }
                if (b == TdsEnums.SQLINFO) {
                    try {
                        _stateObj._accumulateInfoEvents = true;
                        bool ignored;
                        if (!_parser.TryRun(RunBehavior.ReturnImmediately, _command, null, null, _stateObj, out ignored)) {
                            return false;
                        }
                    }
                    finally {
                        _stateObj._accumulateInfoEvents = false;
                    }
                    if (!_stateObj.TryPeekByte(out b)) {
                        return false;
                    }
                }
                _hasRows = IsRowToken(b);
            }
            if (metaDataSet != null) {
                if (_data == null || _data.Length<metaDataSet.Length) {
                    _data = SqlBuffer.CreateBufferArray(metaDataSet.Length);
                }
            }
            return true;
        }

        private void ClearMetaData() {
            _metaData = null;
            _tableNames = null;
            _fieldNameLookup = null;
            _metaDataConsumed = false;
            _browseModeInfoConsumed = false;
        }

        internal bool TrySetMetaData(_SqlMetaDataSet metaData, bool moreInfo) {
            _metaData = metaData;

            // get rid of cached metadata info as well
            _tableNames = null;
            if (_metaData != null) {
                _metaData.schemaTable = null;
                _data = SqlBuffer.CreateBufferArray(metaData.Length);
            }

            _fieldNameLookup = null;

            if (null != metaData) {
                // we are done consuming metadata only if there is no moreInfo
                if (!moreInfo) {
                    _metaDataConsumed = true;

                    if (_parser != null) { // There is a valid case where parser is null
                        // Peek, and if row token present, set _hasRows true since there is a
                        // row in the result
                        byte b;
                        if (!_stateObj.TryPeekByte(out b)) {
                            return false;
                        }

                        // 


                        // simply rip the order token off the wire
                        if (b == TdsEnums.SQLORDER) {                     //  same logic as SetAltMetaDataSet
// Devnote: That's not the right place to process TDS
// Can this result in Reentrance to Run?
//
                            bool ignored;
                            if (!_parser.TryRun(RunBehavior.ReturnImmediately, null, null, null, _stateObj, out ignored)) {
                                return false;
                            }
                            if (!_stateObj.TryPeekByte(out b)) {
                                return false;
                            }
                        }
                        if (b == TdsEnums.SQLINFO)
                        {
                            // VSTFDEVDIV713926
                            // We are accumulating informational events and fire them at next
                            // TdsParser.Run purely to avoid breaking change
                            try {
                                _stateObj._accumulateInfoEvents = true;
                                bool ignored;
                                if (!_parser.TryRun(RunBehavior.ReturnImmediately, null, null, null, _stateObj, out ignored)) {
                                    return false;
                                }
                            }
                            finally {
                                _stateObj._accumulateInfoEvents = false;
                            }                       
                            if (!_stateObj.TryPeekByte(out b)) {
                                return false;
                            }
                        }
                        _hasRows = IsRowToken(b);
                        if (TdsEnums.SQLALTMETADATA == b)
                        {
                            _metaDataConsumed = false;
                        }
                    }
                }
            }
            else {
                _metaDataConsumed = false;
            }

            _browseModeInfoConsumed = false;
            return true;
        }

        private void SetTimeout(long timeoutMilliseconds) {
            // WebData 111653,112003 -- we now set timeouts per operation, not
            // per command (it's not supposed to be a cumulative per command).
            TdsParserStateObject stateObj = _stateObj;
            if (null != stateObj) {
                stateObj.SetTimeoutMilliseconds(timeoutMilliseconds);
            }
        }

        private bool HasActiveStreamOrTextReaderOnColumn(int columnIndex) {
            bool active = false;

            active |= ((_currentStream != null) && (_currentStream.ColumnIndex == columnIndex));
            active |= ((_currentTextReader != null) && (_currentTextReader.ColumnIndex == columnIndex));

            return active;
        }

        private void CheckMetaDataIsReady() {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }
            if (MetaData == null) {
                throw SQL.InvalidRead();
            }
        }

        private void CheckMetaDataIsReady(int columnIndex, bool permitAsync = false) {
            if ((!permitAsync) && (_currentTask != null)) {
                throw ADP.AsyncOperationPending();
            }
            if (MetaData == null) {
                throw SQL.InvalidRead();
            }
            if ((columnIndex < 0) || (columnIndex >= _metaData.Length)) {
                throw ADP.IndexOutOfRange();
            }
        }

        private void CheckDataIsReady() {
            if (_currentTask != null) {
                throw ADP.AsyncOperationPending();
            }
            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
            if ((!_sharedState._dataReady) || (_metaData == null)) {
                throw SQL.InvalidRead();
            }
        }
        
        private void CheckHeaderIsReady(int columnIndex, bool permitAsync = false, string methodName = null) {
            if (_isClosed) {
                throw ADP.DataReaderClosed(methodName ?? "CheckHeaderIsReady");
            }
            if ((!permitAsync) && (_currentTask != null)) {
                throw ADP.AsyncOperationPending();
            }
            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
            if ((!_sharedState._dataReady) || (_metaData == null)) {
                throw SQL.InvalidRead();
            }
            if ((columnIndex < 0) || (columnIndex >= _metaData.Length)) {
                throw ADP.IndexOutOfRange();
            }
            if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) &&                                          // Only for sequential access
                ((_sharedState._nextColumnHeaderToRead > columnIndex + 1) || (_lastColumnWithDataChunkRead > columnIndex))) {  // Read past column
                    throw ADP.NonSequentialColumnAccess(columnIndex, Math.Max(_sharedState._nextColumnHeaderToRead - 1, _lastColumnWithDataChunkRead));
            }
        }

        private void CheckDataIsReady(int columnIndex, bool allowPartiallyReadColumn = false, bool permitAsync = false, string methodName = null) {
            if (_isClosed) {
                throw ADP.DataReaderClosed(methodName ?? "CheckDataIsReady");
            }
            if ((!permitAsync) && (_currentTask != null)) {
                throw ADP.AsyncOperationPending();
            }
            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
            if ((!_sharedState._dataReady) || (_metaData == null)) {
                throw SQL.InvalidRead();
            }
            if ((columnIndex < 0) || (columnIndex >= _metaData.Length)) {
                throw ADP.IndexOutOfRange();
            }
            if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) &&                                    // Only for sequential access
                ((_sharedState._nextColumnDataToRead > columnIndex) || (_lastColumnWithDataChunkRead > columnIndex) ||   // Read past column
                ((!allowPartiallyReadColumn) && (_lastColumnWithDataChunkRead == columnIndex)) ||           // Partially read column
                ((allowPartiallyReadColumn) && (HasActiveStreamOrTextReaderOnColumn(columnIndex))))) {      // Has a Stream or TextReader on a partially-read column
                    throw ADP.NonSequentialColumnAccess(columnIndex, Math.Max(_sharedState._nextColumnDataToRead, _lastColumnWithDataChunkRead + 1));
            }
        }

        [Conditional("DEBUG")]
        private void AssertReaderState(bool requireData, bool permitAsync, int? columnIndex = null, bool enforceSequentialAccess = false) {
            Debug.Assert(!_sharedState._dataReady || _metaData != null, "Data is ready, but there is no metadata?");
            Debug.Assert(permitAsync || _currentTask == null, "Call while async operation is pending");
            Debug.Assert(_metaData != null, "_metaData is null, check MetaData before calling this method");
            Debug.Assert(!requireData || _sharedState._dataReady, "No data is ready to be read");
            if (columnIndex.HasValue) {
                Debug.Assert(columnIndex.Value >= 0 && columnIndex.Value < _metaData.Length, "Invalid column index");
                Debug.Assert((!enforceSequentialAccess) || (!IsCommandBehavior(CommandBehavior.SequentialAccess)) || ((_sharedState._nextColumnDataToRead <= columnIndex) && (_lastColumnWithDataChunkRead <= columnIndex)), "Already read past column");
            }
        }

        public override Task<bool> NextResultAsync(CancellationToken cancellationToken) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.NextResultAsync|API> %d#", ObjectID);

            try {
                TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();

                if (IsClosed) {
                    source.SetException(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("NextResultAsync")));
                    return source.Task;
                }

                IDisposable registration = null;
                if (cancellationToken.CanBeCanceled) {
                    if (cancellationToken.IsCancellationRequested) {
                        source.SetCanceled();
                        return source.Task;
                    }
                    registration = cancellationToken.Register(_command.CancelIgnoreFailure);
                }

                Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
                if (original != null) {
                    source.SetException(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
                    return source.Task;
                }

                // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
                if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
                    source.SetCanceled();
                    _currentTask = null;
                    return source.Task;
                }

                PrepareAsyncInvocation(useSnapshot: true);

                Func<Task, Task<bool>> moreFunc = null;

                moreFunc = (t) => {
                    if (t != null) {
                        Bid.Trace("<sc.SqlDataReader.NextResultAsync> attempt retry %d#\n", ObjectID);
                        PrepareForAsyncContinuation();
                    }

                    bool more;
                    if (TryNextResult(out more)) {
                        // completed 
                        return more ? ADP.TrueTask : ADP.FalseTask;
                    }

                    return ContinueRetryable(moreFunc);
                };

                return InvokeRetryable(moreFunc, source, registration);
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }

        // NOTE: This will return null if it completed sequentially
        // If this returns null, then you can use bytesRead to see how many bytes were read - otherwise bytesRead should be ignored
        internal Task<int> GetBytesAsync(int i, byte[] buffer, int index, int length, int timeout, CancellationToken cancellationToken, out int bytesRead) {
            AssertReaderState(requireData: true, permitAsync: true, columnIndex: i, enforceSequentialAccess: true);
            Debug.Assert(IsCommandBehavior(CommandBehavior.SequentialAccess));

            bytesRead = 0;
            if (IsClosed) {
                TaskCompletionSource<int> source = new TaskCompletionSource<int>();
                source.SetException(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("GetBytesAsync")));
                return source.Task;
            }

            if (_currentTask != null) {
                TaskCompletionSource<int> source = new TaskCompletionSource<int>();
                source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
                return source.Task;
            }
                
            if (cancellationToken.CanBeCanceled) {
                if (cancellationToken.IsCancellationRequested) {
                    return null;
                }
            }

            // Check if we need to skip columns
            Debug.Assert(_sharedState._nextColumnDataToRead <= _lastColumnWithDataChunkRead, "Non sequential access");
            if ((_sharedState._nextColumnHeaderToRead <= _lastColumnWithDataChunkRead) || (_sharedState._nextColumnDataToRead < _lastColumnWithDataChunkRead)) {
                TaskCompletionSource<int> source = new TaskCompletionSource<int>();
                Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
                if (original != null) {
                    source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
                    return source.Task;
                }

                PrepareAsyncInvocation(useSnapshot: true);

                Func<Task, Task<int>> moreFunc = null;

                // Timeout
                CancellationToken timeoutToken = CancellationToken.None;
                CancellationTokenSource timeoutCancellationSource = null;
                if (timeout > 0) {
                    timeoutCancellationSource = new CancellationTokenSource();
                    timeoutCancellationSource.CancelAfter(timeout);
                    timeoutToken = timeoutCancellationSource.Token;
                }

                moreFunc = (t) => {
                    if (t != null) {
                        Bid.Trace("<sc.SqlDataReader.GetBytesAsync> attempt retry %d#\n", ObjectID);
                        PrepareForAsyncContinuation();
                    }

                    // Prepare for stateObj timeout
                    SetTimeout(_defaultTimeoutMilliseconds);

                    if (TryReadColumnHeader(i)) {
                        // Only once we have read upto where we need to be can we check the cancellation tokens (otherwise we will be in an unknown state)

                        if (cancellationToken.IsCancellationRequested) {
                            // User requested cancellation
                            return ADP.CreatedTaskWithCancellation<int>();
                        }
                        else if (timeoutToken.IsCancellationRequested) {
                            // Timeout
                            return ADP.CreatedTaskWithException<int>(ADP.ExceptionWithStackTrace(ADP.IO(SQLMessage.Timeout())));
                        }
                        else {
                            // Upto the correct column - continue to read
                            SwitchToAsyncWithoutSnapshot();
                            int totalBytesRead;
                            var readTask = GetBytesAsyncReadDataStage(i, buffer, index, length, timeout, true, cancellationToken, timeoutToken, out totalBytesRead);
                            if (readTask == null) {
                                // Completed synchronously
                                return Task.FromResult<int>(totalBytesRead);
                            }
                            else {
                                return readTask;
                            }
                        }
                    }
                    else {
                        return ContinueRetryable(moreFunc);
                    }
                };

                return InvokeRetryable(moreFunc, source, timeoutCancellationSource);
            }
            else {
                // We're already at the correct column, just read the data

                // Switch to async
                PrepareAsyncInvocation(useSnapshot: false);

                try {
                    return GetBytesAsyncReadDataStage(i, buffer, index, length, timeout, false, cancellationToken, CancellationToken.None, out bytesRead);
                }
                catch {
                    CleanupAfterAsyncInvocation();
                    throw;
                }
            }
        }

        private Task<int> GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, int length, int timeout, bool isContinuation, CancellationToken cancellationToken, CancellationToken timeoutToken, out int bytesRead) {
            _lastColumnWithDataChunkRead = i;
            TaskCompletionSource<int> source = null;
            CancellationTokenSource timeoutCancellationSource = null;
            
            // Prepare for stateObj timeout
            SetTimeout(_defaultTimeoutMilliseconds);

            // Try to read without any continuations (all the data may already be in the stateObj's buffer)
            if (!TryGetBytesInternalSequential(i, buffer, index, length, out bytesRead)) {
                // This will be the 'state' for the callback
                int totalBytesRead = bytesRead;

                if (!isContinuation) {
                    // This is the first async operation which is happening - setup the _currentTask and timeout
                    source = new TaskCompletionSource<int>();
                    Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
                    if (original != null) {
                        source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
                        return source.Task;
                    }

                    // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
                    if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
                        source.SetCanceled();
                        _currentTask = null;
                        return source.Task;
                    }

                    // Timeout
                     Debug.Assert(timeoutToken == CancellationToken.None, "TimeoutToken is set when GetBytesAsyncReadDataStage is not a continuation");
                    if (timeout > 0) {
                        timeoutCancellationSource = new CancellationTokenSource();
                        timeoutCancellationSource.CancelAfter(timeout);
                        timeoutToken = timeoutCancellationSource.Token;
                    }
                }
                    
                Func<Task, Task<int>> moreFunc = null;
                moreFunc = (_ => {
                    PrepareForAsyncContinuation();

                    if (cancellationToken.IsCancellationRequested) {
                        // User requested cancellation
                        return ADP.CreatedTaskWithCancellation<int>();
                    }
                    else if (timeoutToken.IsCancellationRequested) {
                        // Timeout
                        return ADP.CreatedTaskWithException<int>(ADP.ExceptionWithStackTrace(ADP.IO(SQLMessage.Timeout())));
                    }
                    else {
                        // Prepare for stateObj timeout
                        SetTimeout(_defaultTimeoutMilliseconds);

                        int bytesReadThisIteration;
                        bool result = TryGetBytesInternalSequential(i, buffer, index + totalBytesRead, length - totalBytesRead, out bytesReadThisIteration);
                        totalBytesRead += bytesReadThisIteration;
                        Debug.Assert(totalBytesRead <= length, "Read more bytes than required");

                        if (result) {
                            return Task.FromResult<int>(totalBytesRead);
                        }
                        else {
                            return ContinueRetryable(moreFunc);
                        }
                    }
                });

                Task<int> retryTask = ContinueRetryable(moreFunc);
                if (isContinuation) {
                    // Let the caller handle cleanup\completing
                    return retryTask;
                }
                else {
                    // setup for cleanup\completing
                    retryTask.ContinueWith((t) => CompleteRetryable(t, source, timeoutCancellationSource), TaskScheduler.Default);
                    return source.Task;
                }
            }

            if (!isContinuation) {
                // If this is the first async op, we need to cleanup
                CleanupAfterAsyncInvocation();
            }
            // Completed synchronously, return null
            return null;
        }

        public override Task<bool> ReadAsync(CancellationToken cancellationToken) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlDataReader.ReadAsync|API> %d#", ObjectID);

            try {
                if (IsClosed) {
                    return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("ReadAsync")));
                }

                // If user's token is canceled, return a canceled task
                if (cancellationToken.IsCancellationRequested) {
                    return ADP.CreatedTaskWithCancellation<bool>();
                }

                // Check for existing async
                if (_currentTask != null) {
                    return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
                }
                
                // These variables will be captured in moreFunc so that we can skip searching for a row token once one has been read
                bool rowTokenRead = false;
                bool more = false;

                // Shortcut, do we have enough data to immediately do the ReadAsync?
                try {
                    // First, check if we can finish reading the current row
                    // NOTE: If we are in SingleRow mode and we've read that single row (i.e. _haltRead == true), then skip the shortcut
                    if ((!_haltRead) && ((!_sharedState._dataReady) || (WillHaveEnoughData(_metaData.Length - 1)))) {

#if DEBUG
                        try {
                            _stateObj._shouldHaveEnoughData = true;
#endif
                            if (_sharedState._dataReady) {
                                // Clean off current row
                                CleanPartialReadReliable();
                            }

                            // If there a ROW token ready (as well as any metadata for the row)
                            if (_stateObj.IsRowTokenReady()) {
                                // Read the ROW token
                                bool result = TryReadInternal(true, out more);
                                Debug.Assert(result, "Should not have run out of data");

                                rowTokenRead = true;
                                if (more) {
                                    // Sequential mode, nothing left to do
                                    if (IsCommandBehavior(CommandBehavior.SequentialAccess)) {
                                        return ADP.TrueTask;
                                    }
                                    // For non-sequential, check if we can read the row data now
                                    else if (WillHaveEnoughData(_metaData.Length - 1)) {
                                        // Read row data
                                        result = TryReadColumn(_metaData.Length - 1, setTimeout: true);
                                        Debug.Assert(result, "Should not have run out of data");
                                        return ADP.TrueTask;
                                    }
                                }
                                else {
                                    // No data left, return
                                    return ADP.FalseTask;
                                }
                            }
#if DEBUG
                        }
                        finally {
                            _stateObj._shouldHaveEnoughData = false;
                        }
#endif
                    }
                }
                catch (Exception ex) {
                    if (!ADP.IsCatchableExceptionType(ex)) {
                        throw;
                    }
                    return ADP.CreatedTaskWithException<bool>(ex);
                }

                TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
                Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
                if (original != null) {
                    source.SetException(ADP.ExceptionWithStackTrace(SQL.PendingBeginXXXExists()));
                    return source.Task;
                }

                // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
                if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
                    source.SetCanceled();
                    _currentTask = null;
                    return source.Task;
                }

                IDisposable registration = null;
                if (cancellationToken.CanBeCanceled) {
                    registration = cancellationToken.Register(_command.CancelIgnoreFailure);
                }

                PrepareAsyncInvocation(useSnapshot: true);

                Func<Task, Task<bool>> moreFunc = null;
                moreFunc = (t) => {
                    if (t != null) {
                        Bid.Trace("<sc.SqlDataReader.ReadAsync> attempt retry %d#\n", ObjectID);
                        PrepareForAsyncContinuation();
                    }

                    if (rowTokenRead || TryReadInternal(true, out more)) {

                        // If there are no more rows, or this is Sequential Access, then we are done
                        if (!more || (_commandBehavior & CommandBehavior.SequentialAccess) == CommandBehavior.SequentialAccess) {
                            // completed 
                            return more ? ADP.TrueTask : ADP.FalseTask;
                        }
                        else {
                            // First time reading the row token - update the snapshot
                            if (!rowTokenRead) {
                                rowTokenRead = true;
                                _snapshot = null;
                                PrepareAsyncInvocation(useSnapshot: true);
                            }

                            // if non-sequentialaccess then read entire row before returning
                            if (TryReadColumn(_metaData.Length - 1, true)) {
                                // completed 
                                return ADP.TrueTask;
                            }
                        }
                    }

                    return ContinueRetryable(moreFunc);
                };

                return InvokeRetryable(moreFunc, source, registration);
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }

        override public Task<bool> IsDBNullAsync(int i, CancellationToken cancellationToken) {

            try {
                CheckHeaderIsReady(columnIndex: i, methodName: "IsDBNullAsync");
            }
            catch (Exception ex) {
                if (!ADP.IsCatchableExceptionType(ex)) {
                    throw;
                }
                return ADP.CreatedTaskWithException<bool>(ex);
            }

            // Shortcut - if there are no issues and the data is already read, then just return the value
            if ((_sharedState._nextColumnHeaderToRead > i) && (!cancellationToken.IsCancellationRequested) && (_currentTask == null)) {
                var data = _data;
                if (data != null) {
                    return data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
                }
                else {
                    // Reader was closed between the CheckHeaderIsReady and accessing _data - throw closed exception
                    return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("IsDBNullAsync")));
                }
            }
            else {
                // Throw if there is any current task
                if (_currentTask != null) {
                    return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
                }
                
                // If user's token is canceled, return a canceled task
                if (cancellationToken.IsCancellationRequested) {
                    return ADP.CreatedTaskWithCancellation<bool>();
                }
                
                // Shortcut - if we have enough data, then run [....]
                try {
                    if (WillHaveEnoughData(i, headerOnly: true)) {
#if DEBUG
                    try {
                        _stateObj._shouldHaveEnoughData = true;
#endif
                    ReadColumnHeader(i);
                    return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
#if DEBUG
                    }
                    finally {
                        _stateObj._shouldHaveEnoughData = false;
                    }
#endif
                    }
                }
                catch (Exception ex) {
                    if (!ADP.IsCatchableExceptionType(ex)) {
                        throw;
                    }
                    return ADP.CreatedTaskWithException<bool>(ex);
                }
                
                // Setup and check for pending task
                TaskCompletionSource<bool> source = new TaskCompletionSource<bool>();
                Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
                if (original != null) {
                    source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
                    return source.Task;
                }

                // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
                if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
                    source.SetCanceled();
                    _currentTask = null;
                    return source.Task;
                }

                // Setup cancellations
                IDisposable registration = null;
                if (cancellationToken.CanBeCanceled) {
                    registration = cancellationToken.Register(_command.CancelIgnoreFailure);
                }                

                // Setup async
                PrepareAsyncInvocation(useSnapshot: true);

                // Setup the retryable function
                Func<Task, Task<bool>> moreFunc = null;
                moreFunc = (t) => {
                    if (t != null) {
                        PrepareForAsyncContinuation();
                    }

                    if (TryReadColumnHeader(i)) {
                        return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask;
                    }
                    else {
                        return ContinueRetryable(moreFunc);
                    }
                };

                // Go!
                return InvokeRetryable(moreFunc, source, registration);
            }
        }

        override public Task<T> GetFieldValueAsync<T>(int i, CancellationToken cancellationToken) {

            try {
                CheckDataIsReady(columnIndex: i, methodName: "GetFieldValueAsync");

                // Shortcut - if there are no issues and the data is already read, then just return the value
                if ((!IsCommandBehavior(CommandBehavior.SequentialAccess)) && (_sharedState._nextColumnDataToRead > i) && (!cancellationToken.IsCancellationRequested) && (_currentTask == null)) {
                    var data = _data;
                    var metaData =_metaData;
                    if ((data != null) && (metaData != null)) {
                        return Task.FromResult<T>(GetFieldValueFromSqlBufferInternal<T>(data[i], metaData[i]));
                    }
                    else {
                        // Reader was closed between the CheckDataIsReady and accessing _data\_metaData - throw closed exception
                        return ADP.CreatedTaskWithException<T>(ADP.ExceptionWithStackTrace(ADP.DataReaderClosed("GetFieldValueAsync")));
                    }
                }
            } catch (Exception ex) {
                if (!ADP.IsCatchableExceptionType(ex)) {
                    throw;
                }
                return ADP.CreatedTaskWithException<T>(ex);
            }

            // Throw if there is any current task
            if (_currentTask != null) {
                return ADP.CreatedTaskWithException<T>(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
            }

            // If user's token is canceled, return a canceled task
            if (cancellationToken.IsCancellationRequested) {
                return ADP.CreatedTaskWithCancellation<T>();
            }

            // Shortcut - if we have enough data, then run [....]
            try {
                if (WillHaveEnoughData(i)) {
#if DEBUG
                    try {
                        _stateObj._shouldHaveEnoughData = true;
#endif
                    return Task.FromResult(GetFieldValueInternal<T>(i));
#if DEBUG
                    }
                    finally {
                        _stateObj._shouldHaveEnoughData = false;
                    }
#endif
                }
            }
            catch (Exception ex) {
                if (!ADP.IsCatchableExceptionType(ex)) {
                    throw;
                }
                return ADP.CreatedTaskWithException<T>(ex);
            }

            // Setup and check for pending task
            TaskCompletionSource<T> source = new TaskCompletionSource<T>();            
            Task original = Interlocked.CompareExchange(ref _currentTask, source.Task, null);
            if (original != null) {
                source.SetException(ADP.ExceptionWithStackTrace(ADP.AsyncOperationPending()));
                return source.Task;
            }

            // Check if cancellation due to close is requested (this needs to be done after setting _currentTask)
            if (_cancelAsyncOnCloseToken.IsCancellationRequested) {
                source.SetCanceled();
                _currentTask = null;
                return source.Task;
            }

            // Setup cancellations
            IDisposable registration = null;
            if (cancellationToken.CanBeCanceled) {
                registration = cancellationToken.Register(_command.CancelIgnoreFailure);
            }

            // Setup async
            PrepareAsyncInvocation(useSnapshot: true);

            // Setup the retryable function
            Func<Task, Task<T>> moreFunc = null;
            moreFunc = (t) => {
                if (t != null) {
                    PrepareForAsyncContinuation();
                }

                if (TryReadColumn(i, setTimeout: false)) {
                    return Task.FromResult<T>(GetFieldValueFromSqlBufferInternal<T>(_data[i], _metaData[i]));
                }
                else {
                    return ContinueRetryable(moreFunc);
                }
            };

            // Go!
            return InvokeRetryable(moreFunc, source, registration);
        }

#if DEBUG

        internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) {
            var stateObj = _stateObj;
            if (stateObj != null) {
                stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait);
            }
        }

        internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) {
            var stateObj = _stateObj;
            if (stateObj != null) {
                stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait);
            }
        }

#endif

        class Snapshot {
            public bool _dataReady;
            public bool _haltRead;
            public bool _metaDataConsumed;
            public bool _browseModeInfoConsumed;
            public bool _hasRows;
            public ALTROWSTATUS _altRowStatus;
            public int _nextColumnDataToRead;
            public int _nextColumnHeaderToRead;
            public long _columnDataBytesRead;
            public long _columnDataBytesRemaining;

            public _SqlMetaDataSet _metadata;
            public _SqlMetaDataSetCollection _altMetaDataSetCollection;
            public MultiPartTableName[] _tableNames;

            public SqlSequentialStream _currentStream;
            public SqlSequentialTextReader _currentTextReader;
        }

        private Task<T> ContinueRetryable<T>(Func<Task, Task<T>> moreFunc) {
            // _networkPacketTaskSource could be null if the connection was closed
            // while an async invocation was outstanding.
            TaskCompletionSource<object> completionSource = _stateObj._networkPacketTaskSource;
            if (_cancelAsyncOnCloseToken.IsCancellationRequested || completionSource == null) {
                // Cancellation requested due to datareader being closed
                TaskCompletionSource<T> source = new TaskCompletionSource<T>();
                source.TrySetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
                return source.Task;
            }
            else {
                return completionSource.Task.ContinueWith((retryTask) => {
                    if (retryTask.IsFaulted) {
                        // Somehow the network task faulted - return the exception
                        TaskCompletionSource<T> exceptionSource = new TaskCompletionSource<T>();
                        exceptionSource.TrySetException(retryTask.Exception.InnerException);
                        return exceptionSource.Task;
                    }
                    else if (!_cancelAsyncOnCloseToken.IsCancellationRequested) {
                        TdsParserStateObject stateObj = _stateObj;
                        if (stateObj != null) {
                            // protect continuations against concurrent
                            // close and cancel
                            lock (stateObj) {
                                if (_stateObj != null) { // reader not closed while we waited for the lock
                                    if (retryTask.IsCanceled) {
                                        if (_parser != null) {
                                            _parser.State = TdsParserState.Broken; // We failed to respond to attention, we have to quit!
                                            _parser.Connection.BreakConnection();
                                            _parser.ThrowExceptionAndWarning(_stateObj);
                                        }
                                    }
                                    else {
                                        if (!IsClosed) {
                                            try {
                                                return moreFunc(retryTask);
                                            }
                                            catch (Exception) {
                                                CleanupAfterAsyncInvocation();
                                                throw;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // if stateObj is null, or we closed the connection or the connection was already closed,
                    // then mark this operation as cancelled.
                    TaskCompletionSource<T> source = new TaskCompletionSource<T>();
                    source.SetException(ADP.ExceptionWithStackTrace(ADP.ClosedConnectionError()));
                    return source.Task;
                }, TaskScheduler.Default).Unwrap();
            }
        }

        private Task<T> InvokeRetryable<T>(Func<Task, Task<T>> moreFunc, TaskCompletionSource<T> source, IDisposable objectToDispose = null) {
            try {
                Task<T> task;
                try {
                    task = moreFunc(null);
                }
                catch (Exception ex) {
                    task = ADP.CreatedTaskWithException<T>(ex);
                }

                if (task.IsCompleted) {
                    // If we've completed [....], then don't bother handling the TaskCompletionSource - we'll just return the completed task
                    CompleteRetryable(task, source, objectToDispose);
                    return task;
                }
                else {
                    task.ContinueWith((t) => CompleteRetryable(t, source, objectToDispose), TaskScheduler.Default);
                }
            }
            catch (AggregateException e) {
                source.TrySetException(e.InnerException);
            }
            catch (Exception e) {
                source.TrySetException(e);
            }

            // Fall through for exceptions\completing async
            return source.Task;
        }
        
        private void CompleteRetryable<T>(Task<T> task, TaskCompletionSource<T> source, IDisposable objectToDispose) {
            if (objectToDispose != null) {
                objectToDispose.Dispose();
            }

            // If something has forced us to switch to SyncOverAsync mode while in an async task then we need to guarantee that we do the cleanup
            // This avoids us replaying non-replayable data (such as DONE or ENV_CHANGE tokens)
            var stateObj = _stateObj;
            bool ignoreCloseToken = ((stateObj != null) && (stateObj._syncOverAsync));
            CleanupAfterAsyncInvocation(ignoreCloseToken);

            Task current = Interlocked.CompareExchange(ref _currentTask, null, source.Task);
            Debug.Assert(current == source.Task, "Should not be able to change the _currentTask while an asynchronous operation is pending");

            if (task.IsFaulted) {
                Exception e = task.Exception.InnerException;
                source.TrySetException(e);
            }
            else if (task.IsCanceled) {
                source.TrySetCanceled();
            }
            else {
                source.TrySetResult(task.Result);
            }
        }

        private void PrepareAsyncInvocation(bool useSnapshot) {
            // if there is already a snapshot, then the previous async command
            // completed with exception or cancellation.  We need to continue
            // with the old snapshot.
            if (useSnapshot) {
                Debug.Assert(!_stateObj._asyncReadWithoutSnapshot, "Can't prepare async invocation with snapshot if doing async without snapshots");

                if (_snapshot == null) {
                    _snapshot = new Snapshot {
                        _dataReady = _sharedState._dataReady,
                        _haltRead = _haltRead,
                        _metaDataConsumed = _metaDataConsumed,
                        _browseModeInfoConsumed = _browseModeInfoConsumed,
                        _hasRows = _hasRows,
                        _altRowStatus = _altRowStatus,
                        _nextColumnDataToRead = _sharedState._nextColumnDataToRead,
                        _nextColumnHeaderToRead = _sharedState._nextColumnHeaderToRead,
                        _columnDataBytesRead = _columnDataBytesRead,
                        _columnDataBytesRemaining = _sharedState._columnDataBytesRemaining,

                        // _metadata and _altaMetaDataSetCollection must be Cloned
                        // before they are updated
                        _metadata = _metaData,
                        _altMetaDataSetCollection = _altMetaDataSetCollection,
                        _tableNames = _tableNames,
                    
                        _currentStream = _currentStream,
                        _currentTextReader = _currentTextReader,
                    };

                    _stateObj.SetSnapshot();
                }
            }
            else {
                Debug.Assert(_snapshot == null, "Can prepare async invocation without snapshot if there is currently a snapshot");
                _stateObj._asyncReadWithoutSnapshot = true;
            }

            _stateObj._syncOverAsync = false;
            _stateObj._executionContext = ExecutionContext.Capture();
        }

        private void CleanupAfterAsyncInvocation(bool ignoreCloseToken = false) {
            var stateObj = _stateObj;
            if (stateObj != null) {
                // If close requested cancellation and we have a snapshot, then it will deal with cleaning up
                // NOTE: There are some cases where we wish to ignore the close token, such as when we've read some data that is not replayable (e.g. DONE or ENV_CHANGE token)
                if ((ignoreCloseToken) || (!_cancelAsyncOnCloseToken.IsCancellationRequested) || (stateObj._asyncReadWithoutSnapshot)) {
                    // Prevent race condition between the DataReader being closed (e.g. when another MARS thread has an error)
                    lock(stateObj) {
                        if (_stateObj != null) { // reader not closed while we waited for the lock
                            CleanupAfterAsyncInvocationInternal(_stateObj);
                            Debug.Assert(_snapshot == null && !_stateObj._asyncReadWithoutSnapshot, "Snapshot not null or async without snapshot still enabled after cleaning async state");
                        }
                    }
                }
            }
        }

        // This function is called directly if calling function already closed the reader, so _stateObj is null,
        // in other cases parameterless version should be called 
        private void CleanupAfterAsyncInvocationInternal(TdsParserStateObject stateObj, bool resetNetworkPacketTaskSource = true)
        {
            if (resetNetworkPacketTaskSource) {
                stateObj._networkPacketTaskSource = null;
            }
            stateObj.ResetSnapshot();
            stateObj._syncOverAsync = true;
            stateObj._executionContext = null;
            stateObj._asyncReadWithoutSnapshot = false;
#if DEBUG
            stateObj._permitReplayStackTraceToDiffer = false;
#endif

            // We are setting this to null inside the if-statement because stateObj==null means that the reader hasn't been initialized or has been closed (either way _snapshot should already be null)
            _snapshot = null;
        }

        private void PrepareForAsyncContinuation() {
            Debug.Assert(((_snapshot != null) || (_stateObj._asyncReadWithoutSnapshot)), "Can not prepare for an async continuation if no async if setup");
            if (_snapshot != null) {
                _sharedState._dataReady = _snapshot._dataReady;
                _haltRead = _snapshot._haltRead;
                _metaDataConsumed = _snapshot._metaDataConsumed;
                _browseModeInfoConsumed = _snapshot._browseModeInfoConsumed;
                _hasRows = _snapshot._hasRows;
                _altRowStatus = _snapshot._altRowStatus;
                _sharedState._nextColumnDataToRead = _snapshot._nextColumnDataToRead;
                _sharedState._nextColumnHeaderToRead = _snapshot._nextColumnHeaderToRead;
                _columnDataBytesRead = _snapshot._columnDataBytesRead;
                _sharedState._columnDataBytesRemaining = _snapshot._columnDataBytesRemaining;

                _metaData = _snapshot._metadata;
                _altMetaDataSetCollection = _snapshot._altMetaDataSetCollection;
                _tableNames = _snapshot._tableNames;

                _currentStream = _snapshot._currentStream;
                _currentTextReader = _snapshot._currentTextReader;

                _stateObj.PrepareReplaySnapshot();
            }

            _stateObj._executionContext = ExecutionContext.Capture();
        }

        private void SwitchToAsyncWithoutSnapshot() {
            Debug.Assert(_snapshot != null, "Should currently have a snapshot");
            Debug.Assert(_stateObj != null && !_stateObj._asyncReadWithoutSnapshot, "Already in async without snapshot");

            _snapshot = null;
            _stateObj.ResetSnapshot();
            _stateObj._asyncReadWithoutSnapshot = true;
        }

    }// SqlDataReader
}// namespace