1 //------------------------------------------------------------------------------
2 // <copyright file="SqlUtil.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // <owner current="true" primary="true">[....]</owner>
6 // <owner current="true" primary="false">[....]</owner>
7 //------------------------------------------------------------------------------
9 namespace System.Data.SqlClient {
11 using System.Collections.Generic;
12 using System.ComponentModel;
14 using System.Data.Common;
15 using System.Diagnostics;
16 using System.Globalization;
18 using System.Reflection;
19 using System.Runtime.Serialization.Formatters;
20 using System.Security;
21 using System.Security.Permissions;
22 using System.Security.Principal;
23 using System.Threading;
25 using SysTx = System.Transactions;
26 using System.Runtime.Versioning;
27 using System.Threading.Tasks;
28 using System.Runtime.CompilerServices;
29 using System.Runtime.ExceptionServices;
31 static internal class AsyncHelper {
33 internal static Task CreateContinuationTask(Task task, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) {
39 TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
40 ContinueTask(task, completion,
41 () => { onSuccess(); completion.SetResult(null); },
42 connectionToDoom, onFailure);
43 return completion.Task;
47 internal static Task CreateContinuationTask<T1, T2>(Task task, Action<T1, T2> onSuccess, T1 arg1, T2 arg2, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) {
48 return CreateContinuationTask(task, () => onSuccess(arg1, arg2), connectionToDoom, onFailure);
51 internal static void ContinueTask(Task task,
52 TaskCompletionSource<object> completion,
54 SqlInternalConnectionTds connectionToDoom = null,
55 Action<Exception> onFailure = null,
56 Action onCancellation = null,
57 Func<Exception, Exception> exceptionConverter = null,
58 SqlConnection connectionToAbort = null
60 Debug.Assert((connectionToAbort == null) || (connectionToDoom == null), "Should not specify both connectionToDoom and connectionToAbort");
63 if (tsk.Exception != null) {
64 Exception exc = tsk.Exception.InnerException;
65 if (exceptionConverter != null) {
66 exc = exceptionConverter(exc);
69 if (onFailure != null) {
74 completion.TrySetException(exc);
77 else if (tsk.IsCanceled) {
79 if (onCancellation != null) {
84 completion.TrySetCanceled();
88 if (connectionToDoom != null || connectionToAbort!=null) {
89 RuntimeHelpers.PrepareConstrainedRegions();
92 TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
93 RuntimeHelpers.PrepareConstrainedRegions();
95 tdsReliabilitySection.Start();
101 tdsReliabilitySection.Stop();
105 catch (System.OutOfMemoryException e) {
106 if (connectionToDoom != null) {
107 connectionToDoom.DoomThisConnection();
110 connectionToAbort.Abort(e);
112 completion.SetException(e);
115 catch (System.StackOverflowException e) {
116 if (connectionToDoom != null) {
117 connectionToDoom.DoomThisConnection();
120 connectionToAbort.Abort(e);
122 completion.SetException(e);
125 catch (System.Threading.ThreadAbortException e) {
126 if (connectionToDoom != null) {
127 connectionToDoom.DoomThisConnection();
130 connectionToAbort.Abort(e);
132 completion.SetException(e);
135 catch (Exception e) {
136 completion.SetException(e);
139 else { // no connection to doom - reliability section not required
143 catch (Exception e) {
144 completion.SetException(e);
148 }, TaskScheduler.Default
153 internal static void WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions=true) {
155 task.Wait(timeout > 0 ? (1000 * timeout) : Timeout.Infinite);
157 catch (AggregateException ae) {
158 if (rethrowExceptions) {
159 Debug.Assert(ae.InnerExceptions.Count == 1, "There is more than one exception in AggregateException");
160 ExceptionDispatchInfo.Capture(ae.InnerException).Throw();
163 if (!task.IsCompleted) {
164 if (onTimeout != null) {
170 internal static void SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken) {
172 Task.Delay(timeout * 1000, ctoken).ContinueWith((tsk) => {
173 if (!tsk.IsCanceled && !completion.Task.IsCompleted) {
174 completion.TrySetException(exc());
181 sealed internal class InOutOfProcHelper {
182 private static readonly InOutOfProcHelper SingletonInstance = new InOutOfProcHelper();
184 private bool _inProc = false;
186 // InOutOfProcHelper detects whether it's running inside the server or not. It does this
187 // by checking for the existence of a well-known function export on the current process.
188 // Note that calling conventions, etc. do not matter -- we'll never call the function, so
189 // only the name match or lack thereof matter.
190 [ResourceExposure(ResourceScope.None)]
191 [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
192 private InOutOfProcHelper() {
194 // Don't need to close this handle...
195 // SxS: we use this method to check if we are running inside the SQL Server process. This call should be safe in SxS environment.
196 IntPtr handle = SafeNativeMethods.GetModuleHandle(null);
197 if (IntPtr.Zero != handle) {
198 // SQLBU 359301: Currently, the server exports different names for x86 vs. AMD64 and IA64. Supporting both names
199 // for now gives the server time to unify names across platforms without breaking currently-working ones.
200 // We can remove the obsolete name once the server is changed.
201 if (IntPtr.Zero != SafeNativeMethods.GetProcAddress(handle, "_______SQL______Process______Available@0")) {
204 else if (IntPtr.Zero != SafeNativeMethods.GetProcAddress(handle, "______SQL______Process______Available")) {
211 internal static bool InProc {
213 return SingletonInstance._inProc;
218 static internal class SQL {
219 // The class SQL defines the exceptions that are specific to the SQL Adapter.
220 // The class contains functions that take the proper informational variables and then construct
221 // the appropriate exception with an error string obtained from the resource Framework.txt.
222 // The exception is then returned to the caller, so that the caller may then throw from its
223 // location so that the catcher of the exception will have the appropriate call stack.
224 // This class is used so that there will be compile time checking of error
225 // messages. The resource Framework.txt will ensure proper string text based on the appropriate
229 // SQL specific exceptions
236 static internal Exception CannotGetDTCAddress() {
237 return ADP.InvalidOperation(Res.GetString(Res.SQL_CannotGetDTCAddress));
240 static internal Exception InvalidOptionLength(string key) {
241 return ADP.Argument(Res.GetString(Res.SQL_InvalidOptionLength, key));
243 static internal Exception InvalidInternalPacketSize (string str) {
244 return ADP.ArgumentOutOfRange (str);
246 static internal Exception InvalidPacketSize() {
247 return ADP.ArgumentOutOfRange (Res.GetString(Res.SQL_InvalidTDSPacketSize));
249 static internal Exception InvalidPacketSizeValue() {
250 return ADP.Argument(Res.GetString(Res.SQL_InvalidPacketSizeValue));
252 static internal Exception InvalidSSPIPacketSize() {
253 return ADP.Argument(Res.GetString(Res.SQL_InvalidSSPIPacketSize));
255 static internal Exception NullEmptyTransactionName() {
256 return ADP.Argument(Res.GetString(Res.SQL_NullEmptyTransactionName));
258 static internal Exception SnapshotNotSupported(IsolationLevel level) {
259 return ADP.Argument(Res.GetString(Res.SQL_SnapshotNotSupported, typeof(IsolationLevel), level.ToString()));
261 static internal Exception UserInstanceFailoverNotCompatible() {
262 return ADP.Argument(Res.GetString(Res.SQL_UserInstanceFailoverNotCompatible));
264 static internal Exception CredentialsNotProvided(SqlAuthenticationMethod auth) {
265 return ADP.InvalidOperation(Res.GetString(Res.SQL_CredentialsNotProvided, DbConnectionStringBuilderUtil.AuthenticationTypeToString(auth)));
267 static internal Exception AuthenticationAndIntegratedSecurity() {
268 return ADP.Argument(Res.GetString(Res.SQL_AuthenticationAndIntegratedSecurity));
270 static internal Exception IntegratedWithUserIDAndPassword() {
271 return ADP.Argument(Res.GetString(Res.SQL_IntegratedWithUserIDAndPassword));
273 static internal Exception SettingIntegratedWithCredential() {
274 return ADP.InvalidOperation(Res.GetString(Res.SQL_SettingIntegratedWithCredential));
276 static internal Exception SettingCredentialWithIntegratedArgument() {
277 return ADP.Argument(Res.GetString(Res.SQL_SettingCredentialWithIntegrated));
279 static internal Exception SettingCredentialWithIntegratedInvalid() {
280 return ADP.InvalidOperation(Res.GetString(Res.SQL_SettingCredentialWithIntegrated));
282 static internal Exception InvalidSQLServerVersionUnknown() {
283 return ADP.DataAdapter(Res.GetString(Res.SQL_InvalidSQLServerVersionUnknown));
285 static internal Exception SynchronousCallMayNotPend() {
286 return new Exception(Res.GetString(Res.Sql_InternalError));
288 static internal Exception ConnectionLockedForBcpEvent() {
289 return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionLockedForBcpEvent));
291 static internal Exception AsyncConnectionRequired() {
292 return ADP.InvalidOperation(Res.GetString(Res.SQL_AsyncConnectionRequired));
294 static internal Exception FatalTimeout() {
295 return ADP.InvalidOperation(Res.GetString(Res.SQL_FatalTimeout));
297 static internal Exception InstanceFailure() {
298 return ADP.InvalidOperation(Res.GetString(Res.SQL_InstanceFailure));
300 static internal Exception ChangePasswordArgumentMissing(string argumentName) {
301 return ADP.ArgumentNull(Res.GetString(Res.SQL_ChangePasswordArgumentMissing, argumentName));
303 static internal Exception ChangePasswordConflictsWithSSPI() {
304 return ADP.Argument(Res.GetString(Res.SQL_ChangePasswordConflictsWithSSPI));
306 static internal Exception ChangePasswordRequiresYukon() {
307 return ADP.InvalidOperation(Res.GetString(Res.SQL_ChangePasswordRequiresYukon));
309 static internal Exception UnknownSysTxIsolationLevel(SysTx.IsolationLevel isolationLevel) {
310 return ADP.InvalidOperation(Res.GetString(Res.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString()));
312 static internal Exception ChangePasswordUseOfUnallowedKey (string key) {
313 return ADP.InvalidOperation(Res.GetString(Res.SQL_ChangePasswordUseOfUnallowedKey, key));
315 static internal Exception InvalidPartnerConfiguration (string server, string database) {
316 return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidPartnerConfiguration, server, database));
318 static internal Exception BatchedUpdateColumnEncryptionSettingMismatch () {
319 return ADP.InvalidOperation(Res.GetString(Res.TCE_BatchedUpdateColumnEncryptionSettingMismatch, "SqlCommandColumnEncryptionSetting", "SelectCommand", "InsertCommand", "UpdateCommand", "DeleteCommand"));
321 static internal Exception MARSUnspportedOnConnection() {
322 return ADP.InvalidOperation(Res.GetString(Res.SQL_MarsUnsupportedOnConnection));
325 static internal Exception CannotModifyPropertyAsyncOperationInProgress(string property) {
326 return ADP.InvalidOperation(Res.GetString(Res.SQL_CannotModifyPropertyAsyncOperationInProgress, property));
328 static internal Exception NonLocalSSEInstance() {
329 return ADP.NotSupported(Res.GetString(Res.SQL_NonLocalSSEInstance));
334 static internal Exception NotificationsRequireYukon() {
335 return ADP.NotSupported(Res.GetString(Res.SQL_NotificationsRequireYukon));
338 static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value) {
339 return ADP.ArgumentOutOfRange(Res.GetString(Res.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
342 static internal ArgumentOutOfRangeException NotSupportedCommandType(CommandType value) {
345 case CommandType.Text:
346 case CommandType.StoredProcedure:
347 Debug.Assert(false, "valid CommandType " + value.ToString());
349 case CommandType.TableDirect:
352 Debug.Assert(false, "invalid CommandType " + value.ToString());
356 return NotSupportedEnumerationValue(typeof(CommandType), (int)value);
358 static internal ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value) {
361 case IsolationLevel.Unspecified:
362 case IsolationLevel.ReadCommitted:
363 case IsolationLevel.ReadUncommitted:
364 case IsolationLevel.RepeatableRead:
365 case IsolationLevel.Serializable:
366 case IsolationLevel.Snapshot:
367 Debug.Assert(false, "valid IsolationLevel " + value.ToString());
369 case IsolationLevel.Chaos:
372 Debug.Assert(false, "invalid IsolationLevel " + value.ToString());
376 return NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value);
379 static internal Exception OperationCancelled() {
380 Exception exception = ADP.InvalidOperation(Res.GetString(Res.SQL_OperationCancelled));
384 static internal Exception PendingBeginXXXExists() {
385 return ADP.InvalidOperation(Res.GetString(Res.SQL_PendingBeginXXXExists));
388 static internal ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param) {
389 return ADP.ArgumentOutOfRange(Res.GetString(Res.SqlDependency_InvalidTimeout), param);
392 static internal Exception NonXmlResult() {
393 return ADP.InvalidOperation(Res.GetString(Res.SQL_NonXmlResult));
399 static internal Exception InvalidUdt3PartNameFormat() {
400 return ADP.Argument(Res.GetString(Res.SQL_InvalidUdt3PartNameFormat));
402 static internal Exception InvalidParameterTypeNameFormat() {
403 return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterTypeNameFormat));
405 static internal Exception InvalidParameterNameLength(string value) {
406 return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterNameLength, value));
408 static internal Exception PrecisionValueOutOfRange(byte precision) {
409 return ADP.Argument(Res.GetString(Res.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture)));
411 static internal Exception ScaleValueOutOfRange(byte scale) {
412 return ADP.Argument(Res.GetString(Res.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
414 static internal Exception TimeScaleValueOutOfRange(byte scale) {
415 return ADP.Argument(Res.GetString(Res.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
417 static internal Exception InvalidSqlDbType(SqlDbType value) {
418 return ADP.InvalidEnumerationValue(typeof(SqlDbType), (int) value);
420 static internal Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName) {
421 return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnsupportedTVPOutputParameter,
422 direction.ToString(), paramName));
424 static internal Exception DBNullNotSupportedForTVPValues(string paramName) {
425 return ADP.NotSupported(Res.GetString(Res.SqlParameter_DBNullNotSupportedForTVP, paramName));
427 static internal Exception InvalidTableDerivedPrecisionForTvp(string columnName, byte precision) {
428 return ADP.InvalidOperation(Res.GetString(Res.SqlParameter_InvalidTableDerivedPrecisionForTvp, precision, columnName, System.Data.SqlTypes.SqlDecimal.MaxPrecision));
430 static internal Exception UnexpectedTypeNameForNonStructParams(string paramName) {
431 return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnexpectedTypeNameForNonStruct, paramName));
433 static internal Exception SingleValuedStructNotSupported() {
434 return ADP.NotSupported(Res.GetString(Res.MetaType_SingleValuedStructNotSupported));
436 static internal Exception ParameterInvalidVariant(string paramName) {
437 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParameterInvalidVariant, paramName));
440 static internal Exception MustSetTypeNameForParam(string paramType, string paramName) {
441 return ADP.Argument(Res.GetString(Res.SQL_ParameterTypeNameRequired, paramType, paramName));
443 static internal Exception NullSchemaTableDataTypeNotSupported(string columnName) {
444 return ADP.Argument(Res.GetString(Res.NullSchemaTableDataTypeNotSupported, columnName));
446 static internal Exception InvalidSchemaTableOrdinals() {
447 return ADP.Argument(Res.GetString(Res.InvalidSchemaTableOrdinals));
449 static internal Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber) {
450 return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber));
452 static internal Exception EnumeratedRecordFieldCountChanged(int recordNumber) {
453 return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordFieldCountChanged, recordNumber));
457 // SQL.SqlDataAdapter
463 static internal Exception InvalidTDSVersion() {
464 return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidTDSVersion));
466 static internal Exception ParsingError(ParsingErrorState state) {
467 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)));
469 static internal Exception ParsingError(ParsingErrorState state, Exception innerException) {
470 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)), innerException);
472 static internal Exception ParsingErrorValue(ParsingErrorState state, int value) {
473 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorValue, ((int)state).ToString(CultureInfo.InvariantCulture), value));
475 static internal Exception ParsingErrorOffset(ParsingErrorState state, int offset) {
476 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorOffset, ((int)state).ToString(CultureInfo.InvariantCulture), offset));
478 static internal Exception ParsingErrorFeatureId(ParsingErrorState state, int featureId) {
479 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorFeatureId, ((int)state).ToString(CultureInfo.InvariantCulture), featureId));
481 static internal Exception ParsingErrorToken(ParsingErrorState state, int token) {
482 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorToken, ((int)state).ToString(CultureInfo.InvariantCulture), token));
484 static internal Exception ParsingErrorLength(ParsingErrorState state, int length) {
485 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorLength, ((int)state).ToString(CultureInfo.InvariantCulture), length));
487 static internal Exception ParsingErrorStatus(ParsingErrorState state, int status) {
488 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorStatus, ((int)state).ToString(CultureInfo.InvariantCulture), status));
490 static internal Exception ParsingErrorLibraryType(ParsingErrorState state, int libraryType) {
491 return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorAuthLibraryType, ((int)state).ToString(CultureInfo.InvariantCulture), libraryType));
494 static internal Exception MoneyOverflow(string moneyValue) {
495 return ADP.Overflow(Res.GetString(Res.SQL_MoneyOverflow, moneyValue));
497 static internal Exception SmallDateTimeOverflow(string datetime) {
498 return ADP.Overflow(Res.GetString(Res.SQL_SmallDateTimeOverflow, datetime));
500 static internal Exception SNIPacketAllocationFailure() {
501 return ADP.InvalidOperation(Res.GetString(Res.SQL_SNIPacketAllocationFailure));
503 static internal Exception TimeOverflow(string time) {
504 return ADP.Overflow(Res.GetString(Res.SQL_TimeOverflow, time));
510 static internal Exception InvalidRead() {
511 return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidRead));
514 static internal Exception NonBlobColumn(string columnName) {
515 return ADP.InvalidCast(Res.GetString(Res.SQL_NonBlobColumn, columnName));
518 static internal Exception NonCharColumn(string columnName) {
519 return ADP.InvalidCast(Res.GetString(Res.SQL_NonCharColumn, columnName));
522 static internal Exception StreamNotSupportOnColumnType(string columnName) {
523 return ADP.InvalidCast(Res.GetString(Res.SQL_StreamNotSupportOnColumnType, columnName));
526 static internal Exception StreamNotSupportOnEncryptedColumn(string columnName) {
527 return ADP.InvalidOperation(Res.GetString(Res.TCE_StreamNotSupportOnEncryptedColumn, columnName, "Stream"));
530 static internal Exception SequentialAccessNotSupportedOnEncryptedColumn(string columnName) {
531 return ADP.InvalidOperation(Res.GetString(Res.TCE_SequentialAccessNotSupportedOnEncryptedColumn, columnName, "CommandBehavior=SequentialAccess"));
534 static internal Exception TextReaderNotSupportOnColumnType(string columnName) {
535 return ADP.InvalidCast(Res.GetString(Res.SQL_TextReaderNotSupportOnColumnType, columnName));
538 static internal Exception XmlReaderNotSupportOnColumnType(string columnName) {
539 return ADP.InvalidCast(Res.GetString(Res.SQL_XmlReaderNotSupportOnColumnType, columnName));
542 static internal Exception UDTUnexpectedResult(string exceptionText){
543 return ADP.TypeLoad(Res.GetString(Res.SQLUDT_Unexpected,exceptionText));
548 // SQL.SqlDelegatedTransaction
550 static internal Exception CannotCompleteDelegatedTransactionWithOpenResults(SqlInternalConnectionTds internalConnection) {
551 SqlErrorCollection errors = new SqlErrorCollection();
552 errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, (Res.GetString(Res.ADP_OpenReaderExists)), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
553 return SqlException.CreateException(errors, null, internalConnection);
555 static internal SysTx.TransactionPromotionException PromotionFailed(Exception inner) {
556 SysTx.TransactionPromotionException e = new SysTx.TransactionPromotionException(Res.GetString(Res.SqlDelegatedTransaction_PromotionFailed), inner);
557 ADP.TraceExceptionAsReturnValue(e);
564 static internal Exception SqlCommandHasExistingSqlNotificationRequest(){
565 return ADP.InvalidOperation(Res.GetString(Res.SQLNotify_AlreadyHasCommand));
568 static internal Exception SqlDepCannotBeCreatedInProc() {
569 return ADP.InvalidOperation(Res.GetString(Res.SqlNotify_SqlDepCannotBeCreatedInProc));
572 static internal Exception SqlDepDefaultOptionsButNoStart() {
573 return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DefaultOptionsButNoStart));
576 static internal Exception SqlDependencyDatabaseBrokerDisabled() {
577 return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DatabaseBrokerDisabled));
580 static internal Exception SqlDependencyEventNoDuplicate() {
581 return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_EventNoDuplicate));
584 static internal Exception SqlDependencyDuplicateStart() {
585 return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DuplicateStart));
588 static internal Exception SqlDependencyIdMismatch() {
589 // do not include the id because it may require SecurityPermission(Infrastructure) permission
590 return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_IdMismatch));
593 static internal Exception SqlDependencyNoMatchingServerStart() {
594 return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_NoMatchingServerStart));
597 static internal Exception SqlDependencyNoMatchingServerDatabaseStart() {
598 return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_NoMatchingServerDatabaseStart));
601 static internal Exception SqlNotificationException(SqlNotificationEventArgs notify){
602 return ADP.InvalidOperation(Res.GetString(Res.SQLNotify_ErrorFormat, notify.Type,notify.Info,notify.Source));
608 static internal Exception SqlMetaDataNoMetaData(){
609 return ADP.InvalidOperation(Res.GetString(Res.SqlMetaData_NoMetadata));
612 static internal Exception MustSetUdtTypeNameForUdtParams(){
613 return ADP.Argument(Res.GetString(Res.SQLUDT_InvalidUdtTypeName));
616 static internal Exception UnexpectedUdtTypeNameForNonUdtParams(){
617 return ADP.Argument(Res.GetString(Res.SQLUDT_UnexpectedUdtTypeName));
620 static internal Exception UDTInvalidSqlType(string typeName){
621 return ADP.Argument(Res.GetString(Res.SQLUDT_InvalidSqlType, typeName));
624 static internal Exception InvalidSqlDbTypeForConstructor(SqlDbType type) {
625 return ADP.Argument(Res.GetString(Res.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString()));
628 static internal Exception NameTooLong(string parameterName) {
629 return ADP.Argument(Res.GetString(Res.SqlMetaData_NameTooLong), parameterName);
632 static internal Exception InvalidSortOrder(SortOrder order) {
633 return ADP.InvalidEnumerationValue(typeof(SortOrder), (int)order);
636 static internal Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal) {
637 return ADP.InvalidOperation(Res.GetString(Res.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal));
640 static internal Exception TableTypeCanOnlyBeParameter() {
641 return ADP.Argument(Res.GetString(Res.SQLTVP_TableTypeCanOnlyBeParameter));
643 static internal Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName) {
644 return ADP.Argument(Res.GetString(Res.SqlProvider_InvalidDataColumnType, columnName, typeName));
646 static internal Exception InvalidColumnMaxLength(string columnName, long maxLength) {
647 return ADP.Argument(Res.GetString(Res.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength));
649 static internal Exception InvalidColumnPrecScale() {
650 return ADP.Argument(Res.GetString(Res.SqlMisc_InvalidPrecScaleMessage));
652 static internal Exception NotEnoughColumnsInStructuredType() {
653 return ADP.Argument(Res.GetString(Res.SqlProvider_NotEnoughColumnsInStructuredType));
655 static internal Exception DuplicateSortOrdinal(int sortOrdinal) {
656 return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_DuplicateSortOrdinal, sortOrdinal));
658 static internal Exception MissingSortOrdinal(int sortOrdinal) {
659 return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_MissingSortOrdinal, sortOrdinal));
661 static internal Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal) {
662 return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal));
664 static internal Exception IEnumerableOfSqlDataRecordHasNoRows() {
665 return ADP.Argument(Res.GetString(Res.IEnumerableOfSqlDataRecordHasNoRows));
673 static internal Exception SqlPipeCommandHookedUpToNonContextConnection() {
674 return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_CommandHookedUpToNonContextConnection));
677 static internal Exception SqlPipeMessageTooLong( int messageLength ) {
678 return ADP.Argument(Res.GetString(Res.SqlPipe_MessageTooLong, messageLength));
681 static internal Exception SqlPipeIsBusy() {
682 return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_IsBusy));
685 static internal Exception SqlPipeAlreadyHasAnOpenResultSet( string methodName ) {
686 return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_AlreadyHasAnOpenResultSet, methodName));
689 static internal Exception SqlPipeDoesNotHaveAnOpenResultSet( string methodName ) {
690 return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_DoesNotHaveAnOpenResultSet, methodName));
696 static internal Exception SqlResultSetClosed(string methodname) {
697 if (methodname == null) {
698 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetClosed2));
700 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetClosed, methodname));
702 static internal Exception SqlResultSetNoData(string methodname) {
703 return ADP.InvalidOperation(Res.GetString(Res.ADP_DataReaderNoData, methodname));
705 static internal Exception SqlRecordReadOnly(string methodname) {
706 if (methodname == null) {
707 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlRecordReadOnly2));
709 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlRecordReadOnly, methodname));
712 static internal Exception SqlResultSetRowDeleted(string methodname) {
713 if (methodname == null) {
714 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetRowDeleted2));
716 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetRowDeleted, methodname));
719 static internal Exception SqlResultSetCommandNotInSameConnection() {
720 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetCommandNotInSameConnection));
723 static internal Exception SqlResultSetNoAcceptableCursor() {
724 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetNoAcceptableCursor));
730 static internal Exception BulkLoadMappingInaccessible() {
731 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingInaccessible));
733 static internal Exception BulkLoadMappingsNamesOrOrdinalsOnly() {
734 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingsNamesOrOrdinalsOnly));
737 static internal Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, Exception e) {
738 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadCannotConvertValue, sourcetype.Name, metatype.TypeName), e);
741 static internal Exception BulkLoadNonMatchingColumnMapping() {
742 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnMapping));
744 static internal Exception BulkLoadNonMatchingColumnName(string columnName) {
745 return BulkLoadNonMatchingColumnName(columnName, null);
747 static internal Exception BulkLoadNonMatchingColumnName(string columnName, Exception e) {
748 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnName, columnName), e);
750 static internal Exception BulkLoadStringTooLong() {
751 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadStringTooLong));
753 static internal Exception BulkLoadInvalidVariantValue() {
754 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidVariantValue));
756 static internal Exception BulkLoadInvalidTimeout(int timeout) {
757 return ADP.Argument(Res.GetString(Res.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture)));
759 static internal Exception BulkLoadExistingTransaction() {
760 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadExistingTransaction));
762 static internal Exception BulkLoadNoCollation() {
763 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNoCollation));
765 static internal Exception BulkLoadConflictingTransactionOption() {
766 return ADP.Argument(Res.GetString(Res.SQL_BulkLoadConflictingTransactionOption));
768 static internal Exception BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName) {
769 return ADP.InvalidOperation (Res.GetString (Res.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName));
771 static internal Exception InvalidOperationInsideEvent() {
772 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidOperationInsideEvent));
774 static internal Exception BulkLoadMissingDestinationTable() {
775 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMissingDestinationTable));
777 static internal Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner) {
778 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidDestinationTable, tableName), inner);
780 static internal Exception BulkLoadBulkLoadNotAllowDBNull(string columnName) {
781 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNotAllowDBNull, columnName));
783 static internal Exception BulkLoadPendingOperation() {
784 return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadPendingOperation));
788 // TCE - Certificate Store Provider Errors.
790 static internal Exception InvalidKeyEncryptionAlgorithm(string encryptionAlgorithm, string validEncryptionAlgorithm, bool isSystemOp) {
792 return ADP.Argument(Res.GetString(Res.TCE_InvalidKeyEncryptionAlgorithmSysErr, encryptionAlgorithm, validEncryptionAlgorithm), TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM);
795 return ADP.Argument(Res.GetString(Res.TCE_InvalidKeyEncryptionAlgorithm, encryptionAlgorithm, validEncryptionAlgorithm), TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM);
799 static internal Exception NullKeyEncryptionAlgorithm(bool isSystemOp) {
801 return ADP.ArgumentNull (TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, Res.GetString(Res.TCE_NullKeyEncryptionAlgorithmSysErr));
804 return ADP.ArgumentNull (TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, Res.GetString(Res.TCE_NullKeyEncryptionAlgorithm));
808 static internal Exception EmptyColumnEncryptionKey() {
809 return ADP.Argument(Res.GetString(Res.TCE_EmptyColumnEncryptionKey), TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY);
812 static internal Exception NullColumnEncryptionKey() {
813 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY, Res.GetString(Res.TCE_NullColumnEncryptionKey));
816 static internal Exception EmptyEncryptedColumnEncryptionKey() {
817 return ADP.Argument(Res.GetString(Res.TCE_EmptyEncryptedColumnEncryptionKey), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
820 static internal Exception NullEncryptedColumnEncryptionKey() {
821 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTED_CEK, Res.GetString(Res.TCE_NullEncryptedColumnEncryptionKey));
824 static internal Exception LargeCertificatePathLength(int actualLength, int maxLength, bool isSystemOp) {
826 return ADP.Argument(Res.GetString(Res.TCE_LargeCertificatePathLengthSysErr, actualLength, maxLength), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
829 return ADP.Argument(Res.GetString(Res.TCE_LargeCertificatePathLength, actualLength, maxLength), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
833 static internal Exception NullCertificatePath(string[] validLocations, bool isSystemOp) {
834 Debug.Assert(2 == validLocations.Length);
836 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCertificatePathSysErr, validLocations[0], validLocations[1], @"/"));
839 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCertificatePath, validLocations[0], validLocations[1], @"/"));
843 static internal Exception NullCspKeyPath(bool isSystemOp) {
845 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCspPathSysErr, @"/"));
848 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCspPath, @"/"));
852 static internal Exception NullCngKeyPath(bool isSystemOp) {
854 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCngPathSysErr, @"/"));
857 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCngPath, @"/"));
861 static internal Exception InvalidCertificatePath(string actualCertificatePath, string[] validLocations, bool isSystemOp) {
862 Debug.Assert(2 == validLocations.Length);
864 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificatePathSysErr, actualCertificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
867 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificatePath, actualCertificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
871 static internal Exception InvalidCspPath(string masterKeyPath, bool isSystemOp) {
873 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspPathSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
876 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspPath, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
880 static internal Exception InvalidCngPath(string masterKeyPath, bool isSystemOp) {
882 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngPathSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
885 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngPath, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
889 static internal Exception EmptyCspName(string masterKeyPath, bool isSystemOp) {
891 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspNameSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
894 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspName, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
898 static internal Exception EmptyCngName(string masterKeyPath, bool isSystemOp) {
900 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngNameSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
903 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngName, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
907 static internal Exception EmptyCspKeyId(string masterKeyPath, bool isSystemOp) {
909 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspKeyIdSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
912 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspKeyId, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
916 static internal Exception EmptyCngKeyId(string masterKeyPath, bool isSystemOp) {
918 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngKeyIdSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
921 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngKeyId, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
925 static internal Exception InvalidCspName(string cspName, string masterKeyPath, bool isSystemOp) {
927 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspNameSysErr, cspName, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
930 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspName, cspName, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
934 static internal Exception InvalidCspKeyIdentifier(string keyIdentifier, string masterKeyPath, bool isSystemOp) {
936 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspKeyIdSysErr, keyIdentifier, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
939 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspKeyId, keyIdentifier, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
943 static internal Exception InvalidCngKey(string masterKeyPath, string cngProviderName, string keyIdentifier, bool isSystemOp) {
945 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngKeySysErr, masterKeyPath, cngProviderName, keyIdentifier), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
948 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngKey, masterKeyPath, cngProviderName, keyIdentifier), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
952 static internal Exception InvalidCertificateLocation(string certificateLocation, string certificatePath, string[] validLocations, bool isSystemOp) {
953 Debug.Assert(2 == validLocations.Length);
955 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateLocationSysErr, certificateLocation, certificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
958 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateLocation, certificateLocation, certificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
962 static internal Exception InvalidCertificateStore(string certificateStore, string certificatePath, string validCertificateStore, bool isSystemOp) {
964 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateStoreSysErr, certificateStore, certificatePath, validCertificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
967 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateStore, certificateStore, certificatePath, validCertificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
971 static internal Exception EmptyCertificateThumbprint(string certificatePath, bool isSystemOp) {
973 return ADP.Argument(Res.GetString(Res.TCE_EmptyCertificateThumbprintSysErr, certificatePath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
976 return ADP.Argument(Res.GetString(Res.TCE_EmptyCertificateThumbprint, certificatePath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
980 static internal Exception CertificateNotFound(string thumbprint, string certificateLocation, string certificateStore, bool isSystemOp) {
982 return ADP.Argument(Res.GetString(Res.TCE_CertificateNotFoundSysErr, thumbprint, certificateLocation, certificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
985 return ADP.Argument(Res.GetString(Res.TCE_CertificateNotFound, thumbprint, certificateLocation, certificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
989 static internal Exception InvalidAlgorithmVersionInEncryptedCEK(byte actual, byte expected) {
990 return ADP.Argument(Res.GetString(Res.TCE_InvalidAlgorithmVersionInEncryptedCEK, actual.ToString(@"X2"), expected.ToString(@"X2")), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
993 static internal Exception InvalidCiphertextLengthInEncryptedCEK(int actual, int expected, string certificateName) {
994 return ADP.Argument(Res.GetString(Res.TCE_InvalidCiphertextLengthInEncryptedCEK, actual, expected, certificateName), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
997 static internal Exception InvalidCiphertextLengthInEncryptedCEKCsp(int actual, int expected, string masterKeyPath) {
998 return ADP.Argument(Res.GetString(Res.TCE_InvalidCiphertextLengthInEncryptedCEKCsp, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1001 static internal Exception InvalidCiphertextLengthInEncryptedCEKCng(int actual, int expected, string masterKeyPath) {
1002 return ADP.Argument(Res.GetString(Res.TCE_InvalidCiphertextLengthInEncryptedCEKCng, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1005 static internal Exception InvalidSignatureInEncryptedCEK(int actual, int expected, string masterKeyPath) {
1006 return ADP.Argument(Res.GetString(Res.TCE_InvalidSignatureInEncryptedCEK, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1009 static internal Exception InvalidSignatureInEncryptedCEKCsp(int actual, int expected, string masterKeyPath) {
1010 return ADP.Argument(Res.GetString(Res.TCE_InvalidSignatureInEncryptedCEKCsp, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1013 static internal Exception InvalidSignatureInEncryptedCEKCng(int actual, int expected, string masterKeyPath) {
1014 return ADP.Argument(Res.GetString(Res.TCE_InvalidSignatureInEncryptedCEKCng, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1017 static internal Exception InvalidCertificateSignature(string certificatePath) {
1018 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateSignature, certificatePath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1021 static internal Exception InvalidSignature(string masterKeyPath) {
1022 return ADP.Argument(Res.GetString(Res.TCE_InvalidSignature, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1025 static internal Exception CertificateWithNoPrivateKey(string keyPath, bool isSystemOp) {
1027 return ADP.Argument(Res.GetString(Res.TCE_CertificateWithNoPrivateKeySysErr, keyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
1030 return ADP.Argument(Res.GetString(Res.TCE_CertificateWithNoPrivateKey, keyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
1035 // TCE - Cryptographic Algorithms Error messages
1037 static internal Exception NullColumnEncryptionKeySysErr() {
1038 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTIONKEY,Res.GetString(Res.TCE_NullColumnEncryptionKeySysErr));
1041 static internal Exception InvalidKeySize(string algorithmName, int actualKeylength, int expectedLength) {
1042 return ADP.Argument(Res.GetString(
1043 Res.TCE_InvalidKeySize,
1046 expectedLength), TdsEnums.TCE_PARAM_ENCRYPTIONKEY);
1049 static internal Exception InvalidEncryptionType(string algorithmName, SqlClientEncryptionType encryptionType, params SqlClientEncryptionType[] validEncryptionTypes) {
1050 const string valueSeparator = @", ";
1051 return ADP.Argument(Res.GetString(
1052 Res.TCE_InvalidEncryptionType,
1054 encryptionType.ToString(),
1055 string.Join(valueSeparator, validEncryptionTypes.Select((validEncryptionType => @"'" + validEncryptionType + @"'")))), TdsEnums.TCE_PARAM_ENCRYPTIONTYPE);
1058 static internal Exception NullPlainText () {
1059 return ADP.ArgumentNull (Res.GetString(Res.TCE_NullPlainText));
1062 static internal Exception VeryLargeCiphertext(long cipherTextLength, long maxCipherTextSize, long plainTextLength) {
1063 return ADP.Argument(Res.GetString(Res.TCE_VeryLargeCiphertext, cipherTextLength, maxCipherTextSize, plainTextLength));
1066 static internal Exception NullCipherText () {
1067 return ADP.ArgumentNull (Res.GetString(Res.TCE_NullCipherText));
1070 static internal Exception InvalidCipherTextSize(int actualSize, int minimumSize) {
1071 return ADP.Argument(Res.GetString(Res.TCE_InvalidCipherTextSize, actualSize, minimumSize), TdsEnums.TCE_PARAM_CIPHERTEXT);
1074 static internal Exception InvalidAlgorithmVersion(byte actual, byte expected) {
1075 return ADP.Argument(Res.GetString(Res.TCE_InvalidAlgorithmVersion, actual.ToString(@"X2"), expected.ToString(@"X2")), TdsEnums.TCE_PARAM_CIPHERTEXT);
1078 static internal Exception InvalidAuthenticationTag() {
1079 return ADP.Argument(Res.GetString(Res.TCE_InvalidAuthenticationTag), TdsEnums.TCE_PARAM_CIPHERTEXT);
1082 static internal Exception NullColumnEncryptionAlgorithm (string supportedAlgorithms) {
1083 return ADP.ArgumentNull (TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, Res.GetString(Res.TCE_NullColumnEncryptionAlgorithm, supportedAlgorithms));
1087 // TCE - Errors from sp_describe_parameter_encryption
1089 static internal Exception UnexpectedDescribeParamFormat () {
1090 return ADP.Argument (Res.GetString(Res.TCE_UnexpectedDescribeParamFormat, "sp_describe_parameter_encryption"));
1093 static internal Exception InvalidEncryptionKeyOrdinal (int ordinal, int maxOrdinal) {
1094 return ADP.InvalidOperation(Res.GetString(Res.TCE_InvalidEncryptionKeyOrdinal, "sp_describe_parameter_encryption", ordinal, maxOrdinal));
1097 static internal Exception ParamEncryptionMetadataMissing (string paramName, string procedureName) {
1098 return ADP.Argument (Res.GetString(Res.TCE_ParamEncryptionMetaDataMissing, "sp_describe_parameter_encryption", paramName, procedureName));
1101 static internal Exception ParamInvalidForceColumnEncryptionSetting (string paramName, string procedureName) {
1102 return ADP.InvalidOperation(Res.GetString(Res.TCE_ParamInvalidForceColumnEncryptionSetting, TdsEnums.TCE_PARAM_FORCE_COLUMN_ENCRYPTION, paramName, procedureName, "SqlParameter"));
1105 static internal Exception ParamUnExpectedEncryptionMetadata (string paramName, string procedureName) {
1106 return ADP.InvalidOperation(Res.GetString(Res.TCE_ParamUnExpectedEncryptionMetadata, paramName, procedureName, TdsEnums.TCE_PARAM_FORCE_COLUMN_ENCRYPTION, "SqlParameter"));
1109 static internal Exception ProcEncryptionMetadataMissing (string procedureName) {
1110 return ADP.Argument (Res.GetString(Res.TCE_ProcEncryptionMetaDataMissing, "sp_describe_parameter_encryption", procedureName));
1114 // TCE- Generic toplevel failures.
1116 static internal Exception GetExceptionArray (string serverName, string errorMessage, Exception e) {
1117 // Create and throw an exception array
1118 SqlErrorCollection sqlErs = new SqlErrorCollection();
1119 Exception exceptionToInclude = (null != e.InnerException) ? e.InnerException : e;
1120 sqlErs.Add (new SqlError(infoNumber:0, errorState:(byte)0x00, errorClass:(byte)TdsEnums.MIN_ERROR_CLASS, server:serverName, errorMessage:errorMessage, procedure:null, lineNumber:0));
1122 if (e is SqlException) {
1123 SqlException exThrown = (SqlException)e;
1124 SqlErrorCollection errorList = exThrown.Errors;
1125 for (int i =0; i < exThrown.Errors.Count; i++) {
1126 sqlErs.Add(errorList[i]);
1130 sqlErs.Add (new SqlError(infoNumber:0, errorState:(byte)0x00, errorClass:(byte)TdsEnums.MIN_ERROR_CLASS, server:serverName, errorMessage:e.Message, procedure:null, lineNumber:0));
1133 return SqlException.CreateException(sqlErs, "", null, exceptionToInclude);
1136 static internal Exception ParamEncryptionFailed (string paramName, string serverName, Exception e){
1137 return GetExceptionArray (serverName, Res.GetString(Res.TCE_ParamEncryptionFailed, paramName), e);
1140 static internal Exception ParamDecryptionFailed (string paramName, string serverName, Exception e) {
1141 return GetExceptionArray (serverName, Res.GetString(Res.TCE_ParamDecryptionFailed, paramName), e);
1144 static internal Exception ColumnDecryptionFailed (string columnName, string serverName, Exception e) {
1145 return GetExceptionArray (serverName, Res.GetString(Res.TCE_ColumnDecryptionFailed, columnName), e);
1149 // TCE- Client side query processing errors.
1151 static internal Exception UnknownColumnEncryptionAlgorithm (string algorithmName, string supportedAlgorithms) {
1152 return ADP.Argument(Res.GetString(Res.TCE_UnknownColumnEncryptionAlgorithm, algorithmName, supportedAlgorithms));
1155 static internal Exception UnknownColumnEncryptionAlgorithmId (int algoId, string supportAlgorithmIds) {
1156 return ADP.Argument(Res.GetString(Res.TCE_UnknownColumnEncryptionAlgorithmId, algoId, supportAlgorithmIds), TdsEnums.TCE_PARAM_CIPHER_ALGORITHM_ID);
1159 static internal Exception UnsupportedNormalizationVersion (byte version) {
1160 return ADP.Argument(Res.GetString(Res.TCE_UnsupportedNormalizationVersion, version, "'1'", "SQL Server"));
1163 static internal Exception UnrecognizedKeyStoreProviderName(string providerName, List<string> systemProviders, List<string> customProviders) {
1164 const string valueSeparator = @", ";
1165 string systemProviderStr = string.Join (valueSeparator, systemProviders.Select(provider => @"'" + provider + @"'"));
1166 string customProviderStr = string.Join (valueSeparator, customProviders.Select(provider => @"'" + provider + @"'"));
1167 return ADP.Argument(Res.GetString(Res.TCE_UnrecognizedKeyStoreProviderName, providerName, systemProviderStr, customProviderStr));
1170 static internal Exception InvalidDataTypeForEncryptedParameter(string parameterName, int actualDataType, int expectedDataType) {
1171 return ADP.Argument(Res.GetString(Res.TCE_NullProviderValue, parameterName, actualDataType, expectedDataType));
1174 static internal Exception KeyDecryptionFailed (string providerName, string keyHex, Exception e) {
1175 if (providerName.Equals(SqlColumnEncryptionCertificateStoreProvider.ProviderName)) {
1176 return GetExceptionArray(null, Res.GetString(Res.TCE_KeyDecryptionFailedCertStore, providerName, keyHex), e);
1179 return GetExceptionArray(null, Res.GetString(Res.TCE_KeyDecryptionFailed, providerName, keyHex), e);
1183 static internal Exception UntrustedKeyPath(string keyPath, string serverName) {
1184 return ADP.Argument(Res.GetString(Res.TCE_UntrustedKeyPath, keyPath, serverName));
1187 static internal Exception UnsupportedDatatypeEncryption (string dataType) {
1188 return ADP.Argument(Res.GetString(Res.TCE_UnsupportedDatatype, dataType));
1191 static internal Exception ThrowDecryptionFailed (string keyStr, string valStr, Exception e) {
1192 return GetExceptionArray (null, Res.GetString(Res.TCE_DecryptionFailed, keyStr, valStr), e);
1196 // TCE- SQL connection related error messages
1198 static internal Exception TceNotSupported() {
1199 return ADP.InvalidOperation (Res.GetString (Res.TCE_NotSupportedByServer, "SQL Server"));
1203 // TCE- Extensibility related error messages
1205 static internal Exception CanOnlyCallOnce() {
1206 return ADP.InvalidOperation(Res.GetString(Res.TCE_CanOnlyCallOnce));
1209 static internal Exception NullCustomKeyStoreProviderDictionary() {
1210 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, Res.GetString(Res.TCE_NullCustomKeyStoreProviderDictionary));
1213 static internal Exception InvalidCustomKeyStoreProviderName(string providerName, string prefix) {
1214 return ADP.Argument(Res.GetString(Res.TCE_InvalidCustomKeyStoreProviderName, providerName, prefix), TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS);
1217 static internal Exception NullProviderValue(string providerName) {
1218 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, Res.GetString(Res.TCE_NullProviderValue, providerName));
1221 static internal Exception EmptyProviderName() {
1222 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, Res.GetString(Res.TCE_EmptyProviderName));
1228 static internal Exception ConnectionDoomed() {
1229 return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionDoomed));
1232 static internal Exception OpenResultCountExceeded() {
1233 return ADP.InvalidOperation(Res.GetString(Res.SQL_OpenResultCountExceeded));
1237 // Global Transactions.
1239 static internal Exception GlobalTransactionsNotEnabled() {
1240 return ADP.InvalidOperation(Res.GetString(Res.GT_Disabled));
1243 static internal Exception UnsupportedSysTxForGlobalTransactions() {
1244 return ADP.InvalidOperation(Res.GetString(Res.GT_UnsupportedSysTxVersion));
1247 static internal readonly byte[] AttentionHeader = new byte[] {
1248 TdsEnums.MT_ATTN, // Message Type
1249 TdsEnums.ST_EOM, // Status
1250 TdsEnums.HEADER_LEN >> 8, // length - upper byte
1251 TdsEnums.HEADER_LEN & 0xff, // length - lower byte
1254 0, // packet (out of band)
1259 // MultiSubnetFailover
1263 /// used to block two scenarios if MultiSubnetFailover is true:
1264 /// * server-provided failover partner - raising SqlException in this case
1265 /// * connection string with failover partner and MultiSubnetFailover=true - rasing argument one in this case with the same message
1267 static internal Exception MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection) {
1268 string msg = Res.GetString(Res.SQLMSF_FailoverPartnerNotSupported);
1269 if (serverProvidedFailoverPartner) {
1270 // VSTFDEVDIV\DevDiv2\179041 - replacing InvalidOperation with SQL exception
1271 SqlErrorCollection errors = new SqlErrorCollection();
1272 errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, msg, "", 0));
1273 SqlException exc = SqlException.CreateException(errors, null, internalConnection);
1274 exc._doNotReconnect = true; // disable open retry logic on this error
1278 return ADP.Argument(msg);
1282 static internal Exception MultiSubnetFailoverWithMoreThan64IPs() {
1283 string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs);
1284 return ADP.InvalidOperation(msg);
1287 static internal Exception MultiSubnetFailoverWithInstanceSpecified() {
1288 string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified);
1289 return ADP.Argument(msg);
1292 static internal Exception MultiSubnetFailoverWithNonTcpProtocol() {
1293 string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol);
1294 return ADP.Argument(msg);
1298 // Read-only routing
1301 static internal Exception ROR_FailoverNotSupportedConnString() {
1302 return ADP.Argument(Res.GetString(Res.SQLROR_FailoverNotSupported));
1305 static internal Exception ROR_FailoverNotSupportedServer(SqlInternalConnectionTds internalConnection) {
1306 SqlErrorCollection errors = new SqlErrorCollection();
1307 errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_FailoverNotSupported)), "", 0));
1308 SqlException exc = SqlException.CreateException(errors, null, internalConnection);
1309 exc._doNotReconnect = true;
1313 static internal Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection) {
1314 SqlErrorCollection errors = new SqlErrorCollection();
1315 errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_RecursiveRoutingNotSupported)), "", 0));
1316 SqlException exc=SqlException.CreateException(errors, null, internalConnection);
1317 exc._doNotReconnect = true;
1321 static internal Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection) {
1322 SqlErrorCollection errors = new SqlErrorCollection();
1323 errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_UnexpectedRoutingInfo)), "", 0));
1324 SqlException exc = SqlException.CreateException(errors, null, internalConnection);
1325 exc._doNotReconnect = true;
1329 static internal Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection) {
1330 SqlErrorCollection errors = new SqlErrorCollection();
1331 errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_InvalidRoutingInfo)), "", 0));
1332 SqlException exc = SqlException.CreateException(errors, null, internalConnection);
1333 exc._doNotReconnect = true;
1337 static internal Exception ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection) {
1338 SqlErrorCollection errors = new SqlErrorCollection();
1339 errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_TimeoutAfterRoutingInfo)), "", 0));
1340 SqlException exc = SqlException.CreateException(errors, null, internalConnection);
1341 exc._doNotReconnect = true;
1346 // Connection resiliency
1348 static internal SqlException CR_ReconnectTimeout() {
1349 SqlErrorCollection errors = new SqlErrorCollection();
1350 errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.Timeout(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
1351 SqlException exc = SqlException.CreateException(errors, "");
1355 static internal SqlException CR_ReconnectionCancelled() {
1356 SqlErrorCollection errors = new SqlErrorCollection();
1357 errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.OperationCancelled(), "", 0));
1358 SqlException exc = SqlException.CreateException(errors, "");
1362 static internal Exception CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId) {
1363 SqlErrorCollection errors = new SqlErrorCollection();
1364 errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, Res.GetString(Res.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0));
1365 SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
1369 static internal Exception CR_EncryptionChanged(SqlInternalConnectionTds internalConnection) {
1370 SqlErrorCollection errors = new SqlErrorCollection();
1371 errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_EncryptionChanged), "", 0));
1372 SqlException exc = SqlException.CreateException(errors, "", internalConnection);
1376 static internal SqlException CR_AllAttemptsFailed(SqlException innerException, Guid connectionId) {
1377 SqlErrorCollection errors = new SqlErrorCollection();
1378 errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, Res.GetString(Res.SQLCR_AllAttemptsFailed), "", 0));
1379 SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
1383 static internal SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection) {
1384 SqlErrorCollection errors = new SqlErrorCollection();
1385 errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_NoCRAckAtReconnection), "", 0));
1386 SqlException exc = SqlException.CreateException(errors, "", internalConnection);
1390 static internal SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internalConnection) {
1391 SqlErrorCollection errors = new SqlErrorCollection();
1392 errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_TDSVestionNotPreserved), "", 0));
1393 SqlException exc = SqlException.CreateException(errors, "", internalConnection);
1397 static internal SqlException CR_UnrecoverableServer(Guid connectionId) {
1398 SqlErrorCollection errors = new SqlErrorCollection();
1399 errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_UnrecoverableServer), "", 0));
1400 SqlException exc = SqlException.CreateException(errors, "", connectionId);
1404 static internal SqlException CR_UnrecoverableClient(Guid connectionId) {
1405 SqlErrorCollection errors = new SqlErrorCollection();
1406 errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_UnrecoverableClient), "", 0));
1407 SqlException exc = SqlException.CreateException(errors, "", connectionId);
1414 static internal Exception BatchedUpdatesNotAvailableOnContextConnection() {
1415 return ADP.InvalidOperation(Res.GetString(Res.SQL_BatchedUpdatesNotAvailableOnContextConnection));
1417 static internal Exception ContextAllowsLimitedKeywords() {
1418 return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextAllowsLimitedKeywords));
1420 static internal Exception ContextAllowsOnlyTypeSystem2005() {
1421 return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextAllowsOnlyTypeSystem2005));
1423 static internal Exception ContextConnectionIsInUse() {
1424 return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextConnectionIsInUse));
1426 static internal Exception ContextUnavailableOutOfProc() {
1427 return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextUnavailableOutOfProc));
1429 static internal Exception ContextUnavailableWhileInProc() {
1430 return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextUnavailableWhileInProc));
1432 static internal Exception NestedTransactionScopesNotSupported() {
1433 return ADP.InvalidOperation(Res.GetString(Res.SQL_NestedTransactionScopesNotSupported));
1435 static internal Exception NotAvailableOnContextConnection() {
1436 return ADP.InvalidOperation(Res.GetString(Res.SQL_NotAvailableOnContextConnection));
1438 static internal Exception NotificationsNotAvailableOnContextConnection() {
1439 return ADP.InvalidOperation(Res.GetString(Res.SQL_NotificationsNotAvailableOnContextConnection));
1442 static internal Exception UnexpectedSmiEvent(Microsoft.SqlServer.Server.SmiEventSink_Default.UnexpectedEventType eventType) {
1443 Debug.Assert(false, "UnexpectedSmiEvent: "+eventType.ToString()); // Assert here, because these exceptions will most likely be eaten by the server.
1444 return ADP.InvalidOperation(Res.GetString(Res.SQL_UnexpectedSmiEvent, (int)eventType));
1447 static internal Exception UserInstanceNotAvailableInProc() {
1448 return ADP.InvalidOperation(Res.GetString(Res.SQL_UserInstanceNotAvailableInProc));
1450 static internal Exception ArgumentLengthMismatch( string arg1, string arg2 ) {
1451 return ADP.Argument( Res.GetString( Res.SQL_ArgumentLengthMismatch, arg1, arg2 ) );
1453 static internal Exception InvalidSqlDbTypeOneAllowedType( SqlDbType invalidType, string method, SqlDbType allowedType ) {
1454 return ADP.Argument( Res.GetString( Res.SQL_InvalidSqlDbTypeWithOneAllowedType, invalidType, method, allowedType ) );
1456 static internal Exception SqlPipeErrorRequiresSendEnd( ) {
1457 return ADP.InvalidOperation(Res.GetString(Res.SQL_PipeErrorRequiresSendEnd));
1459 static internal Exception TooManyValues(string arg) {
1460 return ADP.Argument(Res.GetString(Res.SQL_TooManyValues), arg);
1462 static internal Exception StreamWriteNotSupported() {
1463 return ADP.NotSupported(Res.GetString(Res.SQL_StreamWriteNotSupported));
1465 static internal Exception StreamReadNotSupported() {
1466 return ADP.NotSupported(Res.GetString(Res.SQL_StreamReadNotSupported));
1468 static internal Exception StreamSeekNotSupported() {
1469 return ADP.NotSupported(Res.GetString(Res.SQL_StreamSeekNotSupported));
1471 static internal System.Data.SqlTypes.SqlNullValueException SqlNullValue() {
1472 System.Data.SqlTypes.SqlNullValueException e = new System.Data.SqlTypes.SqlNullValueException();
1473 ADP.TraceExceptionAsReturnValue(e);
1476 // SQLBU 402363: Exception to prevent Parameter.Size data corruption case from working.
1477 // This should be temporary until changing to correct behavior can be safely implemented.
1478 static internal Exception ParameterSizeRestrictionFailure(int index) {
1479 return ADP.InvalidOperation(Res.GetString(Res.OleDb_CommandParameterError, index.ToString(CultureInfo.InvariantCulture), "SqlParameter.Size"));
1481 static internal Exception SubclassMustOverride() {
1482 return ADP.InvalidOperation(Res.GetString(Res.SqlMisc_SubclassMustOverride));
1486 /// gets a message for SNI error (sniError must be valid, non-zero error code)
1488 static internal string GetSNIErrorMessage(int sniError) {
1489 Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range");
1491 string errorMessageId = String.Format((IFormatProvider)null, "SNI_ERROR_{0}", sniError);
1492 return Res.GetString(errorMessageId);
1496 internal const string WriteToServer = "WriteToServer";
1498 // Default values for SqlDependency and SqlNotificationRequest
1499 internal const int SqlDependencyTimeoutDefault = 0;
1500 internal const int SqlDependencyServerTimeout = 5 * 24 * 3600; // 5 days - used to compute default TTL of the dependency
1501 internal const string SqlNotificationServiceDefault = "SqlQueryNotificationService";
1502 internal const string SqlNotificationStoredProcedureDefault = "SqlQueryNotificationStoredProcedure";
1505 internal const string Transaction= "Transaction";
1506 internal const string Connection = "Connection";
1509 sealed internal class SQLMessage {
1513 private SQLMessage() { /* prevent utility class from being insantiated*/ }
1515 // The class SQLMessage defines the error messages that are specific to the SqlDataAdapter
1516 // that are caused by a netlib error. The functions will be called and then return the
1517 // appropriate error message from the resource Framework.txt. The SqlDataAdapter will then
1518 // take the error message and then create a SqlError for the message and then place
1519 // that into a SqlException that is either thrown to the user or cached for throwing at
1520 // a later time. This class is used so that there will be compile time checking of error
1521 // messages. The resource Framework.txt will ensure proper string text based on the appropriate
1524 static internal string CultureIdError() {
1525 return Res.GetString(Res.SQL_CultureIdError);
1527 static internal string EncryptionNotSupportedByClient() {
1528 return Res.GetString(Res.SQL_EncryptionNotSupportedByClient);
1530 static internal string EncryptionNotSupportedByServer() {
1531 return Res.GetString(Res.SQL_EncryptionNotSupportedByServer);
1533 static internal string OperationCancelled() {
1534 return Res.GetString(Res.SQL_OperationCancelled);
1536 static internal string SevereError() {
1537 return Res.GetString(Res.SQL_SevereError);
1539 static internal string SSPIInitializeError() {
1540 return Res.GetString(Res.SQL_SSPIInitializeError);
1542 static internal string SSPIGenerateError() {
1543 return Res.GetString(Res.SQL_SSPIGenerateError);
1545 static internal string Timeout() {
1546 return Res.GetString(Res.SQL_Timeout);
1548 static internal string Timeout_PreLogin_Begin() {
1549 return Res.GetString(Res.SQL_Timeout_PreLogin_Begin);
1551 static internal string Timeout_PreLogin_InitializeConnection() {
1552 return Res.GetString(Res.SQL_Timeout_PreLogin_InitializeConnection);
1554 static internal string Timeout_PreLogin_SendHandshake() {
1555 return Res.GetString(Res.SQL_Timeout_PreLogin_SendHandshake);
1557 static internal string Timeout_PreLogin_ConsumeHandshake() {
1558 return Res.GetString(Res.SQL_Timeout_PreLogin_ConsumeHandshake);
1560 static internal string Timeout_Login_Begin() {
1561 return Res.GetString(Res.SQL_Timeout_Login_Begin);
1563 static internal string Timeout_Login_ProcessConnectionAuth() {
1564 return Res.GetString(Res.SQL_Timeout_Login_ProcessConnectionAuth);
1566 static internal string Timeout_PostLogin() {
1567 return Res.GetString(Res.SQL_Timeout_PostLogin);
1569 static internal string Timeout_FailoverInfo() {
1570 return Res.GetString(Res.SQL_Timeout_FailoverInfo);
1572 static internal string Timeout_RoutingDestination() {
1573 return Res.GetString(Res.SQL_Timeout_RoutingDestinationInfo);
1575 static internal string Duration_PreLogin_Begin(long PreLoginBeginDuration) {
1576 return Res.GetString(Res.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration);
1578 static internal string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration) {
1579 return Res.GetString(Res.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration);
1581 static internal string Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration) {
1582 return Res.GetString(Res.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration);
1584 static internal string Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration) {
1585 return Res.GetString(Res.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration);
1587 static internal string Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration) {
1588 return Res.GetString(Res.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration);
1590 static internal string UserInstanceFailure() {
1591 return Res.GetString(Res.SQL_UserInstanceFailure);
1593 static internal string PreloginError() {
1594 return Res.GetString(Res.Snix_PreLogin);
1596 static internal string ExClientConnectionId() {
1597 return Res.GetString(Res.SQL_ExClientConnectionId);
1599 static internal string ExErrorNumberStateClass() {
1600 return Res.GetString(Res.SQL_ExErrorNumberStateClass);
1602 static internal string ExOriginalClientConnectionId() {
1603 return Res.GetString(Res.SQL_ExOriginalClientConnectionId);
1605 static internal string ExRoutingDestination() {
1606 return Res.GetString(Res.SQL_ExRoutingDestination);
1611 /// This class holds helper methods to escape Microsoft SQL Server identifiers, such as table, schema, database or other names
1613 static internal class SqlServerEscapeHelper {
1616 /// Escapes the identifier with square brackets. The input has to be in unescaped form, like the parts received from MultipartIdentifier.ParseMultipartIdentifier.
1618 /// <param name="name">name of the identifier, in unescaped form</param>
1619 /// <returns>escapes the name with [], also escapes the last close bracket with double-bracket</returns>
1620 static internal string EscapeIdentifier(string name) {
1621 Debug.Assert(!ADP.IsEmpty(name), "null or empty identifiers are not allowed");
1622 return "[" + name.Replace("]", "]]") + "]";
1626 /// Same as above EscapeIdentifier, except that output is written into StringBuilder
1628 static internal void EscapeIdentifier(StringBuilder builder, string name) {
1629 Debug.Assert(builder != null, "builder cannot be null");
1630 Debug.Assert(!ADP.IsEmpty(name), "null or empty identifiers are not allowed");
1632 builder.Append("[");
1633 builder.Append(name.Replace("]", "]]"));
1634 builder.Append("]");
1638 /// Escape a string to be used inside TSQL literal, such as N'somename' or 'somename'
1640 static internal string EscapeStringAsLiteral(string input) {
1641 Debug.Assert(input != null, "input string cannot be null");
1642 return input.Replace("'", "''");
1646 /// Escape a string as a TSQL literal, wrapping it around with single quotes.
1647 /// Use this method to escape input strings to prevent SQL injection
1648 /// and to get correct behavior for embedded quotes.
1650 /// <param name="input">unescaped string</param>
1651 /// <returns>escaped and quoted literal string</returns>
1652 static internal string MakeStringLiteral(string input) {
1653 if (ADP.IsEmpty(input)) {
1657 return "'" + EscapeStringAsLiteral(input) + "'";
1663 /// This class holds methods invoked on System.Transactions through reflection for Global Transactions
1665 static internal class SysTxForGlobalTransactions {
1667 private static readonly Lazy<MethodInfo> _enlistPromotableSinglePhase = new Lazy<MethodInfo>(() =>
1668 typeof(SysTx.Transaction).GetMethod("EnlistPromotableSinglePhase", new Type[] {typeof(SysTx.IPromotableSinglePhaseNotification), typeof(Guid)}));
1670 private static readonly Lazy<MethodInfo> _setDistributedTransactionIdentifier = new Lazy<MethodInfo>(() =>
1671 typeof(SysTx.Transaction).GetMethod("SetDistributedTransactionIdentifier", new Type[] { typeof(SysTx.IPromotableSinglePhaseNotification), typeof(Guid) }));
1673 private static readonly Lazy<MethodInfo> _getPromotedToken = new Lazy<MethodInfo>(() =>
1674 typeof(SysTx.Transaction).GetMethod("GetPromotedToken"));
1677 /// Enlists the given IPromotableSinglePhaseNotification and Non-MSDTC Promoter type into a transaction
1679 /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
1680 public static MethodInfo EnlistPromotableSinglePhase {
1682 return _enlistPromotableSinglePhase.Value;
1687 /// Sets the given DistributedTransactionIdentifier for a Transaction instance.
1688 /// Needs to be invoked when using a Non-MSDTC Promoter type
1690 /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
1691 public static MethodInfo SetDistributedTransactionIdentifier {
1693 return _setDistributedTransactionIdentifier.Value;
1698 /// Gets the Promoted Token for a Transaction
1700 /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
1701 public static MethodInfo GetPromotedToken {
1703 return _getPromotedToken.Value;