SqlUtil.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. //------------------------------------------------------------------------------
  2. // <copyright file="SqlUtil.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient {
  9. using System;
  10. using System.ComponentModel;
  11. using System.Data;
  12. using System.Data.Common;
  13. using System.Diagnostics;
  14. using System.Globalization;
  15. using System.Reflection;
  16. using System.Runtime.Serialization.Formatters;
  17. using System.Security;
  18. using System.Security.Permissions;
  19. using System.Security.Principal;
  20. using System.Threading;
  21. using System.Text;
  22. using SysTx = System.Transactions;
  23. using System.Runtime.Versioning;
  24. using System.Threading.Tasks;
  25. using System.Runtime.CompilerServices;
  26. using System.Runtime.ExceptionServices;
  27. static internal class AsyncHelper {
  28. internal static Task CreateContinuationTask(Task task, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) {
  29. if (task == null) {
  30. onSuccess();
  31. return null;
  32. }
  33. else {
  34. TaskCompletionSource<object> completion = new TaskCompletionSource<object>();
  35. ContinueTask(task, completion,
  36. () => { onSuccess(); completion.SetResult(null); },
  37. connectionToDoom, onFailure);
  38. return completion.Task;
  39. }
  40. }
  41. internal static Task CreateContinuationTask<T1, T2>(Task task, Action<T1, T2> onSuccess, T1 arg1, T2 arg2, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) {
  42. return CreateContinuationTask(task, () => onSuccess(arg1, arg2), connectionToDoom, onFailure);
  43. }
  44. internal static void ContinueTask(Task task,
  45. TaskCompletionSource<object> completion,
  46. Action onSuccess,
  47. SqlInternalConnectionTds connectionToDoom = null,
  48. Action<Exception> onFailure = null,
  49. Action onCancellation = null,
  50. Func<Exception, Exception> exceptionConverter = null,
  51. SqlConnection connectionToAbort = null
  52. ) {
  53. Debug.Assert((connectionToAbort == null) || (connectionToDoom == null), "Should not specify both connectionToDoom and connectionToAbort");
  54. task.ContinueWith(
  55. tsk => {
  56. if (tsk.Exception != null) {
  57. Exception exc = tsk.Exception.InnerException;
  58. if (exceptionConverter != null) {
  59. exc = exceptionConverter(exc);
  60. }
  61. try {
  62. if (onFailure != null) {
  63. onFailure(exc);
  64. }
  65. }
  66. finally {
  67. completion.TrySetException(exc);
  68. }
  69. }
  70. else if (tsk.IsCanceled) {
  71. try {
  72. if (onCancellation != null) {
  73. onCancellation();
  74. }
  75. }
  76. finally {
  77. completion.TrySetCanceled();
  78. }
  79. }
  80. else {
  81. if (connectionToDoom != null || connectionToAbort!=null) {
  82. RuntimeHelpers.PrepareConstrainedRegions();
  83. try {
  84. #if DEBUG
  85. TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
  86. RuntimeHelpers.PrepareConstrainedRegions();
  87. try {
  88. tdsReliabilitySection.Start();
  89. #endif //DEBUG
  90. onSuccess();
  91. #if DEBUG
  92. }
  93. finally {
  94. tdsReliabilitySection.Stop();
  95. }
  96. #endif //DEBUG
  97. }
  98. catch (System.OutOfMemoryException e) {
  99. if (connectionToDoom != null) {
  100. connectionToDoom.DoomThisConnection();
  101. }
  102. else {
  103. connectionToAbort.Abort(e);
  104. }
  105. completion.SetException(e);
  106. throw;
  107. }
  108. catch (System.StackOverflowException e) {
  109. if (connectionToDoom != null) {
  110. connectionToDoom.DoomThisConnection();
  111. }
  112. else {
  113. connectionToAbort.Abort(e);
  114. }
  115. completion.SetException(e);
  116. throw;
  117. }
  118. catch (System.Threading.ThreadAbortException e) {
  119. if (connectionToDoom != null) {
  120. connectionToDoom.DoomThisConnection();
  121. }
  122. else {
  123. connectionToAbort.Abort(e);
  124. }
  125. completion.SetException(e);
  126. throw;
  127. }
  128. catch (Exception e) {
  129. completion.SetException(e);
  130. }
  131. }
  132. else { // no connection to doom - reliability section not required
  133. try {
  134. onSuccess();
  135. }
  136. catch (Exception e) {
  137. completion.SetException(e);
  138. }
  139. }
  140. }
  141. }, TaskScheduler.Default
  142. );
  143. }
  144. internal static void WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions=true) {
  145. try {
  146. task.Wait(timeout > 0 ? (1000 * timeout) : Timeout.Infinite);
  147. }
  148. catch (AggregateException ae) {
  149. if (rethrowExceptions) {
  150. Debug.Assert(ae.InnerExceptions.Count == 1, "There is more than one exception in AggregateException");
  151. ExceptionDispatchInfo.Capture(ae.InnerException).Throw();
  152. }
  153. }
  154. if (!task.IsCompleted) {
  155. if (onTimeout != null) {
  156. onTimeout();
  157. }
  158. }
  159. }
  160. internal static void SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken) {
  161. if (timeout > 0) {
  162. Task.Delay(timeout * 1000, ctoken).ContinueWith((tsk) => {
  163. if (!tsk.IsCanceled && !completion.Task.IsCompleted) {
  164. completion.TrySetException(exc());
  165. }
  166. });
  167. }
  168. }
  169. }
  170. sealed internal class InOutOfProcHelper {
  171. private static readonly InOutOfProcHelper SingletonInstance = new InOutOfProcHelper();
  172. private bool _inProc = false;
  173. // InOutOfProcHelper detects whether it's running inside the server or not. It does this
  174. // by checking for the existence of a well-known function export on the current process.
  175. // Note that calling conventions, etc. do not matter -- we'll never call the function, so
  176. // only the name match or lack thereof matter.
  177. [ResourceExposure(ResourceScope.None)]
  178. [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
  179. private InOutOfProcHelper() {
  180. #if !MONO
  181. // Don't need to close this handle...
  182. // SxS: we use this method to check if we are running inside the SQL Server process. This call should be safe in SxS environment.
  183. IntPtr handle = SafeNativeMethods.GetModuleHandle(null);
  184. if (IntPtr.Zero != handle) {
  185. // SQLBU 359301: Currently, the server exports different names for x86 vs. AMD64 and IA64. Supporting both names
  186. // for now gives the server time to unify names across platforms without breaking currently-working ones.
  187. // We can remove the obsolete name once the server is changed.
  188. if (IntPtr.Zero != SafeNativeMethods.GetProcAddress(handle, "_______SQL______Process______Available@0")) {
  189. _inProc = true;
  190. }
  191. else if (IntPtr.Zero != SafeNativeMethods.GetProcAddress(handle, "______SQL______Process______Available")) {
  192. _inProc = true;
  193. }
  194. }
  195. #endif
  196. }
  197. internal static bool InProc {
  198. get {
  199. return SingletonInstance._inProc;
  200. }
  201. }
  202. }
  203. static internal class SQL {
  204. // The class SQL defines the exceptions that are specific to the SQL Adapter.
  205. // The class contains functions that take the proper informational variables and then construct
  206. // the appropriate exception with an error string obtained from the resource Framework.txt.
  207. // The exception is then returned to the caller, so that the caller may then throw from its
  208. // location so that the catcher of the exception will have the appropriate call stack.
  209. // This class is used so that there will be compile time checking of error
  210. // messages. The resource Framework.txt will ensure proper string text based on the appropriate
  211. // locale.
  212. //
  213. // SQL specific exceptions
  214. //
  215. //
  216. // SQL.Connection
  217. //
  218. static internal Exception CannotGetDTCAddress() {
  219. return ADP.InvalidOperation(Res.GetString(Res.SQL_CannotGetDTCAddress));
  220. }
  221. static internal Exception InvalidOptionLength(string key) {
  222. return ADP.Argument(Res.GetString(Res.SQL_InvalidOptionLength, key));
  223. }
  224. static internal Exception InvalidInternalPacketSize (string str) {
  225. return ADP.ArgumentOutOfRange (str);
  226. }
  227. static internal Exception InvalidPacketSize() {
  228. return ADP.ArgumentOutOfRange (Res.GetString(Res.SQL_InvalidTDSPacketSize));
  229. }
  230. static internal Exception InvalidPacketSizeValue() {
  231. return ADP.Argument(Res.GetString(Res.SQL_InvalidPacketSizeValue));
  232. }
  233. static internal Exception InvalidSSPIPacketSize() {
  234. return ADP.Argument(Res.GetString(Res.SQL_InvalidSSPIPacketSize));
  235. }
  236. static internal Exception NullEmptyTransactionName() {
  237. return ADP.Argument(Res.GetString(Res.SQL_NullEmptyTransactionName));
  238. }
  239. static internal Exception SnapshotNotSupported(IsolationLevel level) {
  240. return ADP.Argument(Res.GetString(Res.SQL_SnapshotNotSupported, typeof(IsolationLevel), level.ToString()));
  241. }
  242. static internal Exception UserInstanceFailoverNotCompatible() {
  243. return ADP.Argument(Res.GetString(Res.SQL_UserInstanceFailoverNotCompatible));
  244. }
  245. static internal Exception InvalidSQLServerVersionUnknown() {
  246. return ADP.DataAdapter(Res.GetString(Res.SQL_InvalidSQLServerVersionUnknown));
  247. }
  248. static internal Exception SynchronousCallMayNotPend() {
  249. return new Exception(Res.GetString(Res.Sql_InternalError));
  250. }
  251. static internal Exception ConnectionLockedForBcpEvent() {
  252. return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionLockedForBcpEvent));
  253. }
  254. static internal Exception AsyncConnectionRequired() {
  255. return ADP.InvalidOperation(Res.GetString(Res.SQL_AsyncConnectionRequired));
  256. }
  257. static internal Exception FatalTimeout() {
  258. return ADP.InvalidOperation(Res.GetString(Res.SQL_FatalTimeout));
  259. }
  260. static internal Exception InstanceFailure() {
  261. return ADP.InvalidOperation(Res.GetString(Res.SQL_InstanceFailure));
  262. }
  263. static internal Exception ChangePasswordArgumentMissing(string argumentName) {
  264. return ADP.ArgumentNull(Res.GetString(Res.SQL_ChangePasswordArgumentMissing, argumentName));
  265. }
  266. static internal Exception ChangePasswordConflictsWithSSPI() {
  267. return ADP.Argument(Res.GetString(Res.SQL_ChangePasswordConflictsWithSSPI));
  268. }
  269. static internal Exception ChangePasswordRequiresYukon() {
  270. return ADP.InvalidOperation(Res.GetString(Res.SQL_ChangePasswordRequiresYukon));
  271. }
  272. static internal Exception UnknownSysTxIsolationLevel(SysTx.IsolationLevel isolationLevel) {
  273. return ADP.InvalidOperation(Res.GetString(Res.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString()));
  274. }
  275. static internal Exception ChangePasswordUseOfUnallowedKey (string key) {
  276. return ADP.InvalidOperation(Res.GetString(Res.SQL_ChangePasswordUseOfUnallowedKey, key));
  277. }
  278. static internal Exception InvalidPartnerConfiguration (string server, string database) {
  279. return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidPartnerConfiguration, server, database));
  280. }
  281. static internal Exception MARSUnspportedOnConnection() {
  282. return ADP.InvalidOperation(Res.GetString(Res.SQL_MarsUnsupportedOnConnection));
  283. }
  284. static internal Exception CannotModifyPropertyAsyncOperationInProgress(string property) {
  285. return ADP.InvalidOperation(Res.GetString(Res.SQL_CannotModifyPropertyAsyncOperationInProgress, property));
  286. }
  287. static internal Exception NonLocalSSEInstance() {
  288. return ADP.NotSupported(Res.GetString(Res.SQL_NonLocalSSEInstance));
  289. }
  290. //
  291. // SQL.DataCommand
  292. //
  293. static internal Exception NotificationsRequireYukon() {
  294. return ADP.NotSupported(Res.GetString(Res.SQL_NotificationsRequireYukon));
  295. }
  296. static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value) {
  297. return ADP.ArgumentOutOfRange(Res.GetString(Res.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
  298. }
  299. static internal ArgumentOutOfRangeException NotSupportedCommandType(CommandType value) {
  300. #if DEBUG
  301. switch(value) {
  302. case CommandType.Text:
  303. case CommandType.StoredProcedure:
  304. Debug.Assert(false, "valid CommandType " + value.ToString());
  305. break;
  306. case CommandType.TableDirect:
  307. break;
  308. default:
  309. Debug.Assert(false, "invalid CommandType " + value.ToString());
  310. break;
  311. }
  312. #endif
  313. return NotSupportedEnumerationValue(typeof(CommandType), (int)value);
  314. }
  315. static internal ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value) {
  316. #if DEBUG
  317. switch(value) {
  318. case IsolationLevel.Unspecified:
  319. case IsolationLevel.ReadCommitted:
  320. case IsolationLevel.ReadUncommitted:
  321. case IsolationLevel.RepeatableRead:
  322. case IsolationLevel.Serializable:
  323. case IsolationLevel.Snapshot:
  324. Debug.Assert(false, "valid IsolationLevel " + value.ToString());
  325. break;
  326. case IsolationLevel.Chaos:
  327. break;
  328. default:
  329. Debug.Assert(false, "invalid IsolationLevel " + value.ToString());
  330. break;
  331. }
  332. #endif
  333. return NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value);
  334. }
  335. static internal Exception OperationCancelled() {
  336. Exception exception = ADP.InvalidOperation(Res.GetString(Res.SQL_OperationCancelled));
  337. return exception;
  338. }
  339. static internal Exception PendingBeginXXXExists() {
  340. return ADP.InvalidOperation(Res.GetString(Res.SQL_PendingBeginXXXExists));
  341. }
  342. static internal ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param) {
  343. return ADP.ArgumentOutOfRange(Res.GetString(Res.SqlDependency_InvalidTimeout), param);
  344. }
  345. static internal Exception NonXmlResult() {
  346. return ADP.InvalidOperation(Res.GetString(Res.SQL_NonXmlResult));
  347. }
  348. //
  349. // SQL.DataParameter
  350. //
  351. static internal Exception InvalidUdt3PartNameFormat() {
  352. return ADP.Argument(Res.GetString(Res.SQL_InvalidUdt3PartNameFormat));
  353. }
  354. static internal Exception InvalidParameterTypeNameFormat() {
  355. return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterTypeNameFormat));
  356. }
  357. static internal Exception InvalidParameterNameLength(string value) {
  358. return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterNameLength, value));
  359. }
  360. static internal Exception PrecisionValueOutOfRange(byte precision) {
  361. return ADP.Argument(Res.GetString(Res.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture)));
  362. }
  363. static internal Exception ScaleValueOutOfRange(byte scale) {
  364. return ADP.Argument(Res.GetString(Res.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
  365. }
  366. static internal Exception TimeScaleValueOutOfRange(byte scale) {
  367. return ADP.Argument(Res.GetString(Res.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture)));
  368. }
  369. static internal Exception InvalidSqlDbType(SqlDbType value) {
  370. return ADP.InvalidEnumerationValue(typeof(SqlDbType), (int) value);
  371. }
  372. static internal Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName) {
  373. return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnsupportedTVPOutputParameter,
  374. direction.ToString(), paramName));
  375. }
  376. static internal Exception DBNullNotSupportedForTVPValues(string paramName) {
  377. return ADP.NotSupported(Res.GetString(Res.SqlParameter_DBNullNotSupportedForTVP, paramName));
  378. }
  379. static internal Exception InvalidTableDerivedPrecisionForTvp(string columnName, byte precision) {
  380. return ADP.InvalidOperation(Res.GetString(Res.SqlParameter_InvalidTableDerivedPrecisionForTvp, precision, columnName, System.Data.SqlTypes.SqlDecimal.MaxPrecision));
  381. }
  382. static internal Exception UnexpectedTypeNameForNonStructParams(string paramName) {
  383. return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnexpectedTypeNameForNonStruct, paramName));
  384. }
  385. static internal Exception SingleValuedStructNotSupported() {
  386. return ADP.NotSupported(Res.GetString(Res.MetaType_SingleValuedStructNotSupported));
  387. }
  388. static internal Exception ParameterInvalidVariant(string paramName) {
  389. return ADP.InvalidOperation(Res.GetString(Res.SQL_ParameterInvalidVariant, paramName));
  390. }
  391. static internal Exception MustSetTypeNameForParam(string paramType, string paramName) {
  392. return ADP.Argument(Res.GetString(Res.SQL_ParameterTypeNameRequired, paramType, paramName));
  393. }
  394. static internal Exception NullSchemaTableDataTypeNotSupported(string columnName) {
  395. return ADP.Argument(Res.GetString(Res.NullSchemaTableDataTypeNotSupported, columnName));
  396. }
  397. static internal Exception InvalidSchemaTableOrdinals() {
  398. return ADP.Argument(Res.GetString(Res.InvalidSchemaTableOrdinals));
  399. }
  400. static internal Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber) {
  401. return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber));
  402. }
  403. static internal Exception EnumeratedRecordFieldCountChanged(int recordNumber) {
  404. return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordFieldCountChanged, recordNumber));
  405. }
  406. //
  407. // SQL.SqlDataAdapter
  408. //
  409. //
  410. // SQL.TDSParser
  411. //
  412. static internal Exception InvalidTDSVersion() {
  413. return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidTDSVersion));
  414. }
  415. static internal Exception ParsingError() {
  416. return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingError));
  417. }
  418. static internal Exception MoneyOverflow(string moneyValue) {
  419. return ADP.Overflow(Res.GetString(Res.SQL_MoneyOverflow, moneyValue));
  420. }
  421. static internal Exception SmallDateTimeOverflow(string datetime) {
  422. return ADP.Overflow(Res.GetString(Res.SQL_SmallDateTimeOverflow, datetime));
  423. }
  424. static internal Exception SNIPacketAllocationFailure() {
  425. return ADP.InvalidOperation(Res.GetString(Res.SQL_SNIPacketAllocationFailure));
  426. }
  427. static internal Exception TimeOverflow(string time) {
  428. return ADP.Overflow(Res.GetString(Res.SQL_TimeOverflow, time));
  429. }
  430. //
  431. // SQL.SqlDataReader
  432. //
  433. static internal Exception InvalidRead() {
  434. return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidRead));
  435. }
  436. static internal Exception NonBlobColumn(string columnName) {
  437. return ADP.InvalidCast(Res.GetString(Res.SQL_NonBlobColumn, columnName));
  438. }
  439. static internal Exception NonCharColumn(string columnName) {
  440. return ADP.InvalidCast(Res.GetString(Res.SQL_NonCharColumn, columnName));
  441. }
  442. static internal Exception StreamNotSupportOnColumnType(string columnName) {
  443. return ADP.InvalidCast(Res.GetString(Res.SQL_StreamNotSupportOnColumnType, columnName));
  444. }
  445. static internal Exception TextReaderNotSupportOnColumnType(string columnName) {
  446. return ADP.InvalidCast(Res.GetString(Res.SQL_TextReaderNotSupportOnColumnType, columnName));
  447. }
  448. static internal Exception XmlReaderNotSupportOnColumnType(string columnName) {
  449. return ADP.InvalidCast(Res.GetString(Res.SQL_XmlReaderNotSupportOnColumnType, columnName));
  450. }
  451. static internal Exception UDTUnexpectedResult(string exceptionText){
  452. return ADP.TypeLoad(Res.GetString(Res.SQLUDT_Unexpected,exceptionText));
  453. }
  454. //
  455. // SQL.SqlDelegatedTransaction
  456. //
  457. static internal Exception CannotCompleteDelegatedTransactionWithOpenResults(SqlInternalConnectionTds internalConnection) {
  458. SqlErrorCollection errors = new SqlErrorCollection();
  459. errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, (Res.GetString(Res.ADP_OpenReaderExists)), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
  460. return SqlException.CreateException(errors, null, internalConnection);
  461. }
  462. static internal SysTx.TransactionPromotionException PromotionFailed(Exception inner) {
  463. SysTx.TransactionPromotionException e = new SysTx.TransactionPromotionException(Res.GetString(Res.SqlDelegatedTransaction_PromotionFailed), inner);
  464. ADP.TraceExceptionAsReturnValue(e);
  465. return e;
  466. }
  467. //
  468. // SQL.SqlDependency
  469. //
  470. static internal Exception SqlCommandHasExistingSqlNotificationRequest(){
  471. return ADP.InvalidOperation(Res.GetString(Res.SQLNotify_AlreadyHasCommand));
  472. }
  473. static internal Exception SqlDepCannotBeCreatedInProc() {
  474. return ADP.InvalidOperation(Res.GetString(Res.SqlNotify_SqlDepCannotBeCreatedInProc));
  475. }
  476. static internal Exception SqlDepDefaultOptionsButNoStart() {
  477. return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DefaultOptionsButNoStart));
  478. }
  479. static internal Exception SqlDependencyDatabaseBrokerDisabled() {
  480. return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DatabaseBrokerDisabled));
  481. }
  482. static internal Exception SqlDependencyEventNoDuplicate() {
  483. return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_EventNoDuplicate));
  484. }
  485. static internal Exception SqlDependencyDuplicateStart() {
  486. return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_DuplicateStart));
  487. }
  488. static internal Exception SqlDependencyIdMismatch() {
  489. // do not include the id because it may require SecurityPermission(Infrastructure) permission
  490. return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_IdMismatch));
  491. }
  492. static internal Exception SqlDependencyNoMatchingServerStart() {
  493. return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_NoMatchingServerStart));
  494. }
  495. static internal Exception SqlDependencyNoMatchingServerDatabaseStart() {
  496. return ADP.InvalidOperation(Res.GetString(Res.SqlDependency_NoMatchingServerDatabaseStart));
  497. }
  498. static internal Exception SqlNotificationException(SqlNotificationEventArgs notify){
  499. return ADP.InvalidOperation(Res.GetString(Res.SQLNotify_ErrorFormat, notify.Type,notify.Info,notify.Source));
  500. }
  501. //
  502. // SQL.SqlMetaData
  503. //
  504. static internal Exception SqlMetaDataNoMetaData(){
  505. return ADP.InvalidOperation(Res.GetString(Res.SqlMetaData_NoMetadata));
  506. }
  507. static internal Exception MustSetUdtTypeNameForUdtParams(){
  508. return ADP.Argument(Res.GetString(Res.SQLUDT_InvalidUdtTypeName));
  509. }
  510. static internal Exception UnexpectedUdtTypeNameForNonUdtParams(){
  511. return ADP.Argument(Res.GetString(Res.SQLUDT_UnexpectedUdtTypeName));
  512. }
  513. static internal Exception UDTInvalidSqlType(string typeName){
  514. return ADP.Argument(Res.GetString(Res.SQLUDT_InvalidSqlType, typeName));
  515. }
  516. static internal Exception InvalidSqlDbTypeForConstructor(SqlDbType type) {
  517. return ADP.Argument(Res.GetString(Res.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString()));
  518. }
  519. static internal Exception NameTooLong(string parameterName) {
  520. return ADP.Argument(Res.GetString(Res.SqlMetaData_NameTooLong), parameterName);
  521. }
  522. static internal Exception InvalidSortOrder(SortOrder order) {
  523. return ADP.InvalidEnumerationValue(typeof(SortOrder), (int)order);
  524. }
  525. static internal Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal) {
  526. return ADP.InvalidOperation(Res.GetString(Res.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal));
  527. }
  528. static internal Exception TableTypeCanOnlyBeParameter() {
  529. return ADP.Argument(Res.GetString(Res.SQLTVP_TableTypeCanOnlyBeParameter));
  530. }
  531. static internal Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName) {
  532. return ADP.Argument(Res.GetString(Res.SqlProvider_InvalidDataColumnType, columnName, typeName));
  533. }
  534. static internal Exception InvalidColumnMaxLength(string columnName, long maxLength) {
  535. return ADP.Argument(Res.GetString(Res.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength));
  536. }
  537. static internal Exception InvalidColumnPrecScale() {
  538. return ADP.Argument(Res.GetString(Res.SqlMisc_InvalidPrecScaleMessage));
  539. }
  540. static internal Exception NotEnoughColumnsInStructuredType() {
  541. return ADP.Argument(Res.GetString(Res.SqlProvider_NotEnoughColumnsInStructuredType));
  542. }
  543. static internal Exception DuplicateSortOrdinal(int sortOrdinal) {
  544. return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_DuplicateSortOrdinal, sortOrdinal));
  545. }
  546. static internal Exception MissingSortOrdinal(int sortOrdinal) {
  547. return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_MissingSortOrdinal, sortOrdinal));
  548. }
  549. static internal Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal) {
  550. return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal));
  551. }
  552. static internal Exception IEnumerableOfSqlDataRecordHasNoRows() {
  553. return ADP.Argument(Res.GetString(Res.IEnumerableOfSqlDataRecordHasNoRows));
  554. }
  555. //
  556. // SqlPipe
  557. //
  558. static internal Exception SqlPipeCommandHookedUpToNonContextConnection() {
  559. return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_CommandHookedUpToNonContextConnection));
  560. }
  561. static internal Exception SqlPipeMessageTooLong( int messageLength ) {
  562. return ADP.Argument(Res.GetString(Res.SqlPipe_MessageTooLong, messageLength));
  563. }
  564. static internal Exception SqlPipeIsBusy() {
  565. return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_IsBusy));
  566. }
  567. static internal Exception SqlPipeAlreadyHasAnOpenResultSet( string methodName ) {
  568. return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_AlreadyHasAnOpenResultSet, methodName));
  569. }
  570. static internal Exception SqlPipeDoesNotHaveAnOpenResultSet( string methodName ) {
  571. return ADP.InvalidOperation(Res.GetString(Res.SqlPipe_DoesNotHaveAnOpenResultSet, methodName));
  572. }
  573. //
  574. // : ISqlResultSet
  575. //
  576. static internal Exception SqlResultSetClosed(string methodname) {
  577. if (methodname == null) {
  578. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetClosed2));
  579. }
  580. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetClosed, methodname));
  581. }
  582. static internal Exception SqlResultSetNoData(string methodname) {
  583. return ADP.InvalidOperation(Res.GetString(Res.ADP_DataReaderNoData, methodname));
  584. }
  585. static internal Exception SqlRecordReadOnly(string methodname) {
  586. if (methodname == null) {
  587. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlRecordReadOnly2));
  588. }
  589. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlRecordReadOnly, methodname));
  590. }
  591. static internal Exception SqlResultSetRowDeleted(string methodname) {
  592. if (methodname == null) {
  593. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetRowDeleted2));
  594. }
  595. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetRowDeleted, methodname));
  596. }
  597. static internal Exception SqlResultSetCommandNotInSameConnection() {
  598. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetCommandNotInSameConnection));
  599. }
  600. static internal Exception SqlResultSetNoAcceptableCursor() {
  601. return ADP.InvalidOperation(Res.GetString(Res.SQL_SqlResultSetNoAcceptableCursor));
  602. }
  603. //
  604. // SQL.BulkLoad
  605. //
  606. static internal Exception BulkLoadMappingInaccessible() {
  607. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingInaccessible));
  608. }
  609. static internal Exception BulkLoadMappingsNamesOrOrdinalsOnly() {
  610. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingsNamesOrOrdinalsOnly));
  611. }
  612. static internal Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, Exception e) {
  613. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadCannotConvertValue, sourcetype.Name, metatype.TypeName), e);
  614. }
  615. static internal Exception BulkLoadNonMatchingColumnMapping() {
  616. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnMapping));
  617. }
  618. static internal Exception BulkLoadNonMatchingColumnName(string columnName) {
  619. return BulkLoadNonMatchingColumnName(columnName, null);
  620. }
  621. static internal Exception BulkLoadNonMatchingColumnName(string columnName, Exception e) {
  622. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnName, columnName), e);
  623. }
  624. static internal Exception BulkLoadStringTooLong() {
  625. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadStringTooLong));
  626. }
  627. static internal Exception BulkLoadInvalidVariantValue() {
  628. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidVariantValue));
  629. }
  630. static internal Exception BulkLoadInvalidTimeout(int timeout) {
  631. return ADP.Argument(Res.GetString(Res.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture)));
  632. }
  633. static internal Exception BulkLoadExistingTransaction() {
  634. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadExistingTransaction));
  635. }
  636. static internal Exception BulkLoadNoCollation() {
  637. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNoCollation));
  638. }
  639. static internal Exception BulkLoadConflictingTransactionOption() {
  640. return ADP.Argument(Res.GetString(Res.SQL_BulkLoadConflictingTransactionOption));
  641. }
  642. static internal Exception BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName) {
  643. return ADP.InvalidOperation (Res.GetString (Res.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName));
  644. }
  645. static internal Exception InvalidOperationInsideEvent() {
  646. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidOperationInsideEvent));
  647. }
  648. static internal Exception BulkLoadMissingDestinationTable() {
  649. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMissingDestinationTable));
  650. }
  651. static internal Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner) {
  652. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidDestinationTable, tableName), inner);
  653. }
  654. static internal Exception BulkLoadBulkLoadNotAllowDBNull(string columnName) {
  655. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNotAllowDBNull, columnName));
  656. }
  657. static internal Exception BulkLoadPendingOperation() {
  658. return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadPendingOperation));
  659. }
  660. //
  661. // transactions.
  662. //
  663. static internal Exception ConnectionDoomed() {
  664. return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionDoomed));
  665. }
  666. static internal Exception OpenResultCountExceeded() {
  667. return ADP.InvalidOperation(Res.GetString(Res.SQL_OpenResultCountExceeded));
  668. }
  669. static internal readonly byte[] AttentionHeader = new byte[] {
  670. TdsEnums.MT_ATTN, // Message Type
  671. TdsEnums.ST_EOM, // Status
  672. TdsEnums.HEADER_LEN >> 8, // length - upper byte
  673. TdsEnums.HEADER_LEN & 0xff, // length - lower byte
  674. 0, // spid
  675. 0, // spid
  676. 0, // packet (out of band)
  677. 0 // window
  678. };
  679. //
  680. // MultiSubnetFailover
  681. //
  682. /// <summary>
  683. /// used to block two scenarios if MultiSubnetFailover is true:
  684. /// * server-provided failover partner - raising SqlException in this case
  685. /// * connection string with failover partner and MultiSubnetFailover=true - rasing argument one in this case with the same message
  686. /// </summary>
  687. static internal Exception MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection) {
  688. string msg = Res.GetString(Res.SQLMSF_FailoverPartnerNotSupported);
  689. if (serverProvidedFailoverPartner) {
  690. // VSTFDEVDIV\DevDiv2\179041 - replacing InvalidOperation with SQL exception
  691. SqlErrorCollection errors = new SqlErrorCollection();
  692. errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, msg, "", 0));
  693. SqlException exc = SqlException.CreateException(errors, null, internalConnection);
  694. exc._doNotReconnect = true; // disable open retry logic on this error
  695. return exc;
  696. }
  697. else {
  698. return ADP.Argument(msg);
  699. }
  700. }
  701. static internal Exception MultiSubnetFailoverWithMoreThan64IPs() {
  702. string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs);
  703. return ADP.InvalidOperation(msg);
  704. }
  705. static internal Exception MultiSubnetFailoverWithInstanceSpecified() {
  706. string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified);
  707. return ADP.Argument(msg);
  708. }
  709. static internal Exception MultiSubnetFailoverWithNonTcpProtocol() {
  710. string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol);
  711. return ADP.Argument(msg);
  712. }
  713. //
  714. // Read-only routing
  715. //
  716. static internal Exception ROR_FailoverNotSupportedConnString() {
  717. return ADP.Argument(Res.GetString(Res.SQLROR_FailoverNotSupported));
  718. }
  719. static internal Exception ROR_FailoverNotSupportedServer(SqlInternalConnectionTds internalConnection) {
  720. SqlErrorCollection errors = new SqlErrorCollection();
  721. errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_FailoverNotSupported)), "", 0));
  722. SqlException exc = SqlException.CreateException(errors, null, internalConnection);
  723. exc._doNotReconnect = true;
  724. return exc;
  725. }
  726. static internal Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection) {
  727. SqlErrorCollection errors = new SqlErrorCollection();
  728. errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_RecursiveRoutingNotSupported)), "", 0));
  729. SqlException exc=SqlException.CreateException(errors, null, internalConnection);
  730. exc._doNotReconnect = true;
  731. return exc;
  732. }
  733. static internal Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection) {
  734. SqlErrorCollection errors = new SqlErrorCollection();
  735. errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_UnexpectedRoutingInfo)), "", 0));
  736. SqlException exc = SqlException.CreateException(errors, null, internalConnection);
  737. exc._doNotReconnect = true;
  738. return exc;
  739. }
  740. static internal Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection) {
  741. SqlErrorCollection errors = new SqlErrorCollection();
  742. errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_InvalidRoutingInfo)), "", 0));
  743. SqlException exc = SqlException.CreateException(errors, null, internalConnection);
  744. exc._doNotReconnect = true;
  745. return exc;
  746. }
  747. static internal Exception ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection) {
  748. SqlErrorCollection errors = new SqlErrorCollection();
  749. errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_TimeoutAfterRoutingInfo)), "", 0));
  750. SqlException exc = SqlException.CreateException(errors, null, internalConnection);
  751. exc._doNotReconnect = true;
  752. return exc;
  753. }
  754. //
  755. // Connection resiliency
  756. //
  757. static internal SqlException CR_ReconnectTimeout() {
  758. SqlErrorCollection errors = new SqlErrorCollection();
  759. errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.Timeout(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
  760. SqlException exc = SqlException.CreateException(errors, "");
  761. return exc;
  762. }
  763. static internal SqlException CR_ReconnectionCancelled() {
  764. SqlErrorCollection errors = new SqlErrorCollection();
  765. errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.OperationCancelled(), "", 0));
  766. SqlException exc = SqlException.CreateException(errors, "");
  767. return exc;
  768. }
  769. static internal Exception CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId) {
  770. SqlErrorCollection errors = new SqlErrorCollection();
  771. errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, Res.GetString(Res.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0));
  772. SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
  773. return exc;
  774. }
  775. static internal Exception CR_EncryptionChanged(SqlInternalConnectionTds internalConnection) {
  776. SqlErrorCollection errors = new SqlErrorCollection();
  777. errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_EncryptionChanged), "", 0));
  778. SqlException exc = SqlException.CreateException(errors, "", internalConnection);
  779. return exc;
  780. }
  781. static internal SqlException CR_AllAttemptsFailed(SqlException innerException, Guid connectionId) {
  782. SqlErrorCollection errors = new SqlErrorCollection();
  783. errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, Res.GetString(Res.SQLCR_AllAttemptsFailed), "", 0));
  784. SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException);
  785. return exc;
  786. }
  787. static internal SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection) {
  788. SqlErrorCollection errors = new SqlErrorCollection();
  789. errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_NoCRAckAtReconnection), "", 0));
  790. SqlException exc = SqlException.CreateException(errors, "", internalConnection);
  791. return exc;
  792. }
  793. static internal SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internalConnection) {
  794. SqlErrorCollection errors = new SqlErrorCollection();
  795. errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_TDSVestionNotPreserved), "", 0));
  796. SqlException exc = SqlException.CreateException(errors, "", internalConnection);
  797. return exc;
  798. }
  799. static internal SqlException CR_UnrecoverableServer(Guid connectionId) {
  800. SqlErrorCollection errors = new SqlErrorCollection();
  801. errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_UnrecoverableServer), "", 0));
  802. SqlException exc = SqlException.CreateException(errors, "", connectionId);
  803. return exc;
  804. }
  805. static internal SqlException CR_UnrecoverableClient(Guid connectionId) {
  806. SqlErrorCollection errors = new SqlErrorCollection();
  807. errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_UnrecoverableClient), "", 0));
  808. SqlException exc = SqlException.CreateException(errors, "", connectionId);
  809. return exc;
  810. }
  811. //
  812. // Merged Provider
  813. //
  814. static internal Exception BatchedUpdatesNotAvailableOnContextConnection() {
  815. return ADP.InvalidOperation(Res.GetString(Res.SQL_BatchedUpdatesNotAvailableOnContextConnection));
  816. }
  817. static internal Exception ContextAllowsLimitedKeywords() {
  818. return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextAllowsLimitedKeywords));
  819. }
  820. static internal Exception ContextAllowsOnlyTypeSystem2005() {
  821. return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextAllowsOnlyTypeSystem2005));
  822. }
  823. static internal Exception ContextConnectionIsInUse() {
  824. return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextConnectionIsInUse));
  825. }
  826. static internal Exception ContextUnavailableOutOfProc() {
  827. return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextUnavailableOutOfProc));
  828. }
  829. static internal Exception ContextUnavailableWhileInProc() {
  830. return ADP.InvalidOperation(Res.GetString(Res.SQL_ContextUnavailableWhileInProc));
  831. }
  832. static internal Exception NestedTransactionScopesNotSupported() {
  833. return ADP.InvalidOperation(Res.GetString(Res.SQL_NestedTransactionScopesNotSupported));
  834. }
  835. static internal Exception NotAvailableOnContextConnection() {
  836. return ADP.InvalidOperation(Res.GetString(Res.SQL_NotAvailableOnContextConnection));
  837. }
  838. static internal Exception NotificationsNotAvailableOnContextConnection() {
  839. return ADP.InvalidOperation(Res.GetString(Res.SQL_NotificationsNotAvailableOnContextConnection));
  840. }
  841. static internal Exception UnexpectedSmiEvent(Microsoft.SqlServer.Server.SmiEventSink_Default.UnexpectedEventType eventType) {
  842. Debug.Assert(false, "UnexpectedSmiEvent: "+eventType.ToString()); // Assert here, because these exceptions will most likely be eaten by the server.
  843. return ADP.InvalidOperation(Res.GetString(Res.SQL_UnexpectedSmiEvent, (int)eventType));
  844. }
  845. static internal Exception UserInstanceNotAvailableInProc() {
  846. return ADP.InvalidOperation(Res.GetString(Res.SQL_UserInstanceNotAvailableInProc));
  847. }
  848. static internal Exception ArgumentLengthMismatch( string arg1, string arg2 ) {
  849. return ADP.Argument( Res.GetString( Res.SQL_ArgumentLengthMismatch, arg1, arg2 ) );
  850. }
  851. static internal Exception InvalidSqlDbTypeOneAllowedType( SqlDbType invalidType, string method, SqlDbType allowedType ) {
  852. return ADP.Argument( Res.GetString( Res.SQL_InvalidSqlDbTypeWithOneAllowedType, invalidType, method, allowedType ) );
  853. }
  854. static internal Exception SqlPipeErrorRequiresSendEnd( ) {
  855. return ADP.InvalidOperation(Res.GetString(Res.SQL_PipeErrorRequiresSendEnd));
  856. }
  857. static internal Exception TooManyValues(string arg) {
  858. return ADP.Argument(Res.GetString(Res.SQL_TooManyValues), arg);
  859. }
  860. static internal Exception StreamWriteNotSupported() {
  861. return ADP.NotSupported(Res.GetString(Res.SQL_StreamWriteNotSupported));
  862. }
  863. static internal Exception StreamReadNotSupported() {
  864. return ADP.NotSupported(Res.GetString(Res.SQL_StreamReadNotSupported));
  865. }
  866. static internal Exception StreamSeekNotSupported() {
  867. return ADP.NotSupported(Res.GetString(Res.SQL_StreamSeekNotSupported));
  868. }
  869. static internal System.Data.SqlTypes.SqlNullValueException SqlNullValue() {
  870. System.Data.SqlTypes.SqlNullValueException e = new System.Data.SqlTypes.SqlNullValueException();
  871. ADP.TraceExceptionAsReturnValue(e);
  872. return e;
  873. }
  874. // SQLBU 402363: Exception to prevent Parameter.Size data corruption case from working.
  875. // This should be temporary until changing to correct behavior can be safely implemented.
  876. static internal Exception ParameterSizeRestrictionFailure(int index) {
  877. return ADP.InvalidOperation(Res.GetString(Res.OleDb_CommandParameterError, index.ToString(CultureInfo.InvariantCulture), "SqlParameter.Size"));
  878. }
  879. static internal Exception SubclassMustOverride() {
  880. return ADP.InvalidOperation(Res.GetString(Res.SqlMisc_SubclassMustOverride));
  881. }
  882. /// <summary>
  883. /// gets a message for SNI error (sniError must be valid, non-zero error code)
  884. /// </summary>
  885. static internal string GetSNIErrorMessage(int sniError) {
  886. Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range");
  887. string errorMessageId = String.Format((IFormatProvider)null, "SNI_ERROR_{0}", sniError);
  888. return Res.GetString(errorMessageId);
  889. }
  890. // BulkLoad
  891. internal const string WriteToServer = "WriteToServer";
  892. // Default values for SqlDependency and SqlNotificationRequest
  893. internal const int SqlDependencyTimeoutDefault = 0;
  894. internal const int SqlDependencyServerTimeout = 5 * 24 * 3600; // 5 days - used to compute default TTL of the dependency
  895. internal const string SqlNotificationServiceDefault = "SqlQueryNotificationService";
  896. internal const string SqlNotificationStoredProcedureDefault = "SqlQueryNotificationStoredProcedure";
  897. // constant strings
  898. internal const string Transaction= "Transaction";
  899. internal const string Connection = "Connection";
  900. }
  901. sealed internal class SQLMessage {
  902. //
  903. private SQLMessage() { /* prevent utility class from being insantiated*/ }
  904. // The class SQLMessage defines the error messages that are specific to the SqlDataAdapter
  905. // that are caused by a netlib error. The functions will be called and then return the
  906. // appropriate error message from the resource Framework.txt. The SqlDataAdapter will then
  907. // take the error message and then create a SqlError for the message and then place
  908. // that into a SqlException that is either thrown to the user or cached for throwing at
  909. // a later time. This class is used so that there will be compile time checking of error
  910. // messages. The resource Framework.txt will ensure proper string text based on the appropriate
  911. // locale.
  912. static internal string CultureIdError() {
  913. return Res.GetString(Res.SQL_CultureIdError);
  914. }
  915. static internal string EncryptionNotSupportedByClient() {
  916. return Res.GetString(Res.SQL_EncryptionNotSupportedByClient);
  917. }
  918. static internal string EncryptionNotSupportedByServer() {
  919. return Res.GetString(Res.SQL_EncryptionNotSupportedByServer);
  920. }
  921. static internal string OperationCancelled() {
  922. return Res.GetString(Res.SQL_OperationCancelled);
  923. }
  924. static internal string SevereError() {
  925. return Res.GetString(Res.SQL_SevereError);
  926. }
  927. static internal string SSPIInitializeError() {
  928. return Res.GetString(Res.SQL_SSPIInitializeError);
  929. }
  930. static internal string SSPIGenerateError() {
  931. return Res.GetString(Res.SQL_SSPIGenerateError);
  932. }
  933. static internal string Timeout() {
  934. return Res.GetString(Res.SQL_Timeout);
  935. }
  936. static internal string Timeout_PreLogin_Begin() {
  937. return Res.GetString(Res.SQL_Timeout_PreLogin_Begin);
  938. }
  939. static internal string Timeout_PreLogin_InitializeConnection() {
  940. return Res.GetString(Res.SQL_Timeout_PreLogin_InitializeConnection);
  941. }
  942. static internal string Timeout_PreLogin_SendHandshake() {
  943. return Res.GetString(Res.SQL_Timeout_PreLogin_SendHandshake);
  944. }
  945. static internal string Timeout_PreLogin_ConsumeHandshake() {
  946. return Res.GetString(Res.SQL_Timeout_PreLogin_ConsumeHandshake);
  947. }
  948. static internal string Timeout_Login_Begin() {
  949. return Res.GetString(Res.SQL_Timeout_Login_Begin);
  950. }
  951. static internal string Timeout_Login_ProcessConnectionAuth() {
  952. return Res.GetString(Res.SQL_Timeout_Login_ProcessConnectionAuth);
  953. }
  954. static internal string Timeout_PostLogin() {
  955. return Res.GetString(Res.SQL_Timeout_PostLogin);
  956. }
  957. static internal string Timeout_FailoverInfo() {
  958. return Res.GetString(Res.SQL_Timeout_FailoverInfo);
  959. }
  960. static internal string Timeout_RoutingDestination() {
  961. return Res.GetString(Res.SQL_Timeout_RoutingDestinationInfo);
  962. }
  963. static internal string Duration_PreLogin_Begin(long PreLoginBeginDuration) {
  964. return Res.GetString(Res.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration);
  965. }
  966. static internal string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration) {
  967. return Res.GetString(Res.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration);
  968. }
  969. static internal string Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration) {
  970. return Res.GetString(Res.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration);
  971. }
  972. static internal string Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration) {
  973. return Res.GetString(Res.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration);
  974. }
  975. static internal string Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration) {
  976. return Res.GetString(Res.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration);
  977. }
  978. static internal string UserInstanceFailure() {
  979. return Res.GetString(Res.SQL_UserInstanceFailure);
  980. }
  981. static internal string PreloginError() {
  982. return Res.GetString(Res.Snix_PreLogin);
  983. }
  984. static internal string ExClientConnectionId() {
  985. return Res.GetString(Res.SQL_ExClientConnectionId);
  986. }
  987. static internal string ExErrorNumberStateClass() {
  988. return Res.GetString(Res.SQL_ExErrorNumberStateClass);
  989. }
  990. static internal string ExOriginalClientConnectionId() {
  991. return Res.GetString(Res.SQL_ExOriginalClientConnectionId);
  992. }
  993. static internal string ExRoutingDestination() {
  994. return Res.GetString(Res.SQL_ExRoutingDestination);
  995. }
  996. }
  997. /// <summary>
  998. /// This class holds helper methods to escape Microsoft SQL Server identifiers, such as table, schema, database or other names
  999. /// </summary>
  1000. static internal class SqlServerEscapeHelper {
  1001. /// <summary>
  1002. /// Escapes the identifier with square brackets. The input has to be in unescaped form, like the parts received from MultipartIdentifier.ParseMultipartIdentifier.
  1003. /// </summary>
  1004. /// <param name="name">name of the identifier, in unescaped form</param>
  1005. /// <returns>escapes the name with [], also escapes the last close bracket with double-bracket</returns>
  1006. static internal string EscapeIdentifier(string name) {
  1007. Debug.Assert(!ADP.IsEmpty(name), "null or empty identifiers are not allowed");
  1008. return "[" + name.Replace("]", "]]") + "]";
  1009. }
  1010. /// <summary>
  1011. /// Same as above EscapeIdentifier, except that output is written into StringBuilder
  1012. /// </summary>
  1013. static internal void EscapeIdentifier(StringBuilder builder, string name) {
  1014. Debug.Assert(builder != null, "builder cannot be null");
  1015. Debug.Assert(!ADP.IsEmpty(name), "null or empty identifiers are not allowed");
  1016. builder.Append("[");
  1017. builder.Append(name.Replace("]", "]]"));
  1018. builder.Append("]");
  1019. }
  1020. /// <summary>
  1021. /// Escape a string to be used inside TSQL literal, such as N'somename' or 'somename'
  1022. /// </summary>
  1023. static internal string EscapeStringAsLiteral(string input) {
  1024. Debug.Assert(input != null, "input string cannot be null");
  1025. return input.Replace("'", "''");
  1026. }
  1027. /// <summary>
  1028. /// Escape a string as a TSQL literal, wrapping it around with single quotes.
  1029. /// Use this method to escape input strings to prevent SQL injection
  1030. /// and to get correct behavior for embedded quotes.
  1031. /// </summary>
  1032. /// <param name="input">unescaped string</param>
  1033. /// <returns>escaped and quoted literal string</returns>
  1034. static internal string MakeStringLiteral(string input) {
  1035. if (ADP.IsEmpty(input)) {
  1036. return "''";
  1037. }
  1038. else {
  1039. return "'" + EscapeStringAsLiteral(input) + "'";
  1040. }
  1041. }
  1042. }
  1043. }//namespace