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

SqlConnection.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: 0ce4dbb08763054308721ed6139b428134b0cb54 (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
//------------------------------------------------------------------------------
// <copyright file="SqlConnection.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Data.DataSetExtensions, PublicKey="+AssemblyRef.EcmaPublicKeyFull)] // DevDiv Bugs 92166

namespace System.Data.SqlClient
{
    using System;
    using System.Collections;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Configuration.Assemblies;
    using System.ComponentModel;
    using System.Data;
    using System.Data.Common;
    using System.Data.ProviderBase;
    using System.Data.Sql;
    using System.Data.SqlTypes;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.InteropServices;
    using System.Runtime.Remoting;
    using System.Runtime.Serialization.Formatters;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Security;
    using System.Security.Permissions;
    using System.Reflection;
    using System.Runtime.Versioning;
    
    using Microsoft.SqlServer.Server;
    using System.Security.Principal;
    using System.Diagnostics.CodeAnalysis;

    [DefaultEvent("InfoMessage")]
    public sealed partial class SqlConnection: DbConnection, ICloneable {

        static private readonly object EventInfoMessage = new object();

        // System column encryption key store providers are added by default
        static private readonly Dictionary<string, SqlColumnEncryptionKeyStoreProvider> _SystemColumnEncryptionKeyStoreProviders
            = new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>(capacity: 1, comparer: StringComparer.OrdinalIgnoreCase)
        {
            {SqlColumnEncryptionCertificateStoreProvider.ProviderName, new SqlColumnEncryptionCertificateStoreProvider()},
            {SqlColumnEncryptionCngProvider.ProviderName, new SqlColumnEncryptionCngProvider()},
            {SqlColumnEncryptionCspProvider.ProviderName, new SqlColumnEncryptionCspProvider()}
        };

        /// <summary>
        /// Custom provider list should be provided by the user. We shallow copy the user supplied dictionary into a ReadOnlyDictionary.
        /// Custom provider list can only supplied once per application.
        /// </summary>
        static private ReadOnlyDictionary<string, SqlColumnEncryptionKeyStoreProvider> _CustomColumnEncryptionKeyStoreProviders;

        // Lock to control setting of _CustomColumnEncryptionKeyStoreProviders
        static private readonly Object _CustomColumnEncryptionKeyProvidersLock = new Object();

        /// <summary>
        /// Dictionary object holding trusted key paths for various SQL Servers.
        /// Key to the dictionary is a SQL Server Name
        /// IList contains a list of trusted key paths.
        /// </summary>
        static private readonly ConcurrentDictionary<string, IList<string>> _ColumnEncryptionTrustedMasterKeyPaths
            = new ConcurrentDictionary<string, IList<string>>(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/,
                                                            capacity: 1,
                                                            comparer: StringComparer.OrdinalIgnoreCase);

        [
        DefaultValue(null),
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.TCE_SqlConnection_TrustedColumnMasterKeyPaths),
        ]
        static public IDictionary<string, IList<string>> ColumnEncryptionTrustedMasterKeyPaths
        {
            get
            {
                return _ColumnEncryptionTrustedMasterKeyPaths;
            }
        }
        
        /// <summary>
        /// This function should only be called once in an app. This does shallow copying of the dictionary so that 
        /// the app cannot alter the custom provider list once it has been set.
        /// 
        /// Example:
        /// 
        /// Dictionary<string, SqlColumnEncryptionKeyStoreProvider> customKeyStoreProviders = new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>();
        /// MySqlClientHSMProvider myProvider = new MySqlClientHSMProvider();
        /// customKeyStoreProviders.Add(@"HSM Provider", myProvider);
        /// SqlConnection.RegisterColumnEncryptionKeyStoreProviders(customKeyStoreProviders);
        /// </summary>
        /// <param name="customProviders">Custom column encryption key provider dictionary</param>
        static public void RegisterColumnEncryptionKeyStoreProviders(IDictionary<string, SqlColumnEncryptionKeyStoreProvider> customProviders)
        {

            // Return when the provided dictionary is null.
            if (customProviders == null)
            {
                throw SQL.NullCustomKeyStoreProviderDictionary();
            }

            // Validate that custom provider list doesn't contain any of system provider list
            foreach (string key in customProviders.Keys)
            {
                // Validate the provider name
                //
                // Check for null or empty
                if (string.IsNullOrWhiteSpace(key))
                {
                    throw SQL.EmptyProviderName();
                }

                // Check if the name starts with MSSQL_, since this is reserved namespace for system providers.
                if (key.StartsWith(ADP.ColumnEncryptionSystemProviderNamePrefix, StringComparison.InvariantCultureIgnoreCase)) 
                {
                    throw SQL.InvalidCustomKeyStoreProviderName(key, ADP.ColumnEncryptionSystemProviderNamePrefix);
                }

                // Validate the provider value
                if (customProviders[key] == null)
                {
                    throw SQL.NullProviderValue(key);
                }
            }

            lock (_CustomColumnEncryptionKeyProvidersLock)
            {
                // Provider list can only be set once
                if (_CustomColumnEncryptionKeyStoreProviders != null)
                {
                    throw SQL.CanOnlyCallOnce();
                }

                // Create a temporary dictionary and then add items from the provided dictionary.
                // Dictionary constructor does shallow copying by simply copying the provider name and provider reference pairs
                // in the provided customerProviders dictionary.
                Dictionary<string, SqlColumnEncryptionKeyStoreProvider> customColumnEncryptionKeyStoreProviders =
                    new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>(customProviders, StringComparer.OrdinalIgnoreCase);

                // Set the dictionary to the ReadOnly dictionary.
                _CustomColumnEncryptionKeyStoreProviders = new ReadOnlyDictionary<string, SqlColumnEncryptionKeyStoreProvider>(customColumnEncryptionKeyStoreProviders);
            }
        }

        /// <summary>
        /// This function walks through both system and custom column encryption key store providers and returns an object if found.
        /// </summary>
        /// <param name="providerName">Provider Name to be searched in System Provider diction and Custom provider dictionary.</param>
        /// <param name="columnKeyStoreProvider">If the provider is found, returns the corresponding SqlColumnEncryptionKeyStoreProvider instance.</param>
        /// <returns>true if the provider is found, else returns false</returns>
        static internal bool TryGetColumnEncryptionKeyStoreProvider(string providerName, out SqlColumnEncryptionKeyStoreProvider columnKeyStoreProvider) {
            Debug.Assert(!string.IsNullOrWhiteSpace(providerName), "Provider name is invalid");

            // Initialize the out parameter
            columnKeyStoreProvider = null;

            // Search in the sytem provider list.
            if (_SystemColumnEncryptionKeyStoreProviders.TryGetValue(providerName, out columnKeyStoreProvider))
            {
                return true;
            }

            lock (_CustomColumnEncryptionKeyProvidersLock)
            {
                // If custom provider is not set, then return false
                if (_CustomColumnEncryptionKeyStoreProviders == null)
                {
                    return false;
                }

                // Search in the custom provider list
                return _CustomColumnEncryptionKeyStoreProviders.TryGetValue(providerName, out columnKeyStoreProvider);
            }
        }

        /// <summary>
        /// This function returns a list of system provider dictionary currently supported by this driver.
        /// </summary>
        /// <returns>Combined list of provider names</returns>
        static internal List<string> GetColumnEncryptionSystemKeyStoreProviders() {
            HashSet<string> providerNames = new HashSet<string>(_SystemColumnEncryptionKeyStoreProviders.Keys);
            return providerNames.ToList();
        }

        /// <summary>
        /// This function returns a list of custom provider dictionary currently registered.
        /// </summary>
        /// <returns>Combined list of provider names</returns>
        static internal List<string> GetColumnEncryptionCustomKeyStoreProviders() {
            if(_CustomColumnEncryptionKeyStoreProviders != null)
            {
                HashSet<string> providerNames = new HashSet<string>(_CustomColumnEncryptionKeyStoreProviders.Keys);
                return providerNames.ToList();
            }

            return new List<string>();
        }

        private SqlDebugContext _sdc;   // SQL Debugging support

        private bool    _AsyncCommandInProgress;

        // SQLStatistics support
        internal SqlStatistics _statistics;
        private bool _collectstats;

        private bool _fireInfoMessageEventOnUserErrors; // False by default

        // root task associated with current async invocation
        Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;

        private SqlCredential _credential; // SQL authentication password stored in SecureString
        private string _connectionString;
        private int _connectRetryCount;

        private string _accessToken; // Access Token to be used for token based authententication

        // connection resiliency
        private object _reconnectLock = new object();
        internal Task _currentReconnectionTask;
        private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections
        private Guid _originalConnectionId = Guid.Empty;
        private CancellationTokenSource _reconnectionCancellationSource;
        internal SessionData _recoverySessionData;
        internal WindowsIdentity _lastIdentity;
        internal WindowsIdentity _impersonateIdentity;
        private int _reconnectCount;

        // Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not
        // The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened
        // using SqlConnection.Open() method. 
        internal bool _applyTransientFaultHandling = false;
       
        public SqlConnection(string connectionString) : this(connectionString, null) {
        }

        public SqlConnection(string connectionString, SqlCredential credential) : this() {
            ConnectionString = connectionString;    // setting connection string first so that ConnectionOption is available
            if (credential != null)
            {
                // The following checks are necessary as setting Credential property will call CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential
                //  CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential it will throw InvalidOperationException rather than Arguemtn exception
                //  Need to call setter on Credential property rather than setting _credential directly as pool groups need to be checked
                SqlConnectionString connectionOptions = (SqlConnectionString) ConnectionOptions;
                if (UsesClearUserIdOrPassword(connectionOptions))
                {
                    throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
                }

                if (UsesIntegratedSecurity(connectionOptions))
                {
                    throw ADP.InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity();
                }

                if (UsesContextConnection(connectionOptions))
                {
                    throw ADP.InvalidMixedArgumentOfSecureCredentialAndContextConnection();
                }

                if (UsesActiveDirectoryIntegrated(connectionOptions))
                {
                     throw SQL.SettingCredentialWithIntegratedArgument();
                }

                Credential = credential;
            }
            // else
            //      credential == null:  we should not set "Credential" as this will do additional validation check and
            //      checking pool groups which is not necessary. All necessary operation is already done by calling "ConnectionString = connectionString"
            CacheConnectionStringProperties();
        }

        private SqlConnection(SqlConnection connection) { // Clone
            GC.SuppressFinalize(this);
            CopyFrom(connection);
            _connectionString = connection._connectionString;
            if (connection._credential != null)
            {
                SecureString password = connection._credential.Password.Copy();
                password.MakeReadOnly();
                _credential = new SqlCredential(connection._credential.UserId, password);
            }
            _accessToken = connection._accessToken;
            CacheConnectionStringProperties();
        }

        // This method will be called once connection string is set or changed. 
        private void CacheConnectionStringProperties() {
            SqlConnectionString connString = ConnectionOptions as SqlConnectionString;
            if (connString != null) {
                _connectRetryCount = connString.ConnectRetryCount;
            }
        }

        //
        // PUBLIC PROPERTIES
        //

        // used to start/stop collection of statistics data and do verify the current state
        //
        // devnote: start/stop should not performed using a property since it requires execution of code
        //
        // start statistics
        //  set the internal flag (_statisticsEnabled) to true.
        //  Create a new SqlStatistics object if not already there.
        //  connect the parser to the object.
        //  if there is no parser at this time we need to connect it after creation.
        //

        [
        DefaultValue(false),
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.SqlConnection_StatisticsEnabled),
        ]
        public bool StatisticsEnabled {
            get {
                return (_collectstats);
            }
            set {
                if (IsContextConnection) {
                    if (value) {
                        throw SQL.NotAvailableOnContextConnection();
                    }
                }
                else {
                    if (value) {
                        // start
                        if (ConnectionState.Open == State) {
                            if (null == _statistics) {
                                _statistics = new SqlStatistics();
                                ADP.TimerCurrent(out _statistics._openTimestamp);
                            }
                            // set statistics on the parser
                            // update timestamp;
                            Debug.Assert(Parser != null, "Where's the parser?");
                            Parser.Statistics = _statistics;
                        }
                    }
                    else {
                        // stop
                        if (null != _statistics) {
                            if (ConnectionState.Open == State) {
                                // remove statistics from parser
                                // update timestamp;
                                TdsParser parser = Parser;
                                Debug.Assert(parser != null, "Where's the parser?");
                                parser.Statistics = null;
                                ADP.TimerCurrent(out _statistics._closeTimestamp);
                            }
                        }
                    }
                    this._collectstats = value;
                }
            }
        }

        internal bool AsyncCommandInProgress  {
            get {
                return (_AsyncCommandInProgress);
            }
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            set {
                _AsyncCommandInProgress = value;
            }
        }

        internal bool IsContextConnection {
            get {
                SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
                return UsesContextConnection(opt);
            }
        }

        /// <summary>
        /// Is this connection using column encryption ?
        /// </summary>
        internal bool IsColumnEncryptionSettingEnabled {
            get {
                SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
                return opt != null ? opt.ColumnEncryptionSetting == SqlConnectionColumnEncryptionSetting.Enabled : false;
            }
        }

        // Is this connection is a Context Connection?
        private bool UsesContextConnection(SqlConnectionString opt)
        {
            return opt != null ? opt.ContextConnection : false;
        }

        private bool UsesActiveDirectoryIntegrated(SqlConnectionString opt) 
        {
             return opt != null ? opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated : false;
        }

        private bool UsesAuthentication(SqlConnectionString opt) {
             return opt != null ? opt.Authentication != SqlAuthenticationMethod.NotSpecified : false;
        }
        
        // Does this connection uses Integrated Security?
        private bool UsesIntegratedSecurity(SqlConnectionString opt) {
            return opt != null ? opt.IntegratedSecurity : false;
        }

        // Does this connection uses old style of clear userID or Password in connection string?
        private bool UsesClearUserIdOrPassword(SqlConnectionString opt) {
            bool result = false;
            if (null != opt) {
                result = (!ADP.IsEmpty(opt.UserID) || !ADP.IsEmpty(opt.Password));
            }
            return result;
        }

        internal SqlConnectionString.TransactionBindingEnum TransactionBinding {
            get {
                return ((SqlConnectionString)ConnectionOptions).TransactionBinding;
            }
        }

        internal SqlConnectionString.TypeSystem TypeSystem {
            get {
                return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
            }
        }

        internal Version TypeSystemAssemblyVersion {
            get {
                return ((SqlConnectionString)ConnectionOptions).TypeSystemAssemblyVersion;
            }
        }        

        internal int ConnectRetryInterval {
            get {
                return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
            }
        }

        override protected DbProviderFactory DbProviderFactory {
            get {
                return SqlClientFactory.Instance;
            }
        }

        // AccessToken: To be used for token based authentication
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.SqlConnection_AccessToken),
        ]
        public string AccessToken {
            get {
                string result = _accessToken;
                // When a connection is connecting or is ever opened, make AccessToken available only if "Persist Security Info" is set to true
                // otherwise, return null
                SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
                if (InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo) {
                    result = null;
                }

                return result;
            }
            set {
                // If a connection is connecting or is ever opened, AccessToken cannot be set
                if (!InnerConnection.AllowSetConnectionString) {
                    throw ADP.OpenConnectionPropertySet("AccessToken", InnerConnection.State);
                }
                
                if (value != null) {
                    // Check if the usage of AccessToken has any conflict with the keys used in connection string and credential
                    CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken((SqlConnectionString)ConnectionOptions);
                }
                
                _accessToken = value;
                // Need to call ConnectionString_Set to do proper pool group check
                ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, credential: _credential, accessToken: _accessToken));
            }
        }

        [
        DefaultValue(""),
#pragma warning disable 618 // ignore obsolete warning about RecommendedAsConfigurable to use SettingsBindableAttribute
        RecommendedAsConfigurable(true),
#pragma warning restore 618
        SettingsBindableAttribute(true),
        RefreshProperties(RefreshProperties.All),
        ResCategoryAttribute(Res.DataCategory_Data),
        Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
        ResDescriptionAttribute(Res.SqlConnection_ConnectionString),
        ]
        override public string ConnectionString {
            get {
                return ConnectionString_Get();
            }
            set {
                if(_credential != null || _accessToken != null) {
                    SqlConnectionString connectionOptions = new SqlConnectionString(value);
                    if(_credential != null) {
                        // Check for Credential being used with Authentication=ActiveDirectoryIntegrated. Since a different error string is used
                        // for this case in ConnectionString setter vs in Credential setter, check for this error case before calling
                        // CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential, which is common to both setters.
                        if(UsesActiveDirectoryIntegrated(connectionOptions)) {
                            throw SQL.SettingIntegratedWithCredential();
                        }

                        CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(connectionOptions);
                    }
                    else if(_accessToken != null) {
                        CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(connectionOptions);
                    }
                }
                ConnectionString_Set(new SqlConnectionPoolKey(value, _credential, _accessToken));
                _connectionString = value;  // Change _connectionString value only after value is validated
                CacheConnectionStringProperties();
            }
        }

        [
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.SqlConnection_ConnectionTimeout),
        ]
        override public int ConnectionTimeout {
            get {
                SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
                return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
            }
        }

        [
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.SqlConnection_Database),
        ]
        override public string Database {
            // if the connection is open, we need to ask the inner connection what it's
            // current catalog is because it may have gotten changed, otherwise we can
            // just return what the connection string had.
            get {
                SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
                string result;

                if (null != innerConnection) {
                    result = innerConnection.CurrentDatabase;
                }
                else {
                    SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
                    result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog);
                }
                return result;
            }
        }

        [
        Browsable(true),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.SqlConnection_DataSource),
        ]
        override public string DataSource {
            get {
                SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
                string result;

                if (null != innerConnection) {
                    result = innerConnection.CurrentDataSource;
                }
                else {
                    SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
                    result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source);
                }
                return result;
            }
        }

        [
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.SqlConnection_PacketSize),
        ]
        public int PacketSize {
            // if the connection is open, we need to ask the inner connection what it's
            // current packet size is because it may have gotten changed, otherwise we
            // can just return what the connection string had.
            get {
                if (IsContextConnection) {
                    throw SQL.NotAvailableOnContextConnection();
                }

                SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
                int result;

                if (null != innerConnection) {
                    result = innerConnection.PacketSize;
                }
                else {
                    SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
                    result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size);
                }
                return result;
            }
        }

        [
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.SqlConnection_ClientConnectionId),
        ]
        public Guid ClientConnectionId {
            get {

                SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);

                if (null != innerConnection) {
                    return innerConnection.ClientConnectionId;
                }
                else {
                    Task reconnectTask = _currentReconnectionTask;
                    if (reconnectTask != null && !reconnectTask.IsCompleted) {
                        return _originalConnectionId;
                    }
                    return Guid.Empty;
                }
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.SqlConnection_ServerVersion),
        ]
        override public string ServerVersion {
            get {
                return GetOpenConnection().ServerVersion;
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.DbConnection_State),
        ]
        override public ConnectionState State {
            get {
                Task reconnectTask=_currentReconnectionTask;
                if (reconnectTask != null && !reconnectTask.IsCompleted) {
                    return ConnectionState.Open;
                }
                return InnerConnection.State;
            }
        }


        internal SqlStatistics Statistics {
            get {
                return _statistics;
            }
        }

        [
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResCategoryAttribute(Res.DataCategory_Data),
        ResDescriptionAttribute(Res.SqlConnection_WorkstationId),
        ]
        public string WorkstationId {
            get {
                if (IsContextConnection) {
                    throw SQL.NotAvailableOnContextConnection();
                }

                // If not supplied by the user, the default value is the MachineName
                // Note: In Longhorn you'll be able to rename a machine without
                // rebooting.  Therefore, don't cache this machine name.
                SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
                string result = ((null != constr) ? constr.WorkstationId : null);
                if (null == result) {
                    // getting machine name requires Environment.Permission
                    // user must have that permission in order to retrieve this
                    result = Environment.MachineName;
                }
                return result;
            }
        }

        // SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.SqlConnection_Credential),
        ]
        public SqlCredential Credential
        {
            get
            {
                SqlCredential result = _credential;

                // When a connection is connecting or is ever opened, make credential available only if "Persist Security Info" is set to true
                //  otherwise, return null
                SqlConnectionString connectionOptions = (SqlConnectionString) UserConnectionOptions;
                if (InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo)
                {
                    result = null;
                }

                return result;
            }

            set
            {
                // If a connection is connecting or is ever opened, user id/password cannot be set
                if (!InnerConnection.AllowSetConnectionString)
                {
                    throw ADP.OpenConnectionPropertySet("Credential", InnerConnection.State);
                }

                // check if the usage of credential has any conflict with the keys used in connection string
                if (value != null)
                {
                    // Check for Credential being used with Authentication=ActiveDirectoryIntegrated. Since a different error string is used
                    // for this case in ConnectionString setter vs in Credential setter, check for this error case before calling
                    // CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential, which is common to both setters.
                    if (UsesActiveDirectoryIntegrated((SqlConnectionString) ConnectionOptions)) {
                        throw SQL.SettingCredentialWithIntegratedInvalid();
                    }

                    CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential((SqlConnectionString) ConnectionOptions);
                    if(_accessToken != null) {
                        throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
                    }

                }
                
                _credential = value;

                // Need to call ConnectionString_Set to do proper pool group check
                ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, accessToken: _accessToken));
            }
        }

        // CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential: check if the usage of credential has any conflict
        //  with the keys used in connection string
        //  If there is any conflict, it throws InvalidOperationException
        //  This is to be used setter of ConnectionString and Credential properties
        private void CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(SqlConnectionString connectionOptions)
        {
            if (UsesClearUserIdOrPassword(connectionOptions))
            {
                throw ADP.InvalidMixedUsageOfSecureAndClearCredential();
            }

            if (UsesIntegratedSecurity(connectionOptions))
            {
                throw ADP.InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity();
            }

            if (UsesContextConnection(connectionOptions))
            {
                throw ADP.InvalidMixedArgumentOfSecureCredentialAndContextConnection();
            }
        }

        // CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken: check if the usage of AccessToken has any conflict
        //  with the keys used in connection string and credential
        //  If there is any conflict, it throws InvalidOperationException
        //  This is to be used setter of ConnectionString and AccessToken properties
        private void CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(SqlConnectionString connectionOptions) {
            if (UsesClearUserIdOrPassword(connectionOptions)) {
                throw ADP.InvalidMixedUsageOfAccessTokenAndUserIDPassword();
            }

            if (UsesIntegratedSecurity(connectionOptions)) {
                throw ADP.InvalidMixedUsageOfAccessTokenAndIntegratedSecurity();
            }

            if (UsesContextConnection(connectionOptions)) {
                throw ADP.InvalidMixedUsageOfAccessTokenAndContextConnection();
            }

            if (UsesAuthentication(connectionOptions)) {
                throw ADP.InvalidMixedUsageOfAccessTokenAndAuthentication();
            }

            // Check if the usage of AccessToken has the conflict with credential
            if (_credential != null) {
                throw ADP.InvalidMixedUsageOfAccessTokenAndCredential();
            }
        }

        //
        // PUBLIC EVENTS
        //

        [
        ResCategoryAttribute(Res.DataCategory_InfoMessage),
        ResDescriptionAttribute(Res.DbConnection_InfoMessage),
        ]
        public event SqlInfoMessageEventHandler InfoMessage {
            add {
                Events.AddHandler(EventInfoMessage, value);
            }
            remove {
                Events.RemoveHandler(EventInfoMessage, value);
            }
        }

        public bool FireInfoMessageEventOnUserErrors {
            get {
                return _fireInfoMessageEventOnUserErrors;
            }
            set {
                _fireInfoMessageEventOnUserErrors = value;
            }
        }

        // Approx. number of times that the internal connection has been reconnected
        internal int ReconnectCount {
            get {
                return _reconnectCount;
            }
        }

        //
        // PUBLIC METHODS
        //

        new public SqlTransaction BeginTransaction() {
            // this is just a delegate. The actual method tracks executiontime
            return BeginTransaction(IsolationLevel.Unspecified, null);
        }

        new public SqlTransaction BeginTransaction(IsolationLevel iso) {
            // this is just a delegate. The actual method tracks executiontime
            return BeginTransaction(iso, null);
        }

        public SqlTransaction BeginTransaction(string transactionName) {
                // Use transaction names only on the outermost pair of nested
                // BEGIN...COMMIT or BEGIN...ROLLBACK statements.  Transaction names
                // are ignored for nested BEGIN's.  The only way to rollback a nested
                // transaction is to have a save point from a SAVE TRANSACTION call.
                return BeginTransaction(IsolationLevel.Unspecified, transactionName);
        }

        // suppress this message - we cannot use SafeHandle here. Also, see notes in the code (VSTFDEVDIV# 560355)
        [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
        override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) {
            IntPtr hscp;

            Bid.ScopeEnter(out hscp, "<prov.SqlConnection.BeginDbTransaction|API> %d#, isolationLevel=%d{ds.IsolationLevel}", ObjectID, (int)isolationLevel);
            try {

                DbTransaction transaction = BeginTransaction(isolationLevel);

                // VSTFDEVDIV# 560355 - InnerConnection doesn't maintain a ref on the outer connection (this) and 
                //   subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction
                //   is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
                //   until the completion of BeginTransaction with KeepAlive
                GC.KeepAlive(this);

                return transaction;
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }

        public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName) {
            WaitForPendingReconnection();
            SqlStatistics statistics = null;
            IntPtr hscp;
            string xactName =  ADP.IsEmpty(transactionName)? "None" : transactionName;
            Bid.ScopeEnter(out hscp, "<sc.SqlConnection.BeginTransaction|API> %d#, iso=%d{ds.IsolationLevel}, transactionName='%ls'\n", ObjectID, (int)iso,
                        xactName);

            try {
                statistics = SqlStatistics.StartTimer(Statistics);

                // NOTE: we used to throw an exception if the transaction name was empty
                // (see MDAC 50292) but that was incorrect because we have a BeginTransaction
                // method that doesn't have a transactionName argument.
                SqlTransaction transaction;
                bool isFirstAttempt = true;
                do {
                    transaction = GetOpenConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice
                    Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt");
                    isFirstAttempt = false;
                } while (transaction.InternalTransaction.ConnectionHasBeenRestored);


                // SQLBU 503873  The GetOpenConnection line above doesn't keep a ref on the outer connection (this),
                //  and it could be collected before the inner connection can hook it to the transaction, resulting in
                //  a transaction with a null connection property.  Use GC.KeepAlive to ensure this doesn't happen.
                GC.KeepAlive(this);

                return transaction;
            }
            finally {
                Bid.ScopeLeave(ref hscp);
                SqlStatistics.StopTimer(statistics);
            }
        }

        override public void ChangeDatabase(string database) {
            SqlStatistics statistics = null;
            RepairInnerConnection();
            Bid.CorrelationTrace("<sc.SqlConnection.ChangeDatabase|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
            TdsParser bestEffortCleanupTarget = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(this);
                    statistics = SqlStatistics.StartTimer(Statistics);
                    InnerConnection.ChangeDatabase(database);
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                Abort(e);
                throw;
            }
            catch (System.StackOverflowException e) {
                Abort(e);
                throw;
            }
            catch (System.Threading.ThreadAbortException e) {
                Abort(e);
                SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
                throw;
            }
            finally {
                SqlStatistics.StopTimer(statistics);
            }
        }

        static public void ClearAllPools() {
            (new SqlClientPermission(PermissionState.Unrestricted)).Demand();
            SqlConnectionFactory.SingletonInstance.ClearAllPools();
        }

        static public void ClearPool(SqlConnection connection) {
            ADP.CheckArgumentNull(connection, "connection");

            DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
            if (null != connectionOptions) {
                connectionOptions.DemandPermission();
                if (connection.IsContextConnection) {
                    throw SQL.NotAvailableOnContextConnection();
                }
                SqlConnectionFactory.SingletonInstance.ClearPool(connection);
            }
        }

        object ICloneable.Clone() {
            SqlConnection clone = new SqlConnection(this);
            Bid.Trace("<sc.SqlConnection.Clone|API> %d#, clone=%d#\n", ObjectID, clone.ObjectID);
            return clone;
        }

        void CloseInnerConnection() {
            // CloseConnection() now handles the lock

            // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and 
            // the command will no longer be cancelable.  It might be desirable to be able to cancel the close opperation, but this is
            // outside of the scope of Whidbey RTM.  See (SqlCommand::Cancel) for other lock.
            InnerConnection.CloseConnection(this, ConnectionFactory);
        }

        override public void Close() {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlConnection.Close|API> %d#" , ObjectID);
            Bid.CorrelationTrace("<sc.SqlConnection.Close|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
            try {
                SqlStatistics statistics = null;

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

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

                        Task reconnectTask = _currentReconnectionTask;
                        if (reconnectTask != null && !reconnectTask.IsCompleted) {
                            CancellationTokenSource cts = _reconnectionCancellationSource;
                            if (cts != null) {
                                cts.Cancel();
                            }
                            AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
                            if (State != ConnectionState.Open) {// if we cancelled before the connection was opened 
                                OnStateChange(DbConnectionInternal.StateChangeClosed);
                            }
                        }
                        CancelOpenAndWait(); 
                        CloseInnerConnection();
                        GC.SuppressFinalize(this);

                        if (null != Statistics) {
                            ADP.TimerCurrent(out _statistics._closeTimestamp);
                        }
                    }
 #if DEBUG
                    finally {
                        tdsReliabilitySection.Stop();
                    }
#endif //DEBUG
                }
                catch (System.OutOfMemoryException e) {
                    Abort(e);
                    throw;
                }
                catch (System.StackOverflowException e) {
                    Abort(e);
                    throw;
                }
                catch (System.Threading.ThreadAbortException e) {
                    Abort(e);
                    SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
                    throw;
                }
                finally {
                    SqlStatistics.StopTimer(statistics);
                }
            }
            finally {
                SqlDebugContext  sdc = _sdc;
                _sdc = null;
                Bid.ScopeLeave(ref hscp);
                if (sdc != null) {
                   sdc.Dispose();
                }
            }
        }

        new public SqlCommand CreateCommand() {
            return new SqlCommand(null, this);
        }

        private void DisposeMe(bool disposing) { // MDAC 65459
            // clear credential and AccessToken here rather than in IDisposable.Dispose as these are specific to SqlConnection only
            //  IDisposable.Dispose is generated code from a template and used by other providers as well
            _credential = null; 
            _accessToken = null;

            if (!disposing) {
                // DevDiv2 Bug 457934:SQLConnection leaks when not disposed
                // http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/457934
                // For non-pooled connections we need to make sure that if the SqlConnection was not closed, then we release the GCHandle on the stateObject to allow it to be GCed
                // For pooled connections, we will rely on the pool reclaiming the connection
                var innerConnection = (InnerConnection as SqlInternalConnectionTds);
                if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling)) {
                    var parser = innerConnection.Parser;
                    if ((parser != null) && (parser._physicalStateObj != null)) {
                        parser._physicalStateObj.DecrementPendingCallbacks(release: false);
                    }
                }
            }
        }

