AdapterUtil.cs 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597
  1. //------------------------------------------------------------------------------
  2. // <copyright file="AdapterUtil.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. namespace System.Data.Common {
  9. using Microsoft.Win32;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.ComponentModel;
  14. using System.Configuration;
  15. using System.Data;
  16. using System.Data.ProviderBase;
  17. #if !MOBILE
  18. using System.Data.Odbc;
  19. using System.Data.OleDb;
  20. #endif
  21. using System.Data.Sql;
  22. using System.Data.SqlTypes;
  23. using System.Diagnostics;
  24. using System.Globalization;
  25. using System.IO;
  26. using System.Reflection;
  27. using System.Runtime.ConstrainedExecution;
  28. using System.Runtime.InteropServices;
  29. using System.Runtime.Serialization;
  30. using System.Security;
  31. using System.Security.Permissions;
  32. using System.Data.SqlClient;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Threading.Tasks;
  36. using System.Xml;
  37. using SysTx = System.Transactions;
  38. #if !MOBILE
  39. using SysES = System.EnterpriseServices;
  40. #endif
  41. using System.Runtime.Versioning;
  42. using Microsoft.SqlServer.Server;
  43. internal static class ADP {
  44. // The class ADP defines the exceptions that are specific to the Adapters.f
  45. // The class contains functions that take the proper informational variables and then construct
  46. // the appropriate exception with an error string obtained from the resource Framework.txt.
  47. // The exception is then returned to the caller, so that the caller may then throw from its
  48. // location so that the catcher of the exception will have the appropriate call stack.
  49. // This class is used so that there will be compile time checking of error messages.
  50. // The resource Framework.txt will ensure proper string text based on the appropriate
  51. // locale.
  52. public const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
  53. static internal Task<T> CreatedTaskWithException<T>(Exception ex) {
  54. TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
  55. completion.SetException(ex);
  56. return completion.Task;
  57. }
  58. static internal Task<T> CreatedTaskWithCancellation<T>() {
  59. TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
  60. completion.SetCanceled();
  61. return completion.Task;
  62. }
  63. static internal Exception ExceptionWithStackTrace(Exception e)
  64. {
  65. try {
  66. throw e;
  67. }
  68. catch (Exception caught) {
  69. return caught;
  70. }
  71. }
  72. static internal Task<bool> s_trueTask = Task.FromResult<bool>(true);
  73. static internal Task<bool> s_falseTask = Task.FromResult<bool>(false);
  74. #if MONO
  75. static internal Task<bool> TrueTask => s_trueTask;
  76. static internal Task<bool> FalseTask => s_falseTask;
  77. #endif
  78. [BidMethod] // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it
  79. static private void TraceException(
  80. string trace,
  81. [BidArgumentType(typeof(String))] Exception e) {
  82. Debug.Assert(null != e, "TraceException: null Exception");
  83. if (null != e) {
  84. Bid.Trace(trace, e.ToString()); // will include callstack if permission is available
  85. }
  86. }
  87. static internal void TraceExceptionAsReturnValue(Exception e) {
  88. TraceException("<comm.ADP.TraceException|ERR|THROW> '%ls'\n", e);
  89. }
  90. static internal void TraceExceptionForCapture(Exception e) {
  91. Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
  92. TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
  93. }
  94. static internal void TraceExceptionWithoutRethrow(Exception e) {
  95. Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
  96. TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
  97. }
  98. //
  99. // COM+ exceptions
  100. //
  101. static internal ArgumentException Argument(string error) {
  102. ArgumentException e = new ArgumentException(error);
  103. TraceExceptionAsReturnValue(e);
  104. return e;
  105. }
  106. static internal ArgumentException Argument(string error, Exception inner) {
  107. ArgumentException e = new ArgumentException(error, inner);
  108. TraceExceptionAsReturnValue(e);
  109. return e;
  110. }
  111. static internal ArgumentException Argument(string error, string parameter) {
  112. ArgumentException e = new ArgumentException(error, parameter);
  113. TraceExceptionAsReturnValue(e);
  114. return e;
  115. }
  116. static internal ArgumentException Argument(string error, string parameter, Exception inner) {
  117. ArgumentException e = new ArgumentException(error, parameter, inner);
  118. TraceExceptionAsReturnValue(e);
  119. return e;
  120. }
  121. static internal ArgumentNullException ArgumentNull(string parameter) {
  122. ArgumentNullException e = new ArgumentNullException(parameter);
  123. TraceExceptionAsReturnValue(e);
  124. return e;
  125. }
  126. static internal ArgumentNullException ArgumentNull(string parameter, string error) {
  127. ArgumentNullException e = new ArgumentNullException(parameter, error);
  128. TraceExceptionAsReturnValue(e);
  129. return e;
  130. }
  131. static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName) {
  132. ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
  133. TraceExceptionAsReturnValue(e);
  134. return e;
  135. }
  136. static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) {
  137. ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
  138. TraceExceptionAsReturnValue(e);
  139. return e;
  140. }
  141. static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName, object value) {
  142. ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, value, message);
  143. TraceExceptionAsReturnValue(e);
  144. return e;
  145. }
  146. #if !MOBILE
  147. static internal ConfigurationException Configuration(string message) {
  148. ConfigurationException e = new ConfigurationErrorsException(message);
  149. TraceExceptionAsReturnValue(e);
  150. return e;
  151. }
  152. static internal ConfigurationException Configuration(string message, XmlNode node) {
  153. ConfigurationException e = new ConfigurationErrorsException(message, node);
  154. TraceExceptionAsReturnValue(e);
  155. return e;
  156. }
  157. #endif
  158. static internal DataException Data(string message) {
  159. DataException e = new DataException(message);
  160. TraceExceptionAsReturnValue(e);
  161. return e;
  162. }
  163. static internal IndexOutOfRangeException IndexOutOfRange(int value) {
  164. IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
  165. TraceExceptionAsReturnValue(e);
  166. return e;
  167. }
  168. static internal IndexOutOfRangeException IndexOutOfRange(string error) {
  169. IndexOutOfRangeException e = new IndexOutOfRangeException(error);
  170. TraceExceptionAsReturnValue(e);
  171. return e;
  172. }
  173. static internal IndexOutOfRangeException IndexOutOfRange() {
  174. IndexOutOfRangeException e = new IndexOutOfRangeException();
  175. TraceExceptionAsReturnValue(e);
  176. return e;
  177. }
  178. static internal InvalidCastException InvalidCast(string error) {
  179. return InvalidCast(error, null);
  180. }
  181. static internal InvalidCastException InvalidCast(string error, Exception inner) {
  182. InvalidCastException e = new InvalidCastException(error, inner);
  183. TraceExceptionAsReturnValue(e);
  184. return e;
  185. }
  186. static internal InvalidOperationException InvalidOperation(string error) {
  187. InvalidOperationException e = new InvalidOperationException(error);
  188. TraceExceptionAsReturnValue(e);
  189. return e;
  190. }
  191. static internal TimeoutException TimeoutException(string error) {
  192. TimeoutException e = new TimeoutException(error);
  193. TraceExceptionAsReturnValue(e);
  194. return e;
  195. }
  196. static internal InvalidOperationException InvalidOperation(string error, Exception inner)
  197. {
  198. InvalidOperationException e = new InvalidOperationException(error, inner);
  199. TraceExceptionAsReturnValue(e);
  200. return e;
  201. }
  202. static internal NotImplementedException NotImplemented(string error) {
  203. NotImplementedException e = new NotImplementedException(error);
  204. TraceExceptionAsReturnValue(e);
  205. return e;
  206. }
  207. static internal NotSupportedException NotSupported() {
  208. NotSupportedException e = new NotSupportedException();
  209. TraceExceptionAsReturnValue(e);
  210. return e;
  211. }
  212. static internal NotSupportedException NotSupported(string error) {
  213. NotSupportedException e = new NotSupportedException(error);
  214. TraceExceptionAsReturnValue(e);
  215. return e;
  216. }
  217. static internal OverflowException Overflow(string error) {
  218. return Overflow(error, null);
  219. }
  220. static internal OverflowException Overflow(string error, Exception inner) {
  221. OverflowException e = new OverflowException(error, inner);
  222. TraceExceptionAsReturnValue(e);
  223. return e;
  224. }
  225. static internal PlatformNotSupportedException PropertyNotSupported(string property) {
  226. PlatformNotSupportedException e = new PlatformNotSupportedException(Res.GetString(Res.ADP_PropertyNotSupported, property));
  227. TraceExceptionAsReturnValue(e);
  228. return e;
  229. }
  230. static internal TypeLoadException TypeLoad(string error) {
  231. TypeLoadException e = new TypeLoadException(error);
  232. TraceExceptionAsReturnValue(e);
  233. return e;
  234. }
  235. static internal InvalidCastException InvalidCast() {
  236. InvalidCastException e = new InvalidCastException();
  237. TraceExceptionAsReturnValue(e);
  238. return e;
  239. }
  240. static internal IOException IO(string error) {
  241. IOException e = new IOException(error);
  242. TraceExceptionAsReturnValue(e);
  243. return e;
  244. }
  245. static internal IOException IO(string error, Exception inner) {
  246. IOException e = new IOException(error, inner);
  247. TraceExceptionAsReturnValue(e);
  248. return e;
  249. }
  250. static internal InvalidOperationException DataAdapter(string error) {
  251. return InvalidOperation(error);
  252. }
  253. static internal InvalidOperationException DataAdapter(string error, Exception inner) {
  254. return InvalidOperation(error, inner);
  255. }
  256. static private InvalidOperationException Provider(string error) {
  257. return InvalidOperation(error);
  258. }
  259. static internal ObjectDisposedException ObjectDisposed(object instance) {
  260. ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
  261. TraceExceptionAsReturnValue(e);
  262. return e;
  263. }
  264. static internal InvalidOperationException MethodCalledTwice(string method) {
  265. InvalidOperationException e = new InvalidOperationException(Res.GetString(Res.ADP_CalledTwice, method));
  266. TraceExceptionAsReturnValue(e);
  267. return e;
  268. }
  269. static internal ArgumentException IncorrectAsyncResult() {
  270. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_IncorrectAsyncResult), "AsyncResult");
  271. TraceExceptionAsReturnValue(e);
  272. return e;
  273. }
  274. static internal ArgumentException SingleValuedProperty(string propertyName, string value) {
  275. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_SingleValuedProperty, propertyName, value));
  276. TraceExceptionAsReturnValue(e);
  277. return e;
  278. }
  279. static internal ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) {
  280. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_DoubleValuedProperty, propertyName, value1, value2));
  281. TraceExceptionAsReturnValue(e);
  282. return e;
  283. }
  284. static internal ArgumentException InvalidPrefixSuffix() {
  285. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidPrefixSuffix));
  286. TraceExceptionAsReturnValue(e);
  287. return e;
  288. }
  289. static internal ArgumentException InvalidMultipartName(string property, string value) {
  290. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartName, Res.GetString(property), value));
  291. TraceExceptionAsReturnValue(e);
  292. return e;
  293. }
  294. static internal ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) {
  295. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameQuoteUsage, Res.GetString(property), value));
  296. TraceExceptionAsReturnValue(e);
  297. return e;
  298. }
  299. static internal ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) {
  300. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameToManyParts, Res.GetString(property), value, limit));
  301. TraceExceptionAsReturnValue(e);
  302. return e;
  303. }
  304. static internal ArgumentException BadParameterName(string parameterName) {
  305. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_BadParameterName, parameterName));
  306. TraceExceptionAsReturnValue(e);
  307. return e;
  308. }
  309. static internal ArgumentException MultipleReturnValue() {
  310. ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_MultipleReturnValue));
  311. TraceExceptionAsReturnValue(e);
  312. return e;
  313. }
  314. //
  315. // Helper Functions
  316. //
  317. static internal void CheckArgumentLength(string value, string parameterName) {
  318. CheckArgumentNull(value, parameterName);
  319. if (0 == value.Length) {
  320. throw Argument(Res.GetString(Res.ADP_EmptyString, parameterName)); // MDAC 94859
  321. }
  322. }
  323. static internal void CheckArgumentLength(Array value, string parameterName) {
  324. CheckArgumentNull(value, parameterName);
  325. if (0 == value.Length) {
  326. throw Argument(Res.GetString(Res.ADP_EmptyArray, parameterName));
  327. }
  328. }
  329. static internal void CheckArgumentNull(object value, string parameterName) {
  330. if (null == value) {
  331. throw ArgumentNull(parameterName);
  332. }
  333. }
  334. // only StackOverflowException & ThreadAbortException are sealed classes
  335. static private readonly Type StackOverflowType = typeof(StackOverflowException);
  336. static private readonly Type OutOfMemoryType = typeof(OutOfMemoryException);
  337. static private readonly Type ThreadAbortType = typeof(ThreadAbortException);
  338. static private readonly Type NullReferenceType = typeof(NullReferenceException);
  339. static private readonly Type AccessViolationType = typeof(AccessViolationException);
  340. static private readonly Type SecurityType = typeof(SecurityException);
  341. static internal bool IsCatchableExceptionType (Exception e) {
  342. // a 'catchable' exception is defined by what it is not.
  343. Debug.Assert(e != null, "Unexpected null exception!");
  344. Type type = e.GetType();
  345. return ( (type != StackOverflowType) &&
  346. (type != OutOfMemoryType) &&
  347. (type != ThreadAbortType) &&
  348. (type != NullReferenceType) &&
  349. (type != AccessViolationType) &&
  350. !SecurityType.IsAssignableFrom(type));
  351. }
  352. static internal bool IsCatchableOrSecurityExceptionType(Exception e) {
  353. // a 'catchable' exception is defined by what it is not.
  354. // since IsCatchableExceptionType defined SecurityException as not 'catchable'
  355. // this method will return true for SecurityException has being catchable.
  356. // the other way to write this method is, but then SecurityException is checked twice
  357. // return ((e is SecurityException) || IsCatchableExceptionType(e));
  358. Debug.Assert(e != null, "Unexpected null exception!");
  359. Type type = e.GetType();
  360. return ( (type != StackOverflowType) &&
  361. (type != OutOfMemoryType) &&
  362. (type != ThreadAbortType) &&
  363. (type != NullReferenceType) &&
  364. (type != AccessViolationType));
  365. }
  366. // Invalid Enumeration
  367. static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) {
  368. return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
  369. }
  370. static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) {
  371. return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name);
  372. }
  373. static internal ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value) {
  374. #if DEBUG
  375. switch(value) {
  376. case AcceptRejectRule.None:
  377. case AcceptRejectRule.Cascade:
  378. Debug.Assert(false, "valid AcceptRejectRule " + value.ToString());
  379. break;
  380. }
  381. #endif
  382. return InvalidEnumerationValue(typeof(AcceptRejectRule), (int) value);
  383. }
  384. // DbCommandBuilder.CatalogLocation
  385. static internal ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value) {
  386. #if DEBUG
  387. switch(value) {
  388. case CatalogLocation.Start:
  389. case CatalogLocation.End:
  390. Debug.Assert(false, "valid CatalogLocation " + value.ToString());
  391. break;
  392. }
  393. #endif
  394. return InvalidEnumerationValue(typeof(CatalogLocation), (int) value);
  395. }
  396. static internal ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) {
  397. #if DEBUG
  398. if ((0 <= (int)value) && ((int)value <= 0x3F)) {
  399. Debug.Assert(false, "valid CommandType " + value.ToString());
  400. }
  401. #endif
  402. return InvalidEnumerationValue(typeof(CommandBehavior), (int) value);
  403. }
  404. static internal void ValidateCommandBehavior(CommandBehavior value) {
  405. if (((int)value < 0) || (0x3F < (int)value)) {
  406. throw InvalidCommandBehavior(value);
  407. }
  408. }
  409. static internal ArgumentException InvalidArgumentLength(string argumentName, int limit) {
  410. return Argument(Res.GetString(Res.ADP_InvalidArgumentLength, argumentName, limit));
  411. }
  412. static internal ArgumentException MustBeReadOnly(string argumentName) {
  413. return Argument(Res.GetString(Res.ADP_MustBeReadOnly, argumentName));
  414. }
  415. // IDbCommand.CommandType
  416. static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value) {
  417. #if DEBUG
  418. switch(value) {
  419. case CommandType.Text:
  420. case CommandType.StoredProcedure:
  421. case CommandType.TableDirect:
  422. Debug.Assert(false, "valid CommandType " + value.ToString());
  423. break;
  424. }
  425. #endif
  426. return InvalidEnumerationValue(typeof(CommandType), (int) value);
  427. }
  428. static internal ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value) {
  429. #if DEBUG
  430. switch(value) {
  431. case ConflictOption.CompareAllSearchableValues:
  432. case ConflictOption.CompareRowVersion:
  433. case ConflictOption.OverwriteChanges:
  434. Debug.Assert(false, "valid ConflictOption " + value.ToString());
  435. break;
  436. }
  437. #endif
  438. return InvalidEnumerationValue(typeof(ConflictOption), (int) value);
  439. }
  440. // IDataAdapter.Update
  441. static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState value) {
  442. #if DEBUG
  443. switch(value) {
  444. case DataRowState.Detached:
  445. case DataRowState.Unchanged:
  446. case DataRowState.Added:
  447. case DataRowState.Deleted:
  448. case DataRowState.Modified:
  449. Debug.Assert(false, "valid DataRowState " + value.ToString());
  450. break;
  451. }
  452. #endif
  453. return InvalidEnumerationValue(typeof(DataRowState), (int) value);
  454. }
  455. // IDataParameter.SourceVersion
  456. static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) {
  457. #if DEBUG
  458. switch(value) {
  459. case DataRowVersion.Default:
  460. case DataRowVersion.Current:
  461. case DataRowVersion.Original:
  462. case DataRowVersion.Proposed:
  463. Debug.Assert(false, "valid DataRowVersion " + value.ToString());
  464. break;
  465. }
  466. #endif
  467. return InvalidEnumerationValue(typeof(DataRowVersion), (int) value);
  468. }
  469. // IDbConnection.BeginTransaction, OleDbTransaction.Begin
  470. static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) {
  471. #if DEBUG
  472. switch(value) {
  473. case IsolationLevel.Unspecified:
  474. case IsolationLevel.Chaos:
  475. case IsolationLevel.ReadUncommitted:
  476. case IsolationLevel.ReadCommitted:
  477. case IsolationLevel.RepeatableRead:
  478. case IsolationLevel.Serializable:
  479. case IsolationLevel.Snapshot:
  480. Debug.Assert(false, "valid IsolationLevel " + value.ToString());
  481. break;
  482. }
  483. #endif
  484. return InvalidEnumerationValue(typeof(IsolationLevel), (int) value);
  485. }
  486. // DBDataPermissionAttribute.KeyRestrictionBehavior
  487. static internal ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) {
  488. #if DEBUG
  489. switch(value) {
  490. case KeyRestrictionBehavior.PreventUsage:
  491. case KeyRestrictionBehavior.AllowOnly:
  492. Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
  493. break;
  494. }
  495. #endif
  496. return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int) value);
  497. }
  498. // IDataAdapter.FillLoadOption
  499. static internal ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) {
  500. #if DEBUG
  501. switch(value) {
  502. case LoadOption.OverwriteChanges:
  503. case LoadOption.PreserveChanges:
  504. case LoadOption.Upsert:
  505. Debug.Assert(false, "valid LoadOption " + value.ToString());
  506. break;
  507. }
  508. #endif
  509. return InvalidEnumerationValue(typeof(LoadOption), (int) value);
  510. }
  511. // IDataAdapter.MissingMappingAction
  512. static internal ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value) {
  513. #if DEBUG
  514. switch(value) {
  515. case MissingMappingAction.Passthrough:
  516. case MissingMappingAction.Ignore:
  517. case MissingMappingAction.Error:
  518. Debug.Assert(false, "valid MissingMappingAction " + value.ToString());
  519. break;
  520. }
  521. #endif
  522. return InvalidEnumerationValue(typeof(MissingMappingAction), (int) value);
  523. }
  524. // IDataAdapter.MissingSchemaAction
  525. static internal ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value) {
  526. #if DEBUG
  527. switch(value) {
  528. case MissingSchemaAction.Add:
  529. case MissingSchemaAction.Ignore:
  530. case MissingSchemaAction.Error:
  531. case MissingSchemaAction.AddWithKey:
  532. Debug.Assert(false, "valid MissingSchemaAction " + value.ToString());
  533. break;
  534. }
  535. #endif
  536. return InvalidEnumerationValue(typeof(MissingSchemaAction), (int) value);
  537. }
  538. // IDataParameter.Direction
  539. static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) {
  540. #if DEBUG
  541. switch(value) {
  542. case ParameterDirection.Input:
  543. case ParameterDirection.Output:
  544. case ParameterDirection.InputOutput:
  545. case ParameterDirection.ReturnValue:
  546. Debug.Assert(false, "valid ParameterDirection " + value.ToString());
  547. break;
  548. }
  549. #endif
  550. return InvalidEnumerationValue(typeof(ParameterDirection), (int) value);
  551. }
  552. static internal ArgumentOutOfRangeException InvalidPermissionState(PermissionState value) {
  553. #if DEBUG
  554. switch(value) {
  555. case PermissionState.Unrestricted:
  556. case PermissionState.None:
  557. Debug.Assert(false, "valid PermissionState " + value.ToString());
  558. break;
  559. }
  560. #endif
  561. return InvalidEnumerationValue(typeof(PermissionState), (int) value);
  562. }
  563. static internal ArgumentOutOfRangeException InvalidRule(Rule value) {
  564. #if DEBUG
  565. switch(value) {
  566. case Rule.None:
  567. case Rule.Cascade:
  568. case Rule.SetNull:
  569. case Rule.SetDefault:
  570. Debug.Assert(false, "valid Rule " + value.ToString());
  571. break;
  572. }
  573. #endif
  574. return InvalidEnumerationValue(typeof(Rule), (int) value);
  575. }
  576. // IDataAdapter.FillSchema
  577. static internal ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) {
  578. #if DEBUG
  579. switch(value) {
  580. case SchemaType.Source:
  581. case SchemaType.Mapped:
  582. Debug.Assert(false, "valid SchemaType " + value.ToString());
  583. break;
  584. }
  585. #endif
  586. return InvalidEnumerationValue(typeof(SchemaType), (int) value);
  587. }
  588. // RowUpdatingEventArgs.StatementType
  589. static internal ArgumentOutOfRangeException InvalidStatementType(StatementType value) {
  590. #if DEBUG
  591. switch(value) {
  592. case StatementType.Select:
  593. case StatementType.Insert:
  594. case StatementType.Update:
  595. case StatementType.Delete:
  596. case StatementType.Batch:
  597. Debug.Assert(false, "valid StatementType " + value.ToString());
  598. break;
  599. }
  600. #endif
  601. return InvalidEnumerationValue(typeof(StatementType), (int) value);
  602. }
  603. // IDbCommand.UpdateRowSource
  604. static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) {
  605. #if DEBUG
  606. switch(value) {
  607. case UpdateRowSource.None:
  608. case UpdateRowSource.OutputParameters:
  609. case UpdateRowSource.FirstReturnedRecord:
  610. case UpdateRowSource.Both:
  611. Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
  612. break;
  613. }
  614. #endif
  615. return InvalidEnumerationValue(typeof(UpdateRowSource), (int) value);
  616. }
  617. // RowUpdatingEventArgs.UpdateStatus
  618. static internal ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value) {
  619. #if DEBUG
  620. switch(value) {
  621. case UpdateStatus.Continue:
  622. case UpdateStatus.ErrorsOccurred:
  623. case UpdateStatus.SkipAllRemainingRows:
  624. case UpdateStatus.SkipCurrentRow:
  625. Debug.Assert(false, "valid UpdateStatus " + value.ToString());
  626. break;
  627. }
  628. #endif
  629. return InvalidEnumerationValue(typeof(UpdateStatus), (int) value);
  630. }
  631. static internal ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) {
  632. return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
  633. }
  634. static internal ArgumentOutOfRangeException NotSupportedStatementType(StatementType value, string method) {
  635. return NotSupportedEnumerationValue(typeof(StatementType), value.ToString(), method);
  636. }
  637. static internal ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value) {
  638. #if DEBUG
  639. switch(value) {
  640. case Microsoft.SqlServer.Server.Format.Unknown:
  641. case Microsoft.SqlServer.Server.Format.Native:
  642. case Microsoft.SqlServer.Server.Format.UserDefined:
  643. Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString());
  644. break;
  645. }
  646. #endif
  647. return InvalidEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), (int) value);
  648. }
  649. static internal ArgumentOutOfRangeException NotSupportedUserDefinedTypeSerializationFormat(Microsoft.SqlServer.Server.Format value, string method) {
  650. return ADP.NotSupportedEnumerationValue(typeof(Microsoft.SqlServer.Server.Format), value.ToString(), method);
  651. }
  652. //
  653. // DbProviderFactories
  654. //
  655. static internal ArgumentException ConfigProviderNotFound() {
  656. return Argument(Res.GetString(Res.ConfigProviderNotFound));
  657. }
  658. static internal InvalidOperationException ConfigProviderInvalid() {
  659. return InvalidOperation(Res.GetString(Res.ConfigProviderInvalid));
  660. }
  661. #if !MOBILE
  662. static internal ConfigurationException ConfigProviderNotInstalled() {
  663. return Configuration(Res.GetString(Res.ConfigProviderNotInstalled));
  664. }
  665. static internal ConfigurationException ConfigProviderMissing() {
  666. return Configuration(Res.GetString(Res.ConfigProviderMissing));
  667. }
  668. //
  669. // DbProviderConfigurationHandler
  670. //
  671. static internal ConfigurationException ConfigBaseNoChildNodes(XmlNode node) { // Res.Config_base_no_child_nodes
  672. return Configuration(Res.GetString(Res.ConfigBaseNoChildNodes), node);
  673. }
  674. static internal ConfigurationException ConfigBaseElementsOnly(XmlNode node) { // Res.Config_base_elements_only
  675. return Configuration(Res.GetString(Res.ConfigBaseElementsOnly), node);
  676. }
  677. static internal ConfigurationException ConfigUnrecognizedAttributes(XmlNode node) { // Res.Config_base_unrecognized_attribute
  678. return Configuration(Res.GetString(Res.ConfigUnrecognizedAttributes, node.Attributes[0].Name), node);
  679. }
  680. static internal ConfigurationException ConfigUnrecognizedElement(XmlNode node) { // Res.Config_base_unrecognized_element
  681. return Configuration(Res.GetString(Res.ConfigUnrecognizedElement), node);
  682. }
  683. static internal ConfigurationException ConfigSectionsUnique(string sectionName) { // Res.Res.ConfigSectionsUnique
  684. return Configuration(Res.GetString(Res.ConfigSectionsUnique, sectionName));
  685. }
  686. static internal ConfigurationException ConfigRequiredAttributeMissing(string name, XmlNode node) { // Res.Config_base_required_attribute_missing
  687. return Configuration(Res.GetString(Res.ConfigRequiredAttributeMissing, name), node);
  688. }
  689. static internal ConfigurationException ConfigRequiredAttributeEmpty(string name, XmlNode node) { // Res.Config_base_required_attribute_empty
  690. return Configuration(Res.GetString(Res.ConfigRequiredAttributeEmpty, name), node);
  691. }
  692. #endif
  693. //
  694. // DbConnectionOptions, DataAccess
  695. //
  696. static internal ArgumentException ConnectionStringSyntax(int index) {
  697. return Argument(Res.GetString(Res.ADP_ConnectionStringSyntax, index));
  698. }
  699. static internal ArgumentException KeywordNotSupported(string keyword) {
  700. return Argument(Res.GetString(Res.ADP_KeywordNotSupported, keyword));
  701. }
  702. /*
  703. static internal ArgumentException EmptyKeyValue(string keyword) { // MDAC 80715
  704. return Argument(Res.GetString(Res.ADP_EmptyKeyValue, keyword));
  705. }
  706. */
  707. static internal ArgumentException UdlFileError(Exception inner) {
  708. return Argument(Res.GetString(Res.ADP_UdlFileError), inner);
  709. }
  710. static internal ArgumentException InvalidUDL() {
  711. return Argument(Res.GetString(Res.ADP_InvalidUDL));
  712. }
  713. static internal InvalidOperationException InvalidDataDirectory() {
  714. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidDataDirectory));
  715. }
  716. static internal ArgumentException InvalidKeyname(string parameterName) {
  717. return Argument(Res.GetString(Res.ADP_InvalidKey), parameterName);
  718. }
  719. static internal ArgumentException InvalidValue(string parameterName) {
  720. return Argument(Res.GetString(Res.ADP_InvalidValue), parameterName);
  721. }
  722. static internal ArgumentException InvalidMinMaxPoolSizeValues() {
  723. return ADP.Argument(Res.GetString(Res.ADP_InvalidMinMaxPoolSizeValues));
  724. }
  725. static internal ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) {
  726. return ADP.Argument(Res.GetString(Res.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
  727. }
  728. static internal InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() {
  729. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
  730. }
  731. static internal ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() {
  732. return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureAndClearCredential));
  733. }
  734. static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() {
  735. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
  736. }
  737. static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() {
  738. return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity));
  739. }
  740. static internal InvalidOperationException InvalidMixedUsageOfSecureCredentialAndContextConnection()
  741. {
  742. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
  743. }
  744. static internal ArgumentException InvalidMixedArgumentOfSecureCredentialAndContextConnection()
  745. {
  746. return ADP.Argument(Res.GetString(Res.ADP_InvalidMixedUsageOfSecureCredentialAndContextConnection));
  747. }
  748. static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndContextConnection() {
  749. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndContextConnection));
  750. }
  751. static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() {
  752. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity));
  753. }
  754. static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() {
  755. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword));
  756. }
  757. static internal Exception InvalidMixedUsageOfAccessTokenAndCredential() {
  758. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndCredential));
  759. }
  760. static internal Exception InvalidMixedUsageOfAccessTokenAndAuthentication() {
  761. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication));
  762. }
  763. static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() {
  764. return ADP.InvalidOperation(Res.GetString(Res.ADP_InvalidMixedUsageOfCredentialAndAccessToken));
  765. }
  766. //
  767. // DbConnection
  768. //
  769. static internal InvalidOperationException NoConnectionString() {
  770. return InvalidOperation(Res.GetString(Res.ADP_NoConnectionString));
  771. }
  772. static internal NotImplementedException MethodNotImplemented(string methodName) {
  773. NotImplementedException e = new NotImplementedException(methodName);
  774. TraceExceptionAsReturnValue(e);
  775. return e;
  776. }
  777. static private string ConnectionStateMsg(ConnectionState state) { // MDAC 82165, if the ConnectionState enum to msg the localization looks weird
  778. switch(state) {
  779. case (ConnectionState.Closed):
  780. case (ConnectionState.Connecting|ConnectionState.Broken): // treated the same as closed
  781. return Res.GetString(Res.ADP_ConnectionStateMsg_Closed);
  782. case (ConnectionState.Connecting):
  783. return Res.GetString(Res.ADP_ConnectionStateMsg_Connecting);
  784. case (ConnectionState.Open):
  785. return Res.GetString(Res.ADP_ConnectionStateMsg_Open);
  786. case (ConnectionState.Open|ConnectionState.Executing):
  787. return Res.GetString(Res.ADP_ConnectionStateMsg_OpenExecuting);
  788. case (ConnectionState.Open|ConnectionState.Fetching):
  789. return Res.GetString(Res.ADP_ConnectionStateMsg_OpenFetching);
  790. default:
  791. return Res.GetString(Res.ADP_ConnectionStateMsg, state.ToString());
  792. }
  793. }
  794. #if !MOBILE
  795. static internal ConfigurationException ConfigUnableToLoadXmlMetaDataFile(string settingName){
  796. return Configuration(Res.GetString(Res.OleDb_ConfigUnableToLoadXmlMetaDataFile, settingName));
  797. }
  798. static internal ConfigurationException ConfigWrongNumberOfValues(string settingName){
  799. return Configuration(Res.GetString(Res.OleDb_ConfigWrongNumberOfValues, settingName));
  800. }
  801. #endif
  802. //
  803. // : DbConnectionOptions, DataAccess, SqlClient
  804. //
  805. static internal Exception InvalidConnectionOptionValue(string key) {
  806. return InvalidConnectionOptionValue(key, null);
  807. }
  808. static internal Exception InvalidConnectionOptionValueLength(string key, int limit) {
  809. return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValueLength, key, limit));
  810. }
  811. static internal Exception InvalidConnectionOptionValue(string key, Exception inner) {
  812. return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValue, key), inner);
  813. }
  814. static internal Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) {
  815. return Argument(Res.GetString(Res.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
  816. }
  817. //
  818. // DBDataPermission, DataAccess, Odbc
  819. //
  820. static internal Exception InvalidXMLBadVersion() {
  821. return Argument(Res.GetString(Res.ADP_InvalidXMLBadVersion));
  822. }
  823. static internal Exception NotAPermissionElement() {
  824. return Argument(Res.GetString(Res.ADP_NotAPermissionElement));
  825. }
  826. static internal Exception PermissionTypeMismatch() {
  827. return Argument(Res.GetString(Res.ADP_PermissionTypeMismatch));
  828. }
  829. static internal Exception WrongType(Type got, Type expected) {
  830. return Argument(Res.GetString(Res.SQL_WrongType, got.ToString(), expected.ToString()));
  831. }
  832. static internal Exception OdbcNoTypesFromProvider() {
  833. return InvalidOperation(Res.GetString(Res.ADP_OdbcNoTypesFromProvider));
  834. }
  835. //
  836. // DbConnectionPool and related
  837. //
  838. static internal Exception PooledOpenTimeout() {
  839. return ADP.InvalidOperation(Res.GetString(Res.ADP_PooledOpenTimeout));
  840. }
  841. static internal Exception NonPooledOpenTimeout() {
  842. return ADP.TimeoutException(Res.GetString(Res.ADP_NonPooledOpenTimeout));
  843. }
  844. //
  845. // Generic Data Provider Collection
  846. //
  847. static internal ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) {
  848. return Argument(Res.GetString(Res.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); // MDAC 68201
  849. }
  850. static internal ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) {
  851. return ArgumentNull(parameter, Res.GetString(Res.ADP_CollectionNullValue, collection.Name, itemType.Name));
  852. }
  853. static internal IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) {
  854. return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
  855. }
  856. static internal IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) {
  857. return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
  858. }
  859. static internal InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) {
  860. return InvalidCast(Res.GetString(Res.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
  861. }
  862. static internal Exception CollectionUniqueValue(Type itemType, string propertyName, string propertyValue) {
  863. return Argument(Res.GetString(Res.ADP_CollectionUniqueValue, itemType.Name, propertyName, propertyValue));
  864. }
  865. static internal ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) {
  866. return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
  867. }
  868. static internal ArgumentException ParametersIsParent(Type parameterType, ICollection collection) {
  869. return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
  870. }
  871. //
  872. // DbProviderException
  873. //
  874. static internal InvalidOperationException TransactionConnectionMismatch() {
  875. return Provider(Res.GetString(Res.ADP_TransactionConnectionMismatch));
  876. }
  877. static internal InvalidOperationException TransactionCompletedButNotDisposed()
  878. {
  879. return Provider(Res.GetString(Res.ADP_TransactionCompletedButNotDisposed));
  880. }
  881. static internal InvalidOperationException TransactionRequired(string method) {
  882. return Provider(Res.GetString(Res.ADP_TransactionRequired, method));
  883. }
  884. // IDbDataAdapter.Fill(Schema)
  885. static internal InvalidOperationException MissingSelectCommand(string method) {
  886. return Provider(Res.GetString(Res.ADP_MissingSelectCommand, method));
  887. }
  888. //
  889. // AdapterMappingException
  890. //
  891. static private InvalidOperationException DataMapping(string error) {
  892. return InvalidOperation(error);
  893. }
  894. // DataColumnMapping.GetDataColumnBySchemaAction
  895. static internal InvalidOperationException ColumnSchemaExpression(string srcColumn, string cacheColumn) {
  896. return DataMapping(Res.GetString(Res.ADP_ColumnSchemaExpression, srcColumn, cacheColumn));
  897. }
  898. // DataColumnMapping.GetDataColumnBySchemaAction
  899. static internal InvalidOperationException ColumnSchemaMismatch(string srcColumn, Type srcType, DataColumn column) {
  900. return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMismatch, srcColumn, srcType.Name, column.ColumnName, column.DataType.Name));
  901. }
  902. // DataColumnMapping.GetDataColumnBySchemaAction
  903. static internal InvalidOperationException ColumnSchemaMissing(string cacheColumn, string tableName, string srcColumn) {
  904. if (ADP.IsEmpty(tableName)) {
  905. return InvalidOperation(Res.GetString(Res.ADP_ColumnSchemaMissing1, cacheColumn, tableName, srcColumn));
  906. }
  907. return DataMapping(Res.GetString(Res.ADP_ColumnSchemaMissing2, cacheColumn, tableName, srcColumn));
  908. }
  909. // DataColumnMappingCollection.GetColumnMappingBySchemaAction
  910. static internal InvalidOperationException MissingColumnMapping(string srcColumn) {
  911. return DataMapping(Res.GetString(Res.ADP_MissingColumnMapping, srcColumn));
  912. }
  913. // DataTableMapping.GetDataTableBySchemaAction
  914. static internal InvalidOperationException MissingTableSchema(string cacheTable, string srcTable) {
  915. return DataMapping(Res.GetString(Res.ADP_MissingTableSchema, cacheTable, srcTable));
  916. }
  917. // DataTableMappingCollection.GetTableMappingBySchemaAction
  918. static internal InvalidOperationException MissingTableMapping(string srcTable) {
  919. return DataMapping(Res.GetString(Res.ADP_MissingTableMapping, srcTable));
  920. }
  921. // DbDataAdapter.Update
  922. static internal InvalidOperationException MissingTableMappingDestination(string dstTable) {
  923. return DataMapping(Res.GetString(Res.ADP_MissingTableMappingDestination, dstTable));
  924. }
  925. //
  926. // DataColumnMappingCollection, DataAccess
  927. //
  928. static internal Exception InvalidSourceColumn(string parameter) {
  929. return Argument(Res.GetString(Res.ADP_InvalidSourceColumn), parameter);
  930. }
  931. static internal Exception ColumnsAddNullAttempt(string parameter) {
  932. return CollectionNullValue(parameter, typeof(DataColumnMappingCollection), typeof(DataColumnMapping));
  933. }
  934. static internal Exception ColumnsDataSetColumn(string cacheColumn) {
  935. return CollectionIndexString(typeof(DataColumnMapping), ADP.DataSetColumn, cacheColumn, typeof(DataColumnMappingCollection));
  936. }
  937. static internal Exception ColumnsIndexInt32(int index, IColumnMappingCollection collection) {
  938. return CollectionIndexInt32(index, collection.GetType(), collection.Count);
  939. }
  940. static internal Exception ColumnsIndexSource(string srcColumn) {
  941. return CollectionIndexString(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn, typeof(DataColumnMappingCollection));
  942. }
  943. static internal Exception ColumnsIsNotParent(ICollection collection) {
  944. return ParametersIsNotParent(typeof(DataColumnMapping), collection);
  945. }
  946. static internal Exception ColumnsIsParent(ICollection collection) {
  947. return ParametersIsParent(typeof(DataColumnMapping), collection);
  948. }
  949. static internal Exception ColumnsUniqueSourceColumn(string srcColumn) {
  950. return CollectionUniqueValue(typeof(DataColumnMapping), ADP.SourceColumn, srcColumn);
  951. }
  952. static internal Exception NotADataColumnMapping(object value) {
  953. return CollectionInvalidType(typeof(DataColumnMappingCollection), typeof(DataColumnMapping), value);
  954. }
  955. //
  956. // DataTableMappingCollection, DataAccess
  957. //
  958. static internal Exception InvalidSourceTable(string parameter) {
  959. return Argument(Res.GetString(Res.ADP_InvalidSourceTable), parameter);
  960. }
  961. static internal Exception TablesAddNullAttempt(string parameter) {
  962. return CollectionNullValue(parameter, typeof(DataTableMappingCollection), typeof(DataTableMapping));
  963. }
  964. static internal Exception TablesDataSetTable(string cacheTable) {
  965. return CollectionIndexString(typeof(DataTableMapping), ADP.DataSetTable, cacheTable, typeof(DataTableMappingCollection));
  966. }
  967. static internal Exception TablesIndexInt32(int index, ITableMappingCollection collection) {
  968. return CollectionIndexInt32(index, collection.GetType(), collection.Count);
  969. }
  970. static internal Exception TablesIsNotParent(ICollection collection) {
  971. return ParametersIsNotParent(typeof(DataTableMapping), collection);
  972. }
  973. static internal Exception TablesIsParent(ICollection collection) {
  974. return ParametersIsParent(typeof(DataTableMapping), collection);
  975. }
  976. static internal Exception TablesSourceIndex(string srcTable) {
  977. return CollectionIndexString(typeof(DataTableMapping), ADP.SourceTable, srcTable, typeof(DataTableMappingCollection));
  978. }
  979. static internal Exception TablesUniqueSourceTable(string srcTable) {
  980. return CollectionUniqueValue(typeof(DataTableMapping), ADP.SourceTable, srcTable);
  981. }
  982. static internal Exception NotADataTableMapping(object value) {
  983. return CollectionInvalidType(typeof(DataTableMappingCollection), typeof(DataTableMapping), value);
  984. }
  985. //
  986. // IDbCommand
  987. //
  988. static internal InvalidOperationException CommandAsyncOperationCompleted() {
  989. return InvalidOperation(Res.GetString(Res.SQL_AsyncOperationCompleted));
  990. }
  991. static internal Exception CommandTextRequired(string method) {
  992. return InvalidOperation(Res.GetString(Res.ADP_CommandTextRequired, method));
  993. }
  994. static internal InvalidOperationException ConnectionRequired(string method) {
  995. return InvalidOperation(Res.GetString(Res.ADP_ConnectionRequired, method));
  996. }
  997. static internal InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) {
  998. return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
  999. }
  1000. static internal InvalidOperationException UpdateConnectionRequired(StatementType statementType, bool isRowUpdatingCommand) {
  1001. string resource;
  1002. if (isRowUpdatingCommand) {
  1003. resource = Res.ADP_ConnectionRequired_Clone;
  1004. }
  1005. else {
  1006. switch(statementType) {
  1007. case StatementType.Insert:
  1008. resource = Res.ADP_ConnectionRequired_Insert;
  1009. break;
  1010. case StatementType.Update:
  1011. resource = Res.ADP_ConnectionRequired_Update;
  1012. break;
  1013. case StatementType.Delete:
  1014. resource = Res.ADP_ConnectionRequired_Delete;
  1015. break;
  1016. case StatementType.Batch:
  1017. resource = Res.ADP_ConnectionRequired_Batch;
  1018. goto default;
  1019. #if DEBUG
  1020. case StatementType.Select:
  1021. Debug.Assert(false, "shouldn't be here");
  1022. goto default;
  1023. #endif
  1024. default:
  1025. throw ADP.InvalidStatementType(statementType);
  1026. }
  1027. }
  1028. return InvalidOperation(Res.GetString(resource));
  1029. }
  1030. static internal InvalidOperationException ConnectionRequired_Res(string method) {
  1031. string resource = "ADP_ConnectionRequired_" + method;
  1032. #if DEBUG
  1033. switch(resource) {
  1034. case Res.ADP_ConnectionRequired_Fill:
  1035. case Res.ADP_ConnectionRequired_FillPage:
  1036. case Res.ADP_ConnectionRequired_FillSchema:
  1037. case Res.ADP_ConnectionRequired_Update:
  1038. case Res.ADP_ConnecitonRequired_UpdateRows:
  1039. break;
  1040. default:
  1041. Debug.Assert(false, "missing resource string: " + resource);
  1042. break;
  1043. }
  1044. #endif
  1045. return InvalidOperation(Res.GetString(resource));
  1046. }
  1047. static internal InvalidOperationException UpdateOpenConnectionRequired(StatementType statementType, bool isRowUpdatingCommand, ConnectionState state) {
  1048. string resource;
  1049. if (isRowUpdatingCommand) {
  1050. resource = Res.ADP_OpenConnectionRequired_Clone;
  1051. }
  1052. else {
  1053. switch(statementType) {
  1054. case StatementType.Insert:
  1055. resource = Res.ADP_OpenConnectionRequired_Insert;
  1056. break;
  1057. case StatementType.Update:
  1058. resource = Res.ADP_OpenConnectionRequired_Update;
  1059. break;
  1060. case StatementType.Delete:
  1061. resource = Res.ADP_OpenConnectionRequired_Delete;
  1062. break;
  1063. #if DEBUG
  1064. case StatementType.Select:
  1065. Debug.Assert(false, "shouldn't be here");
  1066. goto default;
  1067. case StatementType.Batch:
  1068. Debug.Assert(false, "isRowUpdatingCommand should have been true");
  1069. goto default;
  1070. #endif
  1071. default:
  1072. throw ADP.InvalidStatementType(statementType);
  1073. }
  1074. }
  1075. return InvalidOperation(Res.GetString(resource, ADP.ConnectionStateMsg(state)));
  1076. }
  1077. static internal Exception NoStoredProcedureExists(string sproc) {
  1078. return InvalidOperation(Res.GetString(Res.ADP_NoStoredProcedureExists, sproc));
  1079. }
  1080. static internal Exception OpenReaderExists() {
  1081. return OpenReaderExists(null);
  1082. }
  1083. static internal Exception OpenReaderExists(Exception e) {
  1084. return InvalidOperation(Res.GetString(Res.ADP_OpenReaderExists), e);
  1085. }
  1086. static internal Exception TransactionCompleted() {
  1087. return DataAdapter(Res.GetString(Res.ADP_TransactionCompleted));
  1088. }
  1089. //
  1090. // DbDataReader
  1091. //
  1092. static internal Exception NonSeqByteAccess(long badIndex, long currIndex, string method) {
  1093. return InvalidOperation(Res.GetString(Res.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
  1094. }
  1095. static internal Exception NegativeParameter(string parameterName) {
  1096. return InvalidOperation(Res.GetString(Res.ADP_NegativeParameter, parameterName));
  1097. }
  1098. static internal Exception NumericToDecimalOverflow() {
  1099. return InvalidCast(Res.GetString(Res.ADP_NumericToDecimalOverflow));
  1100. }
  1101. //
  1102. // Stream, SqlTypes, SqlClient
  1103. //
  1104. static internal Exception ExceedsMaxDataLength(long specifiedLength, long maxLength) {
  1105. return IndexOutOfRange(Res.GetString(Res.SQL_ExceedsMaxDataLength, specifiedLength.ToString(CultureInfo.InvariantCulture), maxLength.ToString(CultureInfo.InvariantCulture)));
  1106. }
  1107. static internal Exception InvalidSeekOrigin(string parameterName) {
  1108. return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSeekOrigin), parameterName);
  1109. }
  1110. //
  1111. // SqlMetaData, SqlTypes, SqlClient
  1112. //
  1113. static internal Exception InvalidImplicitConversion(Type fromtype, string totype) {
  1114. return InvalidCast(Res.GetString(Res.ADP_InvalidImplicitConversion, fromtype.Name, totype));
  1115. }
  1116. static internal Exception InvalidMetaDataValue() {
  1117. return ADP.Argument(Res.GetString(Res.ADP_InvalidMetaDataValue));
  1118. }
  1119. static internal Exception NotRowType() {
  1120. return InvalidOperation(Res.GetString(Res.ADP_NotRowType));
  1121. }
  1122. //
  1123. // DbDataAdapter
  1124. //
  1125. static internal ArgumentException UnwantedStatementType(StatementType statementType) {
  1126. return Argument(Res.GetString(Res.ADP_UnwantedStatementType, statementType.ToString()));
  1127. }
  1128. static internal InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) {
  1129. return InvalidOperation(Res.GetString(Res.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
  1130. }
  1131. //
  1132. // DbDataAdapter.FillSchema
  1133. //
  1134. static internal Exception FillSchemaRequiresSourceTableName(string parameter) {
  1135. return Argument(Res.GetString(Res.ADP_FillSchemaRequiresSourceTableName), parameter);
  1136. }
  1137. //
  1138. // DbDataAdapter.Fill
  1139. //
  1140. static internal Exception InvalidMaxRecords(string parameter, int max) {
  1141. return Argument(Res.GetString(Res.ADP_InvalidMaxRecords, max.ToString(CultureInfo.InvariantCulture)), parameter);
  1142. }
  1143. static internal Exception InvalidStartRecord(string parameter, int start) {
  1144. return Argument(Res.GetString(Res.ADP_InvalidStartRecord, start.ToString(CultureInfo.InvariantCulture)), parameter);
  1145. }
  1146. static internal Exception FillRequires(string parameter) {
  1147. return ArgumentNull(parameter);
  1148. }
  1149. static internal Exception FillRequiresSourceTableName(string parameter) {
  1150. return Argument(Res.GetString(Res.ADP_FillRequiresSourceTableName), parameter);
  1151. }
  1152. static internal Exception FillChapterAutoIncrement() {
  1153. return InvalidOperation(Res.GetString(Res.ADP_FillChapterAutoIncrement));
  1154. }
  1155. static internal InvalidOperationException MissingDataReaderFieldType(int index) {
  1156. return DataAdapter(Res.GetString(Res.ADP_MissingDataReaderFieldType, index));
  1157. }
  1158. static internal InvalidOperationException OnlyOneTableForStartRecordOrMaxRecords() {
  1159. return DataAdapter(Res.GetString(Res.ADP_OnlyOneTableForStartRecordOrMaxRecords));
  1160. }
  1161. //
  1162. // DbDataAdapter.Update
  1163. //
  1164. static internal ArgumentNullException UpdateRequiresNonNullDataSet(string parameter) {
  1165. return ArgumentNull(parameter);
  1166. }
  1167. static internal InvalidOperationException UpdateRequiresSourceTable(string defaultSrcTableName) {
  1168. return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTable, defaultSrcTableName));
  1169. }
  1170. static internal InvalidOperationException UpdateRequiresSourceTableName(string srcTable) {
  1171. return InvalidOperation(Res.GetString(Res.ADP_UpdateRequiresSourceTableName, srcTable)); // MDAC 70448
  1172. }
  1173. static internal ArgumentNullException UpdateRequiresDataTable(string parameter) {
  1174. return ArgumentNull(parameter);
  1175. }
  1176. static internal Exception UpdateConcurrencyViolation(StatementType statementType, int affected, int expected, DataRow[] dataRows) {
  1177. string resource;
  1178. switch(statementType) {
  1179. case StatementType.Update:
  1180. resource = Res.ADP_UpdateConcurrencyViolation_Update;
  1181. break;
  1182. case StatementType.Delete:
  1183. resource = Res.ADP_UpdateConcurrencyViolation_Delete;
  1184. break;
  1185. case StatementType.Batch:
  1186. resource = Res.ADP_UpdateConcurrencyViolation_Batch;
  1187. break;
  1188. #if DEBUG
  1189. case StatementType.Select:
  1190. case StatementType.Insert:
  1191. Debug.Assert(false, "should be here");
  1192. goto default;
  1193. #endif
  1194. default:
  1195. throw ADP.InvalidStatementType(statementType);
  1196. }
  1197. DBConcurrencyException exception = new DBConcurrencyException(Res.GetString(resource, affected.ToString(CultureInfo.InvariantCulture), expected.ToString(CultureInfo.InvariantCulture)), null, dataRows);
  1198. TraceExceptionAsReturnValue(exception);
  1199. return exception;
  1200. }
  1201. static internal InvalidOperationException UpdateRequiresCommand(StatementType statementType, bool isRowUpdatingCommand) {
  1202. string resource;
  1203. if (isRowUpdatingCommand) {
  1204. resource = Res.ADP_UpdateRequiresCommandClone;
  1205. }
  1206. else {
  1207. switch(statementType) {
  1208. case StatementType.Select:
  1209. resource = Res.ADP_UpdateRequiresCommandSelect;
  1210. break;
  1211. case StatementType.Insert:
  1212. resource = Res.ADP_UpdateRequiresCommandInsert;
  1213. break;
  1214. case StatementType.Update:
  1215. resource = Res.ADP_UpdateRequiresCommandUpdate;
  1216. break;
  1217. case StatementType.Delete:
  1218. resource = Res.ADP_UpdateRequiresCommandDelete;
  1219. break;
  1220. #if DEBUG
  1221. case StatementType.Batch:
  1222. Debug.Assert(false, "isRowUpdatingCommand should have been true");
  1223. goto default;
  1224. #endif
  1225. default:
  1226. throw ADP.InvalidStatementType(statementType);
  1227. }
  1228. }
  1229. return InvalidOperation(Res.GetString(resource));
  1230. }
  1231. static internal ArgumentException UpdateMismatchRowTable(int i) {
  1232. return Argument(Res.GetString(Res.ADP_UpdateMismatchRowTable, i.ToString(CultureInfo.InvariantCulture)));
  1233. }
  1234. static internal DataException RowUpdatedErrors() {
  1235. return Data(Res.GetString(Res.ADP_RowUpdatedErrors));
  1236. }
  1237. static internal DataException RowUpdatingErrors() {
  1238. return Data(Res.GetString(Res.ADP_RowUpdatingErrors));
  1239. }
  1240. static internal InvalidOperationException ResultsNotAllowedDuringBatch() {
  1241. return DataAdapter(Res.GetString(Res.ADP_ResultsNotAllowedDuringBatch));
  1242. }
  1243. //
  1244. // : IDbCommand
  1245. //
  1246. static internal Exception InvalidCommandTimeout(int value) {
  1247. return Argument(Res.GetString(Res.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), ADP.CommandTimeout);
  1248. }
  1249. static internal Exception DeriveParametersNotSupported(IDbCommand value) {
  1250. return DataAdapter(Res.GetString(Res.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
  1251. }
  1252. static internal Exception UninitializedParameterSize(int index, Type dataType) {
  1253. return InvalidOperation(Res.GetString(Res.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
  1254. }
  1255. static internal Exception PrepareParameterType(IDbCommand cmd) {
  1256. return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterType, cmd.GetType().Name));
  1257. }
  1258. static internal Exception PrepareParameterSize(IDbCommand cmd) {
  1259. return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterSize, cmd.GetType().Name));
  1260. }
  1261. static internal Exception PrepareParameterScale(IDbCommand cmd, string type) {
  1262. return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterScale, cmd.GetType().Name, type));
  1263. }
  1264. static internal Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) {
  1265. return InvalidOperation(Res.GetString(Res.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
  1266. }
  1267. //
  1268. // : ConnectionUtil
  1269. //
  1270. static internal Exception ConnectionIsDisabled (Exception InnerException) {
  1271. return InvalidOperation(Res.GetString(Res.ADP_ConnectionIsDisabled), InnerException);
  1272. }
  1273. static internal Exception ClosedConnectionError() {
  1274. return InvalidOperation(Res.GetString(Res.ADP_ClosedConnectionError));
  1275. }
  1276. static internal Exception ConnectionAlreadyOpen(ConnectionState state) {
  1277. return InvalidOperation(Res.GetString(Res.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
  1278. }
  1279. static internal Exception DelegatedTransactionPresent() {
  1280. return InvalidOperation(Res.GetString(Res.ADP_DelegatedTransactionPresent));
  1281. }
  1282. static internal Exception TransactionPresent() {
  1283. return InvalidOperation(Res.GetString(Res.ADP_TransactionPresent));
  1284. }
  1285. static internal Exception LocalTransactionPresent() {
  1286. return InvalidOperation(Res.GetString(Res.ADP_LocalTransactionPresent));
  1287. }
  1288. static internal Exception OpenConnectionPropertySet(string property, ConnectionState state) {
  1289. return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
  1290. }
  1291. static internal Exception EmptyDatabaseName() {
  1292. return Argument(Res.GetString(Res.ADP_EmptyDatabaseName));
  1293. }
  1294. static internal Exception DatabaseNameTooLong() {
  1295. return Argument(Res.GetString(Res.ADP_DatabaseNameTooLong));
  1296. }
  1297. internal enum ConnectionError {
  1298. BeginGetConnectionReturnsNull,
  1299. GetConnectionReturnsNull,
  1300. ConnectionOptionsMissing,
  1301. CouldNotSwitchToClosedPreviouslyOpenedState,
  1302. }
  1303. static internal Exception InternalConnectionError(ConnectionError internalError) {
  1304. return InvalidOperation(Res.GetString(Res.ADP_InternalConnectionError, (int)internalError));
  1305. }
  1306. internal enum InternalErrorCode {
  1307. UnpooledObjectHasOwner = 0,
  1308. UnpooledObjectHasWrongOwner = 1,
  1309. PushingObjectSecondTime = 2,
  1310. PooledObjectHasOwner = 3,
  1311. PooledObjectInPoolMoreThanOnce = 4,
  1312. CreateObjectReturnedNull = 5,
  1313. NewObjectCannotBePooled = 6,
  1314. NonPooledObjectUsedMoreThanOnce = 7,
  1315. AttemptingToPoolOnRestrictedToken = 8,
  1316. // ConnectionOptionsInUse = 9,
  1317. ConvertSidToStringSidWReturnedNull = 10,
  1318. // UnexpectedTransactedObject = 11,
  1319. AttemptingToConstructReferenceCollectionOnStaticObject = 12,
  1320. AttemptingToEnlistTwice = 13,
  1321. CreateReferenceCollectionReturnedNull = 14,
  1322. PooledObjectWithoutPool = 15,
  1323. UnexpectedWaitAnyResult = 16,
  1324. SynchronousConnectReturnedPending = 17,
  1325. CompletedConnectReturnedPending = 18,
  1326. NameValuePairNext = 20,
  1327. InvalidParserState1 = 21,
  1328. InvalidParserState2 = 22,
  1329. InvalidParserState3 = 23,
  1330. InvalidBuffer = 30,
  1331. UnimplementedSMIMethod = 40,
  1332. InvalidSmiCall = 41,
  1333. SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
  1334. SqlDependencyProcessDispatcherFailureCreateInstance = 51,
  1335. SqlDependencyProcessDispatcherFailureAppDomain = 52,
  1336. SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
  1337. UnknownTransactionFailure = 60,
  1338. }
  1339. static internal Exception InternalError(InternalErrorCode internalError) {
  1340. return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError));
  1341. }
  1342. static internal Exception InternalError(InternalErrorCode internalError, Exception innerException) {
  1343. return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError), innerException);
  1344. }
  1345. static internal Exception InvalidConnectTimeoutValue() {
  1346. return Argument(Res.GetString(Res.ADP_InvalidConnectTimeoutValue));
  1347. }
  1348. static internal Exception InvalidConnectRetryCountValue() {
  1349. return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryCountValue));
  1350. }
  1351. static internal Exception InvalidConnectRetryIntervalValue() {
  1352. return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryIntervalValue));
  1353. }
  1354. //
  1355. // : DbDataReader
  1356. //
  1357. static internal Exception DataReaderNoData() {
  1358. return InvalidOperation(Res.GetString(Res.ADP_DataReaderNoData));
  1359. }
  1360. static internal Exception DataReaderClosed(string method) {
  1361. return InvalidOperation(Res.GetString(Res.ADP_DataReaderClosed, method));
  1362. }
  1363. static internal ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) {
  1364. return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
  1365. }
  1366. static internal ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) {
  1367. return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
  1368. }
  1369. static internal IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) {
  1370. return IndexOutOfRange(Res.GetString(Res.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
  1371. }
  1372. static internal Exception InvalidDataLength(long length) {
  1373. return IndexOutOfRange(Res.GetString(Res.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
  1374. }
  1375. static internal InvalidOperationException AsyncOperationPending() {
  1376. return InvalidOperation(Res.GetString(Res.ADP_PendingAsyncOperation));
  1377. }
  1378. //
  1379. // : Stream
  1380. //
  1381. static internal Exception StreamClosed(string method) {
  1382. return InvalidOperation(Res.GetString(Res.ADP_StreamClosed, method));
  1383. }
  1384. static internal IOException ErrorReadingFromStream(Exception internalException) {
  1385. return IO(Res.GetString(Res.SqlMisc_StreamErrorMessage), internalException);
  1386. }
  1387. //
  1388. // : DbDataAdapter
  1389. //
  1390. static internal InvalidOperationException DynamicSQLJoinUnsupported() {
  1391. return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLJoinUnsupported));
  1392. }
  1393. static internal InvalidOperationException DynamicSQLNoTableInfo() {
  1394. return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoTableInfo));
  1395. }
  1396. static internal InvalidOperationException DynamicSQLNoKeyInfoDelete() {
  1397. return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoDelete));
  1398. }
  1399. static internal InvalidOperationException DynamicSQLNoKeyInfoUpdate() {
  1400. return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoUpdate));
  1401. }
  1402. static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionDelete() {
  1403. return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionDelete));
  1404. }
  1405. static internal InvalidOperationException DynamicSQLNoKeyInfoRowVersionUpdate() {
  1406. return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNoKeyInfoRowVersionUpdate));
  1407. }
  1408. static internal InvalidOperationException DynamicSQLNestedQuote(string name, string quote) {
  1409. return InvalidOperation(Res.GetString(Res.ADP_DynamicSQLNestedQuote, name, quote));
  1410. }
  1411. static internal InvalidOperationException NoQuoteChange() {
  1412. return InvalidOperation(Res.GetString(Res.ADP_NoQuoteChange));
  1413. }
  1414. static internal InvalidOperationException ComputerNameEx(int lastError) {
  1415. return InvalidOperation(Res.GetString(Res.ADP_ComputerNameEx, lastError));
  1416. }
  1417. static internal InvalidOperationException MissingSourceCommand() {
  1418. return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommand));
  1419. }
  1420. static internal InvalidOperationException MissingSourceCommandConnection() {
  1421. return InvalidOperation(Res.GetString(Res.ADP_MissingSourceCommandConnection));
  1422. }
  1423. //
  1424. // : IDataParameter
  1425. //
  1426. static internal ArgumentException InvalidDataType(TypeCode typecode) {
  1427. return Argument(Res.GetString(Res.ADP_InvalidDataType, typecode.ToString()));
  1428. }
  1429. static internal ArgumentException UnknownDataType(Type dataType) {
  1430. return Argument(Res.GetString(Res.ADP_UnknownDataType, dataType.FullName));
  1431. }
  1432. static internal ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype) {
  1433. return Argument(Res.GetString(Res.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
  1434. }
  1435. static internal ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) {
  1436. return Argument(Res.GetString(Res.ADP_UnknownDataTypeCode, ((int) typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
  1437. }
  1438. static internal ArgumentException InvalidOffsetValue(int value) {
  1439. return Argument(Res.GetString(Res.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
  1440. }
  1441. static internal ArgumentException InvalidSizeValue(int value) {
  1442. return Argument(Res.GetString(Res.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
  1443. }
  1444. static internal ArgumentException ParameterValueOutOfRange(Decimal value) {
  1445. return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
  1446. }
  1447. static internal ArgumentException ParameterValueOutOfRange(SqlDecimal value) {
  1448. return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString()));
  1449. }
  1450. static internal ArgumentException ParameterValueOutOfRange(String value) {
  1451. return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value));
  1452. }
  1453. static internal ArgumentException VersionDoesNotSupportDataType(string typeName) {
  1454. return Argument(Res.GetString(Res.ADP_VersionDoesNotSupportDataType, typeName));
  1455. }
  1456. static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner) { // WebData 75433
  1457. Debug.Assert(null != value, "null value on conversion failure");
  1458. Debug.Assert(null != inner, "null inner on conversion failure");
  1459. Exception e;
  1460. string message = Res.GetString(Res.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
  1461. if (inner is ArgumentException) {
  1462. e = new ArgumentException(message, inner);
  1463. }
  1464. else if (inner is FormatException) {
  1465. e = new FormatException(message, inner);
  1466. }
  1467. else if (inner is InvalidCastException) {
  1468. e = new InvalidCastException(message, inner);
  1469. }
  1470. else if (inner is OverflowException) {
  1471. e = new OverflowException(message, inner);
  1472. }
  1473. else {
  1474. e = inner;
  1475. }
  1476. TraceExceptionAsReturnValue(e);
  1477. return e;
  1478. }
  1479. //
  1480. // : IDataParameterCollection
  1481. //
  1482. static internal Exception ParametersMappingIndex(int index, IDataParameterCollection collection) {
  1483. return CollectionIndexInt32(index, collection.GetType(), collection.Count);
  1484. }
  1485. static internal Exception ParametersSourceIndex(string parameterName, IDataParameterCollection collection, Type parameterType) {
  1486. return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
  1487. }
  1488. static internal Exception ParameterNull(string parameter, IDataParameterCollection collection, Type parameterType) {
  1489. return CollectionNullValue(parameter, collection.GetType(), parameterType);
  1490. }
  1491. static internal Exception InvalidParameterType(IDataParameterCollection collection, Type parameterType, object invalidValue) {
  1492. return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
  1493. }
  1494. //
  1495. // : IDbTransaction
  1496. //
  1497. static internal Exception ParallelTransactionsNotSupported(IDbConnection obj) {
  1498. return InvalidOperation(Res.GetString(Res.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
  1499. }
  1500. static internal Exception TransactionZombied(IDbTransaction obj) {
  1501. return InvalidOperation(Res.GetString(Res.ADP_TransactionZombied, obj.GetType().Name));
  1502. }
  1503. static internal Exception DbRecordReadOnly(string methodname) {
  1504. return InvalidOperation(Res.GetString(Res.ADP_DbRecordReadOnly, methodname));
  1505. }
  1506. static internal Exception OffsetOutOfRangeException() {
  1507. return InvalidOperation(Res.GetString(Res.ADP_OffsetOutOfRangeException));
  1508. }
  1509. //
  1510. // : DbMetaDataFactory
  1511. //
  1512. static internal Exception AmbigousCollectionName(string collectionName) {
  1513. return Argument(Res.GetString(Res.MDF_AmbigousCollectionName,collectionName));
  1514. }
  1515. static internal Exception CollectionNameIsNotUnique(string collectionName) {
  1516. return Argument(Res.GetString(Res.MDF_CollectionNameISNotUnique,collectionName));
  1517. }
  1518. static internal Exception DataTableDoesNotExist(string collectionName) {
  1519. return Argument(Res.GetString(Res.MDF_DataTableDoesNotExist,collectionName));
  1520. }
  1521. static internal Exception IncorrectNumberOfDataSourceInformationRows() {
  1522. return Argument(Res.GetString(Res.MDF_IncorrectNumberOfDataSourceInformationRows));
  1523. }
  1524. static internal ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string restrictionValue) {
  1525. return ADP.Argument(Res.GetString(Res.MDF_InvalidRestrictionValue, collectionName, restrictionName, restrictionValue));
  1526. }
  1527. static internal Exception InvalidXml() {
  1528. return Argument(Res.GetString(Res.MDF_InvalidXml));
  1529. }
  1530. static internal Exception InvalidXmlMissingColumn(string collectionName, string columnName) {
  1531. return Argument(Res.GetString(Res.MDF_InvalidXmlMissingColumn, collectionName, columnName));
  1532. }
  1533. static internal Exception InvalidXmlInvalidValue(string collectionName, string columnName) {
  1534. return Argument(Res.GetString(Res.MDF_InvalidXmlInvalidValue, collectionName, columnName));
  1535. }
  1536. static internal Exception MissingDataSourceInformationColumn() {
  1537. return Argument(Res.GetString(Res.MDF_MissingDataSourceInformationColumn));
  1538. }
  1539. static internal Exception MissingRestrictionColumn() {
  1540. return Argument(Res.GetString(Res.MDF_MissingRestrictionColumn));
  1541. }
  1542. static internal Exception MissingRestrictionRow() {
  1543. return Argument(Res.GetString(Res.MDF_MissingRestrictionRow));
  1544. }
  1545. static internal Exception NoColumns() {
  1546. return Argument(Res.GetString(Res.MDF_NoColumns));
  1547. }
  1548. static internal Exception QueryFailed(string collectionName, Exception e) {
  1549. return InvalidOperation(Res.GetString(Res.MDF_QueryFailed,collectionName), e);
  1550. }
  1551. static internal Exception TooManyRestrictions(string collectionName) {
  1552. return Argument(Res.GetString(Res.MDF_TooManyRestrictions,collectionName));
  1553. }
  1554. static internal Exception UnableToBuildCollection(string collectionName) {
  1555. return Argument(Res.GetString(Res.MDF_UnableToBuildCollection,collectionName));
  1556. }
  1557. static internal Exception UndefinedCollection(string collectionName) {
  1558. return Argument(Res.GetString(Res.MDF_UndefinedCollection,collectionName));
  1559. }
  1560. static internal Exception UndefinedPopulationMechanism(string populationMechanism) {
  1561. return Argument(Res.GetString(Res.MDF_UndefinedPopulationMechanism,populationMechanism));
  1562. }
  1563. static internal Exception UnsupportedVersion(string collectionName) {
  1564. return Argument(Res.GetString(Res.MDF_UnsupportedVersion,collectionName));
  1565. }
  1566. //
  1567. // : CommandBuilder
  1568. //
  1569. static internal InvalidOperationException InvalidDateTimeDigits(string dataTypeName) {
  1570. return InvalidOperation(Res.GetString(Res.ADP_InvalidDateTimeDigits, dataTypeName));
  1571. }
  1572. static internal Exception InvalidFormatValue() {
  1573. return Argument(Res.GetString(Res.ADP_InvalidFormatValue));
  1574. }
  1575. static internal InvalidOperationException InvalidMaximumScale(string dataTypeName) {
  1576. return InvalidOperation(Res.GetString(Res.ADP_InvalidMaximumScale, dataTypeName));
  1577. }
  1578. static internal Exception LiteralValueIsInvalid(string dataTypeName){
  1579. return Argument(Res.GetString(Res.ADP_LiteralValueIsInvalid,dataTypeName));
  1580. }
  1581. static internal Exception EvenLengthLiteralValue(string argumentName) {
  1582. return Argument(Res.GetString(Res.ADP_EvenLengthLiteralValue), argumentName );
  1583. }
  1584. static internal Exception HexDigitLiteralValue(string argumentName) {
  1585. return Argument(Res.GetString(Res.ADP_HexDigitLiteralValue), argumentName );
  1586. }
  1587. static internal InvalidOperationException QuotePrefixNotSet(string method) {
  1588. return InvalidOperation(Res.GetString(Res.ADP_QuotePrefixNotSet, method));
  1589. }
  1590. static internal InvalidOperationException UnableToCreateBooleanLiteral() {
  1591. return ADP.InvalidOperation(Res.GetString(Res.ADP_UnableToCreateBooleanLiteral));
  1592. }
  1593. static internal Exception UnsupportedNativeDataTypeOleDb(string dataTypeName) {
  1594. return Argument(Res.GetString(Res.ADP_UnsupportedNativeDataTypeOleDb, dataTypeName));
  1595. }
  1596. // Sql Result Set and other generic message
  1597. static internal Exception InvalidArgumentValue(string methodName) {
  1598. return Argument(Res.GetString(Res.ADP_InvalidArgumentValue, methodName));
  1599. }
  1600. // global constant strings
  1601. internal const string Append = "Append";
  1602. internal const string BeginExecuteNonQuery = "BeginExecuteNonQuery";
  1603. internal const string BeginExecuteReader = "BeginExecuteReader";
  1604. internal const string BeginTransaction = "BeginTransaction";
  1605. internal const string BeginExecuteXmlReader = "BeginExecuteXmlReader";
  1606. internal const string ChangeDatabase = "ChangeDatabase";
  1607. internal const string Cancel = "Cancel";
  1608. internal const string Clone = "Clone";
  1609. internal const string ColumnEncryptionSystemProviderNamePrefix = "MSSQL_";
  1610. internal const string CommitTransaction = "CommitTransaction";
  1611. internal const string CommandTimeout = "CommandTimeout";
  1612. internal const string ConnectionString = "ConnectionString";
  1613. internal const string DataSetColumn = "DataSetColumn";
  1614. internal const string DataSetTable = "DataSetTable";
  1615. internal const string Delete = "Delete";
  1616. internal const string DeleteCommand = "DeleteCommand";
  1617. internal const string DeriveParameters = "DeriveParameters";
  1618. internal const string EndExecuteNonQuery = "EndExecuteNonQuery";
  1619. internal const string EndExecuteReader = "EndExecuteReader";
  1620. internal const string EndExecuteXmlReader = "EndExecuteXmlReader";
  1621. internal const string ExecuteReader = "ExecuteReader";
  1622. internal const string ExecuteRow = "ExecuteRow";
  1623. internal const string ExecuteNonQuery = "ExecuteNonQuery";
  1624. internal const string ExecuteScalar = "ExecuteScalar";
  1625. internal const string ExecuteSqlScalar = "ExecuteSqlScalar";
  1626. internal const string ExecuteXmlReader = "ExecuteXmlReader";
  1627. internal const string Fill = "Fill";
  1628. internal const string FillPage = "FillPage";
  1629. internal const string FillSchema = "FillSchema";
  1630. internal const string GetBytes = "GetBytes";
  1631. internal const string GetChars = "GetChars";
  1632. internal const string GetOleDbSchemaTable = "GetOleDbSchemaTable";
  1633. internal const string GetProperties = "GetProperties";
  1634. internal const string GetSchema = "GetSchema";
  1635. internal const string GetSchemaTable = "GetSchemaTable";
  1636. internal const string GetServerTransactionLevel = "GetServerTransactionLevel";
  1637. internal const string Insert = "Insert";
  1638. internal const string Open = "Open";
  1639. internal const string Parameter = "Parameter";
  1640. internal const string ParameterBuffer = "buffer";
  1641. internal const string ParameterCount = "count";
  1642. internal const string ParameterDestinationType = "destinationType";
  1643. internal const string ParameterIndex = "index";
  1644. internal const string ParameterName = "ParameterName";
  1645. internal const string ParameterOffset = "offset";
  1646. internal const string ParameterSetPosition = "set_Position";
  1647. internal const string ParameterService = "Service";
  1648. internal const string ParameterTimeout = "Timeout";
  1649. internal const string ParameterUserData = "UserData";
  1650. internal const string Prepare = "Prepare";
  1651. internal const string QuoteIdentifier = "QuoteIdentifier";
  1652. internal const string Read = "Read";
  1653. internal const string ReadAsync = "ReadAsync";
  1654. internal const string Remove = "Remove";
  1655. internal const string RollbackTransaction = "RollbackTransaction";
  1656. internal const string SaveTransaction = "SaveTransaction";
  1657. internal const string SetProperties = "SetProperties";
  1658. internal const string SourceColumn = "SourceColumn";
  1659. internal const string SourceVersion = "SourceVersion";
  1660. internal const string SourceTable = "SourceTable";
  1661. internal const string UnquoteIdentifier = "UnquoteIdentifier";
  1662. internal const string Update = "Update";
  1663. internal const string UpdateCommand = "UpdateCommand";
  1664. internal const string UpdateRows = "UpdateRows";
  1665. internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
  1666. internal const int DecimalMaxPrecision = 29;
  1667. internal const int DecimalMaxPrecision28 = 28; // there are some cases in Odbc where we need that ...
  1668. internal const int DefaultCommandTimeout = 30;
  1669. internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
  1670. internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections
  1671. internal const float FailoverTimeoutStepForTnir = 0.125F; // Fraction of timeout to use in case of Transparent Network IP resolution.
  1672. internal const int MinimumTimeoutForTnirMs = 500; // The first login attempt in Transparent network IP Resolution
  1673. // security issue, don't rely upon static public readonly values - AS/URT 109635
  1674. static internal readonly String StrEmpty = ""; // String.Empty
  1675. static internal readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero
  1676. static internal readonly int PtrSize = IntPtr.Size;
  1677. static internal readonly IntPtr InvalidPtr = new IntPtr(-1); // use for INVALID_HANDLE
  1678. static internal readonly IntPtr RecordsUnaffected = new IntPtr(-1);
  1679. static internal readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  1680. internal const int CharSize = System.Text.UnicodeEncoding.CharSize;
  1681. static internal bool CompareInsensitiveInvariant(string strvalue, string strconst) {
  1682. return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase));
  1683. }
  1684. static internal Delegate FindBuilder(MulticastDelegate mcd) { // V1.2.3300
  1685. if (null != mcd) {
  1686. Delegate[] d = mcd.GetInvocationList();
  1687. for (int i = 0; i < d.Length; i++) {
  1688. if (d[i].Target is DbCommandBuilder)
  1689. return d[i];
  1690. }
  1691. }
  1692. return null;
  1693. }
  1694. static internal readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform);
  1695. static internal readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5));
  1696. static internal SysTx.Transaction GetCurrentTransaction() {
  1697. SysTx.Transaction transaction = SysTx.Transaction.Current;
  1698. return transaction;
  1699. }
  1700. static internal void SetCurrentTransaction(SysTx.Transaction transaction)
  1701. {
  1702. SysTx.Transaction.Current = transaction;
  1703. }
  1704. static internal SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction){
  1705. SysTx.IDtcTransaction oleTxTransaction = null;
  1706. if (null != transaction) {
  1707. oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction);
  1708. }
  1709. return oleTxTransaction;
  1710. }
  1711. [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
  1712. static internal bool IsSysTxEqualSysEsTransaction() {
  1713. #if MOBILE
  1714. return false;
  1715. #else
  1716. // This Method won't JIT inproc (ES isn't available), so we code it
  1717. // separately and call it behind an if statement.
  1718. bool result = (!SysES.ContextUtil.IsInTransaction && null == SysTx.Transaction.Current)
  1719. || (SysES.ContextUtil.IsInTransaction && SysTx.Transaction.Current == (SysTx.Transaction)SysES.ContextUtil.SystemTransaction);
  1720. return result;
  1721. #endif
  1722. }
  1723. static internal bool NeedManualEnlistment() {
  1724. #if !MOBILE && !MONO_PARTIAL_DATA_IMPORT
  1725. // We need to force a manual enlistment of transactions for ODBC and
  1726. // OLEDB whenever the current SysTx transaction != the SysTx transaction
  1727. // on the EnterpriseServices ContextUtil, or when ES.ContextUtil is
  1728. // not available and there is a non-null current SysTx transaction.
  1729. if (IsWindowsNT) { // we can reference SysTx just not use it on Win9X, we can't ever reference SysES on Win9X
  1730. bool isEnterpriseServicesOK = !InOutOfProcHelper.InProc;
  1731. if ((isEnterpriseServicesOK && !IsSysTxEqualSysEsTransaction())
  1732. || (!isEnterpriseServicesOK && null != SysTx.Transaction.Current)) {
  1733. return true;
  1734. }
  1735. }
  1736. #endif
  1737. return false;
  1738. }
  1739. static internal void TimerCurrent(out long ticks) {
  1740. ticks = DateTime.UtcNow.ToFileTimeUtc();
  1741. }
  1742. static internal long TimerCurrent() {
  1743. return DateTime.UtcNow.ToFileTimeUtc();
  1744. }
  1745. static internal long TimerFromSeconds(int seconds) {
  1746. long result = checked((long)seconds * TimeSpan.TicksPerSecond);
  1747. return result;
  1748. }
  1749. static internal long TimerFromMilliseconds(long milliseconds) {
  1750. long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
  1751. return result;
  1752. }
  1753. static internal bool TimerHasExpired(long timerExpire) {
  1754. bool result = TimerCurrent() > timerExpire;
  1755. return result;
  1756. }
  1757. static internal long TimerRemaining(long timerExpire) {
  1758. long timerNow = TimerCurrent();
  1759. long result = checked(timerExpire - timerNow);
  1760. return result;
  1761. }
  1762. static internal long TimerRemainingMilliseconds(long timerExpire) {
  1763. long result = TimerToMilliseconds(TimerRemaining(timerExpire));
  1764. return result;
  1765. }
  1766. static internal long TimerRemainingSeconds(long timerExpire) {
  1767. long result = TimerToSeconds(TimerRemaining(timerExpire));
  1768. return result;
  1769. }
  1770. static internal long TimerToMilliseconds(long timerValue) {
  1771. long result = timerValue / TimeSpan.TicksPerMillisecond;
  1772. return result;
  1773. }
  1774. static private long TimerToSeconds(long timerValue) {
  1775. long result = timerValue / TimeSpan.TicksPerSecond;
  1776. return result;
  1777. }
  1778. [EnvironmentPermission(SecurityAction.Assert, Read = "COMPUTERNAME")]
  1779. static internal string MachineName()
  1780. {
  1781. // Note: In Longhorn you'll be able to rename a machine without
  1782. // rebooting. Therefore, don't cache this machine name.
  1783. return Environment.MachineName;
  1784. }
  1785. static internal string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) {
  1786. StringBuilder resultString = new StringBuilder();
  1787. if (ADP.IsEmpty(quotePrefix) == false) {
  1788. resultString.Append(quotePrefix);
  1789. }
  1790. // Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
  1791. if (ADP.IsEmpty(quoteSuffix) == false) {
  1792. resultString.Append(unQuotedString.Replace(quoteSuffix,quoteSuffix+quoteSuffix));
  1793. resultString.Append(quoteSuffix);
  1794. }
  1795. else {
  1796. resultString.Append(unQuotedString);
  1797. }
  1798. return resultString.ToString();
  1799. }
  1800. private const string hexDigits = "0123456789abcdef";
  1801. static internal byte[] ByteArrayFromString(string hexString, string dataTypeName) {
  1802. if ((hexString.Length & 0x1) != 0) {
  1803. throw ADP.LiteralValueIsInvalid(dataTypeName);
  1804. }
  1805. char[] c = hexString.ToCharArray();
  1806. byte[] b = new byte[hexString.Length / 2];
  1807. CultureInfo invariant = CultureInfo.InvariantCulture;
  1808. for (int i = 0; i < hexString.Length; i += 2) {
  1809. int h = hexDigits.IndexOf(Char.ToLower(c[i], invariant));
  1810. int l = hexDigits.IndexOf(Char.ToLower(c[i+1], invariant));
  1811. if (h < 0 || l < 0) {
  1812. throw ADP.LiteralValueIsInvalid(dataTypeName);
  1813. }
  1814. b[i/2] = (byte)((h << 4) | l);
  1815. }
  1816. return b;
  1817. }
  1818. static internal void EscapeSpecialCharacters(string unescapedString, StringBuilder escapedString){
  1819. // note special characters list is from character escapes
  1820. // in the MSDN regular expression language elements documentation
  1821. // added ] since escaping it seems necessary
  1822. const string specialCharacters = ".$^{[(|)*+?\\]";
  1823. foreach (char currentChar in unescapedString){
  1824. if (specialCharacters.IndexOf(currentChar) >= 0) {
  1825. escapedString.Append("\\");
  1826. }
  1827. escapedString.Append(currentChar);
  1828. }
  1829. return;
  1830. }
  1831. static internal string FixUpDecimalSeparator(string numericString,
  1832. Boolean formatLiteral,
  1833. string decimalSeparator,
  1834. char[] exponentSymbols) {
  1835. String returnString;
  1836. // don't replace the decimal separator if the string is in exponent format
  1837. if (numericString.IndexOfAny(exponentSymbols) == -1){
  1838. // if the user has set a decimal separator use it, if not use the current culture's value
  1839. if (ADP.IsEmpty(decimalSeparator) == true) {
  1840. decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
  1841. }
  1842. if (formatLiteral == true){
  1843. returnString = numericString.Replace(".",decimalSeparator);
  1844. }
  1845. else {
  1846. returnString = numericString.Replace(decimalSeparator,".");
  1847. }
  1848. }
  1849. else {
  1850. returnString = numericString;
  1851. }
  1852. return returnString;
  1853. }
  1854. [FileIOPermission(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery)]
  1855. [ResourceExposure(ResourceScope.Machine)]
  1856. [ResourceConsumption(ResourceScope.Machine)]
  1857. static internal string GetFullPath(string filename) { // MDAC 77686
  1858. return Path.GetFullPath(filename);
  1859. }
  1860. //
  1861. static internal string GetComputerNameDnsFullyQualified() {
  1862. const int ComputerNameDnsFullyQualified = 3; // winbase.h, enum COMPUTER_NAME_FORMAT
  1863. const int ERROR_MORE_DATA = 234; // winerror.h
  1864. string value;
  1865. #if MOBILE
  1866. value = ADP.MachineName();
  1867. #else
  1868. if (IsPlatformNT5) {
  1869. int length = 0; // length parameter must be zero if buffer is null
  1870. // query for the required length
  1871. // VSTFDEVDIV 479551 - ensure that GetComputerNameEx does not fail with unexpected values and that the length is positive
  1872. int getComputerNameExError = 0;
  1873. if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, null, ref length)) {
  1874. getComputerNameExError = Marshal.GetLastWin32Error();
  1875. }
  1876. if ((getComputerNameExError != 0 && getComputerNameExError != ERROR_MORE_DATA) || length <= 0) {
  1877. throw ADP.ComputerNameEx(getComputerNameExError);
  1878. }
  1879. StringBuilder buffer = new StringBuilder(length);
  1880. length = buffer.Capacity;
  1881. if (0 == SafeNativeMethods.GetComputerNameEx(ComputerNameDnsFullyQualified, buffer, ref length)) {
  1882. throw ADP.ComputerNameEx(Marshal.GetLastWin32Error());
  1883. }
  1884. // Note: In Longhorn you'll be able to rename a machine without
  1885. // rebooting. Therefore, don't cache this machine name.
  1886. value = buffer.ToString();
  1887. }
  1888. else {
  1889. value = ADP.MachineName();
  1890. }
  1891. #endif
  1892. return value;
  1893. }
  1894. // SxS: the file is opened in FileShare.Read mode allowing several threads/apps to read it simultaneously
  1895. [ResourceExposure(ResourceScope.Machine)]
  1896. [ResourceConsumption(ResourceScope.Machine)]
  1897. static internal Stream GetFileStream(string filename) {
  1898. #if MONO_FEATURE_CAS
  1899. (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert();
  1900. try {
  1901. return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
  1902. }
  1903. finally {
  1904. FileIOPermission.RevertAssert();
  1905. }
  1906. #else
  1907. return new FileStream(filename,FileMode.Open,FileAccess.Read,FileShare.Read);
  1908. #endif
  1909. }
  1910. [ResourceExposure(ResourceScope.Machine)]
  1911. [ResourceConsumption(ResourceScope.Machine)]
  1912. static internal FileVersionInfo GetVersionInfo(string filename) {
  1913. #if MONO_FEATURE_CAS
  1914. (new FileIOPermission(FileIOPermissionAccess.Read, filename)).Assert(); // MDAC 62038
  1915. try {
  1916. return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
  1917. }
  1918. finally {
  1919. FileIOPermission.RevertAssert();
  1920. }
  1921. #else
  1922. return FileVersionInfo.GetVersionInfo(filename); // MDAC 60411
  1923. #endif
  1924. }
  1925. #if MOBILE
  1926. static internal object LocalMachineRegistryValue(string subkey, string queryvalue) {
  1927. return null;
  1928. }
  1929. #else
  1930. [ResourceExposure(ResourceScope.Machine)]
  1931. [ResourceConsumption(ResourceScope.Machine)]
  1932. static internal Stream GetXmlStreamFromValues(String[] values, String errorString) {
  1933. if (values.Length != 1){
  1934. throw ADP.ConfigWrongNumberOfValues(errorString);
  1935. }
  1936. return ADP.GetXmlStream(values[0],errorString);
  1937. }
  1938. // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
  1939. // this operation is safe in SxS because the file is opened in read-only mode and each NDP runtime accesses its own copy of the metadata
  1940. // under the runtime folder.
  1941. // This method returns stream to open file, so its ResourceExposure value is ResourceScope.Machine.
  1942. [ResourceExposure(ResourceScope.Machine)]
  1943. [ResourceConsumption(ResourceScope.Machine)]
  1944. static internal Stream GetXmlStream(String value, String errorString) {
  1945. Stream XmlStream;
  1946. const string config = "config\\";
  1947. // get location of config directory
  1948. string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
  1949. if (rootPath == null) {
  1950. throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
  1951. }
  1952. StringBuilder tempstring = new StringBuilder(rootPath.Length+config.Length+value.Length);
  1953. tempstring.Append(rootPath);
  1954. tempstring.Append(config);
  1955. tempstring.Append(value);
  1956. String fullPath = tempstring.ToString();
  1957. // don't allow relative paths
  1958. if (ADP.GetFullPath(fullPath) != fullPath) {
  1959. throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
  1960. }
  1961. try {
  1962. XmlStream = ADP.GetFileStream(fullPath);
  1963. }
  1964. catch(Exception e){
  1965. //
  1966. if (!ADP.IsCatchableExceptionType(e)) {
  1967. throw;
  1968. }
  1969. throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
  1970. }
  1971. return XmlStream;
  1972. }
  1973. [ResourceExposure(ResourceScope.Machine)]
  1974. [ResourceConsumption(ResourceScope.Machine)]
  1975. static internal object ClassesRootRegistryValue(string subkey, string queryvalue) { // MDAC 77697
  1976. (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_CLASSES_ROOT\\" + subkey)).Assert(); // MDAC 62028
  1977. try {
  1978. using(RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false)) {
  1979. return ((null != key) ? key.GetValue(queryvalue) : null);
  1980. }
  1981. }
  1982. catch(SecurityException e) {
  1983. // Even though we assert permission - it's possible there are
  1984. // ACL's on registry that cause SecurityException to be thrown.
  1985. ADP.TraceExceptionWithoutRethrow(e);
  1986. return null;
  1987. }
  1988. finally {
  1989. RegistryPermission.RevertAssert();
  1990. }
  1991. }
  1992. [ResourceExposure(ResourceScope.Machine)]
  1993. [ResourceConsumption(ResourceScope.Machine)]
  1994. static internal object LocalMachineRegistryValue(string subkey, string queryvalue) { // MDAC 77697
  1995. (new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\" + subkey)).Assert(); // MDAC 62028
  1996. try {
  1997. using(RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false)) {
  1998. return ((null != key) ? key.GetValue(queryvalue) : null);
  1999. }
  2000. }
  2001. catch(SecurityException e) {
  2002. // Even though we assert permission - it's possible there are
  2003. // ACL's on registry that cause SecurityException to be thrown.
  2004. ADP.TraceExceptionWithoutRethrow(e);
  2005. return null;
  2006. }
  2007. finally {
  2008. RegistryPermission.RevertAssert();
  2009. }
  2010. }
  2011. // SxS: although this method uses registry, it does not expose anything out
  2012. [ResourceExposure(ResourceScope.None)]
  2013. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  2014. static internal void CheckVersionMDAC(bool ifodbcelseoledb) {
  2015. // we don't have that version info on the registry implementation, so it won't work.
  2016. if (Environment.OSVersion.Platform == PlatformID.Unix)
  2017. return;
  2018. int major, minor, build;
  2019. string version;
  2020. try {
  2021. version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer");
  2022. if (ADP.IsEmpty(version)) {
  2023. string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, ADP.StrEmpty);
  2024. FileVersionInfo versionInfo = ADP.GetVersionInfo(filename); // MDAC 60411
  2025. major = versionInfo.FileMajorPart;
  2026. minor = versionInfo.FileMinorPart;
  2027. build = versionInfo.FileBuildPart;
  2028. version = versionInfo.FileVersion;
  2029. }
  2030. else {
  2031. string[] parts = version.Split('.');
  2032. major = Int32.Parse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture);
  2033. minor = Int32.Parse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture);
  2034. build = Int32.Parse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture);
  2035. Int32.Parse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture);
  2036. }
  2037. }
  2038. catch(Exception e) {
  2039. //
  2040. if (!ADP.IsCatchableExceptionType(e)) {
  2041. throw;
  2042. }
  2043. throw System.Data.OleDb.ODB.MDACNotAvailable(e);
  2044. }
  2045. // disallow any MDAC version before MDAC 2.6 rtm
  2046. // include MDAC 2.51 that ships with Win2k
  2047. if ((major < 2) || ((major == 2) && ((minor < 60) || ((minor == 60) && (build < 6526))))) { // MDAC 66628
  2048. if (ifodbcelseoledb) {
  2049. throw ADP.DataAdapter(Res.GetString(Res.Odbc_MDACWrongVersion, version));
  2050. }
  2051. else {
  2052. throw ADP.DataAdapter(Res.GetString(Res.OleDb_MDACWrongVersion, version));
  2053. }
  2054. }
  2055. }
  2056. #endif
  2057. // the return value is true if the string was quoted and false if it was not
  2058. // this allows the caller to determine if it is an error or not for the quotedString to not be quoted
  2059. static internal Boolean RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) {
  2060. int prefixLength;
  2061. if (quotePrefix == null){
  2062. prefixLength = 0;
  2063. }
  2064. else {
  2065. prefixLength = quotePrefix.Length;
  2066. }
  2067. int suffixLength;
  2068. if (quoteSuffix == null){
  2069. suffixLength = 0;
  2070. }
  2071. else{
  2072. suffixLength = quoteSuffix.Length;
  2073. }
  2074. if ((suffixLength + prefixLength) == 0) {
  2075. unquotedString = quotedString;
  2076. return true;
  2077. }
  2078. if (quotedString == null){
  2079. unquotedString = quotedString;
  2080. return false;
  2081. }
  2082. int quotedStringLength = quotedString.Length;
  2083. // is the source string too short to be quoted
  2084. if (quotedStringLength < prefixLength + suffixLength){
  2085. unquotedString = quotedString;
  2086. return false;
  2087. }
  2088. // is the prefix present?
  2089. if ( prefixLength > 0) {
  2090. if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false){
  2091. unquotedString = quotedString;
  2092. return false;
  2093. }
  2094. }
  2095. // is the suffix present?
  2096. if ( suffixLength > 0) {
  2097. if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false){
  2098. unquotedString = quotedString;
  2099. return false;
  2100. }
  2101. unquotedString = quotedString.Substring(prefixLength,quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix+quoteSuffix,quoteSuffix);
  2102. }
  2103. else {
  2104. unquotedString = quotedString.Substring(prefixLength,quotedStringLength - prefixLength);
  2105. }
  2106. return true;
  2107. }
  2108. static internal DataRow[] SelectAdapterRows(DataTable dataTable, bool sorted) {
  2109. const DataRowState rowStates = DataRowState.Added | DataRowState.Deleted | DataRowState.Modified;
  2110. // equivalent to but faster than 'return dataTable.Select("", "", rowStates);'
  2111. int countAdded = 0, countDeleted = 0, countModifed = 0;
  2112. DataRowCollection rowCollection = dataTable.Rows;
  2113. foreach(DataRow dataRow in rowCollection) {
  2114. switch(dataRow.RowState) {
  2115. case DataRowState.Added:
  2116. countAdded++;
  2117. break;
  2118. case DataRowState.Deleted:
  2119. countDeleted++;
  2120. break;
  2121. case DataRowState.Modified:
  2122. countModifed++;
  2123. break;
  2124. default:
  2125. Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
  2126. break;
  2127. }
  2128. }
  2129. DataRow[] dataRows = new DataRow[countAdded + countDeleted + countModifed];
  2130. if(sorted) {
  2131. countModifed = countAdded + countDeleted;
  2132. countDeleted = countAdded;
  2133. countAdded = 0;
  2134. foreach(DataRow dataRow in rowCollection) {
  2135. switch(dataRow.RowState) {
  2136. case DataRowState.Added:
  2137. dataRows[countAdded++] = dataRow;
  2138. break;
  2139. case DataRowState.Deleted:
  2140. dataRows[countDeleted++] = dataRow;
  2141. break;
  2142. case DataRowState.Modified:
  2143. dataRows[countModifed++] = dataRow;
  2144. break;
  2145. default:
  2146. Debug.Assert(0 == (rowStates & dataRow.RowState), "flagged RowState");
  2147. break;
  2148. }
  2149. }
  2150. }
  2151. else {
  2152. int index = 0;
  2153. foreach(DataRow dataRow in rowCollection) {
  2154. if (0 != (dataRow.RowState & rowStates)) {
  2155. dataRows[index++] = dataRow;
  2156. if (index == dataRows.Length) {
  2157. break;
  2158. }
  2159. }
  2160. }
  2161. }
  2162. return dataRows;
  2163. }
  2164. internal static int StringLength(string inputString) {
  2165. return ((null != inputString) ? inputString.Length : 0);
  2166. }
  2167. // { "a", "a", "a" } -> { "a", "a1", "a2" }
  2168. // { "a", "a", "a1" } -> { "a", "a2", "a1" }
  2169. // { "a", "A", "a" } -> { "a", "A1", "a2" }
  2170. // { "a", "A", "a1" } -> { "a", "A2", "a1" } // MDAC 66718
  2171. static internal void BuildSchemaTableInfoTableNames(string[] columnNameArray) {
  2172. Dictionary<string,int> hash = new Dictionary<string,int>(columnNameArray.Length);
  2173. int startIndex = columnNameArray.Length; // lowest non-unique index
  2174. for (int i = columnNameArray.Length - 1; 0 <= i; --i) {
  2175. string columnName = columnNameArray[i];
  2176. if ((null != columnName) && (0 < columnName.Length)) {
  2177. columnName = columnName.ToLower(CultureInfo.InvariantCulture);
  2178. int index;
  2179. if (hash.TryGetValue(columnName, out index)) {
  2180. startIndex = Math.Min(startIndex, index);
  2181. }
  2182. hash[columnName] = i;
  2183. }
  2184. else {
  2185. columnNameArray[i] = ADP.StrEmpty; // MDAC 66681
  2186. startIndex = i;
  2187. }
  2188. }
  2189. int uniqueIndex = 1;
  2190. for (int i = startIndex; i < columnNameArray.Length; ++i) {
  2191. string columnName = columnNameArray[i];
  2192. if (0 == columnName.Length) { // generate a unique name
  2193. columnNameArray[i] = "Column";
  2194. uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
  2195. }
  2196. else {
  2197. columnName = columnName.ToLower(CultureInfo.InvariantCulture);
  2198. if (i != hash[columnName]) {
  2199. GenerateUniqueName(hash, ref columnNameArray[i], i, 1); // MDAC 66718
  2200. }
  2201. }
  2202. }
  2203. }
  2204. static private int GenerateUniqueName(Dictionary<string,int> hash, ref string columnName, int index, int uniqueIndex) {
  2205. for (;; ++uniqueIndex) {
  2206. string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
  2207. string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); // MDAC 66978
  2208. if (!hash.ContainsKey(lowerName)) {
  2209. columnName = uniqueName;
  2210. hash.Add(lowerName, index);
  2211. break;
  2212. }
  2213. }
  2214. return uniqueIndex;
  2215. }
  2216. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  2217. static internal IntPtr IntPtrOffset(IntPtr pbase, Int32 offset) {
  2218. if (4 == ADP.PtrSize) {
  2219. return (IntPtr) checked(pbase.ToInt32() + offset);
  2220. }
  2221. Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size"); // MDAC 73747
  2222. return (IntPtr) checked(pbase.ToInt64() + offset);
  2223. }
  2224. static internal int IntPtrToInt32(IntPtr value) {
  2225. if (4 == ADP.PtrSize) {
  2226. return (int)value;
  2227. }
  2228. else {
  2229. long lval = (long)value;
  2230. lval = Math.Min((long)Int32.MaxValue, lval);
  2231. lval = Math.Max((long)Int32.MinValue, lval);
  2232. return (int)lval;
  2233. }
  2234. }
  2235. //
  2236. static internal int SrcCompare(string strA, string strB) { // this is null safe
  2237. return ((strA == strB) ? 0 : 1);
  2238. }
  2239. static internal int DstCompare(string strA, string strB) { // this is null safe
  2240. return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions);
  2241. }
  2242. static internal bool IsDirection(IDataParameter value, ParameterDirection condition) {
  2243. #if DEBUG
  2244. IsDirectionValid(condition);
  2245. #endif
  2246. return (condition == (condition & value.Direction));
  2247. }
  2248. #if DEBUG
  2249. static private void IsDirectionValid(ParameterDirection value) {
  2250. switch (value) { // @perfnote: Enum.IsDefined
  2251. case ParameterDirection.Input:
  2252. case ParameterDirection.Output:
  2253. case ParameterDirection.InputOutput:
  2254. case ParameterDirection.ReturnValue:
  2255. break;
  2256. default:
  2257. throw ADP.InvalidParameterDirection(value);
  2258. }
  2259. }
  2260. #endif
  2261. static internal bool IsEmpty(string str) {
  2262. return ((null == str) || (0 == str.Length));
  2263. }
  2264. static internal bool IsEmptyArray(string[] array) {
  2265. return ((null == array) || (0 == array.Length));
  2266. }
  2267. static internal bool IsNull(object value) {
  2268. if ((null == value) || (DBNull.Value == value)) {
  2269. return true;
  2270. }
  2271. INullable nullable = (value as INullable);
  2272. return ((null != nullable) && nullable.IsNull);
  2273. }
  2274. static internal void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) {
  2275. if ((value == null) || (value == DBNull.Value)) {
  2276. isNull = true;
  2277. isSqlType = false;
  2278. }
  2279. else {
  2280. INullable nullable = (value as INullable);
  2281. if (nullable != null) {
  2282. isNull = nullable.IsNull;
  2283. isSqlType = DataStorage.IsSqlType(value.GetType());
  2284. }
  2285. else {
  2286. isNull = false;
  2287. isSqlType = false;
  2288. }
  2289. }
  2290. }
  2291. private static Version _systemDataVersion;
  2292. static internal Version GetAssemblyVersion() {
  2293. // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
  2294. if (_systemDataVersion == null) {
  2295. _systemDataVersion = new Version(ThisAssembly.InformationalVersion);
  2296. }
  2297. return _systemDataVersion;
  2298. }
  2299. static internal readonly string[] AzureSqlServerEndpoints = {Res.GetString(Res.AZURESQL_GenericEndpoint),
  2300. Res.GetString(Res.AZURESQL_GermanEndpoint),
  2301. Res.GetString(Res.AZURESQL_UsGovEndpoint),
  2302. Res.GetString(Res.AZURESQL_ChinaEndpoint)};
  2303. // This method assumes dataSource parameter is in TCP connection string format.
  2304. static internal bool IsAzureSqlServerEndpoint(string dataSource)
  2305. {
  2306. // remove server port
  2307. int i = dataSource.LastIndexOf(',');
  2308. if (i >= 0)
  2309. {
  2310. dataSource = dataSource.Substring(0, i);
  2311. }
  2312. // check for the instance name
  2313. i = dataSource.LastIndexOf('\\');
  2314. if (i >= 0)
  2315. {
  2316. dataSource = dataSource.Substring(0, i);
  2317. }
  2318. // trim redundant whitespaces
  2319. dataSource = dataSource.Trim();
  2320. // check if servername end with any azure endpoints
  2321. for (i = 0; i < AzureSqlServerEndpoints.Length; i++)
  2322. {
  2323. if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase))
  2324. {
  2325. return true;
  2326. }
  2327. }
  2328. return false;
  2329. }
  2330. }
  2331. }