1 //------------------------------------------------------------------------------
2 // <copyright file="SqlUtil.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>
5 // <owner current="true" primary="true">Microsoft</owner>
6 // <owner current="true" primary="false">Microsoft</owner>
7 //------------------------------------------------------------------------------
8 
9 namespace System.Data.SqlClient {
10     using System;
11     using System.Collections.Generic;
12     using System.ComponentModel;
13     using System.Data;
14     using System.Data.Common;
15     using System.Diagnostics;
16     using System.Globalization;
17     using System.Linq;
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;
24     using System.Text;
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;
30 
31     static internal class AsyncHelper {
32 #if !MONO
CreateContinuationTask(Task task, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null)33         internal static Task CreateContinuationTask(Task task, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) {
34             if (task == null) {
35                 onSuccess();
36                 return null;
37             }
38             else {
39                 TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
40                 ContinueTask(task, completion,
41                     () => { onSuccess(); completion.SetResult(null); },
42                     connectionToDoom, onFailure);
43                 return completion.Task;
44             }
45         }
46 
CreateContinuationTask(Task task, Action<T1, T2> onSuccess, T1 arg1, T2 arg2, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null)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);
49         }
50 
ContinueTask(Task task, TaskCompletionSource<object> completion, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null, Action onCancellation = null, Func<Exception, Exception> exceptionConverter = null, SqlConnection connectionToAbort = null )51         internal static void ContinueTask(Task task,
52                 TaskCompletionSource<object> completion,
53                 Action onSuccess,
54                 SqlInternalConnectionTds connectionToDoom = null,
55                 Action<Exception> onFailure = null,
56                 Action onCancellation = null,
57                 Func<Exception, Exception> exceptionConverter = null,
58                 SqlConnection connectionToAbort = null
59             ) {
60             Debug.Assert((connectionToAbort == null) || (connectionToDoom == null), "Should not specify both connectionToDoom and connectionToAbort");
61             task.ContinueWith(
62                 tsk => {
63                     if (tsk.Exception != null) {
64                         Exception exc = tsk.Exception.InnerException;
65                         if (exceptionConverter != null) {
66                             exc = exceptionConverter(exc);
67                         }
68                         try {
69                             if (onFailure != null) {
70                                 onFailure(exc);
71                             }
72                         }
73                         finally {
74                             completion.TrySetException(exc);
75                         }
76                     }
77                     else if (tsk.IsCanceled) {
78                         try {
79                             if (onCancellation != null) {
80                                 onCancellation();
81                             }
82                         }
83                         finally {
84                             completion.TrySetCanceled();
85                         }
86                     }
87                     else {
88                         if (connectionToDoom != null || connectionToAbort!=null) {
89                             RuntimeHelpers.PrepareConstrainedRegions();
90                             try {
91 #if DEBUG
92                                 TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
93                                 RuntimeHelpers.PrepareConstrainedRegions();
94                                 try {
95                                     tdsReliabilitySection.Start();
96 #endif //DEBUG
97                                     onSuccess();
98 #if DEBUG
99                                 }
100                                 finally {
101                                     tdsReliabilitySection.Stop();
102                                 }
103 #endif //DEBUG
104                             }
105                             catch (System.OutOfMemoryException e) {
106                                 if (connectionToDoom != null) {
107                                     connectionToDoom.DoomThisConnection();
108                                 }
109                                 else {
110                                     connectionToAbort.Abort(e);
111                                 }
112                                 completion.SetException(e);
113                                 throw;
114                             }
115                             catch (System.StackOverflowException e) {
116                                 if (connectionToDoom != null) {
117                                     connectionToDoom.DoomThisConnection();
118                                 }
119                                 else {
120                                     connectionToAbort.Abort(e);
121                                 }
122                                 completion.SetException(e);
123                                 throw;
124                             }
125                             catch (System.Threading.ThreadAbortException e) {
126                                 if (connectionToDoom != null) {
127                                     connectionToDoom.DoomThisConnection();
128                                 }
129                                 else {
130                                     connectionToAbort.Abort(e);
131                                 }
132                                 completion.SetException(e);
133                                 throw;
134                             }
135                             catch (Exception e) {
136                                 completion.SetException(e);
137                             }
138                         }
139                         else { // no connection to doom - reliability section not required
140                             try {
141                                 onSuccess();
142                             }
143                             catch (Exception e) {
144                                 completion.SetException(e);
145                             }
146                         }
147                     }
148                 }, TaskScheduler.Default
149             );
150         }
151 #endif
152 
WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions=true)153         internal static void WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions=true) {
154             try {
155                 task.Wait(timeout > 0 ? (1000 * timeout) : Timeout.Infinite);
156             }
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();
161                 }
162             }
163             if (!task.IsCompleted) {
164                 if (onTimeout != null) {
165                     onTimeout();
166                 }
167             }
168         }
169 
SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken)170         internal static void SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken) {
171             if (timeout > 0) {
172                 Task.Delay(timeout * 1000, ctoken).ContinueWith((tsk) => {
173                     if (!tsk.IsCanceled && !completion.Task.IsCompleted) {
174                         completion.TrySetException(exc());
175                     }
176                 });
177             }
178         }
179     }
180 
181     sealed internal class InOutOfProcHelper {
182         private static readonly InOutOfProcHelper SingletonInstance = new InOutOfProcHelper();
183 
184         private bool _inProc = false;
185 
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)]
InOutOfProcHelper()192         private InOutOfProcHelper() {
193 #if !MONO
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")) {
202                     _inProc = true;
203                 }
204                 else if (IntPtr.Zero != SafeNativeMethods.GetProcAddress(handle, "______SQL______Process______Available")) {
205                     _inProc = true;
206                 }
207             }
208 #endif
209         }
210 
211         internal static bool InProc {
212             get {
213                 return SingletonInstance._inProc;
214             }
215         }
216     }
217 
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
226         // locale.
227 
228         //
229         // SQL specific exceptions
230         //
231 
232         //
233         // SQL.Connection
234         //
235 
CannotGetDTCAddress()236         static internal Exception CannotGetDTCAddress() {
237             return ADP.InvalidOperation(Res.GetString(Res.SQL_CannotGetDTCAddress));
238         }
239 
InvalidOptionLength(string key)240         static internal Exception InvalidOptionLength(string key) {
241             return ADP.Argument(Res.GetString(Res.SQL_InvalidOptionLength, key));
242         }
InvalidInternalPacketSize(string str)243         static internal Exception InvalidInternalPacketSize (string str) {
244             return ADP.ArgumentOutOfRange (str);
245         }
InvalidPacketSize()246         static internal Exception InvalidPacketSize() {
247             return ADP.ArgumentOutOfRange (Res.GetString(Res.SQL_InvalidTDSPacketSize));
248         }
InvalidPacketSizeValue()249         static internal Exception InvalidPacketSizeValue() {
250             return ADP.Argument(Res.GetString(Res.SQL_InvalidPacketSizeValue));
251         }
InvalidSSPIPacketSize()252         static internal Exception InvalidSSPIPacketSize() {
253             return ADP.Argument(Res.GetString(Res.SQL_InvalidSSPIPacketSize));
254         }
NullEmptyTransactionName()255         static internal Exception NullEmptyTransactionName() {
256             return ADP.Argument(Res.GetString(Res.SQL_NullEmptyTransactionName));
257         }
SnapshotNotSupported(IsolationLevel level)258         static internal Exception SnapshotNotSupported(IsolationLevel level) {
259             return ADP.Argument(Res.GetString(Res.SQL_SnapshotNotSupported, typeof(IsolationLevel), level.ToString()));
260         }
UserInstanceFailoverNotCompatible()261         static internal Exception UserInstanceFailoverNotCompatible() {
262             return ADP.Argument(Res.GetString(Res.SQL_UserInstanceFailoverNotCompatible));
263         }
CredentialsNotProvided(SqlAuthenticationMethod auth)264         static internal Exception CredentialsNotProvided(SqlAuthenticationMethod auth) {
265             return ADP.InvalidOperation(Res.GetString(Res.SQL_CredentialsNotProvided, DbConnectionStringBuilderUtil.AuthenticationTypeToString(auth)));
266         }
AuthenticationAndIntegratedSecurity()267         static internal Exception AuthenticationAndIntegratedSecurity() {
268             return ADP.Argument(Res.GetString(Res.SQL_AuthenticationAndIntegratedSecurity));
269         }
IntegratedWithUserIDAndPassword()270         static internal Exception IntegratedWithUserIDAndPassword() {
271             return ADP.Argument(Res.GetString(Res.SQL_IntegratedWithUserIDAndPassword));
272         }
SettingIntegratedWithCredential()273         static internal Exception SettingIntegratedWithCredential() {
274             return ADP.InvalidOperation(Res.GetString(Res.SQL_SettingIntegratedWithCredential));
275         }
SettingCredentialWithIntegratedArgument()276         static internal Exception SettingCredentialWithIntegratedArgument() {
277             return ADP.Argument(Res.GetString(Res.SQL_SettingCredentialWithIntegrated));
278         }
SettingCredentialWithIntegratedInvalid()279         static internal Exception SettingCredentialWithIntegratedInvalid() {
280             return ADP.InvalidOperation(Res.GetString(Res.SQL_SettingCredentialWithIntegrated));
281         }
InvalidSQLServerVersionUnknown()282         static internal Exception InvalidSQLServerVersionUnknown() {
283             return ADP.DataAdapter(Res.GetString(Res.SQL_InvalidSQLServerVersionUnknown));
284         }
SynchronousCallMayNotPend()285         static internal Exception SynchronousCallMayNotPend() {
286             return new Exception(Res.GetString(Res.Sql_InternalError));
287         }
ConnectionLockedForBcpEvent()288         static internal Exception ConnectionLockedForBcpEvent() {
289             return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionLockedForBcpEvent));
290         }
AsyncConnectionRequired()291         static internal Exception AsyncConnectionRequired() {
292             return ADP.InvalidOperation(Res.GetString(Res.SQL_AsyncConnectionRequired));
293         }
FatalTimeout()294         static internal Exception FatalTimeout() {
295             return ADP.InvalidOperation(Res.GetString(Res.SQL_FatalTimeout));
296         }
InstanceFailure()297         static internal Exception InstanceFailure() {
298             return ADP.InvalidOperation(Res.GetString(Res.SQL_InstanceFailure));
299         }
ChangePasswordArgumentMissing(string argumentName)300         static internal Exception ChangePasswordArgumentMissing(string argumentName) {
301             return ADP.ArgumentNull(Res.GetString(Res.SQL_ChangePasswordArgumentMissing, argumentName));
302         }
ChangePasswordConflictsWithSSPI()303         static internal Exception ChangePasswordConflictsWithSSPI() {
304             return ADP.Argument(Res.GetString(Res.SQL_ChangePasswordConflictsWithSSPI));
305         }
ChangePasswordRequiresYukon()306         static internal Exception ChangePasswordRequiresYukon() {
307             return ADP.InvalidOperation(Res.GetString(Res.SQL_ChangePasswordRequiresYukon));
308         }
UnknownSysTxIsolationLevel(SysTx.IsolationLevel isolationLevel)309         static internal Exception UnknownSysTxIsolationLevel(SysTx.IsolationLevel isolationLevel) {
310             return ADP.InvalidOperation(Res.GetString(Res.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString()));
311         }
ChangePasswordUseOfUnallowedKey(string key)312         static internal Exception ChangePasswordUseOfUnallowedKey (string key) {
313             return ADP.InvalidOperation(Res.GetString(Res.SQL_ChangePasswordUseOfUnallowedKey, key));
314         }
InvalidPartnerConfiguration(string server, string database)315         static internal Exception InvalidPartnerConfiguration (string server, string database) {
316             return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidPartnerConfiguration, server, database));
317         }
BatchedUpdateColumnEncryptionSettingMismatch()318         static internal Exception BatchedUpdateColumnEncryptionSettingMismatch () {
319             return ADP.InvalidOperation(Res.GetString(Res.TCE_BatchedUpdateColumnEncryptionSettingMismatch, "SqlCommandColumnEncryptionSetting", "SelectCommand", "InsertCommand", "UpdateCommand", "DeleteCommand"));
320         }
MARSUnspportedOnConnection()321         static internal Exception MARSUnspportedOnConnection() {
322             return ADP.InvalidOperation(Res.GetString(Res.SQL_MarsUnsupportedOnConnection));
323         }
324 
CannotModifyPropertyAsyncOperationInProgress(string property)325         static internal Exception CannotModifyPropertyAsyncOperationInProgress(string property) {
326             return ADP.InvalidOperation(Res.GetString(Res.SQL_CannotModifyPropertyAsyncOperationInProgress, property));
327         }
NonLocalSSEInstance()328         static internal Exception NonLocalSSEInstance() {
329             return ADP.NotSupported(Res.GetString(Res.SQL_NonLocalSSEInstance));
330         }
331         //
332         // SQL.DataCommand
333         //
NotificationsRequireYukon()334         static internal Exception NotificationsRequireYukon() {
335             return ADP.NotSupported(Res.GetString(Res.SQL_NotificationsRequireYukon));
336         }
337 
NotSupportedEnumerationValue(Type type, int value)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);
340         }
341 
NotSupportedCommandType(CommandType value)342         static internal ArgumentOutOfRangeException NotSupportedCommandType(CommandType value) {
343 #if DEBUG
344             switch(value) {
345             case CommandType.Text:
346             case CommandType.StoredProcedure:
347                 Debug.Assert(false, "valid CommandType " + value.ToString());
348                 break;
349             case CommandType.TableDirect:
350                 break;
351             default:
352                 Debug.Assert(false, "invalid CommandType " + value.ToString());
353                 break;
354             }
355 #endif
356             return NotSupportedEnumerationValue(typeof(CommandType), (int)value);
357         }
NotSupportedIsolationLevel(IsolationLevel value)358         static internal ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value) {
359 #if DEBUG
360             switch(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());
368                 break;
369             case IsolationLevel.Chaos:
370                 break;
371             default:
372                 Debug.Assert(false, "invalid IsolationLevel " + value.ToString());
373                 break;
374             }
375 #endif
376             return NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value);
377         }
378 
OperationCancelled()379         static internal Exception OperationCancelled() {
380             Exception exception = ADP.InvalidOperation(Res.GetString(Res.SQL_OperationCancelled));
381             return exception;
382         }
383 
PendingBeginXXXExists()384         static internal Exception PendingBeginXXXExists() {
385             return ADP.InvalidOperation(Res.GetString(Res.SQL_PendingBeginXXXExists));
386         }
387 
InvalidSqlDependencyTimeout(string param)388         static internal ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param) {
389             return ADP.ArgumentOutOfRange(Res.GetString(Res.SqlDependency_InvalidTimeout), param);
390         }
391 
NonXmlResult()392         static internal Exception NonXmlResult() {
393             return ADP.InvalidOperation(Res.GetString(Res.SQL_NonXmlResult));
394         }
395 
396         //
397         // SQL.DataParameter
398         //
InvalidUdt3PartNameFormat()399         static internal Exception InvalidUdt3PartNameFormat() {
400             return ADP.Argument(Res.GetString(Res.SQL_InvalidUdt3PartNameFormat));
401         }
InvalidParameterTypeNameFormat()402         static internal Exception InvalidParameterTypeNameFormat() {
403             return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterTypeNameFormat));
404         }
InvalidParameterNameLength(string value)405         static internal Exception InvalidParameterNameLength(string value) {
406             return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterNameLength, value));
407         }
PrecisionValueOutOfRange(byte precision)408         static internal Exception PrecisionValueOutOfRange(byte precision) {
409             return ADP.Argument(Res.GetString(Res.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture)));
410         }
ScaleValueOutOfRange(byte scale)411         static internal Exception ScaleValueOutOfRange(byte scale) {
412             return ADP.Argument(Res.GetString(Res.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
413         }
TimeScaleValueOutOfRange(byte scale)414         static internal Exception TimeScaleValueOutOfRange(byte scale) {
415             return ADP.Argument(Res.GetString(Res.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
416         }
InvalidSqlDbType(SqlDbType value)417         static internal Exception InvalidSqlDbType(SqlDbType value) {
418             return ADP.InvalidEnumerationValue(typeof(SqlDbType), (int) value);
419         }
UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName)420         static internal Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName) {
421             return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnsupportedTVPOutputParameter,
422                         direction.ToString(), paramName));
423         }
DBNullNotSupportedForTVPValues(string paramName)424         static internal Exception DBNullNotSupportedForTVPValues(string paramName) {
425             return ADP.NotSupported(Res.GetString(Res.SqlParameter_DBNullNotSupportedForTVP, paramName));
426         }
InvalidTableDerivedPrecisionForTvp(string columnName, byte precision)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));
429         }
UnexpectedTypeNameForNonStructParams(string paramName)430         static internal Exception UnexpectedTypeNameForNonStructParams(string paramName) {
431             return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnexpectedTypeNameForNonStruct, paramName));
432         }
SingleValuedStructNotSupported()433         static internal Exception SingleValuedStructNotSupported() {
434             return ADP.NotSupported(Res.GetString(Res.MetaType_SingleValuedStructNotSupported));
435         }
ParameterInvalidVariant(string paramName)436         static internal Exception ParameterInvalidVariant(string paramName) {
437             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParameterInvalidVariant, paramName));
438         }
439 
MustSetTypeNameForParam(string paramType, string paramName)440         static internal Exception MustSetTypeNameForParam(string paramType, string paramName) {
441             return ADP.Argument(Res.GetString(Res.SQL_ParameterTypeNameRequired, paramType, paramName));
442         }
NullSchemaTableDataTypeNotSupported(string columnName)443         static internal Exception NullSchemaTableDataTypeNotSupported(string columnName) {
444             return ADP.Argument(Res.GetString(Res.NullSchemaTableDataTypeNotSupported, columnName));
445         }
InvalidSchemaTableOrdinals()446         static internal Exception InvalidSchemaTableOrdinals() {
447             return ADP.Argument(Res.GetString(Res.InvalidSchemaTableOrdinals));
448         }
EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber)449         static internal Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber) {
450             return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber));
451         }
EnumeratedRecordFieldCountChanged(int recordNumber)452         static internal Exception EnumeratedRecordFieldCountChanged(int recordNumber) {
453             return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordFieldCountChanged, recordNumber));
454         }
455 
456         //
457         // SQL.SqlDataAdapter
458         //
459 
460         //
461         // SQL.TDSParser
462         //
InvalidTDSVersion()463         static internal Exception InvalidTDSVersion() {
464             return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidTDSVersion));
465         }
ParsingError(ParsingErrorState state)466         static internal Exception ParsingError(ParsingErrorState state) {
467             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)));
468         }
ParsingError(ParsingErrorState state, Exception innerException)469         static internal Exception ParsingError(ParsingErrorState state, Exception innerException) {
470             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)), innerException);
471         }
ParsingErrorValue(ParsingErrorState state, int value)472         static internal Exception ParsingErrorValue(ParsingErrorState state, int value) {
473             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorValue, ((int)state).ToString(CultureInfo.InvariantCulture), value));
474         }
ParsingErrorOffset(ParsingErrorState state, int offset)475         static internal Exception ParsingErrorOffset(ParsingErrorState state, int offset) {
476             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorOffset, ((int)state).ToString(CultureInfo.InvariantCulture), offset));
477         }
ParsingErrorFeatureId(ParsingErrorState state, int featureId)478         static internal Exception ParsingErrorFeatureId(ParsingErrorState state, int featureId) {
479             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorFeatureId, ((int)state).ToString(CultureInfo.InvariantCulture), featureId));
480         }
ParsingErrorToken(ParsingErrorState state, int token)481         static internal Exception ParsingErrorToken(ParsingErrorState state, int token) {
482             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorToken, ((int)state).ToString(CultureInfo.InvariantCulture), token));
483         }
ParsingErrorLength(ParsingErrorState state, int length)484         static internal Exception ParsingErrorLength(ParsingErrorState state, int length) {
485             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorLength, ((int)state).ToString(CultureInfo.InvariantCulture), length));
486         }
ParsingErrorStatus(ParsingErrorState state, int status)487         static internal Exception ParsingErrorStatus(ParsingErrorState state, int status) {
488             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorStatus, ((int)state).ToString(CultureInfo.InvariantCulture), status));
489         }
ParsingErrorLibraryType(ParsingErrorState state, int libraryType)490         static internal Exception ParsingErrorLibraryType(ParsingErrorState state, int libraryType) {
491             return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingErrorAuthLibraryType, ((int)state).ToString(CultureInfo.InvariantCulture), libraryType));
492         }
493 
MoneyOverflow(string moneyValue)494         static internal Exception MoneyOverflow(string moneyValue) {
495             return ADP.Overflow(Res.GetString(Res.SQL_MoneyOverflow, moneyValue));
496         }
SmallDateTimeOverflow(string datetime)497         static internal Exception SmallDateTimeOverflow(string datetime) {
498             return ADP.Overflow(Res.GetString(Res.SQL_SmallDateTimeOverflow, datetime));
499         }
SNIPacketAllocationFailure()500         static internal Exception SNIPacketAllocationFailure() {
501             return ADP.InvalidOperation(Res.GetString(Res.SQL_SNIPacketAllocationFailure));
502         }
TimeOverflow(string time)503         static internal Exception TimeOverflow(string time) {
504             return ADP.Overflow(Res.GetString(Res.SQL_TimeOverflow, time));
505         }
506 
507         //
508         // SQL.SqlDataReader
509         //
InvalidRead()510         static internal Exception InvalidRead() {
511             return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidRead));
512         }
513 
NonBlobColumn(string columnName)514         static internal Exception NonBlobColumn(string columnName) {
515             return ADP.InvalidCast(Res.GetString(Res.SQL_NonBlobColumn, columnName));
516         }
517 
NonCharColumn(string columnName)518         static internal Exception NonCharColumn(string columnName) {
519             return ADP.InvalidCast(Res.GetString(Res.SQL_NonCharColumn, columnName));
520         }
521 
StreamNotSupportOnColumnType(string columnName)522         static internal Exception StreamNotSupportOnColumnType(string columnName) {
523             return ADP.InvalidCast(Res.GetString(Res.SQL_StreamNotSupportOnColumnType, columnName));
524         }
525 
StreamNotSupportOnEncryptedColumn(string columnName)526         static internal Exception StreamNotSupportOnEncryptedColumn(string columnName) {
527             return ADP.InvalidOperation(Res.GetString(Res.TCE_StreamNotSupportOnEncryptedColumn, columnName, "Stream"));
528         }
529 
SequentialAccessNotSupportedOnEncryptedColumn(string columnName)530         static internal Exception SequentialAccessNotSupportedOnEncryptedColumn(string columnName) {
531             return ADP.InvalidOperation(Res.GetString(Res.TCE_SequentialAccessNotSupportedOnEncryptedColumn, columnName, "CommandBehavior=SequentialAccess"));
532         }
533 
TextReaderNotSupportOnColumnType(string columnName)534         static internal Exception TextReaderNotSupportOnColumnType(string columnName) {
535             return ADP.InvalidCast(Res.GetString(Res.SQL_TextReaderNotSupportOnColumnType, columnName));
536         }
537 
XmlReaderNotSupportOnColumnType(string columnName)538         static internal Exception XmlReaderNotSupportOnColumnType(string columnName) {
539             return ADP.InvalidCast(Res.GetString(Res.SQL_XmlReaderNotSupportOnColumnType, columnName));
540         }
541 
UDTUnexpectedResult(string exceptionText)542         static internal Exception UDTUnexpectedResult(string exceptionText){
543             return ADP.TypeLoad(Res.GetString(Res.SQLUDT_Unexpected,exceptionText));
544         }
545 
546 
547         //
548         // SQL.SqlDelegatedTransaction
549         //
CannotCompleteDelegatedTransactionWithOpenResults(SqlInternalConnectionTds internalConnection)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);
554         }
PromotionFailed(Exception inner)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);
558             return e;
559         }
560 
561         //
562         // SQL.SqlDependency
563         //
SqlCommandHasExistingSqlNotificationRequest()564         static internal Exception SqlCommandHasExistingSqlNotificationRequest(){
565             return ADP.InvalidOperation(Res.GetString(Res.SQLNotify_AlreadyHasCommand));
566         }
567 
SqlDepCannotBeCreatedInProc()568         static internal Exception SqlDepCannotBeCreatedInProc() {
569             return ADP.InvalidOperation(Res.GetString(Res.SqlNotify_SqlDepCannotBeCreatedInProc));
570         }
571 
SqlDepDefaultOptionsButNoStart()572         static internal Exception SqlDepDefaultOptionsButNoStart() {
573             return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DefaultOptionsButNoStart));
574         }
575 
SqlDependencyDatabaseBrokerDisabled()576         static internal Exception SqlDependencyDatabaseBrokerDisabled() {
577             return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DatabaseBrokerDisabled));
578         }
579 
SqlDependencyEventNoDuplicate()580         static internal Exception SqlDependencyEventNoDuplicate() {
581             return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_EventNoDuplicate));
582         }
583 
SqlDependencyDuplicateStart()584         static internal Exception SqlDependencyDuplicateStart() {
585             return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DuplicateStart));
586         }
587 
SqlDependencyIdMismatch()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));
591         }
592 
SqlDependencyNoMatchingServerStart()593         static internal Exception SqlDependencyNoMatchingServerStart() {
594             return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_NoMatchingServerStart));
595         }
596 
SqlDependencyNoMatchingServerDatabaseStart()597         static internal Exception SqlDependencyNoMatchingServerDatabaseStart() {
598             return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_NoMatchingServerDatabaseStart));
599         }
600 
SqlNotificationException(SqlNotificationEventArgs notify)601         static internal Exception SqlNotificationException(SqlNotificationEventArgs notify){
602             return ADP.InvalidOperation(Res.GetString(Res.SQLNotify_ErrorFormat, notify.Type,notify.Info,notify.Source));
603         }
604 
605         //
606         // SQL.SqlMetaData
607         //
SqlMetaDataNoMetaData()608         static internal Exception SqlMetaDataNoMetaData(){
609             return ADP.InvalidOperation(Res.GetString(Res.SqlMetaData_NoMetadata));
610         }
611 
MustSetUdtTypeNameForUdtParams()612         static internal Exception MustSetUdtTypeNameForUdtParams(){
613             return ADP.Argument(Res.GetString(Res.SQLUDT_InvalidUdtTypeName));
614         }
615 
UnexpectedUdtTypeNameForNonUdtParams()616         static internal Exception UnexpectedUdtTypeNameForNonUdtParams(){
617             return ADP.Argument(Res.GetString(Res.SQLUDT_UnexpectedUdtTypeName));
618         }
619 
UDTInvalidSqlType(string typeName)620         static internal Exception UDTInvalidSqlType(string typeName){
621             return ADP.Argument(Res.GetString(Res.SQLUDT_InvalidSqlType, typeName));
622         }
623 
InvalidSqlDbTypeForConstructor(SqlDbType type)624         static internal Exception InvalidSqlDbTypeForConstructor(SqlDbType type) {
625             return ADP.Argument(Res.GetString(Res.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString()));
626         }
627 
NameTooLong(string parameterName)628         static internal Exception NameTooLong(string parameterName) {
629             return ADP.Argument(Res.GetString(Res.SqlMetaData_NameTooLong), parameterName);
630         }
631 
InvalidSortOrder(SortOrder order)632         static internal Exception InvalidSortOrder(SortOrder order) {
633             return ADP.InvalidEnumerationValue(typeof(SortOrder), (int)order);
634         }
635 
MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal)636         static internal Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal) {
637             return ADP.InvalidOperation(Res.GetString(Res.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal));
638         }
639 
TableTypeCanOnlyBeParameter()640         static internal Exception TableTypeCanOnlyBeParameter() {
641             return ADP.Argument(Res.GetString(Res.SQLTVP_TableTypeCanOnlyBeParameter));
642         }
UnsupportedColumnTypeForSqlProvider(string columnName, string typeName)643         static internal Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName) {
644             return ADP.Argument(Res.GetString(Res.SqlProvider_InvalidDataColumnType, columnName, typeName));
645         }
InvalidColumnMaxLength(string columnName, long maxLength)646         static internal Exception InvalidColumnMaxLength(string columnName, long maxLength) {
647             return ADP.Argument(Res.GetString(Res.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength));
648         }
InvalidColumnPrecScale()649         static internal Exception InvalidColumnPrecScale() {
650             return ADP.Argument(Res.GetString(Res.SqlMisc_InvalidPrecScaleMessage));
651         }
NotEnoughColumnsInStructuredType()652         static internal Exception NotEnoughColumnsInStructuredType() {
653             return ADP.Argument(Res.GetString(Res.SqlProvider_NotEnoughColumnsInStructuredType));
654         }
DuplicateSortOrdinal(int sortOrdinal)655         static internal Exception DuplicateSortOrdinal(int sortOrdinal) {
656             return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_DuplicateSortOrdinal, sortOrdinal));
657         }
MissingSortOrdinal(int sortOrdinal)658         static internal Exception MissingSortOrdinal(int sortOrdinal) {
659             return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_MissingSortOrdinal, sortOrdinal));
660         }
SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal)661         static internal Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal) {
662             return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal));
663         }
IEnumerableOfSqlDataRecordHasNoRows()664         static internal Exception IEnumerableOfSqlDataRecordHasNoRows() {
665             return ADP.Argument(Res.GetString(Res.IEnumerableOfSqlDataRecordHasNoRows));
666         }
667 
668 
669 
670         //
671         //  SqlPipe
672         //
SqlPipeCommandHookedUpToNonContextConnection()673         static internal Exception SqlPipeCommandHookedUpToNonContextConnection() {
674             return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_CommandHookedUpToNonContextConnection));
675         }
676 
SqlPipeMessageTooLong( int messageLength )677         static internal Exception SqlPipeMessageTooLong( int messageLength ) {
678             return ADP.Argument(Res.GetString(Res.SqlPipe_MessageTooLong, messageLength));
679         }
680 
SqlPipeIsBusy()681         static internal Exception SqlPipeIsBusy() {
682             return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_IsBusy));
683         }
684 
SqlPipeAlreadyHasAnOpenResultSet( string methodName )685         static internal Exception SqlPipeAlreadyHasAnOpenResultSet( string methodName ) {
686             return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_AlreadyHasAnOpenResultSet, methodName));
687         }
688 
SqlPipeDoesNotHaveAnOpenResultSet( string methodName )689         static internal Exception SqlPipeDoesNotHaveAnOpenResultSet( string methodName ) {
690             return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_DoesNotHaveAnOpenResultSet, methodName));
691         }
692 
693         //
694         // : ISqlResultSet
695         //
SqlResultSetClosed(string methodname)696         static internal Exception SqlResultSetClosed(string methodname) {
697             if (methodname == null) {
698                 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetClosed2));
699             }
700             return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetClosed, methodname));
701         }
SqlResultSetNoData(string methodname)702         static internal Exception SqlResultSetNoData(string methodname) {
703             return ADP.InvalidOperation(Res.GetString(Res.ADP_DataReaderNoData, methodname));
704         }
SqlRecordReadOnly(string methodname)705         static internal Exception SqlRecordReadOnly(string methodname) {
706             if (methodname == null) {
707                 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlRecordReadOnly2));
708             }
709             return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlRecordReadOnly, methodname));
710         }
711 
SqlResultSetRowDeleted(string methodname)712         static internal Exception SqlResultSetRowDeleted(string methodname) {
713             if (methodname == null) {
714                 return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetRowDeleted2));
715             }
716             return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetRowDeleted, methodname));
717         }
718 
SqlResultSetCommandNotInSameConnection()719         static internal Exception SqlResultSetCommandNotInSameConnection() {
720             return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetCommandNotInSameConnection));
721         }
722 
SqlResultSetNoAcceptableCursor()723         static internal Exception SqlResultSetNoAcceptableCursor() {
724             return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetNoAcceptableCursor));
725         }
726 
727         //
728         // SQL.BulkLoad
729         //
BulkLoadMappingInaccessible()730         static internal Exception BulkLoadMappingInaccessible() {
731             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingInaccessible));
732         }
BulkLoadMappingsNamesOrOrdinalsOnly()733         static internal Exception BulkLoadMappingsNamesOrOrdinalsOnly() {
734             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingsNamesOrOrdinalsOnly));
735         }
736 #if !MONO
BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, Exception e)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);
739         }
740 #endif
BulkLoadNonMatchingColumnMapping()741         static internal Exception BulkLoadNonMatchingColumnMapping() {
742             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnMapping));
743         }
BulkLoadNonMatchingColumnName(string columnName)744         static internal Exception BulkLoadNonMatchingColumnName(string columnName) {
745             return BulkLoadNonMatchingColumnName(columnName, null);
746         }
BulkLoadNonMatchingColumnName(string columnName, Exception e)747         static internal Exception BulkLoadNonMatchingColumnName(string columnName, Exception e) {
748             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnName, columnName), e);
749         }
BulkLoadStringTooLong()750         static internal Exception BulkLoadStringTooLong() {
751             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadStringTooLong));
752         }
BulkLoadInvalidVariantValue()753         static internal Exception BulkLoadInvalidVariantValue() {
754             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidVariantValue));
755         }
BulkLoadInvalidTimeout(int timeout)756         static internal Exception BulkLoadInvalidTimeout(int timeout) {
757             return ADP.Argument(Res.GetString(Res.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture)));
758         }
BulkLoadExistingTransaction()759         static internal Exception BulkLoadExistingTransaction() {
760             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadExistingTransaction));
761         }
BulkLoadNoCollation()762         static internal Exception BulkLoadNoCollation() {
763             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNoCollation));
764         }
BulkLoadConflictingTransactionOption()765         static internal Exception BulkLoadConflictingTransactionOption() {
766             return ADP.Argument(Res.GetString(Res.SQL_BulkLoadConflictingTransactionOption));
767         }
BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName)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));
770         }
InvalidOperationInsideEvent()771         static internal Exception InvalidOperationInsideEvent() {
772             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidOperationInsideEvent));
773         }
BulkLoadMissingDestinationTable()774         static internal Exception BulkLoadMissingDestinationTable() {
775             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMissingDestinationTable));
776         }
BulkLoadInvalidDestinationTable(string tableName, Exception inner)777         static internal Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner) {
778             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidDestinationTable, tableName), inner);
779         }
BulkLoadBulkLoadNotAllowDBNull(string columnName)780         static internal Exception BulkLoadBulkLoadNotAllowDBNull(string columnName) {
781             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNotAllowDBNull, columnName));
782         }
BulkLoadPendingOperation()783         static internal Exception BulkLoadPendingOperation() {
784             return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadPendingOperation));
785         }
786 
787         //
788         // TCE - Certificate Store Provider Errors.
789         //
InvalidKeyEncryptionAlgorithm(string encryptionAlgorithm, string validEncryptionAlgorithm, bool isSystemOp)790         static internal Exception InvalidKeyEncryptionAlgorithm(string encryptionAlgorithm, string validEncryptionAlgorithm, bool isSystemOp) {
791             if (isSystemOp) {
792                 return ADP.Argument(Res.GetString(Res.TCE_InvalidKeyEncryptionAlgorithmSysErr, encryptionAlgorithm, validEncryptionAlgorithm), TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM);
793             }
794             else {
795                 return ADP.Argument(Res.GetString(Res.TCE_InvalidKeyEncryptionAlgorithm, encryptionAlgorithm, validEncryptionAlgorithm), TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM);
796             }
797         }
798 
NullKeyEncryptionAlgorithm(bool isSystemOp)799         static internal Exception NullKeyEncryptionAlgorithm(bool isSystemOp) {
800             if (isSystemOp) {
801                 return ADP.ArgumentNull (TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, Res.GetString(Res.TCE_NullKeyEncryptionAlgorithmSysErr));
802             }
803             else {
804                 return ADP.ArgumentNull (TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, Res.GetString(Res.TCE_NullKeyEncryptionAlgorithm));
805             }
806         }
807 
EmptyColumnEncryptionKey()808         static internal Exception EmptyColumnEncryptionKey() {
809             return ADP.Argument(Res.GetString(Res.TCE_EmptyColumnEncryptionKey), TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY);
810         }
811 
NullColumnEncryptionKey()812         static internal Exception NullColumnEncryptionKey() {
813             return ADP.ArgumentNull(TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY, Res.GetString(Res.TCE_NullColumnEncryptionKey));
814         }
815 
EmptyEncryptedColumnEncryptionKey()816         static internal Exception EmptyEncryptedColumnEncryptionKey() {
817             return ADP.Argument(Res.GetString(Res.TCE_EmptyEncryptedColumnEncryptionKey), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
818         }
819 
NullEncryptedColumnEncryptionKey()820         static internal Exception NullEncryptedColumnEncryptionKey() {
821             return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTED_CEK, Res.GetString(Res.TCE_NullEncryptedColumnEncryptionKey));
822         }
823 
LargeCertificatePathLength(int actualLength, int maxLength, bool isSystemOp)824         static internal Exception LargeCertificatePathLength(int actualLength, int maxLength, bool isSystemOp) {
825             if (isSystemOp) {
826                 return ADP.Argument(Res.GetString(Res.TCE_LargeCertificatePathLengthSysErr, actualLength, maxLength), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
827             }
828             else {
829                 return ADP.Argument(Res.GetString(Res.TCE_LargeCertificatePathLength, actualLength, maxLength), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
830             }
831         }
832 
NullCertificatePath(string[] validLocations, bool isSystemOp)833         static internal Exception NullCertificatePath(string[] validLocations, bool isSystemOp) {
834             Debug.Assert(2 == validLocations.Length);
835             if (isSystemOp) {
836                 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCertificatePathSysErr, validLocations[0], validLocations[1], @"/"));
837             }
838             else {
839                 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCertificatePath, validLocations[0], validLocations[1], @"/"));
840             }
841         }
842 
NullCspKeyPath(bool isSystemOp)843         static internal Exception NullCspKeyPath(bool isSystemOp) {
844             if (isSystemOp) {
845                 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCspPathSysErr, @"/"));
846             }
847             else {
848                 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCspPath, @"/"));
849             }
850         }
851 
NullCngKeyPath(bool isSystemOp)852         static internal Exception NullCngKeyPath(bool isSystemOp) {
853             if (isSystemOp) {
854                 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCngPathSysErr, @"/"));
855             }
856             else {
857                 return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, Res.GetString(Res.TCE_NullCngPath, @"/"));
858             }
859         }
860 
InvalidCertificatePath(string actualCertificatePath, string[] validLocations, bool isSystemOp)861         static internal Exception InvalidCertificatePath(string actualCertificatePath, string[] validLocations, bool isSystemOp) {
862             Debug.Assert(2 == validLocations.Length);
863             if (isSystemOp) {
864                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificatePathSysErr, actualCertificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
865             }
866             else {
867                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificatePath, actualCertificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
868             }
869         }
870 
InvalidCspPath(string masterKeyPath, bool isSystemOp)871         static internal Exception InvalidCspPath(string masterKeyPath, bool isSystemOp) {
872             if (isSystemOp) {
873                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspPathSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
874             }
875             else {
876                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspPath, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
877             }
878         }
879 
InvalidCngPath(string masterKeyPath, bool isSystemOp)880         static internal Exception InvalidCngPath(string masterKeyPath, bool isSystemOp) {
881             if (isSystemOp) {
882                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngPathSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
883             }
884             else {
885                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngPath, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
886             }
887         }
888 
EmptyCspName(string masterKeyPath, bool isSystemOp)889         static internal Exception EmptyCspName(string masterKeyPath, bool isSystemOp) {
890             if (isSystemOp) {
891                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspNameSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
892             }
893             else {
894                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspName, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
895             }
896         }
897 
EmptyCngName(string masterKeyPath, bool isSystemOp)898         static internal Exception EmptyCngName(string masterKeyPath, bool isSystemOp) {
899             if (isSystemOp) {
900                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngNameSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
901             }
902             else {
903                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngName, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
904             }
905         }
906 
EmptyCspKeyId(string masterKeyPath, bool isSystemOp)907         static internal Exception EmptyCspKeyId(string masterKeyPath, bool isSystemOp) {
908             if (isSystemOp) {
909                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspKeyIdSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
910             }
911             else {
912                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCspKeyId, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
913             }
914         }
915 
EmptyCngKeyId(string masterKeyPath, bool isSystemOp)916         static internal Exception EmptyCngKeyId(string masterKeyPath, bool isSystemOp) {
917             if (isSystemOp) {
918                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngKeyIdSysErr, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
919             }
920             else {
921                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCngKeyId, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
922             }
923         }
924 
InvalidCspName(string cspName, string masterKeyPath, bool isSystemOp)925         static internal Exception InvalidCspName(string cspName, string masterKeyPath, bool isSystemOp) {
926             if (isSystemOp) {
927                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspNameSysErr, cspName, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
928             }
929             else {
930                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspName, cspName, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
931             }
932         }
933 
InvalidCspKeyIdentifier(string keyIdentifier, string masterKeyPath, bool isSystemOp)934         static internal Exception InvalidCspKeyIdentifier(string keyIdentifier, string masterKeyPath, bool isSystemOp) {
935             if (isSystemOp) {
936                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspKeyIdSysErr, keyIdentifier, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
937             }
938             else {
939                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCspKeyId, keyIdentifier, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
940             }
941         }
942 
InvalidCngKey(string masterKeyPath, string cngProviderName, string keyIdentifier, bool isSystemOp)943         static internal Exception InvalidCngKey(string masterKeyPath, string cngProviderName, string keyIdentifier, bool isSystemOp) {
944             if (isSystemOp) {
945                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngKeySysErr, masterKeyPath, cngProviderName, keyIdentifier), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
946             }
947             else {
948                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCngKey, masterKeyPath, cngProviderName, keyIdentifier), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
949             }
950         }
951 
InvalidCertificateLocation(string certificateLocation, string certificatePath, string[] validLocations, bool isSystemOp)952         static internal Exception InvalidCertificateLocation(string certificateLocation, string certificatePath, string[] validLocations, bool isSystemOp) {
953             Debug.Assert(2 == validLocations.Length);
954             if (isSystemOp) {
955                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateLocationSysErr, certificateLocation, certificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
956             }
957             else {
958                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateLocation, certificateLocation, certificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
959             }
960         }
961 
InvalidCertificateStore(string certificateStore, string certificatePath, string validCertificateStore, bool isSystemOp)962         static internal Exception InvalidCertificateStore(string certificateStore, string certificatePath, string validCertificateStore, bool isSystemOp) {
963             if (isSystemOp) {
964                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateStoreSysErr, certificateStore, certificatePath, validCertificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
965             }
966             else {
967                 return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateStore, certificateStore, certificatePath, validCertificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
968             }
969         }
970 
EmptyCertificateThumbprint(string certificatePath, bool isSystemOp)971         static internal Exception EmptyCertificateThumbprint(string certificatePath, bool isSystemOp) {
972             if (isSystemOp) {
973                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCertificateThumbprintSysErr, certificatePath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
974             }
975             else {
976                 return ADP.Argument(Res.GetString(Res.TCE_EmptyCertificateThumbprint, certificatePath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
977             }
978         }
979 
CertificateNotFound(string thumbprint, string certificateLocation, string certificateStore, bool isSystemOp)980         static internal Exception CertificateNotFound(string thumbprint, string certificateLocation, string certificateStore, bool isSystemOp) {
981             if (isSystemOp) {
982                 return ADP.Argument(Res.GetString(Res.TCE_CertificateNotFoundSysErr, thumbprint, certificateLocation, certificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
983             }
984             else {
985                 return ADP.Argument(Res.GetString(Res.TCE_CertificateNotFound, thumbprint, certificateLocation, certificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
986             }
987         }
988 
InvalidAlgorithmVersionInEncryptedCEK(byte actual, byte expected)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);
991         }
992 
InvalidCiphertextLengthInEncryptedCEK(int actual, int expected, string certificateName)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);
995         }
996 
InvalidCiphertextLengthInEncryptedCEKCsp(int actual, int expected, string masterKeyPath)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);
999         }
1000 
InvalidCiphertextLengthInEncryptedCEKCng(int actual, int expected, string masterKeyPath)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);
1003         }
1004 
InvalidSignatureInEncryptedCEK(int actual, int expected, string masterKeyPath)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);
1007         }
1008 
InvalidSignatureInEncryptedCEKCsp(int actual, int expected, string masterKeyPath)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);
1011         }
1012 
InvalidSignatureInEncryptedCEKCng(int actual, int expected, string masterKeyPath)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);
1015         }
1016 
InvalidCertificateSignature(string certificatePath)1017         static internal Exception InvalidCertificateSignature(string certificatePath) {
1018             return ADP.Argument(Res.GetString(Res.TCE_InvalidCertificateSignature, certificatePath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1019         }
1020 
InvalidSignature(string masterKeyPath)1021         static internal Exception InvalidSignature(string masterKeyPath) {
1022             return ADP.Argument(Res.GetString(Res.TCE_InvalidSignature, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK);
1023         }
1024 
CertificateWithNoPrivateKey(string keyPath, bool isSystemOp)1025         static internal Exception CertificateWithNoPrivateKey(string keyPath, bool isSystemOp) {
1026             if (isSystemOp) {
1027                 return ADP.Argument(Res.GetString(Res.TCE_CertificateWithNoPrivateKeySysErr, keyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
1028             }
1029             else {
1030                 return ADP.Argument(Res.GetString(Res.TCE_CertificateWithNoPrivateKey, keyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH);
1031             }
1032         }
1033 
1034         //
1035         // TCE - Cryptographic Algorithms Error messages
1036         //
NullColumnEncryptionKeySysErr()1037         static internal Exception NullColumnEncryptionKeySysErr() {
1038             return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTIONKEY,Res.GetString(Res.TCE_NullColumnEncryptionKeySysErr));
1039         }
1040 
InvalidKeySize(string algorithmName, int actualKeylength, int expectedLength)1041         static internal Exception InvalidKeySize(string algorithmName, int actualKeylength, int expectedLength) {
1042             return ADP.Argument(Res.GetString(
1043                                 Res.TCE_InvalidKeySize,
1044                                 algorithmName,
1045                                 actualKeylength,
1046                                 expectedLength), TdsEnums.TCE_PARAM_ENCRYPTIONKEY);
1047         }
1048 
InvalidEncryptionType(string algorithmName, SqlClientEncryptionType encryptionType, params SqlClientEncryptionType[] validEncryptionTypes)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,
1053                                 algorithmName,
1054                                 encryptionType.ToString(),
1055                                 string.Join(valueSeparator, validEncryptionTypes.Select((validEncryptionType => @"'" + validEncryptionType + @"'")))), TdsEnums.TCE_PARAM_ENCRYPTIONTYPE);
1056         }
1057 
NullPlainText()1058         static internal Exception NullPlainText () {
1059             return ADP.ArgumentNull (Res.GetString(Res.TCE_NullPlainText));
1060         }
1061 
VeryLargeCiphertext(long cipherTextLength, long maxCipherTextSize, long plainTextLength)1062         static internal Exception VeryLargeCiphertext(long cipherTextLength, long maxCipherTextSize, long plainTextLength) {
1063             return ADP.Argument(Res.GetString(Res.TCE_VeryLargeCiphertext, cipherTextLength,  maxCipherTextSize, plainTextLength));
1064         }
1065 
NullCipherText()1066         static internal Exception NullCipherText () {
1067             return ADP.ArgumentNull (Res.GetString(Res.TCE_NullCipherText));
1068         }
1069 
InvalidCipherTextSize(int actualSize, int minimumSize)1070         static internal Exception InvalidCipherTextSize(int actualSize, int minimumSize) {
1071             return ADP.Argument(Res.GetString(Res.TCE_InvalidCipherTextSize, actualSize, minimumSize), TdsEnums.TCE_PARAM_CIPHERTEXT);
1072         }
1073 
InvalidAlgorithmVersion(byte actual, byte expected)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);
1076         }
1077 
InvalidAuthenticationTag()1078         static internal Exception InvalidAuthenticationTag() {
1079             return ADP.Argument(Res.GetString(Res.TCE_InvalidAuthenticationTag), TdsEnums.TCE_PARAM_CIPHERTEXT);
1080         }
1081 
NullColumnEncryptionAlgorithm(string supportedAlgorithms)1082         static internal Exception NullColumnEncryptionAlgorithm (string supportedAlgorithms) {
1083             return ADP.ArgumentNull (TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, Res.GetString(Res.TCE_NullColumnEncryptionAlgorithm, supportedAlgorithms));
1084         }
1085 
1086         //
1087         // TCE - Errors from sp_describe_parameter_encryption
1088         //
UnexpectedDescribeParamFormat()1089         static internal Exception UnexpectedDescribeParamFormat () {
1090             return ADP.Argument (Res.GetString(Res.TCE_UnexpectedDescribeParamFormat, "sp_describe_parameter_encryption"));
1091         }
1092 
InvalidEncryptionKeyOrdinal(int ordinal, int maxOrdinal)1093         static internal Exception InvalidEncryptionKeyOrdinal (int ordinal, int maxOrdinal) {
1094             return ADP.InvalidOperation(Res.GetString(Res.TCE_InvalidEncryptionKeyOrdinal, "sp_describe_parameter_encryption",  ordinal, maxOrdinal));
1095         }
1096 
ParamEncryptionMetadataMissing(string paramName, string procedureName)1097         static internal Exception ParamEncryptionMetadataMissing (string paramName, string procedureName) {
1098             return ADP.Argument (Res.GetString(Res.TCE_ParamEncryptionMetaDataMissing, "sp_describe_parameter_encryption", paramName, procedureName));
1099         }
1100 
ParamInvalidForceColumnEncryptionSetting(string paramName, string 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"));
1103         }
1104 
ParamUnExpectedEncryptionMetadata(string paramName, string procedureName)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"));
1107         }
1108 
ProcEncryptionMetadataMissing(string procedureName)1109         static internal Exception ProcEncryptionMetadataMissing (string procedureName) {
1110             return ADP.Argument (Res.GetString(Res.TCE_ProcEncryptionMetaDataMissing, "sp_describe_parameter_encryption", procedureName));
1111         }
1112 
1113         //
1114         // TCE- Generic toplevel failures.
1115         //
GetExceptionArray(string serverName, string errorMessage, Exception e)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));
1121 
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]);
1127                 }
1128             }
1129             else {
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));
1131             }
1132 
1133             return SqlException.CreateException(sqlErs, "", null, exceptionToInclude);
1134         }
1135 
ParamEncryptionFailed(string paramName, string serverName, Exception e)1136         static internal Exception ParamEncryptionFailed (string paramName, string serverName, Exception e){
1137             return GetExceptionArray (serverName, Res.GetString(Res.TCE_ParamEncryptionFailed, paramName), e);
1138         }
1139 
ParamDecryptionFailed(string paramName, string serverName, Exception e)1140         static internal Exception ParamDecryptionFailed (string paramName, string serverName, Exception e) {
1141             return GetExceptionArray (serverName, Res.GetString(Res.TCE_ParamDecryptionFailed, paramName), e);
1142         }
1143 
ColumnDecryptionFailed(string columnName, string serverName, Exception e)1144         static internal Exception ColumnDecryptionFailed (string columnName, string serverName, Exception e) {
1145             return GetExceptionArray (serverName, Res.GetString(Res.TCE_ColumnDecryptionFailed, columnName), e);
1146         }
1147 
1148         //
1149         // TCE- Client side query processing errors.
1150         //
UnknownColumnEncryptionAlgorithm(string algorithmName, string supportedAlgorithms)1151         static internal Exception UnknownColumnEncryptionAlgorithm (string algorithmName, string supportedAlgorithms) {
1152             return ADP.Argument(Res.GetString(Res.TCE_UnknownColumnEncryptionAlgorithm, algorithmName, supportedAlgorithms));
1153         }
1154 
UnknownColumnEncryptionAlgorithmId(int algoId, string supportAlgorithmIds)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);
1157         }
1158 
UnsupportedNormalizationVersion(byte version)1159         static internal Exception UnsupportedNormalizationVersion (byte version) {
1160             return ADP.Argument(Res.GetString(Res.TCE_UnsupportedNormalizationVersion, version, "'1'", "SQL Server"));
1161         }
1162 
UnrecognizedKeyStoreProviderName(string providerName, List<string> systemProviders, List<string> customProviders)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));
1168         }
1169 
InvalidDataTypeForEncryptedParameter(string parameterName, int actualDataType, int expectedDataType)1170         static internal Exception InvalidDataTypeForEncryptedParameter(string parameterName, int actualDataType, int expectedDataType) {
1171             return ADP.Argument(Res.GetString(Res.TCE_NullProviderValue, parameterName, actualDataType, expectedDataType));
1172         }
1173 #if !MONO
KeyDecryptionFailed(string providerName, string keyHex, Exception e)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);
1177             }
1178             else {
1179                 return GetExceptionArray(null, Res.GetString(Res.TCE_KeyDecryptionFailed, providerName, keyHex), e);
1180             }
1181         }
1182 #endif
UntrustedKeyPath(string keyPath, string serverName)1183         static internal Exception UntrustedKeyPath(string keyPath, string serverName) {
1184             return ADP.Argument(Res.GetString(Res.TCE_UntrustedKeyPath, keyPath, serverName));
1185         }
1186 
UnsupportedDatatypeEncryption(string dataType)1187         static internal Exception UnsupportedDatatypeEncryption (string dataType) {
1188             return ADP.Argument(Res.GetString(Res.TCE_UnsupportedDatatype, dataType));
1189         }
1190 
ThrowDecryptionFailed(string keyStr, string valStr, Exception e)1191         static internal Exception ThrowDecryptionFailed (string keyStr, string valStr, Exception e) {
1192             return GetExceptionArray (null, Res.GetString(Res.TCE_DecryptionFailed, keyStr, valStr), e);
1193         }
1194 
1195         //
1196         // TCE- SQL connection related error messages
1197         //
TceNotSupported()1198         static internal Exception TceNotSupported() {
1199             return ADP.InvalidOperation (Res.GetString (Res.TCE_NotSupportedByServer, "SQL Server"));
1200         }
1201 
1202         //
1203         // TCE- Extensibility related error messages
1204         //
CanOnlyCallOnce()1205         static internal Exception CanOnlyCallOnce() {
1206             return ADP.InvalidOperation(Res.GetString(Res.TCE_CanOnlyCallOnce));
1207         }
1208 
NullCustomKeyStoreProviderDictionary()1209         static internal Exception NullCustomKeyStoreProviderDictionary() {
1210             return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, Res.GetString(Res.TCE_NullCustomKeyStoreProviderDictionary));
1211         }
1212 
InvalidCustomKeyStoreProviderName(string providerName, string prefix)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);
1215         }
1216 
NullProviderValue(string providerName)1217         static internal Exception NullProviderValue(string providerName) {
1218             return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, Res.GetString(Res.TCE_NullProviderValue, providerName));
1219         }
1220 
EmptyProviderName()1221         static internal Exception EmptyProviderName() {
1222             return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, Res.GetString(Res.TCE_EmptyProviderName));
1223         }
1224 
1225         //
1226         // transactions.
1227         //
ConnectionDoomed()1228         static internal Exception ConnectionDoomed() {
1229             return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionDoomed));
1230         }
1231 
OpenResultCountExceeded()1232         static internal Exception OpenResultCountExceeded() {
1233             return ADP.InvalidOperation(Res.GetString(Res.SQL_OpenResultCountExceeded));
1234         }
1235 
1236         //
1237         // Global Transactions.
1238         //
GlobalTransactionsNotEnabled()1239         static internal Exception GlobalTransactionsNotEnabled() {
1240             return ADP.InvalidOperation(Res.GetString(Res.GT_Disabled));
1241         }
1242 
UnsupportedSysTxForGlobalTransactions()1243         static internal Exception UnsupportedSysTxForGlobalTransactions() {
1244             return ADP.InvalidOperation(Res.GetString(Res.GT_UnsupportedSysTxVersion));
1245         }
1246 
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
1252             0,                              // spid
1253             0,                              // spid
1254             0,                              // packet (out of band)
1255             0                               // window
1256         };
1257 
1258         //
1259         // MultiSubnetFailover
1260         //
1261 
1262         /// <summary>
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
1266         /// </summary>
MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection)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
1275                 return exc;
1276             }
1277             else {
1278                 return ADP.Argument(msg);
1279             }
1280         }
1281 #if !MONO
MultiSubnetFailoverWithMoreThan64IPs()1282         static internal Exception MultiSubnetFailoverWithMoreThan64IPs() {
1283             string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs);
1284             return ADP.InvalidOperation(msg);
1285         }
1286 
MultiSubnetFailoverWithInstanceSpecified()1287         static internal Exception MultiSubnetFailoverWithInstanceSpecified() {
1288             string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified);
1289             return ADP.Argument(msg);
1290         }
1291 
MultiSubnetFailoverWithNonTcpProtocol()1292         static internal Exception MultiSubnetFailoverWithNonTcpProtocol() {
1293             string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol);
1294             return ADP.Argument(msg);
1295         }
1296 #endif
1297         //
1298         // Read-only routing
1299         //
1300 
ROR_FailoverNotSupportedConnString()1301         static internal Exception ROR_FailoverNotSupportedConnString() {
1302             return ADP.Argument(Res.GetString(Res.SQLROR_FailoverNotSupported));
1303         }
1304 
ROR_FailoverNotSupportedServer(SqlInternalConnectionTds internalConnection)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;
1310             return exc;
1311         }
1312 
ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection)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;
1318             return exc;
1319         }
1320 
ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection)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;
1326             return exc;
1327         }
1328 
ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection)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;
1334             return exc;
1335         }
1336 
ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection)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;
1342             return exc;
1343         }
1344 
1345         //
1346         // Connection resiliency
1347         //
CR_ReconnectTimeout()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, "");
1352             return exc;
1353         }
1354 
CR_ReconnectionCancelled()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, "");
1359             return exc;
1360         }
1361 
CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId)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);
1366             return exc;
1367         }
1368 
CR_EncryptionChanged(SqlInternalConnectionTds internalConnection)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);
1373             return exc;
1374         }
1375 
CR_AllAttemptsFailed(SqlException innerException, Guid connectionId)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);
1380             return exc;
1381         }
1382 
CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection)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);
1387             return exc;
1388         }
1389 
CR_TDSVersionNotPreserved(SqlInternalConnectionTds 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);
1394             return exc;
1395         }
1396 
CR_UnrecoverableServer(Guid connectionId)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);
1401             return exc;
1402         }
1403 
CR_UnrecoverableClient(Guid 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);
1408             return exc;
1409         }
1410 
1411         //
1412         // Merged Provider
1413         //
BatchedUpdatesNotAvailableOnContextConnection()1414         static internal Exception BatchedUpdatesNotAvailableOnContextConnection() {
1415             return ADP.InvalidOperation(Res.GetString(Res.SQL_BatchedUpdatesNotAvailableOnContextConnection));
1416         }
ContextAllowsLimitedKeywords()1417         static internal Exception ContextAllowsLimitedKeywords() {
1418             return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextAllowsLimitedKeywords));
1419         }
ContextAllowsOnlyTypeSystem2005()1420         static internal Exception ContextAllowsOnlyTypeSystem2005() {
1421             return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextAllowsOnlyTypeSystem2005));
1422         }
ContextConnectionIsInUse()1423         static internal Exception ContextConnectionIsInUse() {
1424             return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextConnectionIsInUse));
1425         }
ContextUnavailableOutOfProc()1426         static internal Exception ContextUnavailableOutOfProc() {
1427             return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextUnavailableOutOfProc));
1428         }
ContextUnavailableWhileInProc()1429         static internal Exception ContextUnavailableWhileInProc() {
1430             return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextUnavailableWhileInProc));
1431         }
NestedTransactionScopesNotSupported()1432         static internal Exception NestedTransactionScopesNotSupported() {
1433             return ADP.InvalidOperation(Res.GetString(Res.SQL_NestedTransactionScopesNotSupported));
1434         }
NotAvailableOnContextConnection()1435         static internal Exception NotAvailableOnContextConnection() {
1436             return ADP.InvalidOperation(Res.GetString(Res.SQL_NotAvailableOnContextConnection));
1437         }
NotificationsNotAvailableOnContextConnection()1438         static internal Exception NotificationsNotAvailableOnContextConnection() {
1439             return ADP.InvalidOperation(Res.GetString(Res.SQL_NotificationsNotAvailableOnContextConnection));
1440         }
1441 #if !MONO
UnexpectedSmiEvent(Microsoft.SqlServer.Server.SmiEventSink_Default.UnexpectedEventType eventType)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));
1445         }
1446 #endif
UserInstanceNotAvailableInProc()1447         static internal Exception UserInstanceNotAvailableInProc() {
1448             return ADP.InvalidOperation(Res.GetString(Res.SQL_UserInstanceNotAvailableInProc));
1449         }
ArgumentLengthMismatch( string arg1, string arg2 )1450         static internal Exception ArgumentLengthMismatch( string arg1, string arg2 ) {
1451             return ADP.Argument( Res.GetString( Res.SQL_ArgumentLengthMismatch, arg1, arg2 ) );
1452         }
InvalidSqlDbTypeOneAllowedType( SqlDbType invalidType, string method, SqlDbType allowedType )1453         static internal Exception InvalidSqlDbTypeOneAllowedType( SqlDbType invalidType, string method, SqlDbType allowedType ) {
1454             return ADP.Argument( Res.GetString( Res.SQL_InvalidSqlDbTypeWithOneAllowedType, invalidType, method, allowedType ) );
1455         }
SqlPipeErrorRequiresSendEnd( )1456         static internal Exception SqlPipeErrorRequiresSendEnd( ) {
1457             return ADP.InvalidOperation(Res.GetString(Res.SQL_PipeErrorRequiresSendEnd));
1458         }
TooManyValues(string arg)1459         static internal Exception TooManyValues(string arg) {
1460             return ADP.Argument(Res.GetString(Res.SQL_TooManyValues), arg);
1461         }
StreamWriteNotSupported()1462         static internal Exception StreamWriteNotSupported() {
1463             return ADP.NotSupported(Res.GetString(Res.SQL_StreamWriteNotSupported));
1464         }
StreamReadNotSupported()1465         static internal Exception StreamReadNotSupported() {
1466             return ADP.NotSupported(Res.GetString(Res.SQL_StreamReadNotSupported));
1467         }
StreamSeekNotSupported()1468         static internal Exception StreamSeekNotSupported() {
1469             return ADP.NotSupported(Res.GetString(Res.SQL_StreamSeekNotSupported));
1470         }
SqlNullValue()1471         static internal System.Data.SqlTypes.SqlNullValueException SqlNullValue() {
1472             System.Data.SqlTypes.SqlNullValueException e = new System.Data.SqlTypes.SqlNullValueException();
1473             ADP.TraceExceptionAsReturnValue(e);
1474             return e;
1475         }
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.
ParameterSizeRestrictionFailure(int index)1478         static internal Exception ParameterSizeRestrictionFailure(int index) {
1479             return ADP.InvalidOperation(Res.GetString(Res.OleDb_CommandParameterError, index.ToString(CultureInfo.InvariantCulture), "SqlParameter.Size"));
1480         }
SubclassMustOverride()1481         static internal Exception SubclassMustOverride() {
1482             return ADP.InvalidOperation(Res.GetString(Res.SqlMisc_SubclassMustOverride));
1483         }
1484 #if !MONO
1485         /// <summary>
1486         /// gets a message for SNI error (sniError must be valid, non-zero error code)
1487         /// </summary>
GetSNIErrorMessage(int sniError)1488         static internal string GetSNIErrorMessage(int sniError) {
1489             Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range");
1490 
1491             string errorMessageId = String.Format((IFormatProvider)null, "SNI_ERROR_{0}", sniError);
1492             return Res.GetString(errorMessageId);
1493         }
1494 #endif
1495         // BulkLoad
1496         internal const string WriteToServer = "WriteToServer";
1497 
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";
1503 
1504          // constant strings
1505         internal const string Transaction= "Transaction";
1506         internal const string Connection = "Connection";
1507     }
1508 
1509     sealed internal class SQLMessage {
1510 
1511         //
1512 
SQLMessage()1513         private SQLMessage() { /* prevent utility class from being insantiated*/ }
1514 
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
1522         // locale.
1523 
CultureIdError()1524         static internal string CultureIdError() {
1525             return Res.GetString(Res.SQL_CultureIdError);
1526         }
EncryptionNotSupportedByClient()1527         static internal string EncryptionNotSupportedByClient() {
1528             return Res.GetString(Res.SQL_EncryptionNotSupportedByClient);
1529         }
EncryptionNotSupportedByServer()1530         static internal string EncryptionNotSupportedByServer() {
1531             return Res.GetString(Res.SQL_EncryptionNotSupportedByServer);
1532         }
OperationCancelled()1533         static internal string OperationCancelled() {
1534             return Res.GetString(Res.SQL_OperationCancelled);
1535         }
SevereError()1536         static internal string SevereError() {
1537             return Res.GetString(Res.SQL_SevereError);
1538         }
SSPIInitializeError()1539         static internal string SSPIInitializeError() {
1540             return Res.GetString(Res.SQL_SSPIInitializeError);
1541         }
SSPIGenerateError()1542         static internal string SSPIGenerateError() {
1543             return Res.GetString(Res.SQL_SSPIGenerateError);
1544         }
Timeout()1545         static internal string Timeout() {
1546             return Res.GetString(Res.SQL_Timeout_Execution);
1547         }
Timeout_PreLogin_Begin()1548         static internal string Timeout_PreLogin_Begin() {
1549             return Res.GetString(Res.SQL_Timeout_PreLogin_Begin);
1550         }
Timeout_PreLogin_InitializeConnection()1551         static internal string Timeout_PreLogin_InitializeConnection() {
1552             return Res.GetString(Res.SQL_Timeout_PreLogin_InitializeConnection);
1553         }
Timeout_PreLogin_SendHandshake()1554         static internal string Timeout_PreLogin_SendHandshake() {
1555             return Res.GetString(Res.SQL_Timeout_PreLogin_SendHandshake);
1556         }
Timeout_PreLogin_ConsumeHandshake()1557         static internal string Timeout_PreLogin_ConsumeHandshake() {
1558             return Res.GetString(Res.SQL_Timeout_PreLogin_ConsumeHandshake);
1559         }
Timeout_Login_Begin()1560         static internal string Timeout_Login_Begin() {
1561             return Res.GetString(Res.SQL_Timeout_Login_Begin);
1562         }
Timeout_Login_ProcessConnectionAuth()1563         static internal string Timeout_Login_ProcessConnectionAuth() {
1564             return Res.GetString(Res.SQL_Timeout_Login_ProcessConnectionAuth);
1565         }
Timeout_PostLogin()1566         static internal string Timeout_PostLogin() {
1567             return Res.GetString(Res.SQL_Timeout_PostLogin);
1568         }
Timeout_FailoverInfo()1569         static internal string Timeout_FailoverInfo() {
1570             return Res.GetString(Res.SQL_Timeout_FailoverInfo);
1571         }
Timeout_RoutingDestination()1572         static internal string Timeout_RoutingDestination() {
1573             return Res.GetString(Res.SQL_Timeout_RoutingDestinationInfo);
1574         }
Duration_PreLogin_Begin(long PreLoginBeginDuration)1575         static internal string Duration_PreLogin_Begin(long PreLoginBeginDuration) {
1576             return Res.GetString(Res.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration);
1577         }
Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration)1578         static internal string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration) {
1579             return Res.GetString(Res.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration);
1580         }
Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration)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);
1583         }
Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration)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);
1586         }
Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration)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);
1589         }
UserInstanceFailure()1590         static internal string UserInstanceFailure() {
1591             return Res.GetString(Res.SQL_UserInstanceFailure);
1592         }
PreloginError()1593         static internal string PreloginError() {
1594             return Res.GetString(Res.Snix_PreLogin);
1595         }
ExClientConnectionId()1596         static internal string ExClientConnectionId() {
1597             return Res.GetString(Res.SQL_ExClientConnectionId);
1598         }
ExErrorNumberStateClass()1599         static internal string ExErrorNumberStateClass() {
1600             return Res.GetString(Res.SQL_ExErrorNumberStateClass);
1601         }
ExOriginalClientConnectionId()1602         static internal string ExOriginalClientConnectionId() {
1603             return Res.GetString(Res.SQL_ExOriginalClientConnectionId);
1604         }
ExRoutingDestination()1605         static internal string ExRoutingDestination() {
1606             return Res.GetString(Res.SQL_ExRoutingDestination);
1607         }
1608     }
1609 
1610     /// <summary>
1611     /// This class holds helper methods to escape Microsoft SQL Server identifiers, such as table, schema, database or other names
1612     /// </summary>
1613     static internal class SqlServerEscapeHelper {
1614 
1615         /// <summary>
1616         /// Escapes the identifier with square brackets. The input has to be in unescaped form, like the parts received from MultipartIdentifier.ParseMultipartIdentifier.
1617         /// </summary>
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>
EscapeIdentifier(string name)1620         static internal string EscapeIdentifier(string name) {
1621             Debug.Assert(!ADP.IsEmpty(name), "null or empty identifiers are not allowed");
1622             return "[" + name.Replace("]", "]]") + "]";
1623         }
1624 
1625         /// <summary>
1626         /// Same as above EscapeIdentifier, except that output is written into StringBuilder
1627         /// </summary>
EscapeIdentifier(StringBuilder builder, string name)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");
1631 
1632             builder.Append("[");
1633             builder.Append(name.Replace("]", "]]"));
1634             builder.Append("]");
1635         }
1636 
1637         /// <summary>
1638         ///  Escape a string to be used inside TSQL literal, such as N'somename' or 'somename'
1639         /// </summary>
EscapeStringAsLiteral(string input)1640         static internal string EscapeStringAsLiteral(string input) {
1641             Debug.Assert(input != null, "input string cannot be null");
1642             return input.Replace("'", "''");
1643         }
1644 
1645         /// <summary>
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.
1649         /// </summary>
1650         /// <param name="input">unescaped string</param>
1651         /// <returns>escaped and quoted literal string</returns>
MakeStringLiteral(string input)1652         static internal string MakeStringLiteral(string input) {
1653             if (ADP.IsEmpty(input)) {
1654                 return "''";
1655             }
1656             else {
1657                 return "'" + EscapeStringAsLiteral(input) + "'";
1658             }
1659         }
1660     }
1661 
1662     /// <summary>
1663     /// This class holds methods invoked on System.Transactions through reflection for Global Transactions
1664     /// </summary>
1665     static internal class SysTxForGlobalTransactions {
1666 
1667         private static readonly Lazy<MethodInfo> _enlistPromotableSinglePhase = new Lazy<MethodInfo>(() =>
1668             typeof(SysTx.Transaction).GetMethod("EnlistPromotableSinglePhase", new Type[] {typeof(SysTx.IPromotableSinglePhaseNotification), typeof(Guid)}));
1669 
1670         private static readonly Lazy<MethodInfo> _setDistributedTransactionIdentifier = new Lazy<MethodInfo>(() =>
1671             typeof(SysTx.Transaction).GetMethod("SetDistributedTransactionIdentifier", new Type[] { typeof(SysTx.IPromotableSinglePhaseNotification), typeof(Guid) }));
1672 
1673         private static readonly Lazy<MethodInfo> _getPromotedToken = new Lazy<MethodInfo>(() =>
1674             typeof(SysTx.Transaction).GetMethod("GetPromotedToken"));
1675 
1676         /// <summary>
1677         /// Enlists the given IPromotableSinglePhaseNotification and Non-MSDTC Promoter type into a transaction
1678         /// </summary>
1679         /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
1680         public static MethodInfo EnlistPromotableSinglePhase {
1681             get {
1682                 return _enlistPromotableSinglePhase.Value;
1683             }
1684         }
1685 
1686         /// <summary>
1687         /// Sets the given DistributedTransactionIdentifier for a Transaction instance.
1688         /// Needs to be invoked when using a Non-MSDTC Promoter type
1689         /// </summary>
1690         /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
1691         public static MethodInfo SetDistributedTransactionIdentifier {
1692             get {
1693                 return _setDistributedTransactionIdentifier.Value;
1694             }
1695         }
1696 
1697         /// <summary>
1698         /// Gets the Promoted Token for a Transaction
1699         /// </summary>
1700         /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
1701         public static MethodInfo GetPromotedToken {
1702             get {
1703                 return _getPromotedToken.Value;
1704             }
1705         }
1706     }
1707 }//namespace
1708