#if !MOBILE
        public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction transaction) {
            if (IsContextConnection) {
                throw SQL.NotAvailableOnContextConnection();
            }

            EnlistDistributedTransactionHelper(transaction);
        }
#endif

        override public void Open() {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlConnection.Open|API> %d#", ObjectID) ;
            Bid.CorrelationTrace("<sc.SqlConnection.Open|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
           
            try {
                if (StatisticsEnabled) {
                    if (null == _statistics) {
                        _statistics = new SqlStatistics();
                    }
                    else {
                        _statistics.ContinueOnNewConnection();
                    }
                }

                SqlStatistics statistics = null;
                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    statistics = SqlStatistics.StartTimer(Statistics);

                    if (!TryOpen(null)) {
                        throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
                    }
                }
                finally {
                    SqlStatistics.StopTimer(statistics);
                }
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }

        internal void RegisterWaitingForReconnect(Task waitingTask) {
            if (((SqlConnectionString)ConnectionOptions).MARS) {
                return;
            }
            Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null);
            if (_asyncWaitingForReconnection != waitingTask) { // somebody else managed to register 
                throw SQL.MARSUnspportedOnConnection();
            }
        }

        private async Task ReconnectAsync(int timeout) {
            try {
                long commandTimeoutExpiration = 0;
                if (timeout > 0) {
                    commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout);
                }
                CancellationTokenSource cts = new CancellationTokenSource();
                _reconnectionCancellationSource = cts;
                CancellationToken ctoken = cts.Token;
                int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string
                for (int attempt = 0; attempt < retryCount; attempt++) {                                       
                    if (ctoken.IsCancellationRequested) {
                        Bid.Trace("<sc.SqlConnection.ReconnectAsync|INFO> Orginal ClientConnectionID %ls - reconnection cancelled\n", _originalConnectionId.ToString());
                        return;
                    }
                    try {
                        _impersonateIdentity = _lastIdentity;
                        try {
                            ForceNewConnection = true;
                            await OpenAsync(ctoken).ConfigureAwait(false);
                            // On success, increment the reconnect count - we don't really care if it rolls over since it is approx.
                            _reconnectCount = unchecked(_reconnectCount + 1);
#if DEBUG
                            Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !");
#endif
                        }
                        finally {
                            _impersonateIdentity = null;
                            ForceNewConnection = false;
                        }
                        Bid.Trace("<sc.SqlConnection.ReconnectIfNeeded|INFO> Reconnection suceeded.  ClientConnectionID %ls -> %ls \n", _originalConnectionId.ToString(), ClientConnectionId.ToString());
                        return;
                    }
                    catch (SqlException e) {
                        Bid.Trace("<sc.SqlConnection.ReconnectAsyncINFO> Orginal ClientConnectionID %ls - reconnection attempt failed error %ls\n", _originalConnectionId.ToString(), e.Message);
                        if (attempt == retryCount - 1) {
                            Bid.Trace("<sc.SqlConnection.ReconnectAsync|INFO> Orginal ClientConnectionID %ls - give up reconnection\n", _originalConnectionId.ToString());
                            throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
                        }
                        if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) {
                            throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId);
                        }
                    }
                    await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false);
                }
            }
            finally {               
                _recoverySessionData = null;
                _supressStateChangeForReconnection = false;
            }
            Debug.Assert(false, "Should not reach this point");
        }

        internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) {
            Task runningReconnect = _currentReconnectionTask;
            // This loop in the end will return not completed reconnect task or null
            while (runningReconnect != null && runningReconnect.IsCompleted) {
                // clean current reconnect task (if it is the same one we checked
                Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect);
                // make sure nobody started new task (if which case we did not clean it)
                runningReconnect = _currentReconnectionTask;
            }
            if (runningReconnect == null) {
                if (_connectRetryCount > 0) {
                    SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();                    
                    if (tdsConn._sessionRecoveryAcknowledged) {
                        TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;     
                        if (!stateObj.ValidateSNIConnection()) {                           
                            if (tdsConn.Parser._sessionPool != null) {
                                if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0) {
                                    // >1 MARS session 
                                    if (beforeDisconnect != null) {
                                        beforeDisconnect();
                                    }
                                    OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
                                }
                            }
                            SessionData cData = tdsConn.CurrentSessionData;
                            cData.AssertUnrecoverableStateCountIsCorrect();
                            if (cData._unrecoverableStatesCount == 0) {
                                bool callDisconnect = false;
                                lock (_reconnectLock) {
                                    tdsConn.CheckEnlistedTransactionBinding();
                                    runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
                                    if (runningReconnect == null) {
                                        if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken
                                            _originalConnectionId = ClientConnectionId;
                                            Bid.Trace("<sc.SqlConnection.ReconnectIfNeeded|INFO> Connection ClientConnectionID %ls is invalid, reconnecting\n", _originalConnectionId.ToString());
                                            _recoverySessionData = cData;
                                            if (beforeDisconnect != null) {
                                                beforeDisconnect();
                                            }
                                            try {
                                                _supressStateChangeForReconnection = true;
                                                tdsConn.DoomThisConnection();
                                            }
                                            catch (SqlException) {
                                            }
                                            runningReconnect = Task.Run(() => ReconnectAsync(timeout));
                                            // if current reconnect is not null, somebody already started reconnection task - some kind of race condition
                                            Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");                                            
                                            _currentReconnectionTask = runningReconnect;
                                        }
                                    }
                                    else {
                                        callDisconnect = true;
                                    }
                                }
                                if (callDisconnect && beforeDisconnect != null) {
                                    beforeDisconnect();
                                }
                            }
                            else {
                                if (beforeDisconnect != null) {
                                    beforeDisconnect();
                                }
                                OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
                            }
                        } // ValidateSNIConnection
                    } // sessionRecoverySupported                  
                } // connectRetryCount>0
            }
            else { // runningReconnect = null
                if (beforeDisconnect != null) {
                    beforeDisconnect();
                }
            }
            return runningReconnect;
        }

        // this is straightforward, but expensive method to do connection resiliency - it take locks and all prepartions as for TDS request
        partial void RepairInnerConnection() {
            WaitForPendingReconnection();
            if (_connectRetryCount == 0) {
                return;
            }
            SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds;
            if (tdsConn != null) {
                tdsConn.ValidateConnectionForExecute(null);
                tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this);
            }
        }

        private void WaitForPendingReconnection() {
            Task reconnectTask = _currentReconnectionTask;
            if (reconnectTask != null && !reconnectTask.IsCompleted) {
                AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false);
            }
        }

        void CancelOpenAndWait()
        {
            // copy from member to avoid changes by background thread
            var completion = _currentCompletion;
            if (completion != null)
            {
                completion.Item1.TrySetCanceled();
                ((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne();
            }
            Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source");
        }

        public override Task OpenAsync(CancellationToken cancellationToken) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlConnection.OpenAsync|API> %d#", ObjectID) ;
            Bid.CorrelationTrace("<sc.SqlConnection.OpenAsync|API|Correlation> ObjectID%d#, ActivityID %ls\n", ObjectID);
            try {

                if (StatisticsEnabled) {
                    if (null == _statistics) {
                        _statistics = new SqlStatistics();
                    }
                    else {
                        _statistics.ContinueOnNewConnection();
                    }
                }

                SqlStatistics statistics = null;
                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    statistics = SqlStatistics.StartTimer(Statistics);

                    System.Transactions.Transaction transaction = ADP.GetCurrentTransaction();
                    TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(transaction);
                    TaskCompletionSource<object> result = new TaskCompletionSource<object>();

                    if (cancellationToken.IsCancellationRequested) {
                        result.SetCanceled();
                        return result.Task;
                    }

                    if (IsContextConnection) {
                        // Async not supported on Context Connections
                        result.SetException(ADP.ExceptionWithStackTrace(SQL.NotAvailableOnContextConnection()));
                        return result.Task;
                    }

                    bool completed;
                    
                    try {
                        completed = TryOpen(completion);
                    }
                    catch (Exception e) {
                        result.SetException(e);
                        return result.Task;
                    }
                    
                    if (completed) {
                        result.SetResult(null);
                    }
                    else {
                        CancellationTokenRegistration registration = new CancellationTokenRegistration();
                        if (cancellationToken.CanBeCanceled) {
                            registration = cancellationToken.Register(() => completion.TrySetCanceled());
                        }
                        OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration);
                        _currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task);
                        completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default);
                        return result.Task;
                    }

                    return result.Task;
                }
                finally {
                    SqlStatistics.StopTimer(statistics);
                }
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }

        private class OpenAsyncRetry {
            SqlConnection _parent;
            TaskCompletionSource<DbConnectionInternal> _retry;
            TaskCompletionSource<object> _result;
            CancellationTokenRegistration _registration;

            public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result,  CancellationTokenRegistration registration) {
                _parent = parent;
                _retry = retry;
                _result = result;
                _registration = registration;
            }

            internal void Retry(Task<DbConnectionInternal> retryTask) {
                Bid.Trace("<sc.SqlConnection.OpenAsyncRetry|Info> %d#\n", _parent.ObjectID);
                _registration.Dispose();
                try {
                    SqlStatistics statistics = null;
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try {
                        statistics = SqlStatistics.StartTimer(_parent.Statistics);

                        if (retryTask.IsFaulted) {
                            Exception e = retryTask.Exception.InnerException;
                            _parent.CloseInnerConnection();
                            _parent._currentCompletion = null;
                            _result.SetException(retryTask.Exception.InnerException);
                        }
                        else if (retryTask.IsCanceled) {
                            _parent.CloseInnerConnection();
                            _parent._currentCompletion = null;
                            _result.SetCanceled();
                        }
                        else {
                            bool result;
                            // protect continuation from ----s with close and cancel
                            lock (_parent.InnerConnection) {
                                result = _parent.TryOpen(_retry);
                            }
                            if (result)
                            {
                                _parent._currentCompletion = null;
                                _result.SetResult(null);
                            }
                            else {
                                _parent.CloseInnerConnection();
                                _parent._currentCompletion = null;
                                _result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending)));
                            }
                        }
                    }
                    finally {
                        SqlStatistics.StopTimer(statistics);
                    }
                }
                catch (Exception e) {
                    _parent.CloseInnerConnection();
                    _parent._currentCompletion = null;
                    _result.SetException(e);
                }
            }
        }

        private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry) {
            SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
            
            _applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0 );

            if (connectionOptions != null &&
                (connectionOptions.Authentication == SqlAuthenticationMethod.SqlPassword || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryPassword) &&
                (!connectionOptions.HasUserIdKeyword || !connectionOptions.HasPasswordKeyword) &&
                _credential == null) {
                    throw SQL.CredentialsNotProvided(connectionOptions.Authentication);
            }

           if (_impersonateIdentity != null) {
                if (_impersonateIdentity.User == DbConnectionPoolIdentity.GetCurrentWindowsIdentity().User) {
                    return TryOpenInner(retry);
                }
                else {
                    using (WindowsImpersonationContext context = _impersonateIdentity.Impersonate()) {
                        return TryOpenInner(retry);
                    }                    
                }
            }
            else {
                if (this.UsesIntegratedSecurity(connectionOptions) || this.UsesActiveDirectoryIntegrated(connectionOptions)) {
                    _lastIdentity = DbConnectionPoolIdentity.GetCurrentWindowsIdentity();
                }
                else {
                    _lastIdentity = null;
                }
                return TryOpenInner(retry);
            }
        }

        private bool TryOpenInner(TaskCompletionSource<DbConnectionInternal> retry) {
            TdsParser bestEffortCleanupTarget = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
#if DEBUG
                TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();

                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                    tdsReliabilitySection.Start();
#else
                {
#endif //DEBUG
                    if (ForceNewConnection) {
                        if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions)) {
                            return false;
                        }
                    }
                    else {
                        if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions)) {
                            return false;
                        }
                    }
                    // does not require GC.KeepAlive(this) because of OnStateChange

                    // GetBestEffortCleanup must happen AFTER OpenConnection to get the correct target.
                    bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(this);

                    var tdsInnerConnection = (InnerConnection as SqlInternalConnectionTds);
                    if (tdsInnerConnection == null) {
                        SqlInternalConnectionSmi innerConnection = (InnerConnection as SqlInternalConnectionSmi);
                        innerConnection.AutomaticEnlistment();
                    }
                    else {
                        Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");

                        if (!tdsInnerConnection.ConnectionOptions.Pooling) {
                            // For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles
                            GC.ReRegisterForFinalize(this);
                        }

                        if (StatisticsEnabled) {
                            ADP.TimerCurrent(out _statistics._openTimestamp);
                            tdsInnerConnection.Parser.Statistics = _statistics;
                        }
                        else {
                            tdsInnerConnection.Parser.Statistics = null;
                            _statistics = null; // in case of previous Open/Close/reset_CollectStats sequence
                        }
                        CompleteOpen();
                    }
                }
