SqlConnection.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  1. //
  2. // System.Data.SqlClient.SqlConnection.cs
  3. //
  4. // Authors:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. // Tim Coleman ([email protected])
  8. // Phillip Jerkins ([email protected])
  9. // Diego Caravana ([email protected])
  10. //
  11. // Copyright (C) Ximian, Inc 2002
  12. // Copyright (C) Daniel Morgan 2002, 2003
  13. // Copyright (C) Tim Coleman, 2002, 2003
  14. // Copyright (C) Phillip Jerkins, 2003
  15. //
  16. //
  17. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  18. //
  19. // Permission is hereby granted, free of charge, to any person obtaining
  20. // a copy of this software and associated documentation files (the
  21. // "Software"), to deal in the Software without restriction, including
  22. // without limitation the rights to use, copy, modify, merge, publish,
  23. // distribute, sublicense, and/or sell copies of the Software, and to
  24. // permit persons to whom the Software is furnished to do so, subject to
  25. // the following conditions:
  26. //
  27. // The above copyright notice and this permission notice shall be
  28. // included in all copies or substantial portions of the Software.
  29. //
  30. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  31. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  33. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  34. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  35. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  36. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  37. //
  38. using Mono.Data.Tds;
  39. using Mono.Data.Tds.Protocol;
  40. using System;
  41. using System.Collections;
  42. using System.Collections.Specialized;
  43. using System.ComponentModel;
  44. using System.Data;
  45. using System.Data.Common;
  46. using System.EnterpriseServices;
  47. using System.Globalization;
  48. using System.Net;
  49. using System.Net.Sockets;
  50. using System.Text;
  51. using System.Xml;
  52. namespace System.Data.SqlClient {
  53. [DefaultEvent ("InfoMessage")]
  54. #if NET_2_0
  55. public sealed class SqlConnection : DbConnection, IDbConnection, ICloneable
  56. #else
  57. public sealed class SqlConnection : Component, IDbConnection, ICloneable
  58. #endif // NET_2_0
  59. {
  60. #region Fields
  61. bool disposed = false;
  62. // The set of SQL connection pools
  63. static TdsConnectionPoolManager sqlConnectionPools = new TdsConnectionPoolManager (TdsVersion.tds70);
  64. // The current connection pool
  65. TdsConnectionPool pool;
  66. // The connection string that identifies this connection
  67. string connectionString = null;
  68. // The transaction object for the current transaction
  69. SqlTransaction transaction = null;
  70. // Connection parameters
  71. TdsConnectionParameters parms = new TdsConnectionParameters ();
  72. NameValueCollection connStringParameters = null;
  73. bool connectionReset;
  74. bool pooling;
  75. string dataSource;
  76. int connectionTimeout;
  77. int minPoolSize;
  78. int maxPoolSize;
  79. int packetSize;
  80. int port = 1433;
  81. bool fireInfoMessageEventOnUserErrors;
  82. bool statisticsEnabled;
  83. // The current state
  84. ConnectionState state = ConnectionState.Closed;
  85. SqlDataReader dataReader = null;
  86. XmlReader xmlReader = null;
  87. // The TDS object
  88. ITds tds;
  89. #endregion // Fields
  90. #region Constructors
  91. public SqlConnection ()
  92. : this (String.Empty)
  93. {
  94. }
  95. public SqlConnection (string connectionString)
  96. {
  97. Init (connectionString);
  98. }
  99. private void Init (string connectionString)
  100. {
  101. connectionTimeout = 15; // default timeout
  102. dataSource = ""; // default datasource
  103. packetSize = 8192; // default packetsize
  104. ConnectionString = connectionString;
  105. }
  106. #endregion // Constructors
  107. #region Properties
  108. #if NET_1_0 || ONLY_1_1
  109. [DataSysDescription ("Information used to connect to a DataSource, such as 'Data Source=x;Initial Catalog=x;Integrated Security=SSPI'.")]
  110. #endif
  111. [DefaultValue ("")]
  112. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  113. [RecommendedAsConfigurable (true)]
  114. [RefreshProperties (RefreshProperties.All)]
  115. [MonoTODO("persist security info, encrypt, enlist keyword not implemented")]
  116. public
  117. #if NET_2_0
  118. override
  119. #endif // NET_2_0
  120. string ConnectionString {
  121. get { return connectionString; }
  122. set {
  123. if (state == ConnectionState.Open)
  124. throw new InvalidOperationException ("Not Allowed to change ConnectionString property while Connection state is OPEN");
  125. SetConnectionString (value);
  126. }
  127. }
  128. #if !NET_2_0
  129. [DataSysDescription ("Current connection timeout value, 'Connect Timeout=X' in the ConnectionString.")]
  130. #endif
  131. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  132. public
  133. #if NET_2_0
  134. override
  135. #endif // NET_2_0
  136. int ConnectionTimeout {
  137. get { return connectionTimeout; }
  138. }
  139. #if !NET_2_0
  140. [DataSysDescription ("Current SQL Server database, 'Initial Catalog=X' in the connection string.")]
  141. #endif
  142. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  143. public
  144. #if NET_2_0
  145. override
  146. #endif // NET_2_0
  147. string Database {
  148. get {
  149. if (State == ConnectionState.Open)
  150. return tds.Database;
  151. return parms.Database ;
  152. }
  153. }
  154. internal SqlDataReader DataReader {
  155. get { return dataReader; }
  156. set { dataReader = value; }
  157. }
  158. #if !NET_2_0
  159. [DataSysDescription ("Current SqlServer that the connection is opened to, 'Data Source=X' in the connection string. ")]
  160. #else
  161. [Browsable(true)]
  162. #endif
  163. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  164. public
  165. #if NET_2_0
  166. override
  167. #endif // NET_2_0
  168. string DataSource {
  169. get { return dataSource; }
  170. }
  171. #if !NET_2_0
  172. [DataSysDescription ("Network packet size, 'Packet Size=x' in the connection string.")]
  173. #endif
  174. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  175. public int PacketSize {
  176. get {
  177. if (State == ConnectionState.Open)
  178. return ((Tds)tds).PacketSize ;
  179. return packetSize;
  180. }
  181. }
  182. [Browsable (false)]
  183. #if !NET_2_0
  184. [DataSysDescription ("Version of the SQL Server accessed by the SqlConnection.")]
  185. #endif
  186. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  187. public
  188. #if NET_2_0
  189. override
  190. #endif // NET_2_0
  191. string ServerVersion {
  192. get {
  193. if (state == ConnectionState.Closed)
  194. throw new InvalidOperationException ("Invalid Operation.The Connection is Closed");
  195. else
  196. return tds.ServerVersion;
  197. }
  198. }
  199. [Browsable (false)]
  200. #if !NET_2_0
  201. [DataSysDescription ("The ConnectionState indicating whether the connection is open or closed.")]
  202. #endif
  203. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  204. public
  205. #if NET_2_0
  206. override
  207. #endif // NET_2_0
  208. ConnectionState State {
  209. get { return state; }
  210. }
  211. internal ITds Tds {
  212. get { return tds; }
  213. }
  214. internal SqlTransaction Transaction {
  215. get { return transaction; }
  216. set { transaction = value; }
  217. }
  218. #if !NET_2_0
  219. [DataSysDescription ("Workstation Id, 'Workstation ID=x' in the connection string.")]
  220. #endif
  221. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  222. public string WorkstationId {
  223. get { return parms.Hostname; }
  224. }
  225. internal XmlReader XmlReader {
  226. get { return xmlReader; }
  227. set { xmlReader = value; }
  228. }
  229. #if NET_2_0
  230. public bool FireInfoMessageEventOnUserErrors {
  231. get { return fireInfoMessageEventOnUserErrors; }
  232. set { fireInfoMessageEventOnUserErrors = value; }
  233. }
  234. [DefaultValue (false)]
  235. public bool StatisticsEnabled {
  236. get { return statisticsEnabled; }
  237. set { statisticsEnabled = value; }
  238. }
  239. #endif
  240. #endregion // Properties
  241. #region Events
  242. #if !NET_2_0
  243. [DataSysDescription ("Event triggered when messages arrive from the DataSource.")]
  244. #endif
  245. public event SqlInfoMessageEventHandler InfoMessage;
  246. #if !NET_2_0
  247. [DataSysDescription ("Event triggered when the connection changes state.")]
  248. public new event StateChangeEventHandler StateChange;
  249. #endif
  250. #endregion // Events
  251. #region Delegates
  252. private void ErrorHandler (object sender, TdsInternalErrorMessageEventArgs e)
  253. {
  254. throw new SqlException (e.Class, e.LineNumber, e.Message, e.Number, e.Procedure, e.Server, "Mono SqlClient Data Provider", e.State);
  255. }
  256. private void MessageHandler (object sender, TdsInternalInfoMessageEventArgs e)
  257. {
  258. OnSqlInfoMessage (CreateSqlInfoMessageEvent (e.Errors));
  259. }
  260. #endregion // Delegates
  261. #region Methods
  262. internal string GetConnStringKeyValue (params string [] keys)
  263. {
  264. if (connStringParameters == null || connStringParameters.Count == 0)
  265. return "";
  266. foreach (string key in keys) {
  267. string value = connStringParameters [key];
  268. if (value != null)
  269. return value;
  270. }
  271. return "";
  272. }
  273. public new SqlTransaction BeginTransaction ()
  274. {
  275. return BeginTransaction (IsolationLevel.ReadCommitted, String.Empty);
  276. }
  277. public new SqlTransaction BeginTransaction (IsolationLevel iso)
  278. {
  279. return BeginTransaction (iso, String.Empty);
  280. }
  281. public SqlTransaction BeginTransaction (string transactionName)
  282. {
  283. return BeginTransaction (IsolationLevel.ReadCommitted, transactionName);
  284. }
  285. public SqlTransaction BeginTransaction (IsolationLevel iso, string transactionName)
  286. {
  287. if (state == ConnectionState.Closed)
  288. throw new InvalidOperationException ("The connection is not open.");
  289. if (transaction != null)
  290. throw new InvalidOperationException ("SqlConnection does not support parallel transactions.");
  291. if (iso == IsolationLevel.Chaos)
  292. throw new ArgumentException ("Invalid IsolationLevel parameter: must be ReadCommitted, ReadUncommitted, RepeatableRead, or Serializable.");
  293. string isolevel = String.Empty;
  294. switch (iso) {
  295. case IsolationLevel.ReadCommitted:
  296. isolevel = "READ COMMITTED";
  297. break;
  298. case IsolationLevel.ReadUncommitted:
  299. isolevel = "READ UNCOMMITTED";
  300. break;
  301. case IsolationLevel.RepeatableRead:
  302. isolevel = "REPEATABLE READ";
  303. break;
  304. case IsolationLevel.Serializable:
  305. isolevel = "SERIALIZABLE";
  306. break;
  307. }
  308. tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0};BEGIN TRANSACTION {1}", isolevel, transactionName));
  309. transaction = new SqlTransaction (this, iso);
  310. return transaction;
  311. }
  312. public
  313. #if NET_2_0
  314. override
  315. #endif // NET_2_0
  316. void ChangeDatabase (string database)
  317. {
  318. if (!IsValidDatabaseName (database))
  319. throw new ArgumentException (String.Format ("The database name {0} is not valid.", database));
  320. if (state != ConnectionState.Open)
  321. throw new InvalidOperationException ("The connection is not open.");
  322. tds.Execute (String.Format ("use [{0}]", database));
  323. }
  324. private void ChangeState (ConnectionState currentState)
  325. {
  326. ConnectionState originalState = state;
  327. state = currentState;
  328. OnStateChange (CreateStateChangeEvent (originalState, currentState));
  329. }
  330. public
  331. #if NET_2_0
  332. override
  333. #endif // NET_2_0
  334. void Close ()
  335. {
  336. if (transaction != null && transaction.IsOpen)
  337. transaction.Rollback ();
  338. if (dataReader != null || xmlReader != null) {
  339. if(tds != null) tds.SkipToEnd ();
  340. dataReader = null;
  341. xmlReader = null;
  342. }
  343. if (tds != null && tds.IsConnected) {
  344. if (pooling && tds.Pooling) {
  345. #if NET_2_0
  346. if(pool != null) pool.ReleaseConnection (ref tds);
  347. #else
  348. if(pool != null) pool.ReleaseConnection (tds);
  349. #endif
  350. }else
  351. if(tds != null) tds.Disconnect ();
  352. }
  353. if (tds != null) {
  354. tds.TdsErrorMessage -= new TdsInternalErrorMessageEventHandler (ErrorHandler);
  355. tds.TdsInfoMessage -= new TdsInternalInfoMessageEventHandler (MessageHandler);
  356. }
  357. ChangeState (ConnectionState.Closed);
  358. }
  359. public new SqlCommand CreateCommand ()
  360. {
  361. SqlCommand command = new SqlCommand ();
  362. command.Connection = this;
  363. return command;
  364. }
  365. private SqlInfoMessageEventArgs CreateSqlInfoMessageEvent (TdsInternalErrorCollection errors)
  366. {
  367. return new SqlInfoMessageEventArgs (errors);
  368. }
  369. private StateChangeEventArgs CreateStateChangeEvent (ConnectionState originalState, ConnectionState currentState)
  370. {
  371. return new StateChangeEventArgs (originalState, currentState);
  372. }
  373. protected override void Dispose (bool disposing)
  374. {
  375. if (disposed)
  376. return;
  377. try {
  378. if (disposing) {
  379. if (State == ConnectionState.Open)
  380. Close ();
  381. ConnectionString = "";
  382. SetDefaultConnectionParameters (this.connStringParameters);
  383. }
  384. } finally {
  385. disposed = true;
  386. base.Dispose (disposing);
  387. }
  388. }
  389. [MonoTODO ("Not sure what this means at present.")]
  390. public void EnlistDistributedTransaction (ITransaction transaction)
  391. {
  392. throw new NotImplementedException ();
  393. }
  394. object ICloneable.Clone ()
  395. {
  396. return new SqlConnection (ConnectionString);
  397. }
  398. #if NET_2_0
  399. protected override DbTransaction BeginDbTransaction (IsolationLevel level)
  400. {
  401. return (DbTransaction)BeginTransaction (level);
  402. }
  403. protected override DbCommand CreateDbCommand ()
  404. {
  405. return CreateCommand ();
  406. }
  407. #else
  408. IDbTransaction IDbConnection.BeginTransaction ()
  409. {
  410. return BeginTransaction ();
  411. }
  412. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso)
  413. {
  414. return BeginTransaction (iso);
  415. }
  416. IDbCommand IDbConnection.CreateCommand ()
  417. {
  418. return CreateCommand ();
  419. }
  420. #endif
  421. public
  422. #if NET_2_0
  423. override
  424. #endif // NET_2_0
  425. void Open ()
  426. {
  427. string serverName = "";
  428. if (state == ConnectionState.Open)
  429. throw new InvalidOperationException ("The Connection is already Open (State=Open)");
  430. if (connectionString == null || connectionString.Trim().Length == 0)
  431. throw new InvalidOperationException ("Connection string has not been initialized.");
  432. try {
  433. if (!pooling) {
  434. if(!ParseDataSource (dataSource, out port, out serverName))
  435. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  436. tds = new Tds70 (serverName, port, PacketSize, ConnectionTimeout);
  437. }
  438. else {
  439. if(!ParseDataSource (dataSource, out port, out serverName))
  440. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  441. TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize);
  442. pool = sqlConnectionPools.GetConnectionPool (connectionString, info);
  443. tds = pool.GetConnection ();
  444. }
  445. } catch (TdsTimeoutException e) {
  446. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  447. } catch (TdsInternalException e) {
  448. throw SqlException.FromTdsInternalException (e);
  449. }
  450. tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
  451. tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);
  452. if (!tds.IsConnected) {
  453. try {
  454. tds.Connect (parms);
  455. } catch {
  456. if (pooling)
  457. pool.ReleaseConnection (tds);
  458. throw;
  459. }
  460. } else if (connectionReset) {
  461. tds.Reset ();
  462. }
  463. disposed = false; // reset this, so using () would call Close ().
  464. ChangeState (ConnectionState.Open);
  465. }
  466. private bool ParseDataSource (string theDataSource, out int thePort, out string theServerName)
  467. {
  468. theServerName = "";
  469. string theInstanceName = "";
  470. if (theDataSource == null)
  471. throw new ArgumentException("Format of initialization string does not conform to specifications");
  472. thePort = 1433; // default TCP port for SQL Server
  473. bool success = true;
  474. int idx = 0;
  475. if ((idx = theDataSource.IndexOf (",")) > -1) {
  476. theServerName = theDataSource.Substring (0, idx);
  477. string p = theDataSource.Substring (idx + 1);
  478. thePort = Int32.Parse (p);
  479. }
  480. else if ((idx = theDataSource.IndexOf ("\\")) > -1) {
  481. theServerName = theDataSource.Substring (0, idx);
  482. theInstanceName = theDataSource.Substring (idx + 1);
  483. // do port discovery via UDP port 1434
  484. port = DiscoverTcpPortViaSqlMonitor (theServerName, theInstanceName);
  485. if (port == -1)
  486. success = false;
  487. }
  488. else if (theDataSource == "" || theDataSource == "(local)")
  489. theServerName = "localhost";
  490. else
  491. theServerName = theDataSource;
  492. if ((idx = theServerName.IndexOf ("tcp:")) > -1) {
  493. theServerName = theServerName.Substring (idx + 4);
  494. }
  495. return success;
  496. }
  497. private bool ConvertIntegratedSecurity (string value)
  498. {
  499. if (value.ToUpper() == "SSPI")
  500. {
  501. return true;
  502. }
  503. return ConvertToBoolean("integrated security", value);
  504. }
  505. private bool ConvertToBoolean(string key, string value)
  506. {
  507. string upperValue = value.ToUpper();
  508. if (upperValue == "TRUE" ||upperValue == "YES")
  509. {
  510. return true;
  511. }
  512. else if (upperValue == "FALSE" || upperValue == "NO")
  513. {
  514. return false;
  515. }
  516. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  517. "Invalid value \"{0}\" for key '{1}'.", value, key));
  518. }
  519. private int ConvertToInt32(string key, string value)
  520. {
  521. try
  522. {
  523. return int.Parse(value);
  524. } catch (Exception ex) {
  525. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  526. "Invalid value \"{0}\" for key '{1}'.", value, key));
  527. }
  528. }
  529. private int DiscoverTcpPortViaSqlMonitor(string ServerName, string InstanceName)
  530. {
  531. SqlMonitorSocket msock;
  532. msock = new SqlMonitorSocket (ServerName, InstanceName);
  533. int SqlServerPort = msock.DiscoverTcpPort ();
  534. msock = null;
  535. return SqlServerPort;
  536. }
  537. void SetConnectionString (string connectionString)
  538. {
  539. NameValueCollection parameters = new NameValueCollection ();
  540. SetDefaultConnectionParameters (parameters);
  541. if ((connectionString == null) || (connectionString.Trim().Length == 0)) {
  542. this.connectionString = connectionString;
  543. this.connStringParameters = parameters;
  544. return;
  545. }
  546. connectionString += ";";
  547. bool inQuote = false;
  548. bool inDQuote = false;
  549. bool inName = true;
  550. string name = String.Empty;
  551. string value = String.Empty;
  552. StringBuilder sb = new StringBuilder ();
  553. for (int i = 0; i < connectionString.Length; i += 1) {
  554. char c = connectionString [i];
  555. char peek;
  556. if (i == connectionString.Length - 1)
  557. peek = '\0';
  558. else
  559. peek = connectionString [i + 1];
  560. switch (c) {
  561. case '\'':
  562. if (inDQuote)
  563. sb.Append (c);
  564. else if (peek.Equals (c)) {
  565. sb.Append (c);
  566. i += 1;
  567. }
  568. else
  569. inQuote = !inQuote;
  570. break;
  571. case '"':
  572. if (inQuote)
  573. sb.Append (c);
  574. else if (peek.Equals (c)) {
  575. sb.Append (c);
  576. i += 1;
  577. }
  578. else
  579. inDQuote = !inDQuote;
  580. break;
  581. case ';':
  582. if (inDQuote || inQuote)
  583. sb.Append (c);
  584. else {
  585. if (name != String.Empty && name != null) {
  586. value = sb.ToString ();
  587. SetProperties (name.ToUpper ().Trim() , value);
  588. parameters [name.ToUpper ().Trim ()] = value.Trim ();
  589. }
  590. else if (sb.Length != 0)
  591. throw new ArgumentException ("Format of initialization string does not conform to specifications");
  592. inName = true;
  593. name = String.Empty;
  594. value = String.Empty;
  595. sb = new StringBuilder ();
  596. }
  597. break;
  598. case '=':
  599. if (inDQuote || inQuote || !inName)
  600. sb.Append (c);
  601. else if (peek.Equals (c)) {
  602. sb.Append (c);
  603. i += 1;
  604. }
  605. else {
  606. name = sb.ToString ();
  607. sb = new StringBuilder ();
  608. inName = false;
  609. }
  610. break;
  611. case ' ':
  612. if (inQuote || inDQuote)
  613. sb.Append (c);
  614. else if (sb.Length > 0 && !peek.Equals (';'))
  615. sb.Append (c);
  616. break;
  617. default:
  618. sb.Append (c);
  619. break;
  620. }
  621. }
  622. connectionString = connectionString.Substring (0 , connectionString.Length-1);
  623. this.connectionString = connectionString;
  624. this.connStringParameters = parameters;
  625. }
  626. void SetDefaultConnectionParameters (NameValueCollection parameters)
  627. {
  628. parms.Reset ();
  629. dataSource = "";
  630. connectionTimeout= 15;
  631. connectionReset = true;
  632. pooling = true;
  633. maxPoolSize = 100;
  634. minPoolSize = 0;
  635. packetSize = 8192;
  636. parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
  637. parameters["CONNECT TIMEOUT"] = "15";
  638. parameters["CONNECTION LIFETIME"] = "0";
  639. parameters["CONNECTION RESET"] = "true";
  640. parameters["ENLIST"] = "true";
  641. parameters["INTEGRATED SECURITY"] = "false";
  642. parameters["INITIAL CATALOG"] = "";
  643. parameters["MAX POOL SIZE"] = "100";
  644. parameters["MIN POOL SIZE"] = "0";
  645. parameters["NETWORK LIBRARY"] = "dbmssocn";
  646. parameters["PACKET SIZE"] = "8192";
  647. parameters["PERSIST SECURITY INFO"] = "false";
  648. parameters["POOLING"] = "true";
  649. parameters["WORKSTATION ID"] = Dns.GetHostName();
  650. #if NET_2_0
  651. async = false;
  652. parameters ["ASYNCHRONOUS PROCESSING"] = "false";
  653. #endif
  654. }
  655. private void SetProperties (string name , string value)
  656. {
  657. switch (name)
  658. {
  659. case "APP" :
  660. case "APPLICATION NAME" :
  661. parms.ApplicationName = value;
  662. break;
  663. case "ATTACHDBFILENAME" :
  664. case "EXTENDED PROPERTIES" :
  665. case "INITIAL FILE NAME" :
  666. parms.AttachDBFileName = value;
  667. break;
  668. case "TIMEOUT" :
  669. case "CONNECT TIMEOUT" :
  670. case "CONNECTION TIMEOUT" :
  671. int tmpTimeout = ConvertToInt32 ("connection timeout", value);
  672. if (tmpTimeout < 0)
  673. throw new ArgumentException ("Invalid CONNECTION TIMEOUT .. Must be an integer >=0 ");
  674. else
  675. connectionTimeout = tmpTimeout;
  676. break;
  677. case "CONNECTION LIFETIME" :
  678. break;
  679. case "CONNECTION RESET" :
  680. connectionReset = ConvertToBoolean ("connection reset", value);
  681. break;
  682. case "LANGUAGE" :
  683. case "CURRENT LANGUAGE" :
  684. parms.Language = value;
  685. break;
  686. case "DATA SOURCE" :
  687. case "SERVER" :
  688. case "ADDRESS" :
  689. case "ADDR" :
  690. case "NETWORK ADDRESS" :
  691. dataSource = value;
  692. break;
  693. case "ENCRYPT":
  694. if (ConvertToBoolean("encrypt", value))
  695. {
  696. throw new NotImplementedException("SSL encryption for"
  697. + " data sent between client and server is not"
  698. + " implemented.");
  699. }
  700. break;
  701. case "ENLIST" :
  702. if (!ConvertToBoolean("enlist", value))
  703. {
  704. throw new NotImplementedException("Disabling the automatic"
  705. + " enlistment of connections in the thread's current"
  706. + " transaction context is not implemented.");
  707. }
  708. break;
  709. case "INITIAL CATALOG" :
  710. case "DATABASE" :
  711. parms.Database = value;
  712. break;
  713. case "INTEGRATED SECURITY" :
  714. case "TRUSTED_CONNECTION" :
  715. parms.DomainLogin = ConvertIntegratedSecurity(value);
  716. break;
  717. case "MAX POOL SIZE" :
  718. int tmpMaxPoolSize = ConvertToInt32 ("max pool size" , value);
  719. if (tmpMaxPoolSize < 0)
  720. throw new ArgumentException ("Invalid MAX POOL SIZE. Must be a intger >= 0");
  721. else
  722. maxPoolSize = tmpMaxPoolSize;
  723. break;
  724. case "MIN POOL SIZE" :
  725. int tmpMinPoolSize = ConvertToInt32 ("min pool size" , value);
  726. if (tmpMinPoolSize < 0)
  727. throw new ArgumentException ("Invalid MIN POOL SIZE. Must be a intger >= 0");
  728. else
  729. minPoolSize = tmpMinPoolSize;
  730. break;
  731. #if NET_2_0
  732. case "MULTIPLEACTIVERESULTSETS":
  733. break;
  734. case "ASYNCHRONOUS PROCESSING" :
  735. case "ASYNC" :
  736. async = ConvertToBoolean (name, value);
  737. break;
  738. #endif
  739. case "NET" :
  740. case "NETWORK" :
  741. case "NETWORK LIBRARY" :
  742. if (!value.ToUpper ().Equals ("DBMSSOCN"))
  743. throw new ArgumentException ("Unsupported network library.");
  744. break;
  745. case "PACKET SIZE" :
  746. int tmpPacketSize = ConvertToInt32 ("packet size", value);
  747. if (tmpPacketSize < 512 || tmpPacketSize > 32767)
  748. throw new ArgumentException ("Invalid PACKET SIZE. The integer must be between 512 and 32767");
  749. else
  750. packetSize = tmpPacketSize;
  751. break;
  752. case "PASSWORD" :
  753. case "PWD" :
  754. parms.Password = value;
  755. break;
  756. case "PERSISTSECURITYINFO" :
  757. case "PERSIST SECURITY INFO" :
  758. // FIXME : not implemented
  759. // throw new NotImplementedException ();
  760. break;
  761. case "POOLING" :
  762. pooling = ConvertToBoolean("pooling", value);
  763. break;
  764. case "UID" :
  765. case "USER" :
  766. case "USER ID" :
  767. parms.User = value;
  768. break;
  769. case "WSID" :
  770. case "WORKSTATION ID" :
  771. parms.Hostname = value;
  772. break;
  773. default :
  774. throw new ArgumentException("Keyword not supported :"+name);
  775. }
  776. }
  777. static bool IsValidDatabaseName (string database)
  778. {
  779. if ( database == null || database.Trim() == String.Empty || database.Length > 128)
  780. return false ;
  781. if (database[0] == '"' && database[database.Length] == '"')
  782. database = database.Substring (1, database.Length - 2);
  783. else if (Char.IsDigit (database[0]))
  784. return false;
  785. if (database[0] == '_')
  786. return false;
  787. foreach (char c in database.Substring (1, database.Length - 1))
  788. if (!Char.IsLetterOrDigit (c) && c != '_' && c != '-')
  789. return false;
  790. return true;
  791. }
  792. private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
  793. {
  794. if (InfoMessage != null)
  795. InfoMessage (this, value);
  796. }
  797. #if !NET_2_0
  798. private new void OnStateChange (StateChangeEventArgs value)
  799. {
  800. if (StateChange != null)
  801. StateChange (this, value);
  802. }
  803. #endif
  804. private sealed class SqlMonitorSocket : UdpClient
  805. {
  806. // UDP port that the SQL Monitor listens
  807. private static readonly int SqlMonitorUdpPort = 1434;
  808. //private static readonly string SqlServerNotExist = "SQL Server does not exist or access denied";
  809. private string server;
  810. private string instance;
  811. internal SqlMonitorSocket (string ServerName, string InstanceName)
  812. : base (ServerName, SqlMonitorUdpPort)
  813. {
  814. server = ServerName;
  815. instance = InstanceName;
  816. }
  817. internal int DiscoverTcpPort ()
  818. {
  819. int SqlServerTcpPort;
  820. Client.Blocking = false;
  821. // send command to UDP 1434 (SQL Monitor) to get
  822. // the TCP port to connect to the MS SQL server
  823. ASCIIEncoding enc = new ASCIIEncoding ();
  824. Byte[] rawrq = new Byte [instance.Length + 1];
  825. rawrq[0] = 4;
  826. enc.GetBytes (instance, 0, instance.Length, rawrq, 1);
  827. int bytes = Send (rawrq, rawrq.Length);
  828. if (!Active)
  829. return -1; // Error
  830. bool result;
  831. result = Client.Poll (100, SelectMode.SelectRead);
  832. if (result == false)
  833. return -1; // Error
  834. if (Client.Available <= 0)
  835. return -1; // Error
  836. #if NET_2_0
  837. IPEndPoint endpoint = new IPEndPoint (Dns.GetHostEntry ("localhost").AddressList [0], 0);
  838. #else
  839. IPEndPoint endpoint = new IPEndPoint (Dns.GetHostByName ("localhost").AddressList [0], 0);
  840. #endif
  841. Byte [] rawrs;
  842. rawrs = Receive (ref endpoint);
  843. string rs = Encoding.ASCII.GetString (rawrs);
  844. string[] rawtokens = rs.Split (';');
  845. Hashtable data = new Hashtable ();
  846. for (int i = 0; i < rawtokens.Length / 2 && i < 256; i++) {
  847. data [rawtokens [i * 2]] = rawtokens [ i * 2 + 1];
  848. }
  849. if (!data.ContainsKey ("tcp"))
  850. throw new NotImplementedException ("Only TCP/IP is supported.");
  851. SqlServerTcpPort = int.Parse ((string) data ["tcp"]);
  852. Close ();
  853. return SqlServerTcpPort;
  854. }
  855. }
  856. #if NET_2_0
  857. struct ColumnInfo {
  858. public string name;
  859. public Type type;
  860. public ColumnInfo (string name, Type type)
  861. {
  862. this.name = name; this.type = type;
  863. }
  864. }
  865. static class ReservedWords
  866. {
  867. static readonly string [] reservedWords =
  868. {
  869. "ADD", "EXCEPT", "PERCENT", "ALL", "EXEC", "PLAN", "ALTER",
  870. "EXECUTE", "PRECISION", "AND", "EXISTS", "PRIMARY", "ANY",
  871. "EXIT", "PRINT", "AS", "FETCH", "PROC", "ASC", "FILE",
  872. "PROCEDURE", "AUTHORIZATION", "FILLFACTOR", "PUBLIC",
  873. "BACKUP", "FOR", "RAISERROR", "BEGIN", "FOREIGN", "READ",
  874. "BETWEEN", "FREETEXT", "READTEXT", "BREAK", "FREETEXTTABLE",
  875. "RECONFIGURE", "BROWSE", "FROM", "REFERENCES", "BULK",
  876. "FULL", "REPLICATION", "BY", "FUNCTION", "RESTORE",
  877. "CASCADE", "GOTO", "RESTRICT", "CASE", "GRANT", "RETURN",
  878. "CHECK", "GROUP", "REVOKE", "CHECKPOINT", "HAVING", "RIGHT",
  879. "CLOSE", "HOLDLOCK", "ROLLBACK", "CLUSTERED", "IDENTITY",
  880. "ROWCOUNT", "COALESCE", "IDENTITY_INSERT", "ROWGUIDCOL",
  881. "COLLATE", "IDENTITYCOL", "RULE", "COLUMN", "IF", "SAVE",
  882. "COMMIT", "IN", "SCHEMA", "COMPUTE", "INDEX", "SELECT",
  883. "CONSTRAINT", "INNER", "SESSION_USER", "CONTAINS", "INSERT",
  884. "SET", "CONTAINSTABLE", "INTERSECT", "SETUSER", "CONTINUE",
  885. "INTO", "SHUTDOWN", "CONVERT", "IS", "SOME", "CREATE",
  886. "JOIN", "STATISTICS", "CROSS", "KEY", "SYSTEM_USER",
  887. "CURRENT", "KILL", "TABLE", "CURRENT_DATE", "LEFT",
  888. "TEXTSIZE", "CURRENT_TIME", "LIKE", "THEN",
  889. "CURRENT_TIMESTAMP", "LINENO", "TO", "CURRENT_USER", "LOAD",
  890. "TOP", "CURSOR", "NATIONAL", "TRAN", "DATABASE", "NOCHECK",
  891. "TRANSACTION", "DBCC", "NONCLUSTERED", "TRIGGER",
  892. "DEALLOCATE", "NOT", "TRUNCATE", "DECLARE", "NULL",
  893. "TSEQUAL", "DEFAULT", "NULLIF", "UNION", "DELETE", "OF",
  894. "UNIQUE", "DENY", "OFF", "UPDATE", "DESC", "OFFSETS",
  895. "UPDATETEXT", "DISK", "ON", "USE", "DISTINCT", "OPEN",
  896. "USER", "DISTRIBUTED", "OPENDATASOURCE", "VALUES", "DOUBLE",
  897. "OPENQUERY", "VARYING", "DROP", "OPENROWSET", "VIEW",
  898. "DUMMY", "OPENXML", "WAITFOR", "DUMP", "OPTION", "WHEN",
  899. "ELSE", "OR", "WHERE", "END", "ORDER", "WHILE", "ERRLVL",
  900. "OUTER", "WITH", "ESCAPE", "OVER", "WRITETEXT", "ABSOLUTE",
  901. "FOUND", "PRESERVE", "ACTION", "FREE", "PRIOR", "ADMIN",
  902. "GENERAL", "PRIVILEGES", "AFTER", "GET", "READS",
  903. "AGGREGATE", "GLOBAL", "REAL", "ALIAS", "GO", "RECURSIVE",
  904. "ALLOCATE", "GROUPING", "REF", "ARE", "HOST", "REFERENCING",
  905. "ARRAY", "HOUR", "RELATIVE", "ASSERTION", "IGNORE", "RESULT",
  906. "AT", "IMMEDIATE", "RETURNS", "BEFORE", "INDICATOR", "ROLE",
  907. "BINARY", "INITIALIZE", "ROLLUP", "BIT", "INITIALLY",
  908. "ROUTINE", "BLOB", "INOUT", "ROW", "BOOLEAN", "INPUT",
  909. "ROWS", "BOTH", "INT", "SAVEPOINT", "BREADTH", "INTEGER",
  910. "SCROLL", "CALL", "INTERVAL", "SCOPE", "CASCADED",
  911. "ISOLATION", "SEARCH", "CAST", "ITERATE", "SECOND",
  912. "CATALOG", "LANGUAGE", "SECTION", "CHAR", "LARGE",
  913. "SEQUENCE", "CHARACTER", "LAST", "SESSION", "CLASS",
  914. "LATERAL", "SETS", "CLOB", "LEADING", "SIZE", "COLLATION",
  915. "LESS", "SMALLINT", "COMPLETION", "LEVEL", "SPACE",
  916. "CONNECT", "LIMIT", "SPECIFIC", "CONNECTION", "LOCAL",
  917. "SPECIFICTYPE", "CONSTRAINTS", "LOCALTIME", "SQL",
  918. "CONSTRUCTOR", "LOCALTIMESTAMP", "SQLEXCEPTION",
  919. "CORRESPONDING", "LOCATOR", "SQLSTATE", "CUBE", "MAP",
  920. "SQLWARNING", "CURRENT_PATH", "MATCH", "START",
  921. "CURRENT_ROLE", "MINUTE", "STATE", "CYCLE", "MODIFIES",
  922. "STATEMENT", "DATA", "MODIFY", "STATIC", "DATE", "MODULE",
  923. "STRUCTURE", "DAY", "MONTH", "TEMPORARY", "DEC", "NAMES",
  924. "TERMINATE", "DECIMAL", "NATURAL", "THAN", "DEFERRABLE",
  925. "NCHAR", "TIME", "DEFERRED", "NCLOB", "TIMESTAMP", "DEPTH",
  926. "NEW", "TIMEZONE_HOUR", "DEREF", "NEXT", "TIMEZONE_MINUTE",
  927. "DESCRIBE", "NO", "TRAILING", "DESCRIPTOR", "NONE",
  928. "TRANSLATION", "DESTROY", "NUMERIC", "TREAT", "DESTRUCTOR",
  929. "OBJECT", "TRUE", "DETERMINISTIC", "OLD", "UNDER",
  930. "DICTIONARY", "ONLY", "UNKNOWN", "DIAGNOSTICS", "OPERATION",
  931. "UNNEST", "DISCONNECT", "ORDINALITY", "USAGE", "DOMAIN",
  932. "OUT", "USING", "DYNAMIC", "OUTPUT", "VALUE", "EACH",
  933. "PAD", "VARCHAR", "END-EXEC", "PARAMETER", "VARIABLE",
  934. "EQUALS", "PARAMETERS", "WHENEVER", "EVERY", "PARTIAL",
  935. "WITHOUT", "EXCEPTION", "PATH", "WORK", "EXTERNAL",
  936. "POSTFIX", "WRITE", "FALSE", "PREFIX", "YEAR", "FIRST",
  937. "PREORDER", "ZONE", "FLOAT", "PREPARE", "ADA", "AVG",
  938. "BIT_LENGTH", "CHAR_LENGTH", "CHARACTER_LENGTH", "COUNT",
  939. "EXTRACT", "FORTRAN", "INCLUDE", "INSENSITIVE", "LOWER",
  940. "MAX", "MIN", "OCTET_LENGTH", "OVERLAPS", "PASCAL",
  941. "POSITION", "SQLCA", "SQLCODE", "SQLERROR", "SUBSTRING",
  942. "SUM", "TRANSLATE", "TRIM", "UPPER"
  943. };
  944. static DataTable instance;
  945. static public DataTable Instance {
  946. get {
  947. if (instance == null) {
  948. DataRow row = null;
  949. instance = new DataTable ("ReservedWords");
  950. instance.Columns.Add ("ReservedWord", typeof(string));
  951. foreach (string reservedWord in reservedWords)
  952. {
  953. row = instance.NewRow();
  954. row["ReservedWord"] = reservedWord;
  955. instance.Rows.Add(row);
  956. }
  957. }
  958. return instance;
  959. }
  960. }
  961. }
  962. static class MetaDataCollections
  963. {
  964. static readonly ColumnInfo [] columns = {
  965. new ColumnInfo ("CollectionName", typeof (string)),
  966. new ColumnInfo ("NumberOfRestrictions", typeof (int)),
  967. new ColumnInfo ("NumberOfIdentifierParts", typeof (int))
  968. };
  969. static readonly object [][] rows = {
  970. new object [] {"MetaDataCollections", 0, 0},
  971. new object [] {"DataSourceInformation", 0, 0},
  972. new object [] {"DataTypes", 0, 0},
  973. new object [] {"Restrictions", 0, 0},
  974. new object [] {"ReservedWords", 0, 0},
  975. new object [] {"Users", 1, 1},
  976. new object [] {"Databases", 1, 1},
  977. new object [] {"Tables", 4, 3},
  978. new object [] {"Columns", 4, 4},
  979. new object [] {"Views", 3, 3},
  980. new object [] {"ViewColumns", 4, 4},
  981. new object [] {"ProcedureParameters", 4, 1},
  982. new object [] {"Procedures", 4, 3},
  983. new object [] {"ForeignKeys", 4, 3},
  984. new object [] {"IndexColumns", 5, 4},
  985. new object [] {"Indexes", 4, 3},
  986. new object [] {"UserDefinedTypes", 2, 1}
  987. };
  988. static DataTable instance;
  989. static public DataTable Instance {
  990. get {
  991. if (instance == null) {
  992. instance = new DataTable ("GetSchema");
  993. foreach (ColumnInfo c in columns)
  994. instance.Columns.Add (c.name, c.type);
  995. foreach (object [] row in rows)
  996. instance.LoadDataRow (row, true);
  997. }
  998. return instance;
  999. }
  1000. }
  1001. }
  1002. static class DataTypes
  1003. {
  1004. static readonly ColumnInfo [] columns = {
  1005. new ColumnInfo ("TypeName", typeof(string)),
  1006. new ColumnInfo ("ProviderDbType", typeof(int)),
  1007. new ColumnInfo ("ColumnSize", typeof(long)),
  1008. new ColumnInfo ("CreateFormat", typeof(string)),
  1009. new ColumnInfo ("CreateParameters", typeof(string)),
  1010. new ColumnInfo ("DataType", typeof(string)),
  1011. new ColumnInfo ("IsAutoIncrementable", typeof(bool)),
  1012. new ColumnInfo ("IsBestMatch", typeof(bool)),
  1013. new ColumnInfo ("IsCaseSensitive", typeof(bool)),
  1014. new ColumnInfo ("IsFixedLength", typeof(bool)),
  1015. new ColumnInfo ("IsFixedPrecisionScale", typeof(bool)),
  1016. new ColumnInfo ("IsLong", typeof(bool)),
  1017. new ColumnInfo ("IsNullable", typeof(bool)),
  1018. new ColumnInfo ("IsSearchable", typeof(bool)),
  1019. new ColumnInfo ("IsSearchableWithLike", typeof(bool)),
  1020. new ColumnInfo ("IsUnsigned", typeof(bool)),
  1021. new ColumnInfo ("MaximumScale", typeof(short)),
  1022. new ColumnInfo ("MinimumScale", typeof(short)),
  1023. new ColumnInfo ("IsConcurrencyType", typeof(bool)),
  1024. new ColumnInfo ("IsLiteralSupported", typeof(bool)),
  1025. new ColumnInfo ("LiteralPrefix", typeof(string)),
  1026. new ColumnInfo ("LiteralSuffix", typeof(string))
  1027. };
  1028. static readonly object [][] rows = {
  1029. new object [] {"smallint", 16, 5, "smallint", null, "System.Int16", true, true,
  1030. false, true, true, false, true, true, false, false, null,
  1031. null, false, null, null, null},
  1032. new object [] {"int", 8, 10, "int", null, "System.Int32",
  1033. true, true, false, true, true, false, true, true, false,
  1034. false, null, null, false, null, null, null},
  1035. new object [] {"real", 13, 7, "real", null,
  1036. "System.Single", false, true, false, true, false, false,
  1037. true, true, false, false, null, null, false, null, null, null},
  1038. new object [] {"float", 6, 53, "float({0})",
  1039. "number of bits used to store the mantissa", "System.Double",
  1040. false, true, false, true, false, false, true, true,
  1041. false, false, null, null, false, null, null, null},
  1042. new object [] {"money", 9, 19, "money", null,
  1043. "System.Decimal", false, false, false, true, true,
  1044. false, true, true, false, false, null, null, false,
  1045. null, null, null},
  1046. new object [] {"smallmoney", 17, 10, "smallmoney", null,
  1047. "System.Decimal", false, false, false, true, true, false,
  1048. true, true, false, false, null, null, false, null, null, null},
  1049. new object [] {"bit", 2, 1, "bit", null, "System.Boolean",
  1050. false, false, false, true, false, false, true, true,
  1051. false, null, null, null, false, null, null, null},
  1052. new object [] {"tinyint", 20, 3, "tinyint", null,
  1053. "System.SByte", true, true, false, true, true, false,
  1054. true, true, false, true, null, null, false, null, null, null},
  1055. new object [] {"bigint", 0, 19, "bigint", null,
  1056. "System.Int64", true, true, false, true, true, false,
  1057. true, true, false, false, null, null, false, null, null, null},
  1058. new object [] {"timestamp", 19, 8, "timestamp", null,
  1059. "System.Byte[]", false, false, false, true, false, false,
  1060. false, true, false, null, null, null, true, null, "0x", null},
  1061. new object [] {"binary", 1, 8000, "binary({0})", "length",
  1062. "System.Byte[]", false, true, false, true, false, false,
  1063. true, true, false, null, null, null, false, null, "0x", null},
  1064. new object [] {"image", 7, 2147483647, "image", null,
  1065. "System.Byte[]", false, true, false, false, false, true,
  1066. true, false, false, null, null, null, false, null, "0x", null},
  1067. new object [] {"text", 18, 2147483647, "text", null,
  1068. "System.String", false, true, false, false, false, true,
  1069. true, false, true, null, null, null, false, null, "'", "'"},
  1070. new object [] {"ntext", 11, 1073741823, "ntext", null,
  1071. "System.String", false, true, false, false, false, true,
  1072. true, false, true, null, null, null, false, null, "N'", "'"},
  1073. new object [] {"decimal", 5, 38, "decimal({0}, {1})",
  1074. "precision,scale", "System.Decimal", true, true, false,
  1075. true, false, false, true, true, false, false, 38, 0,
  1076. false, null, null, null},
  1077. new object [] {"numeric", 5, 38, "numeric({0}, {1})",
  1078. "precision,scale", "System.Decimal", true, true, false,
  1079. true, false, false, true, true, false, false, 38, 0,
  1080. false, null, null, null},
  1081. new object [] {"datetime", 4, 23, "datetime", null,
  1082. "System.DateTime", false, true, false, true, false, false,
  1083. true, true, true, null, null, null, false, null, "{ts '", "'}"},
  1084. new object [] {"smalldatetime", 15, 16, "smalldatetime", null,
  1085. "System.DateTime", false, true, false, true, false, false,
  1086. true, true, true, null, null, null, false, null, "{ts '", "'}"},
  1087. new object [] {"sql_variant", 23, null, "sql_variant",
  1088. null, "System.Object", false, true, false, false, false,
  1089. false, true, true, false, null, null, null, false, false,
  1090. null, null},
  1091. new object [] {"xml", 25, 2147483647, "xml", null,
  1092. "System.String", false, false, false, false, false, true,
  1093. true, false, false, null, null, null, false, false, null, null},
  1094. new object [] {"varchar", 22, 2147483647, "varchar({0})",
  1095. "max length", "System.String", false, true, false, false,
  1096. false, false, true, true, true, null, null, null, false,
  1097. null, "'", "'"},
  1098. new object [] {"char", 3, 2147483647, "char({0})", "length",
  1099. "System.String", false, true, false, true, false, false,
  1100. true, true, true, null, null, null, false, null, "'", "'"},
  1101. new object [] {"nchar", 10, 1073741823, "nchar({0})", "length",
  1102. "System.String", false, true, false, true, false, false,
  1103. true, true, true, null, null, null, false, null, "N'", "'"},
  1104. new object [] {"nvarchar", 12, 1073741823, "nvarchar({0})", "max length",
  1105. "System.String", false, true, false, false, false, false, true, true,
  1106. true, null, null, null, false, null, "N'", "'"},
  1107. new object [] {"varbinary", 21, 1073741823, "varbinary({0})",
  1108. "max length", "System.Byte[]", false, true, false, false,
  1109. false, false, true, true, false, null, null, null, false,
  1110. null, "0x", null},
  1111. new object [] {"uniqueidentifier", 14, 16, "uniqueidentifier", null,
  1112. "System.Guid", false, true, false, true, false, false, true,
  1113. true, false, null, null, null, false, null, "'", "'"}
  1114. };
  1115. static DataTable instance;
  1116. static public DataTable Instance {
  1117. get {
  1118. if (instance == null) {
  1119. instance = new DataTable ("DataTypes");
  1120. foreach (ColumnInfo c in columns)
  1121. instance.Columns.Add (c.name, c.type);
  1122. foreach (object [] row in rows)
  1123. instance.LoadDataRow (row, true);
  1124. }
  1125. return instance;
  1126. }
  1127. }
  1128. }
  1129. static class Restrictions
  1130. {
  1131. static readonly ColumnInfo [] columns = {
  1132. new ColumnInfo ("CollectionName", typeof (string)),
  1133. new ColumnInfo ("RestrictionName", typeof(string)),
  1134. new ColumnInfo ("ParameterName", typeof(string)),
  1135. new ColumnInfo ("RestrictionDefault", typeof(string)),
  1136. new ColumnInfo ("RestrictionNumber", typeof(int))
  1137. };
  1138. static readonly object [][] rows = {
  1139. new object [] {"Users", "User_Name", "@Name", "name", 1},
  1140. new object [] {"Databases", "Name", "@Name", "Name", 1},
  1141. new object [] {"Tables", "Catalog", "@Catalog", "TABLE_CATALOG", 1},
  1142. new object [] {"Tables", "Owner", "@Owner", "TABLE_SCHEMA", 2},
  1143. new object [] {"Tables", "Table", "@Name", "TABLE_NAME", 3},
  1144. new object [] {"Tables", "TableType", "@TableType", "TABLE_TYPE", 4},
  1145. new object [] {"Columns", "Catalog", "@Catalog", "TABLE_CATALOG", 1},
  1146. new object [] {"Columns", "Owner", "@Owner", "TABLE_SCHEMA", 2},
  1147. new object [] {"Columns", "Table", "@Table", "TABLE_NAME", 3},
  1148. new object [] {"Columns", "Column", "@Column", "COLUMN_NAME", 4},
  1149. new object [] {"Views", "Catalog", "@Catalog", "TABLE_CATALOG", 1},
  1150. new object [] {"Views", "Owner", "@Owner", "TABLE_SCHEMA", 2},
  1151. new object [] {"Views", "Table", "@Table", "TABLE_NAME", 3},
  1152. new object [] {"ViewColumns", "Catalog", "@Catalog", "VIEW_CATALOG", 1},
  1153. new object [] {"ViewColumns", "Owner", "@Owner", "VIEW_SCHEMA", 2},
  1154. new object [] {"ViewColumns", "Table", "@Table", "VIEW_NAME", 3},
  1155. new object [] {"ViewColumns", "Column", "@Column", "COLUMN_NAME", 4},
  1156. new object [] {"ProcedureParameters", "Catalog", "@Catalog", "SPECIFIC_CATALOG", 1},
  1157. new object [] {"ProcedureParameters", "Owner", "@Owner", "SPECIFIC_SCHEMA", 2},
  1158. new object [] {"ProcedureParameters", "Name", "@Name", "SPECIFIC_NAME", 3},
  1159. new object [] {"ProcedureParameters", "Parameter", "@Parameter", "PARAMETER_NAME", 4},
  1160. new object [] {"Procedures", "Catalog", "@Catalog", "SPECIFIC_CATALOG", 1},
  1161. new object [] {"Procedures", "Owner", "@Owner", "SPECIFIC_SCHEMA", 2},
  1162. new object [] {"Procedures", "Name", "@Name", "SPECIFIC_NAME", 3},
  1163. new object [] {"Procedures", "Type", "@Type", "ROUTINE_TYPE", 4},
  1164. new object [] {"IndexColumns", "Catalog", "@Catalog", "db_name(}", 1},
  1165. new object [] {"IndexColumns", "Owner", "@Owner", "user_name(}", 2},
  1166. new object [] {"IndexColumns", "Table", "@Table", "o.name", 3},
  1167. new object [] {"IndexColumns", "ConstraintName", "@ConstraintName", "x.name", 4},
  1168. new object [] {"IndexColumns", "Column", "@Column", "c.name", 5},
  1169. new object [] {"Indexes", "Catalog", "@Catalog", "db_name(}", 1},
  1170. new object [] {"Indexes", "Owner", "@Owner", "user_name(}", 2},
  1171. new object [] {"Indexes", "Table", "@Table", "o.name", 3},
  1172. new object [] {"Indexes", "Name", "@Name", "x.name", 4},
  1173. new object [] {"UserDefinedTypes", "assembly_name", "@AssemblyName", "assemblies.name", 1},
  1174. new object [] {"UserDefinedTypes", "udt_name", "@UDTName", "types.assembly_class", 2},
  1175. new object [] {"ForeignKeys", "Catalog", "@Catalog", "CONSTRAINT_CATALOG", 1},
  1176. new object [] {"ForeignKeys", "Owner", "@Owner", "CONSTRAINT_SCHEMA", 2},
  1177. new object [] {"ForeignKeys", "Table", "@Table", "TABLE_NAME", 3},
  1178. new object [] {"ForeignKeys", "Name", "@Name", "CONSTRAINT_NAME", 4}
  1179. };
  1180. static DataTable instance;
  1181. static public DataTable Instance {
  1182. get {
  1183. if (instance == null) {
  1184. instance = new DataTable ("Restrictions");
  1185. foreach (ColumnInfo c in columns)
  1186. instance.Columns.Add (c.name, c.type);
  1187. foreach (object [] row in rows)
  1188. instance.LoadDataRow (row, true);
  1189. }
  1190. return instance;
  1191. }
  1192. }
  1193. }
  1194. public override DataTable GetSchema ()
  1195. {
  1196. return MetaDataCollections.Instance;
  1197. }
  1198. public override DataTable GetSchema (String collectionName)
  1199. {
  1200. return GetSchema (collectionName, null);
  1201. }
  1202. public override DataTable GetSchema (String collectionName, string [] restrictionValues)
  1203. {
  1204. if (collectionName == null)
  1205. //LAMESPEC: In MS.NET, if collectionName is null, it throws ArgumentException.
  1206. throw new ArgumentException ();
  1207. String cName = null;
  1208. DataTable schemaTable = MetaDataCollections.Instance;
  1209. int length = restrictionValues == null ? 0 : restrictionValues.Length;
  1210. foreach (DataRow row in schemaTable.Rows) {
  1211. if (String.Compare ((string) row["CollectionName"], collectionName, true) == 0) {
  1212. if (length > (int) row["NumberOfRestrictions"]) {
  1213. throw new ArgumentException ("More restrictions were provided " +
  1214. "than the requested schema ('" +
  1215. row["CollectionName"].ToString () + "') supports");
  1216. }
  1217. cName = row["CollectionName"].ToString();
  1218. }
  1219. }
  1220. if (cName == null)
  1221. throw new ArgumentException ("The requested collection ('" + collectionName + "') is not defined.");
  1222. SqlCommand command = null;
  1223. DataTable dataTable = new DataTable ();
  1224. SqlDataAdapter dataAdapter = new SqlDataAdapter ();
  1225. switch (cName)
  1226. {
  1227. case "Databases":
  1228. command = new SqlCommand ("select name as database_name, dbid, crdate as create_date " +
  1229. "from master.sys.sysdatabases where (name = @Name or (@Name " +
  1230. "is null))", this);
  1231. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1232. break;
  1233. case "ForeignKeys":
  1234. command = new SqlCommand ("select CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, " +
  1235. "TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE, " +
  1236. "IS_DEFERRABLE, INITIALLY_DEFERRED from " +
  1237. "INFORMATION_SCHEMA.TABLE_CONSTRAINTS where (CONSTRAINT_CATALOG" +
  1238. " = @Catalog or (@Catalog is null)) and (CONSTRAINT_SCHEMA = " +
  1239. "@Owner or (@Owner is null)) and (TABLE_NAME = @Table or (" +
  1240. "@Table is null)) and (CONSTRAINT_NAME = @Name or (@Name is null))" +
  1241. " and CONSTRAINT_TYPE = 'FOREIGN KEY' order by CONSTRAINT_CATALOG," +
  1242. " CONSTRAINT_SCHEMA, CONSTRAINT_NAME", this);
  1243. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1244. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1245. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1246. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1247. break;
  1248. case "Indexes":
  1249. command = new SqlCommand ("select distinct db_name() as constraint_catalog, " +
  1250. "constraint_schema = user_name (o.uid), " +
  1251. "constraint_name = x.name, table_catalog = db_name (), " +
  1252. "table_schema = user_name (o.uid), table_name = o.name, " +
  1253. "index_name = x.name from sysobjects o, sysindexes x, " +
  1254. "sysindexkeys xk where o.type in ('U') and x.id = o.id and " +
  1255. "o.id = xk.id and x.indid = xk.indid and xk.keyno = x.keycnt " +
  1256. "and (db_name() = @Catalog or (@Catalog is null)) and " +
  1257. "(user_name() = @Owner or (@Owner is null)) and (o.name = " +
  1258. "@Table or (@Table is null)) and (x.name = @Name or (@Name is null))" +
  1259. "order by table_name, index_name", this);
  1260. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1261. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1262. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1263. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1264. break;
  1265. case "IndexColumns":
  1266. command = new SqlCommand ("select distinct db_name() as constraint_catalog, " +
  1267. "constraint_schema = user_name (o.uid), constraint_name = x.name, " +
  1268. "table_catalog = db_name (), table_schema = user_name (o.uid), " +
  1269. "table_name = o.name, column_name = c.name, " +
  1270. "ordinal_position = convert (int, xk.keyno), keyType = c.xtype, " +
  1271. "index_name = x.name from sysobjects o, sysindexes x, syscolumns c, " +
  1272. "sysindexkeys xk where o.type in ('U') and x.id = o.id and o.id = c.id " +
  1273. "and o.id = xk.id and x.indid = xk.indid and c.colid = xk.colid " +
  1274. "and xk.keyno <= x.keycnt and permissions (o.id, c.name) <> 0 " +
  1275. "and (db_name() = @Catalog or (@Catalog is null)) and (user_name() " +
  1276. "= @Owner or (@Owner is null)) and (o.name = @Table or (@Table is" +
  1277. " null)) and (x.name = @ConstraintName or (@ConstraintName is null)) " +
  1278. "and (c.name = @Column or (@Column is null)) order by table_name, " +
  1279. "index_name", this);
  1280. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 8);
  1281. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1282. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 13);
  1283. command.Parameters.Add ("@ConstraintName", SqlDbType.NVarChar, 4000);
  1284. command.Parameters.Add ("@Column", SqlDbType.NVarChar, 4000);
  1285. break;
  1286. case "Procedures":
  1287. command = new SqlCommand ("select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, " +
  1288. "ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, " +
  1289. "CREATED, LAST_ALTERED from INFORMATION_SCHEMA.ROUTINES where " +
  1290. "(SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and " +
  1291. "(SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME" +
  1292. " = @Name or (@Name is null)) and (ROUTINE_TYPE = @Type or (@Type " +
  1293. "is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME", this);
  1294. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1295. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1296. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1297. command.Parameters.Add ("@Type", SqlDbType.NVarChar, 4000);
  1298. break;
  1299. case "ProcedureParameters":
  1300. command = new SqlCommand ("select SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, " +
  1301. "ORDINAL_POSITION, PARAMETER_MODE, IS_RESULT, AS_LOCATOR, " +
  1302. "PARAMETER_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, " +
  1303. "CHARACTER_OCTET_LENGTH, COLLATION_CATALOG, COLLATION_SCHEMA, " +
  1304. "COLLATION_NAME, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, " +
  1305. "CHARACTER_SET_NAME, NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, " +
  1306. "NUMERIC_SCALE, DATETIME_PRECISION, INTERVAL_TYPE, " +
  1307. "INTERVAL_PRECISION from INFORMATION_SCHEMA.PARAMETERS where " +
  1308. "(SPECIFIC_CATALOG = @Catalog or (@Catalog is null)) and " +
  1309. "(SPECIFIC_SCHEMA = @Owner or (@Owner is null)) and (SPECIFIC_NAME = " +
  1310. "@Name or (@Name is null)) and (PARAMETER_NAME = @Parameter or (" +
  1311. "@Parameter is null)) order by SPECIFIC_CATALOG, SPECIFIC_SCHEMA," +
  1312. " SPECIFIC_NAME, PARAMETER_NAME", this);
  1313. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1314. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1315. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1316. command.Parameters.Add ("@Parameter", SqlDbType.NVarChar, 4000);
  1317. break;
  1318. case "Tables":
  1319. command = new SqlCommand ("select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE " +
  1320. "from INFORMATION_SCHEMA.TABLES where" +
  1321. " (TABLE_CATALOG = @catalog or (@catalog is null)) and " +
  1322. "(TABLE_SCHEMA = @owner or (@owner is null))and " +
  1323. "(TABLE_NAME = @name or (@name is null)) and " +
  1324. "(TABLE_TYPE = @table_type or (@table_type is null))", this);
  1325. command.Parameters.Add ("@catalog", SqlDbType.NVarChar, 8);
  1326. command.Parameters.Add ("@owner", SqlDbType.NVarChar, 3);
  1327. command.Parameters.Add ("@name", SqlDbType.NVarChar, 11);
  1328. command.Parameters.Add ("@table_type", SqlDbType.NVarChar, 10);
  1329. break;
  1330. case "Columns":
  1331. command = new SqlCommand ("select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, " +
  1332. "ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, " +
  1333. "CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH, " +
  1334. "NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE, " +
  1335. "DATETIME_PRECISION, CHARACTER_SET_CATALOG, CHARACTER_SET_SCHEMA, " +
  1336. "CHARACTER_SET_NAME, COLLATION_CATALOG from INFORMATION_SCHEMA.COLUMNS" +
  1337. " where (TABLE_CATALOG = @Catalog or (@Catalog is null)) and (" +
  1338. "TABLE_SCHEMA = @Owner or (@Owner is null)) and (TABLE_NAME = @table" +
  1339. " or (@Table is null)) and (COLUMN_NAME = @column or (@Column is null" +
  1340. ")) order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME", this);
  1341. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1342. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1343. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1344. command.Parameters.Add ("@Column", SqlDbType.NVarChar, 4000);
  1345. break;
  1346. case "Users":
  1347. command = new SqlCommand ("select uid, name as user_name, createdate, updatedate from sysusers" +
  1348. " where (name = @Name or (@Name is null))", this);
  1349. command.Parameters.Add ("@Name", SqlDbType.NVarChar, 4000);
  1350. break;
  1351. case "Views":
  1352. command = new SqlCommand ("select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, CHECK_OPTION, " +
  1353. "IS_UPDATABLE from INFORMATION_SCHEMA.VIEWS where (TABLE_CATALOG" +
  1354. " = @Catalog or (@Catalog is null)) TABLE_SCHEMA = @Owner or " +
  1355. "(@Owner is null)) and (TABLE_NAME = @table or (@Table is null))" +
  1356. " order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME", this);
  1357. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1358. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1359. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1360. break;
  1361. case "ViewColumns":
  1362. command = new SqlCommand ("select VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME, TABLE_CATALOG, " +
  1363. "TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME from " +
  1364. "INFORMATION_SCHEMA.VIEW_COLUMN_USAGE where (VIEW_CATALOG = " +
  1365. "@Catalog (@Catalog is null)) and (VIEW_SCHEMA = @Owner (@Owner" +
  1366. " is null)) and (VIEW_NAME = @Table or (@Table is null)) and " +
  1367. "(COLUMN_NAME = @Column or (@Column is null)) order by " +
  1368. "VIEW_CATALOG, VIEW_SCHEMA, VIEW_NAME", this);
  1369. command.Parameters.Add ("@Catalog", SqlDbType.NVarChar, 4000);
  1370. command.Parameters.Add ("@Owner", SqlDbType.NVarChar, 4000);
  1371. command.Parameters.Add ("@Table", SqlDbType.NVarChar, 4000);
  1372. command.Parameters.Add ("@Column", SqlDbType.NVarChar, 4000);
  1373. break;
  1374. case "UserDefinedTypes":
  1375. command = new SqlCommand ("select assemblies.name as assembly_name, types.assembly_class " +
  1376. "as udt_name, ASSEMBLYPROPERTY(assemblies.name, 'VersionMajor') " +
  1377. "as version_major, ASSEMBLYPROPERTY(assemblies.name, 'VersionMinor') " +
  1378. "as version_minor, ASSEMBLYPROPERTY(assemblies.name, 'VersionBuild') " +
  1379. "as version_build, ASSEMBLYPROPERTY(assemblies.name, 'VersionRevision') " +
  1380. "as version_revision, ASSEMBLYPROPERTY(assemblies.name, 'CultureInfo') " +
  1381. "as culture_info, ASSEMBLYPROPERTY(assemblies.name, 'PublicKey') " +
  1382. "as public_key, is_fixed_length, max_length, Create_Date, " +
  1383. "Permission_set_desc from sys.assemblies as assemblies join " +
  1384. "sys.assembly_types as types on assemblies.assembly_id = types.assembly_id" +
  1385. " where (assportemblies.name = @AssemblyName or (@AssemblyName is null)) and " +
  1386. "(types.assembly_class = @UDTName or (@UDTName is null))",
  1387. this);
  1388. command.Parameters.Add ("@AssemblyName", SqlDbType.NVarChar, 4000);
  1389. command.Parameters.Add ("@UDTName", SqlDbType.NVarChar, 4000);
  1390. break;
  1391. case "MetaDataCollections":
  1392. return MetaDataCollections.Instance;
  1393. case "DataSourceInformation":
  1394. throw new NotImplementedException ();
  1395. case "DataTypes":
  1396. return DataTypes.Instance;
  1397. case "ReservedWords":
  1398. return ReservedWords.Instance;
  1399. case "Restrictions":
  1400. return Restrictions.Instance;
  1401. }
  1402. for (int i = 0; i < length; i++) {
  1403. command.Parameters[i].Value = restrictionValues[i];
  1404. }
  1405. dataAdapter.SelectCommand = command;
  1406. dataAdapter.Fill (dataTable);
  1407. return dataTable;
  1408. }
  1409. public static void ChangePassword (string connectionString, string newPassword)
  1410. {
  1411. if (connectionString == null || newPassword == null || newPassword == String.Empty)
  1412. throw new ArgumentNullException ();
  1413. if (newPassword.Length > 128)
  1414. throw new ArgumentException ("The value of newPassword exceeds its permittable length which is 128");
  1415. using (SqlConnection conn = new SqlConnection (connectionString)) {
  1416. conn.Open ();
  1417. conn.tds.Execute (String.Format ("sp_password '{0}', '{1}', '{2}'",
  1418. conn.parms.Password, newPassword, conn.parms.User));
  1419. }
  1420. }
  1421. public static void ClearAllPools ()
  1422. {
  1423. Hashtable pools = SqlConnection.sqlConnectionPools.GetConnectionPool ();
  1424. foreach (TdsConnectionPool pool in pools.Values) {
  1425. if (pool != null) {
  1426. pool.ResetConnectionPool ();
  1427. ITds tds = pool.GetConnection ();
  1428. tds.Pooling = false;
  1429. }
  1430. }
  1431. }
  1432. public static void ClearPool (SqlConnection connection)
  1433. {
  1434. if (connection.pooling) {
  1435. connection.pooling = false;
  1436. if (connection.pool != null)
  1437. connection.pool.ResetConnectionPool (connection.Tds);
  1438. }
  1439. }
  1440. #endif // NET_2_0
  1441. #endregion // Methods
  1442. #if NET_2_0
  1443. #region Fields Net 2
  1444. bool async = false;
  1445. #endregion // Fields Net 2
  1446. #region Properties Net 2
  1447. #if NET_1_0
  1448. [DataSysDescription ("Enable Asynchronous processing, 'Asynchrouse Processing=true/false' in the ConnectionString.")]
  1449. #endif
  1450. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1451. internal bool AsyncProcessing {
  1452. get { return async; }
  1453. }
  1454. #endregion // Properties Net 2
  1455. #endif // NET_2_0
  1456. }
  1457. }