forked from dotnet/SqlClient
/
SqlConnection.cs
2222 lines (1969 loc) · 98.3 KB
/
SqlConnection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Common;
using Microsoft.Data.ProviderBase;
using Microsoft.Data.SqlClient.Server;
namespace Microsoft.Data.SqlClient
{
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/SqlConnection/*' />
public sealed partial class SqlConnection : DbConnection, ICloneable
{
private enum CultureCheckState : uint
{
Unknown = 0,
Standard = 1,
Invariant = 2
}
private bool _AsyncCommandInProgress;
// SQLStatistics support
internal SqlStatistics _statistics;
private bool _collectstats;
private bool _fireInfoMessageEventOnUserErrors; // False by default
// root task associated with current async invocation
private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;
private SqlCredential _credential;
private string _connectionString;
private int _connectRetryCount;
private string _accessToken; // Access Token to be used for token based authentication
// connection resiliency
private object _reconnectLock;
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 bool _suppressStateChangeForReconnection;
private int _reconnectCount;
// diagnostics listener
private static readonly SqlDiagnosticListener s_diagnosticListener = new SqlDiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName);
// 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;
// System column encryption key store providers are added by default
private static 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()}
};
// Lock to control setting of _CustomColumnEncryptionKeyStoreProviders
private static readonly object _CustomColumnEncryptionKeyProvidersLock = new object();
// status of invariant culture environment check
private static CultureCheckState _cultureCheckState;
/// <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>
private static ReadOnlyDictionary<string, SqlColumnEncryptionKeyStoreProvider> _CustomColumnEncryptionKeyStoreProviders;
/// <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>
private static readonly ConcurrentDictionary<string, IList<string>> _ColumnEncryptionTrustedMasterKeyPaths
= new ConcurrentDictionary<string, IList<string>>(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/,
capacity: 1,
comparer: StringComparer.OrdinalIgnoreCase);
private static readonly Action<object> s_openAsyncCancel = OpenAsyncCancel;
private static readonly Action<Task<object>, object> s_openAsyncComplete = OpenAsyncComplete;
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ColumnEncryptionKeyCacheTtl/*' />
public static TimeSpan ColumnEncryptionKeyCacheTtl { get; set; } = TimeSpan.FromHours(2);
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ColumnEncryptionQueryMetadataCacheEnabled/*' />
public static bool ColumnEncryptionQueryMetadataCacheEnabled { get; set; } = true;
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ColumnEncryptionTrustedMasterKeyPaths/*' />
public static IDictionary<string, IList<string>> ColumnEncryptionTrustedMasterKeyPaths => _ColumnEncryptionTrustedMasterKeyPaths;
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ctorConnectionString/*' />
public SqlConnection(string connectionString) : this()
{
ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ctorConnectionStringCredential/*' />
public SqlConnection(string connectionString, SqlCredential credential) : this()
{
ConnectionString = connectionString;
if (credential != null)
{
// The following checks are necessary as setting Credential property will call CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential it will throw InvalidOperationException rather than ArgumentException
// 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 (UsesActiveDirectoryIntegrated(connectionOptions))
{
throw SQL.SettingCredentialWithIntegratedArgument();
}
if (UsesActiveDirectoryInteractive(connectionOptions))
{
throw SQL.SettingCredentialWithInteractiveArgument();
}
if (UsesActiveDirectoryDeviceCodeFlow(connectionOptions))
{
throw SQL.SettingCredentialWithDeviceFlowArgument();
}
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"
}
private SqlConnection(SqlConnection connection)
{
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();
}
/// <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>();
}
/// <summary>
/// Is this connection using column encryption ?
/// </summary>
internal bool IsColumnEncryptionSettingEnabled
{
get
{
SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
return opt?.ColumnEncryptionSetting == SqlConnectionColumnEncryptionSetting.Enabled;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/RegisterColumnEncryptionKeyStoreProviders/*' />
public static 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>
/// Get enclave attestation url to be used with enclave based Always Encrypted
/// </summary>
internal string EnclaveAttestationUrl => ((SqlConnectionString)ConnectionOptions).EnclaveAttestationUrl;
/// <summary>
/// Get attestation protocol
/// </summary>
internal SqlConnectionAttestationProtocol AttestationProtocol
{
get
{
SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
return opt.AttestationProtocol;
}
}
// 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;
// For Azure SQL connection, set _connectRetryCount to 2 instead of 1 will greatly improve recovery
// success rate
if (_connectRetryCount == 1 && ADP.IsAzureSqlServerEndpoint(connString.DataSource))
{
_connectRetryCount = 2;
}
}
}
//
// PUBLIC PROPERTIES
//
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/StatisticsEnabled/*' />
// 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.
public bool StatisticsEnabled
{
get
{
return (_collectstats);
}
set
{
{
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);
}
}
}
_collectstats = value;
}
}
}
internal bool AsyncCommandInProgress
{
get => _AsyncCommandInProgress;
set => _AsyncCommandInProgress = value;
}
private bool UsesActiveDirectoryIntegrated(SqlConnectionString opt)
{
return opt != null ? opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated : false;
}
private bool UsesActiveDirectoryInteractive(SqlConnectionString opt)
{
return opt != null ? opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive : false;
}
private bool UsesActiveDirectoryDeviceCodeFlow(SqlConnectionString opt)
{
return opt != null ? opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow : false;
}
private bool UsesAuthentication(SqlConnectionString opt)
{
return opt != null ? opt.Authentication != SqlAuthenticationMethod.NotSpecified : false;
}
// Does this connection use Integrated Security?
private bool UsesIntegratedSecurity(SqlConnectionString opt)
{
return opt != null ? opt.IntegratedSecurity : false;
}
// Does this connection use old style of clear userID or Password in connection string?
private bool UsesClearUserIdOrPassword(SqlConnectionString opt)
{
bool result = false;
if (null != opt)
{
result = (!string.IsNullOrEmpty(opt.UserID) || !string.IsNullOrEmpty(opt.Password));
}
return result;
}
internal SqlConnectionString.TransactionBindingEnum TransactionBinding
{
get => ((SqlConnectionString)ConnectionOptions).TransactionBinding;
}
internal SqlConnectionString.TypeSystem TypeSystem
{
get => ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
}
internal Version TypeSystemAssemblyVersion
{
get => ((SqlConnectionString)ConnectionOptions).TypeSystemAssemblyVersion;
}
internal int ConnectRetryInterval
{
get => ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ConnectionString/*' />
public override 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/ActiveDirectoryInteractive/ActiveDirectoryDeviceCodeFlow. 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();
}
else if (UsesActiveDirectoryInteractive(connectionOptions))
{
throw SQL.SettingInteractiveWithCredential();
}
else if (UsesActiveDirectoryDeviceCodeFlow(connectionOptions))
{
throw SQL.SettingDeviceFlowWithCredential();
}
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();
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ConnectionTimeout/*' />
public override int ConnectionTimeout
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/CommandTimeout/*' />
public int CommandTimeout
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.CommandTimeout : SqlConnectionString.DEFAULT.Command_Timeout);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/AccessToken/*' />
// AccessToken: To be used for token based authentication
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;
return InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo ? null : _accessToken;
}
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);
}
// Need to call ConnectionString_Set to do proper pool group check
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, credential: _credential, accessToken: value));
_accessToken = value;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/Database/*' />
public override 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;
}
}
///
/// To indicate the IsSupported flag sent by the server for DNS Caching. This property is for internal testing only.
///
internal string SQLDNSCachingSupportedState
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
string result;
if (null != innerConnection)
{
result = innerConnection.IsSQLDNSCachingSupported ? "true" : "false";
}
else
{
result = "innerConnection is null!";
}
return result;
}
}
///
/// To indicate the IsSupported flag sent by the server for DNS Caching before redirection. This property is for internal testing only.
///
internal string SQLDNSCachingSupportedStateBeforeRedirect
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
string result;
if (null != innerConnection)
{
result = innerConnection.IsDNSCachingBeforeRedirectSupported ? "true" : "false";
}
else
{
result = "innerConnection is null!";
}
return result;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/DataSource/*' />
public override 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;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="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
{
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;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ClientConnectionId/*' />
public Guid ClientConnectionId
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null != innerConnection)
{
return innerConnection.ClientConnectionId;
}
else
{
Task reconnectTask = _currentReconnectionTask;
// Connection closed but previously open should return the correct ClientConnectionId
DbConnectionClosedPreviouslyOpened innerConnectionClosed = (InnerConnection as DbConnectionClosedPreviouslyOpened);
if ((reconnectTask != null && !reconnectTask.IsCompleted) || null != innerConnectionClosed)
{
return _originalConnectionId;
}
return Guid.Empty;
}
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ServerVersion/*' />
public override string ServerVersion
{
get => GetOpenTdsConnection().ServerVersion;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ServerProcessId/*' />
public int ServerProcessId
{
get => State.Equals(ConnectionState.Open) | State.Equals(ConnectionState.Executing) | State.Equals(ConnectionState.Fetching) ?
GetOpenTdsConnection().ServerProcessId : 0;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/State/*' />
public override ConnectionState State
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return ConnectionState.Open;
}
return InnerConnection.State;
}
}
internal SqlStatistics Statistics
{
get => _statistics;
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/WorkstationId/*' />
public string WorkstationId
{
get
{
// 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 = constr?.WorkstationId ?? Environment.MachineName;
return result;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="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(nameof(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/ActiveDirectoryInteractive. 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();
}
else if (UsesActiveDirectoryInteractive((SqlConnectionString)ConnectionOptions))
{
throw SQL.SettingCredentialWithInteractiveInvalid();
}
else if (UsesActiveDirectoryDeviceCodeFlow((SqlConnectionString)ConnectionOptions))
{
throw SQL.SettingCredentialWithDeviceFlowInvalid();
}
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 used in the setter of ConnectionString and Credential properties.
private void CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(SqlConnectionString connectionOptions)
{
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureAndClearCredential();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity();
}
}
// 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 (UsesAuthentication(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndAuthentication();
}
// Check if the usage of AccessToken has the conflict with credential
if (_credential != null)
{
throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/DbProviderFactory/*' />
protected override DbProviderFactory DbProviderFactory
{
get => SqlClientFactory.Instance;
}
// SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
//
// PUBLIC EVENTS
//
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/InfoMessage/*' />
public event SqlInfoMessageEventHandler InfoMessage;
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/FireInfoMessageEventOnUserErrors/*' />
public bool FireInfoMessageEventOnUserErrors
{
get => _fireInfoMessageEventOnUserErrors;
set => _fireInfoMessageEventOnUserErrors = value;
}
// Approx. number of times that the internal connection has been reconnected
internal int ReconnectCount
{
get => _reconnectCount;
}
internal bool ForceNewConnection { get; set; }
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/OnStateChange/*' />
protected override void OnStateChange(StateChangeEventArgs stateChange)
{
if (!_suppressStateChangeForReconnection)
{
base.OnStateChange(stateChange);
}
}
//
// PUBLIC METHODS
//
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransaction2/*' />
new public SqlTransaction BeginTransaction()
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(System.Data.IsolationLevel.Unspecified, null);
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransactionIso/*' />
new public SqlTransaction BeginTransaction(System.Data.IsolationLevel iso)
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(iso, null);
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransactionTransactionName/*' />
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(System.Data.IsolationLevel.Unspecified, transactionName);
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginDbTransaction/*' />
[SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
override protected DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel)
{
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<prov.SqlConnection.BeginDbTransaction|API> {0}, isolationLevel={1}", ObjectID, (int)isolationLevel);
try
{
DbTransaction transaction = BeginTransaction(isolationLevel);
// 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
{
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransactionIsoTransactionName/*' />
public SqlTransaction BeginTransaction(System.Data.IsolationLevel iso, string transactionName)
{
WaitForPendingReconnection();
SqlStatistics statistics = null;
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<sc.SqlConnection.BeginTransaction|API> {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, transactionName);
try
{
statistics = SqlStatistics.StartTimer(Statistics);
SqlTransaction transaction;
bool isFirstAttempt = true;
do
{
transaction = GetOpenTdsConnection().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);
// 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
{
SqlStatistics.StopTimer(statistics);
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ChangeDatabase/*' />
public override void ChangeDatabase(string database)
{
SqlStatistics statistics = null;
RepairInnerConnection();
SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlConnection.ChangeDatabase|API|Correlation> ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current);
try
{
statistics = SqlStatistics.StartTimer(Statistics);
InnerConnection.ChangeDatabase(database);
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ClearAllPools/*' />
public static void ClearAllPools()
{
SqlConnectionFactory.SingletonInstance.ClearAllPools();
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ClearPool/*' />
public static void ClearPool(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
if (null != connectionOptions)
{
SqlConnectionFactory.SingletonInstance.ClearPool(connection);
}
}
private void CloseInnerConnection()