#if DEBUG
                finally {
                    tdsReliabilitySection.Stop();
                }
#endif //DEBUG
            }
            catch (System.OutOfMemoryException e) {
                Abort(e);
                throw;
            }
            catch (System.StackOverflowException e) {
                Abort(e);
                throw;
            }
            catch (System.Threading.ThreadAbortException e) {
                Abort(e);
                SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
                throw;
            }

            return true;
        }


        //
        // INTERNAL PROPERTIES
        //

        internal bool HasLocalTransaction {
            get {
                return GetOpenConnection().HasLocalTransaction;
            }
        }

        internal bool HasLocalTransactionFromAPI {
            get {
                Task reconnectTask = _currentReconnectionTask;
                if (reconnectTask != null  && !reconnectTask.IsCompleted) {
                    return false; //we will not go into reconnection if we are inside the transaction
                }
                return GetOpenConnection().HasLocalTransactionFromAPI;
            }
        }

        internal bool IsShiloh {
            get {
                if (_currentReconnectionTask != null) { // holds true even if task is completed
                    return true; // if CR is enabled, connection, if established, will be Katmai+
                }
                return GetOpenConnection().IsShiloh;
            }
        }

        internal bool IsYukonOrNewer {
            get {
                if (_currentReconnectionTask != null) { // holds true even if task is completed
                    return true; // if CR is enabled, connection, if established, will be Katmai+
                }
                return GetOpenConnection().IsYukonOrNewer;
            }
        }

        internal bool IsKatmaiOrNewer {
            get {
                if (_currentReconnectionTask != null) { // holds true even if task is completed
                    return true; // if CR is enabled, connection, if established, will be Katmai+
                }
                return GetOpenConnection().IsKatmaiOrNewer;
            }
        }

        internal TdsParser Parser {
            get {
                SqlInternalConnectionTds tdsConnection = (GetOpenConnection() as SqlInternalConnectionTds);
                if (null == tdsConnection) {
                    throw SQL.NotAvailableOnContextConnection();
                }
                return tdsConnection.Parser;
            }
        }

        internal bool Asynchronous {
            get {
                SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
                return ((null != constr) ? constr.Asynchronous : SqlConnectionString.DEFAULT.Asynchronous);
            }
        }

        //
        // INTERNAL METHODS
        //
        
        internal void ValidateConnectionForExecute(string method, SqlCommand command) {
            Task asyncWaitingForReconnection=_asyncWaitingForReconnection;
            if (asyncWaitingForReconnection!=null) {
                if (!asyncWaitingForReconnection.IsCompleted) {
                    throw SQL.MARSUnspportedOnConnection();
                }
                else {
                    Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection);
                }
            }
            if (_currentReconnectionTask != null) {
                Task currentReconnectionTask = _currentReconnectionTask;
                if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted) {
                    return; // execution will wait for this task later
                }
            }
            SqlInternalConnection innerConnection = GetOpenConnection(method);
            innerConnection.ValidateConnectionForExecute(command);
        }

        // Surround name in brackets and then escape any end bracket to protect against SQL Injection.
        // NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well
        // as native OleDb and Odbc.
        static internal string FixupDatabaseTransactionName(string name) {
            if (!ADP.IsEmpty(name)) {
                return SqlServerEscapeHelper.EscapeIdentifier(name);
            }
            else {
                return name;
            }
        }
        
        // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
        // The close action also supports being run asynchronously
        internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction) {
            Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!");

            // Bug fix - MDAC 49022 - connection open after failure...  Problem was parser was passing
            // Open as a state - because the parser's connection to the netlib was open.  We would
            // then set the connection state to the parser's state - which is not correct.  The only
            // time the connection state should change to what is passed in to this function is if
            // the parser is broken, then we should be closed.  Changed to passing in
            // TdsParserState, not ConnectionState.
            // fixed by [....]

            if (breakConnection && (ConnectionState.Open == State)) {

                if (wrapCloseInAction != null) {
                    int capturedCloseCount = _closeCount;

                    Action closeAction = () => {
                        if (capturedCloseCount == _closeCount) {
                            Bid.Trace("<sc.SqlConnection.OnError|INFO> %d#, Connection broken.\n", ObjectID);
                            Close();
                        }
                    };

                    wrapCloseInAction(closeAction);
                }
                else {
                    Bid.Trace("<sc.SqlConnection.OnError|INFO> %d#, Connection broken.\n", ObjectID);
                    Close();
                }
            }

            if (exception.Class >= TdsEnums.MIN_ERROR_CLASS) {
                // It is an error, and should be thrown.  Class of TdsEnums.MIN_ERROR_CLASS or above is an error,
                // below TdsEnums.MIN_ERROR_CLASS denotes an info message.
                throw exception;
            }
            else {
                // If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler
                this.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
            }
        }

        //
        // PRIVATE METHODS
        //

        // SxS: using Debugger.IsAttached
        // 
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
        private void CompleteOpen() {
            Debug.Assert(ConnectionState.Open == State, "CompleteOpen not open");
            // be sure to mark as open so SqlDebugCheck can issue Query

            // check to see if we need to hook up sql-debugging if a debugger is attached
            // We only need this check for Shiloh and earlier servers.
            if (!GetOpenConnection().IsYukonOrNewer && 
                    System.Diagnostics.Debugger.IsAttached) {
                bool debugCheck = false;
                try {
                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); // MDAC 66682, 69017
                    debugCheck = true;
                }
                catch (SecurityException e) {
                    ADP.TraceExceptionWithoutRethrow(e);
                }

                if (debugCheck) {
                    // if we don't have Unmanaged code permission, don't check for debugging
                    // but let the connection be opened while under the debugger
                    CheckSQLDebugOnConnect();
                }
            }
        }
    
        internal SqlInternalConnection GetOpenConnection() {
            SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
            if (null == innerConnection) {
                throw ADP.ClosedConnectionError();
            }
            return innerConnection;
        }

        internal SqlInternalConnection GetOpenConnection(string method) {
            DbConnectionInternal innerConnection = InnerConnection;
            SqlInternalConnection innerSqlConnection = (innerConnection as SqlInternalConnection);
            if (null == innerSqlConnection) {
                throw ADP.OpenConnectionRequired(method, innerConnection.State);
            }
            return innerSqlConnection;
        }
        
        internal SqlInternalConnectionTds GetOpenTdsConnection() {
            SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
            if (null == innerConnection) {
                throw ADP.ClosedConnectionError();
            }
            return innerConnection;
        }
        
        internal SqlInternalConnectionTds GetOpenTdsConnection(string method) {
            SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
            if (null == innerConnection) {
                throw ADP.OpenConnectionRequired(method, InnerConnection.State);
            }
            return innerConnection;
        }

        internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) {
            bool notified;
            OnInfoMessage(imevent, out notified);
        }

        internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) {
            if (Bid.TraceOn) {
                Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs");
                Bid.Trace("<sc.SqlConnection.OnInfoMessage|API|INFO> %d#, Message='%ls'\n", ObjectID, ((null != imevent) ? imevent.Message : ""));
            }
            SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage];
            if (null != handler) {
                notified = true;
                try {
                    handler(this, imevent);
                }
                catch (Exception e) { // MDAC 53175
                    if (!ADP.IsCatchableOrSecurityExceptionType(e)) {
                        throw;
                    }

                    ADP.TraceExceptionWithoutRethrow(e);
                }
            } else {
                notified = false;
            }
        }

        //
        // SQL DEBUGGING SUPPORT
        //

        // this only happens once per connection
        // SxS: using named file mapping APIs
        // 
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        private void CheckSQLDebugOnConnect() {
            IntPtr hFileMap;
            uint pid = (uint)SafeNativeMethods.GetCurrentProcessId();

            string mapFileName;

            // If Win2k or later, prepend "Global\\" to enable this to work through TerminalServices.
            if (ADP.IsPlatformNT5) {
                mapFileName = "Global\\" + TdsEnums.SDCI_MAPFILENAME;
            }
            else {
                mapFileName = TdsEnums.SDCI_MAPFILENAME;
            }

            mapFileName = mapFileName + pid.ToString(CultureInfo.InvariantCulture);

            hFileMap = NativeMethods.OpenFileMappingA(0x4/*FILE_MAP_READ*/, false, mapFileName);

            if (ADP.PtrZero != hFileMap) {
                IntPtr pMemMap = NativeMethods.MapViewOfFile(hFileMap, 0x4/*FILE_MAP_READ*/, 0, 0, IntPtr.Zero);
                if (ADP.PtrZero != pMemMap) {
                    SqlDebugContext sdc = new SqlDebugContext();
                    sdc.hMemMap = hFileMap;
                    sdc.pMemMap = pMemMap;
                    sdc.pid = pid;

                    // optimization: if we only have to refresh memory-mapped data at connection open time
                    // optimization: then call here instead of in CheckSQLDebug() which gets called
                    // optimization: at command execution time
                    // RefreshMemoryMappedData(sdc);

                    // delaying setting out global state until after we issue this first SQLDebug command so that
                    // we don't reentrantly call into CheckSQLDebug
                    CheckSQLDebug(sdc);
                    // now set our global state
                    _sdc = sdc;
                }
            }
        }

        // This overload is called by the Command object when executing stored procedures.  Note that
        // if SQLDebug has never been called, it is a noop.
        internal void CheckSQLDebug() {
            if (null != _sdc)
                CheckSQLDebug(_sdc);
        }

        // SxS: using GetCurrentThreadId
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] // MDAC 66682, 69017
        private void CheckSQLDebug(SqlDebugContext sdc) {
            // check to see if debugging has been activated
            Debug.Assert(null != sdc, "SQL Debug: invalid null debugging context!");

#pragma warning disable 618
            uint tid = (uint)AppDomain.GetCurrentThreadId();    // Sql Debugging doesn't need fiber support;
#pragma warning restore 618
            RefreshMemoryMappedData(sdc);

            // 



            // If we get here, the debugger must be hooked up.
            if (!sdc.active) {
                if (sdc.fOption/*TdsEnums.SQLDEBUG_ON*/) {
                    // turn on
                    sdc.active = true;
                    sdc.tid = tid;
                    try {
                        IssueSQLDebug(TdsEnums.SQLDEBUG_ON, sdc.machineName, sdc.pid, sdc.dbgpid, sdc.sdiDllName, sdc.data);
                        sdc.tid = 0; // reset so that the first successful time through, we notify the server of the context switch
                    }
                    catch {
                        sdc.active = false;
                        throw;
                    }
                }
            }

            // be sure to pick up thread context switch, especially the first time through
            if (sdc.active) {
                if (!sdc.fOption/*TdsEnums.SQLDEBUG_OFF*/) {
                    // turn off and free the memory
                    sdc.Dispose();
                    // okay if we throw out here, no state to clean up
                    IssueSQLDebug(TdsEnums.SQLDEBUG_OFF, null, 0, 0, null, null);
                }
                else {
                    // notify server of context change
                    if (sdc.tid != tid) {
                        sdc.tid = tid;
                        try {
                            IssueSQLDebug(TdsEnums.SQLDEBUG_CONTEXT, null, sdc.pid, sdc.tid, null, null);
                        }
                        catch {
                            sdc.tid = 0;
                            throw;
                        }
                    }
                }
            }
        }

        private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, string sdiDllName, byte[] data) {

            if (GetOpenConnection().IsYukonOrNewer) {
                // 
                return;
            }

            // 

            SqlCommand c = new SqlCommand(TdsEnums.SP_SDIDEBUG, this);
            c.CommandType = CommandType.StoredProcedure;

            // context param
            SqlParameter p = new SqlParameter(null, SqlDbType.VarChar, TdsEnums.SQLDEBUG_MODE_NAMES[option].Length);
            p.Value = TdsEnums.SQLDEBUG_MODE_NAMES[option];
            c.Parameters.Add(p);

            if (option == TdsEnums.SQLDEBUG_ON) {
                // debug dll name
                p = new SqlParameter(null, SqlDbType.VarChar, sdiDllName.Length);
                p.Value = sdiDllName;
                c.Parameters.Add(p);
                // debug machine name
                p = new SqlParameter(null, SqlDbType.VarChar, machineName.Length);
                p.Value = machineName;
                c.Parameters.Add(p);
            }

            if (option != TdsEnums.SQLDEBUG_OFF) {
                // client pid
                p = new SqlParameter(null, SqlDbType.Int);
                p.Value = pid;
                c.Parameters.Add(p);
                // dbgpid or tid
                p = new SqlParameter(null, SqlDbType.Int);
                p.Value = id;
                c.Parameters.Add(p);
            }

            if (option == TdsEnums.SQLDEBUG_ON) {
                // debug data
                p = new SqlParameter(null, SqlDbType.VarBinary, (null != data) ? data.Length : 0);
                p.Value = data;
                c.Parameters.Add(p);
            }

            c.ExecuteNonQuery();
        }


        public static void ChangePassword(string connectionString, string newPassword) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlConnection.ChangePassword|API>") ;
            Bid.CorrelationTrace("<sc.SqlConnection.ChangePassword|API|Correlation> ActivityID %ls\n");
            try {
                if (ADP.IsEmpty(connectionString)) {
                    throw SQL.ChangePasswordArgumentMissing("connectionString");
                }
                if (ADP.IsEmpty(newPassword)) {
                    throw SQL.ChangePasswordArgumentMissing("newPassword");
                }
                if (TdsEnums.MAXLEN_NEWPASSWORD < newPassword.Length) {
                    throw ADP.InvalidArgumentLength("newPassword", TdsEnums.MAXLEN_NEWPASSWORD);
                }

                SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential: null, accessToken: null);

                SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
                if (connectionOptions.IntegratedSecurity || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated) {

                    throw SQL.ChangePasswordConflictsWithSSPI();
                }
                if (! ADP.IsEmpty(connectionOptions.AttachDBFilename)) {
                    throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
                }
                if (connectionOptions.ContextConnection) {
                    throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.Context_Connection);
                }

                System.Security.PermissionSet permissionSet = connectionOptions.CreatePermissionSet();
                permissionSet.Demand();

                ChangePassword(connectionString, connectionOptions, null, newPassword, null);
             }
            finally {
                Bid.ScopeLeave(ref hscp) ;
            }
       }

        public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) {
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlConnection.ChangePassword|API>") ;
            Bid.CorrelationTrace("<sc.SqlConnection.ChangePassword|API|Correlation> ActivityID %ls\n");
            try {
                if (ADP.IsEmpty(connectionString)) {
                    throw SQL.ChangePasswordArgumentMissing("connectionString");
                }

                // check credential; not necessary to check the length of password in credential as the check is done by SqlCredential class
                if (credential == null) {
                    throw SQL.ChangePasswordArgumentMissing("credential");
                }

                if (newSecurePassword == null || newSecurePassword.Length == 0) {
                    throw SQL.ChangePasswordArgumentMissing("newSecurePassword");;
                }

                if (!newSecurePassword.IsReadOnly()) {
                    throw ADP.MustBeReadOnly("newSecurePassword");
                }

                if (TdsEnums.MAXLEN_NEWPASSWORD < newSecurePassword.Length) {
                    throw ADP.InvalidArgumentLength("newSecurePassword", TdsEnums.MAXLEN_NEWPASSWORD);
                }

                SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null);

                SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);

                // Check for incompatible connection string value with SqlCredential
                if (!ADP.IsEmpty(connectionOptions.UserID) || !ADP.IsEmpty(connectionOptions.Password)) {
                    throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
                }

                if (connectionOptions.IntegratedSecurity || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated) {
                    throw SQL.ChangePasswordConflictsWithSSPI();
                }

                if (! ADP.IsEmpty(connectionOptions.AttachDBFilename)) {
                    throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
                }

                if (connectionOptions.ContextConnection) {
                    throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.Context_Connection);
                }

                System.Security.PermissionSet permissionSet = connectionOptions.CreatePermissionSet();
                permissionSet.Demand();

                ChangePassword(connectionString, connectionOptions, credential, null, newSecurePassword);
            }
            finally {
                Bid.ScopeLeave(ref hscp) ;
            }
        }

        private static void ChangePassword(string connectionString, SqlConnectionString connectionOptions, SqlCredential credential, string newPassword, SecureString newSecurePassword ) {
            // note: This is the only case where we directly construt the internal connection, passing in the new password.
            // Normally we would simply create a regular connectoin and open it but there is no other way to pass the
            // new password down to the constructor. Also it would have an unwanted impact on the connection pool
            //
            using (SqlInternalConnectionTds con = new SqlInternalConnectionTds(null, connectionOptions, credential, null, newPassword, newSecurePassword, false)) {
                if (!con.IsYukonOrNewer) {
                    throw SQL.ChangePasswordRequiresYukon();
                }
            }
            SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null);

            SqlConnectionFactory.SingletonInstance.ClearPool(key);
        }

        internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outterTask, object value, int tag) {
            // Connection exists,  schedule removal, will be added to ref collection after calling ValidateAndReconnect
            outterTask = outterTask.ContinueWith(task => {
                RemoveWeakReference(value);
                return task;
            }, TaskScheduler.Default).Unwrap();
        }

        // updates our context with any changes made to the memory-mapped data by an external process
        static private void RefreshMemoryMappedData(SqlDebugContext sdc) {
            Debug.Assert(ADP.PtrZero != sdc.pMemMap, "SQL Debug: invalid null value for pMemMap!");
            // copy memory mapped file contents into managed types
            MEMMAP memMap = (MEMMAP)Marshal.PtrToStructure(sdc.pMemMap, typeof(MEMMAP));
            sdc.dbgpid = memMap.dbgpid;
            sdc.fOption = (memMap.fOption == 1) ? true : false;
            // xlate ansi byte[] -> managed strings
            Encoding cp = System.Text.Encoding.GetEncoding(TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_VALUE);
            sdc.machineName = cp.GetString(memMap.rgbMachineName, 0, memMap.rgbMachineName.Length);
            sdc.sdiDllName = cp.GetString(memMap.rgbDllName, 0, memMap.rgbDllName.Length);
            // just get data reference
            sdc.data = memMap.rgbData;
        }

        public void ResetStatistics() {
            if (IsContextConnection) {
                throw SQL.NotAvailableOnContextConnection();
            }

            if (null != Statistics) {
                Statistics.Reset();
                if (ConnectionState.Open == State) {
                    // update timestamp;
                    ADP.TimerCurrent(out _statistics._openTimestamp);
                }
            }
        }

        public IDictionary RetrieveStatistics() {
            if (IsContextConnection) {
                throw SQL.NotAvailableOnContextConnection();
            }

            if (null != Statistics) {
                UpdateStatistics();
                return Statistics.GetHashtable();
            }
            else {
                return new SqlStatistics().GetHashtable();
            }
        }

        private void UpdateStatistics() {
            if (ConnectionState.Open == State) {
                // update timestamp
                ADP.TimerCurrent(out _statistics._closeTimestamp);
            }
            // delegate the rest of the work to the SqlStatistics class
            Statistics.UpdateStatistics();
        }

        //
        // UDT SUPPORT
        //

        private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) {
            Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !");
            if (string.Compare(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase) == 0) {
                if (Bid.TraceOn) {
                    if (asmRef.Version!=TypeSystemAssemblyVersion) {
                        Bid.Trace("<sc.SqlConnection.ResolveTypeAssembly> SQL CLR type version change: Server sent %ls, client will instantiate %ls", 
                            asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString());
                    }
                }
                asmRef.Version = TypeSystemAssemblyVersion;
            }
            try {
                return Assembly.Load(asmRef);
            }
            catch (Exception e) {
                if (throwOnError || !ADP.IsCatchableExceptionType(e)) {
                    throw;
                }
                else {
                    return null;
                };
            }
        }

        // 
        internal void CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, bool fThrow) {
            if (metaData.udtType == null) { // If null, we have not obtained extended info.
                Debug.Assert(!ADP.IsEmpty(metaData.udtAssemblyQualifiedName), "Unexpected state on GetUDTInfo");
                // Parameter throwOnError determines whether exception from Assembly.Load is thrown.
                metaData.udtType =                
                    Type.GetType(typeName:metaData.udtAssemblyQualifiedName, assemblyResolver:asmRef => ResolveTypeAssembly(asmRef, fThrow), typeResolver:null, throwOnError: fThrow); 

                if (fThrow && metaData.udtType == null) {
                    // 
                    throw SQL.UDTUnexpectedResult(metaData.udtAssemblyQualifiedName); 
                }
            }
        }

        internal object GetUdtValue(object value, SqlMetaDataPriv metaData, bool returnDBNull) {
            if (returnDBNull && ADP.IsNull(value)) {
                return DBNull.Value;
            }

            object o = null;

            // Since the serializer doesn't handle nulls...
            if (ADP.IsNull(value)) {
                Type t = metaData.udtType;
                Debug.Assert(t != null, "Unexpected null of udtType on GetUdtValue!");
                o = t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, new Object[]{}, CultureInfo.InvariantCulture);
                Debug.Assert(o != null);
                return o;
            }
            else {

                MemoryStream stm = new MemoryStream((byte[]) value);

                o = SerializationHelperSql9.Deserialize(stm, metaData.udtType);

                Debug.Assert(o != null, "object could NOT be created");
                return o;
            }
        }

        internal byte[] GetBytes(object o) {
            Microsoft.SqlServer.Server.Format format  = Microsoft.SqlServer.Server.Format.Native;
            int    maxSize = 0;
            return GetBytes(o, out format, out maxSize);
        }

        internal byte[] GetBytes(object o, out Microsoft.SqlServer.Server.Format format, out int maxSize) {
            SqlUdtInfo attr = AssemblyCache.GetInfoFromType(o.GetType());
            maxSize = attr.MaxByteSize;
            format  = attr.SerializationFormat;

            if (maxSize < -1 || maxSize >= UInt16.MaxValue) { // Do we need this?  Is this the right place?
                throw new InvalidOperationException(o.GetType() + ": invalid Size");
            }

            byte[] retval;

            using (MemoryStream stm = new MemoryStream(maxSize < 0 ? 0 : maxSize)) {
                SerializationHelperSql9.Serialize(stm, o);
                retval = stm.ToArray();
            }
            return retval;
        }
    } // SqlConnection

    // 





    [
    ComVisible(true),
    ClassInterface(ClassInterfaceType.None),
    Guid("afef65ad-4577-447a-a148-83acadd3d4b9"),
    ]
    [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")]
    public sealed class SQLDebugging: ISQLDebug {

        // Security stuff
        const int STANDARD_RIGHTS_REQUIRED = (0x000F0000);
        const int DELETE = (0x00010000);
        const int READ_CONTROL = (0x00020000);
        const int WRITE_DAC = (0x00040000);
        const int WRITE_OWNER = (0x00080000);
        const int SYNCHRONIZE = (0x00100000);
        const int FILE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x000001FF);
        const uint GENERIC_READ = (0x80000000);
        const uint GENERIC_WRITE = (0x40000000);
        const uint GENERIC_EXECUTE = (0x20000000);
        const uint GENERIC_ALL = (0x10000000);

        const int SECURITY_DESCRIPTOR_REVISION = (1);
        const int ACL_REVISION = (2);

        const int SECURITY_AUTHENTICATED_USER_RID = (0x0000000B);
        const int SECURITY_LOCAL_SYSTEM_RID = (0x00000012);
        const int SECURITY_BUILTIN_DOMAIN_RID = (0x00000020);
        const int SECURITY_WORLD_RID = (0x00000000);
        const byte SECURITY_NT_AUTHORITY = 5;
        const int DOMAIN_GROUP_RID_ADMINS = (0x00000200);
        const int DOMAIN_ALIAS_RID_ADMINS = (0x00000220);

        const int sizeofSECURITY_ATTRIBUTES = 12; // sizeof(SECURITY_ATTRIBUTES);
        const int sizeofSECURITY_DESCRIPTOR = 20; // sizeof(SECURITY_DESCRIPTOR);
        const int sizeofACCESS_ALLOWED_ACE = 12; // sizeof(ACCESS_ALLOWED_ACE);
        const int sizeofACCESS_DENIED_ACE = 12; // sizeof(ACCESS_DENIED_ACE);
        const int sizeofSID_IDENTIFIER_AUTHORITY = 6; // sizeof(SID_IDENTIFIER_AUTHORITY)
        const int sizeofACL = 8; // sizeof(ACL);

        private IntPtr CreateSD(ref IntPtr pDacl) {
            IntPtr pSecurityDescriptor = IntPtr.Zero;
            IntPtr pUserSid = IntPtr.Zero;
            IntPtr pAdminSid = IntPtr.Zero;
            IntPtr pNtAuthority = IntPtr.Zero;
            int cbAcl = 0;
            bool status = false;

            pNtAuthority = Marshal.AllocHGlobal(sizeofSID_IDENTIFIER_AUTHORITY);
            if (pNtAuthority == IntPtr.Zero)
                goto cleanup;
            Marshal.WriteInt32(pNtAuthority, 0, 0);
            Marshal.WriteByte(pNtAuthority, 4, 0);
            Marshal.WriteByte(pNtAuthority, 5, SECURITY_NT_AUTHORITY);

            status =
            NativeMethods.AllocateAndInitializeSid(
            pNtAuthority,
            (byte)1,
            SECURITY_AUTHENTICATED_USER_RID,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            ref pUserSid);

            if (!status || pUserSid == IntPtr.Zero) {
                goto cleanup;
            }
            status =
            NativeMethods.AllocateAndInitializeSid(
            pNtAuthority,
            (byte)2,
            SECURITY_BUILTIN_DOMAIN_RID,
            DOMAIN_ALIAS_RID_ADMINS,
            0,
            0,
            0,
            0,
            0,
            0,
            ref pAdminSid);

            if (!status || pAdminSid == IntPtr.Zero) {
                goto cleanup;
            }
            status = false;
            pSecurityDescriptor = Marshal.AllocHGlobal(sizeofSECURITY_DESCRIPTOR);
            if (pSecurityDescriptor == IntPtr.Zero) {
                goto cleanup;
            }
            for (int i = 0; i < sizeofSECURITY_DESCRIPTOR; i++)
                Marshal.WriteByte(pSecurityDescriptor, i, (byte)0);
            cbAcl = sizeofACL
            + (2 * (sizeofACCESS_ALLOWED_ACE))
            + sizeofACCESS_DENIED_ACE
            + NativeMethods.GetLengthSid(pUserSid)
            + NativeMethods.GetLengthSid(pAdminSid);

            pDacl = Marshal.AllocHGlobal(cbAcl);
            if (pDacl == IntPtr.Zero) {
                goto cleanup;
            }
            // rights must be added in a certain order.  Namely, deny access first, then add access
            if (NativeMethods.InitializeAcl(pDacl, cbAcl, ACL_REVISION))
                if (NativeMethods.AddAccessDeniedAce(pDacl, ACL_REVISION, WRITE_DAC, pUserSid))
                    if (NativeMethods.AddAccessAllowedAce(pDacl, ACL_REVISION, GENERIC_READ, pUserSid))
                        if (NativeMethods.AddAccessAllowedAce(pDacl, ACL_REVISION, GENERIC_ALL, pAdminSid))
                            if (NativeMethods.InitializeSecurityDescriptor(pSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION))
                                if (NativeMethods.SetSecurityDescriptorDacl(pSecurityDescriptor, true, pDacl, false)) {
                                    status = true;
                                }

            cleanup :
            if (pNtAuthority != IntPtr.Zero) {
                Marshal.FreeHGlobal(pNtAuthority);
            }
            if (pAdminSid != IntPtr.Zero)
                NativeMethods.FreeSid(pAdminSid);
            if (pUserSid != IntPtr.Zero)
                NativeMethods.FreeSid(pUserSid);
            if (status)
                return pSecurityDescriptor;
            else {
                if (pSecurityDescriptor != IntPtr.Zero) {
                    Marshal.FreeHGlobal(pSecurityDescriptor);
                }
            }
            return IntPtr.Zero;
        }

        // SxS: using file mapping API (CreateFileMapping)
        // 
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        bool ISQLDebug.SQLDebug(int dwpidDebugger, int dwpidDebuggee, [MarshalAs(UnmanagedType.LPStr)] string pszMachineName,
        [MarshalAs(UnmanagedType.LPStr)] string pszSDIDLLName, int dwOption, int cbData, byte[] rgbData) {
            bool result = false;
            IntPtr hFileMap = IntPtr.Zero;
            IntPtr pMemMap = IntPtr.Zero;
            IntPtr pSecurityDescriptor = IntPtr.Zero;
            IntPtr pSecurityAttributes = IntPtr.Zero;
            IntPtr pDacl = IntPtr.Zero;

            // validate the structure
            if (null == pszMachineName || null == pszSDIDLLName)
                return false;

            if (pszMachineName.Length > TdsEnums.SDCI_MAX_MACHINENAME ||
            pszSDIDLLName.Length > TdsEnums.SDCI_MAX_DLLNAME)
                return false;

            // note that these are ansi strings
            Encoding cp = System.Text.Encoding.GetEncoding(TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_VALUE);
            byte[] rgbMachineName = cp.GetBytes(pszMachineName);
            byte[] rgbSDIDLLName = cp.GetBytes(pszSDIDLLName);

            if (null != rgbData && cbData > TdsEnums.SDCI_MAX_DATA)
                return false;

            string mapFileName;

            // If Win2k or later, prepend "Global\\" to enable this to work through TerminalServices.
            if (ADP.IsPlatformNT5) {
                mapFileName = "Global\\" + TdsEnums.SDCI_MAPFILENAME;
            }
            else {
                mapFileName = TdsEnums.SDCI_MAPFILENAME;
            }

            mapFileName = mapFileName + dwpidDebuggee.ToString(CultureInfo.InvariantCulture);

            // Create Security Descriptor
            pSecurityDescriptor = CreateSD(ref pDacl);
            pSecurityAttributes = Marshal.AllocHGlobal(sizeofSECURITY_ATTRIBUTES);
            if ((pSecurityDescriptor == IntPtr.Zero) || (pSecurityAttributes == IntPtr.Zero))
                return false;

            Marshal.WriteInt32(pSecurityAttributes, 0, sizeofSECURITY_ATTRIBUTES); // nLength = sizeof(SECURITY_ATTRIBUTES)
            Marshal.WriteIntPtr(pSecurityAttributes, 4, pSecurityDescriptor); // lpSecurityDescriptor = pSecurityDescriptor
            Marshal.WriteInt32(pSecurityAttributes, 8, 0); // bInheritHandle = FALSE
            hFileMap = NativeMethods.CreateFileMappingA(
            ADP.InvalidPtr/*INVALID_HANDLE_VALUE*/,
            pSecurityAttributes,
            0x4/*PAGE_READWRITE*/,
            0,
            Marshal.SizeOf(typeof(MEMMAP)),
            mapFileName);

            if (IntPtr.Zero == hFileMap) {
                goto cleanup;
            }


            pMemMap = NativeMethods.MapViewOfFile(hFileMap, 0x6/*FILE_MAP_READ|FILE_MAP_WRITE*/, 0, 0, IntPtr.Zero);

            if (IntPtr.Zero == pMemMap) {
                goto cleanup;
            }

            // copy data to memory-mapped file
            // layout of MEMMAP structure is:
            // uint dbgpid
            // uint fOption
            // byte[32] machineName
            // byte[16] sdiDllName
            // uint dbData
            // byte[255] vData
            int offset = 0;
            Marshal.WriteInt32(pMemMap, offset, (int)dwpidDebugger);
            offset += 4;
            Marshal.WriteInt32(pMemMap, offset, (int)dwOption);
            offset += 4;
            Marshal.Copy(rgbMachineName, 0, ADP.IntPtrOffset(pMemMap, offset), rgbMachineName.Length);
            offset += TdsEnums.SDCI_MAX_MACHINENAME;
            Marshal.Copy(rgbSDIDLLName, 0, ADP.IntPtrOffset(pMemMap, offset), rgbSDIDLLName.Length);
            offset += TdsEnums.SDCI_MAX_DLLNAME;
            Marshal.WriteInt32(pMemMap, offset, (int)cbData);
            offset += 4;
            if (null != rgbData) {
                Marshal.Copy(rgbData, 0, ADP.IntPtrOffset(pMemMap, offset), (int)cbData);
            }
            NativeMethods.UnmapViewOfFile(pMemMap);
            result = true;
        cleanup :
            if (result == false) {
                if (hFileMap != IntPtr.Zero)
                    NativeMethods.CloseHandle(hFileMap);
            }
            if (pSecurityAttributes != IntPtr.Zero)
                Marshal.FreeHGlobal(pSecurityAttributes);
            if (pSecurityDescriptor != IntPtr.Zero)
                Marshal.FreeHGlobal(pSecurityDescriptor);
            if (pDacl != IntPtr.Zero)
                Marshal.FreeHGlobal(pDacl);
            return result;
        }
    }

    // this is a private interface to com+ users
    // do not change this guid
    [
    ComImport,
    ComVisible(true),
    Guid("6cb925bf-c3c0-45b3-9f44-5dd67c7b7fe8"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    BestFitMapping(false, ThrowOnUnmappableChar = true),
    ]
    interface ISQLDebug {

        [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")]
        bool SQLDebug(
        int dwpidDebugger,
        int dwpidDebuggee,
        [MarshalAs(UnmanagedType.LPStr)] string pszMachineName,
        [MarshalAs(UnmanagedType.LPStr)] string pszSDIDLLName,
        int dwOption,
        int cbData,
        byte[] rgbData);
    }

    sealed class SqlDebugContext: IDisposable {
        // context data
        internal uint pid = 0;
        internal uint tid = 0;
        internal bool active = false;
        // memory-mapped data
        internal IntPtr pMemMap = ADP.PtrZero;
        internal IntPtr hMemMap = ADP.PtrZero;
        internal uint dbgpid = 0;
        internal bool fOption = false;
        internal string machineName = null;
        internal string sdiDllName = null;
        internal byte[] data = null;

        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // using CloseHandle and UnmapViewOfFile - no exposure
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        private void Dispose(bool disposing) {
            if (disposing) {
                // Nothing to do here
                ;
            }
            if (pMemMap != IntPtr.Zero) {
                NativeMethods.UnmapViewOfFile(pMemMap);
                pMemMap = IntPtr.Zero;
            }
            if (hMemMap != IntPtr.Zero) {
                NativeMethods.CloseHandle(hMemMap);
                hMemMap = IntPtr.Zero;
            }
            active = false;
        }
        
        ~SqlDebugContext() {
                Dispose(false);
        }

    }

    // native interop memory mapped structure for sdi debugging
    [StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)]
    internal struct MEMMAP {
        [MarshalAs(UnmanagedType.U4)]
        internal uint dbgpid; // id of debugger
        [MarshalAs(UnmanagedType.U4)]
        internal uint fOption; // 1 - start debugging, 0 - stop debugging
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
        internal byte[] rgbMachineName;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
        internal byte[] rgbDllName;
        [MarshalAs(UnmanagedType.U4)]
        internal uint cbData;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
        internal byte[] rgbData;
    }
} // System.Data.SqlClient namespace