AdapterUtil.cs 116 KB

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