2
0

SqlConnection.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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. #if NET_2_0
  47. using System.Data.ProviderBase;
  48. #endif // NET_2_0
  49. using System.EnterpriseServices;
  50. using System.Globalization;
  51. using System.Net;
  52. using System.Net.Sockets;
  53. using System.Text;
  54. using System.Xml;
  55. namespace System.Data.SqlClient {
  56. [DefaultEvent ("InfoMessage")]
  57. #if NET_2_0
  58. public sealed class SqlConnection : DbConnectionBase, IDbConnection, ICloneable
  59. #else
  60. public sealed class SqlConnection : Component, IDbConnection, ICloneable
  61. #endif // NET_2_0
  62. {
  63. #region Fields
  64. bool disposed = false;
  65. // The set of SQL connection pools
  66. static TdsConnectionPoolManager sqlConnectionPools = new TdsConnectionPoolManager (TdsVersion.tds70);
  67. // The current connection pool
  68. TdsConnectionPool pool;
  69. // The connection string that identifies this connection
  70. string connectionString = null;
  71. // The transaction object for the current transaction
  72. SqlTransaction transaction = null;
  73. // Connection parameters
  74. TdsConnectionParameters parms = new TdsConnectionParameters ();
  75. NameValueCollection connStringParameters = null;
  76. bool connectionReset;
  77. bool pooling;
  78. string dataSource;
  79. int connectionTimeout;
  80. int minPoolSize;
  81. int maxPoolSize;
  82. int packetSize;
  83. int port = 1433;
  84. // The current state
  85. ConnectionState state = ConnectionState.Closed;
  86. SqlDataReader dataReader = null;
  87. XmlReader xmlReader = null;
  88. // The TDS object
  89. ITds tds;
  90. #endregion // Fields
  91. #region Constructors
  92. public SqlConnection ()
  93. : this (String.Empty)
  94. {
  95. }
  96. public SqlConnection (string connectionString)
  97. {
  98. Init (connectionString);
  99. }
  100. #if NET_2_0
  101. internal SqlConnection (DbConnectionFactory connectionFactory) : base (connectionFactory)
  102. {
  103. Init (String.Empty);
  104. }
  105. #endif //NET_2_0
  106. private void Init (string connectionString)
  107. {
  108. connectionTimeout = 15; // default timeout
  109. dataSource = ""; // default datasource
  110. packetSize = 8192; // default packetsize
  111. ConnectionString = connectionString;
  112. }
  113. #endregion // Constructors
  114. #region Properties
  115. [DataCategory ("Data")]
  116. [DataSysDescription ("Information used to connect to a DataSource, such as 'Data Source=x;Initial Catalog=x;Integrated Security=SSPI'.")]
  117. [DefaultValue ("")]
  118. [EditorAttribute ("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  119. [RecommendedAsConfigurable (true)]
  120. [RefreshProperties (RefreshProperties.All)]
  121. [MonoTODO("persist security info, encrypt, enlist and , attachdbfilename keyword not implemented")]
  122. public
  123. #if NET_2_0
  124. override
  125. #endif // NET_2_0
  126. string ConnectionString {
  127. get { return connectionString; }
  128. set {
  129. if (state == ConnectionState.Open)
  130. throw new InvalidOperationException ("Not Allowed to change ConnectionString property while Connection state is OPEN");
  131. SetConnectionString (value);
  132. }
  133. }
  134. [DataSysDescription ("Current connection timeout value, 'Connect Timeout=X' in the ConnectionString.")]
  135. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  136. public
  137. #if NET_2_0
  138. override
  139. #endif // NET_2_0
  140. int ConnectionTimeout {
  141. get { return connectionTimeout; }
  142. }
  143. [DataSysDescription ("Current SQL Server database, 'Initial Catalog=X' in the connection string.")]
  144. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  145. public
  146. #if NET_2_0
  147. override
  148. #endif // NET_2_0
  149. string Database {
  150. get {
  151. if (State == ConnectionState.Open)
  152. return tds.Database;
  153. return parms.Database ;
  154. }
  155. }
  156. internal SqlDataReader DataReader {
  157. get { return dataReader; }
  158. set { dataReader = value; }
  159. }
  160. [DataSysDescription ("Current SqlServer that the connection is opened to, 'Data Source=X' in the connection string. ")]
  161. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  162. public
  163. #if NET_2_0
  164. override
  165. #endif // NET_2_0
  166. string DataSource {
  167. get { return dataSource; }
  168. }
  169. [DataSysDescription ("Network packet size, 'Packet Size=x' in the connection string.")]
  170. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  171. public int PacketSize {
  172. get { return packetSize; }
  173. }
  174. [Browsable (false)]
  175. [DataSysDescription ("Version of the SQL Server accessed by the SqlConnection.")]
  176. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  177. public
  178. #if NET_2_0
  179. override
  180. #endif // NET_2_0
  181. string ServerVersion {
  182. get {
  183. if (state == ConnectionState.Closed)
  184. throw new InvalidOperationException ("Invalid Operation.The Connection is Closed");
  185. else
  186. return tds.ServerVersion;
  187. }
  188. }
  189. [Browsable (false)]
  190. [DataSysDescription ("The ConnectionState indicating whether the connection is open or closed.")]
  191. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  192. public
  193. #if NET_2_0
  194. override
  195. #endif // NET_2_0
  196. ConnectionState State {
  197. get { return state; }
  198. }
  199. internal ITds Tds {
  200. get { return tds; }
  201. }
  202. internal SqlTransaction Transaction {
  203. get { return transaction; }
  204. set { transaction = value; }
  205. }
  206. [DataSysDescription ("Workstation Id, 'Workstation ID=x' in the connection string.")]
  207. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  208. public string WorkstationId {
  209. get { return parms.Hostname; }
  210. }
  211. internal XmlReader XmlReader {
  212. get { return xmlReader; }
  213. set { xmlReader = value; }
  214. }
  215. #endregion // Properties
  216. #region Events
  217. [DataCategory ("InfoMessage")]
  218. [DataSysDescription ("Event triggered when messages arrive from the DataSource.")]
  219. public event SqlInfoMessageEventHandler InfoMessage;
  220. [DataCategory ("StateChange")]
  221. [DataSysDescription ("Event triggered when the connection changes state.")]
  222. public
  223. #if NET_2_0
  224. override
  225. #endif // NET_2_0
  226. event StateChangeEventHandler StateChange;
  227. #endregion // Events
  228. #region Delegates
  229. private void ErrorHandler (object sender, TdsInternalErrorMessageEventArgs e)
  230. {
  231. throw new SqlException (e.Class, e.LineNumber, e.Message, e.Number, e.Procedure, e.Server, "Mono SqlClient Data Provider", e.State);
  232. }
  233. private void MessageHandler (object sender, TdsInternalInfoMessageEventArgs e)
  234. {
  235. OnSqlInfoMessage (CreateSqlInfoMessageEvent (e.Errors));
  236. }
  237. #endregion // Delegates
  238. #region Methods
  239. internal string GetConnStringKeyValue (params string [] keys)
  240. {
  241. if (connStringParameters == null || connStringParameters.Count == 0)
  242. return "";
  243. foreach (string key in keys) {
  244. string value = connStringParameters [key];
  245. if (value != null)
  246. return value;
  247. }
  248. return "";
  249. }
  250. public new SqlTransaction BeginTransaction ()
  251. {
  252. return BeginTransaction (IsolationLevel.ReadCommitted, String.Empty);
  253. }
  254. public new SqlTransaction BeginTransaction (IsolationLevel iso)
  255. {
  256. return BeginTransaction (iso, String.Empty);
  257. }
  258. public SqlTransaction BeginTransaction (string transactionName)
  259. {
  260. return BeginTransaction (IsolationLevel.ReadCommitted, transactionName);
  261. }
  262. public SqlTransaction BeginTransaction (IsolationLevel iso, string transactionName)
  263. {
  264. if (state == ConnectionState.Closed)
  265. throw new InvalidOperationException ("The connection is not open.");
  266. if (transaction != null)
  267. throw new InvalidOperationException ("SqlConnection does not support parallel transactions.");
  268. if (iso == IsolationLevel.Chaos)
  269. throw new ArgumentException ("Invalid IsolationLevel parameter: must be ReadCommitted, ReadUncommitted, RepeatableRead, or Serializable.");
  270. string isolevel = String.Empty;
  271. switch (iso) {
  272. case IsolationLevel.ReadCommitted:
  273. isolevel = "READ COMMITTED";
  274. break;
  275. case IsolationLevel.ReadUncommitted:
  276. isolevel = "READ UNCOMMITTED";
  277. break;
  278. case IsolationLevel.RepeatableRead:
  279. isolevel = "REPEATABLE READ";
  280. break;
  281. case IsolationLevel.Serializable:
  282. isolevel = "SERIALIZABLE";
  283. break;
  284. }
  285. tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0};BEGIN TRANSACTION {1}", isolevel, transactionName));
  286. transaction = new SqlTransaction (this, iso);
  287. return transaction;
  288. }
  289. public
  290. #if NET_2_0
  291. override
  292. #endif // NET_2_0
  293. void ChangeDatabase (string database)
  294. {
  295. if (!IsValidDatabaseName (database))
  296. throw new ArgumentException (String.Format ("The database name {0} is not valid.", database));
  297. if (state != ConnectionState.Open)
  298. throw new InvalidOperationException ("The connection is not open.");
  299. tds.Execute (String.Format ("use [{0}]", database));
  300. }
  301. private void ChangeState (ConnectionState currentState)
  302. {
  303. ConnectionState originalState = state;
  304. state = currentState;
  305. OnStateChange (CreateStateChangeEvent (originalState, currentState));
  306. }
  307. public
  308. #if NET_2_0
  309. override
  310. #endif // NET_2_0
  311. void Close ()
  312. {
  313. if (transaction != null && transaction.IsOpen)
  314. transaction.Rollback ();
  315. if (dataReader != null || xmlReader != null) {
  316. if(tds != null) tds.SkipToEnd ();
  317. dataReader = null;
  318. xmlReader = null;
  319. }
  320. if (pooling) {
  321. if(pool != null) pool.ReleaseConnection (tds);
  322. }else
  323. if(tds != null) tds.Disconnect ();
  324. if(tds != null) {
  325. tds.TdsErrorMessage -= new TdsInternalErrorMessageEventHandler (ErrorHandler);
  326. tds.TdsInfoMessage -= new TdsInternalInfoMessageEventHandler (MessageHandler);
  327. }
  328. ChangeState (ConnectionState.Closed);
  329. }
  330. public new SqlCommand CreateCommand ()
  331. {
  332. SqlCommand command = new SqlCommand ();
  333. command.Connection = this;
  334. return command;
  335. }
  336. private SqlInfoMessageEventArgs CreateSqlInfoMessageEvent (TdsInternalErrorCollection errors)
  337. {
  338. return new SqlInfoMessageEventArgs (errors);
  339. }
  340. private StateChangeEventArgs CreateStateChangeEvent (ConnectionState originalState, ConnectionState currentState)
  341. {
  342. return new StateChangeEventArgs (originalState, currentState);
  343. }
  344. protected override void Dispose (bool disposing)
  345. {
  346. if (!disposed) {
  347. try {
  348. if (disposing) {
  349. if (State == ConnectionState.Open)
  350. Close ();
  351. parms.Reset ();
  352. ConnectionString = "";
  353. SetDefaultConnectionParameters (this.connStringParameters);
  354. }
  355. } finally {
  356. disposed = true;
  357. base.Dispose (disposing);
  358. }
  359. }
  360. }
  361. [MonoTODO ("Not sure what this means at present.")]
  362. public
  363. #if NET_2_0
  364. override
  365. #endif // NET_2_0
  366. void EnlistDistributedTransaction (ITransaction transaction)
  367. {
  368. throw new NotImplementedException ();
  369. }
  370. object ICloneable.Clone ()
  371. {
  372. return new SqlConnection (ConnectionString);
  373. }
  374. IDbTransaction IDbConnection.BeginTransaction ()
  375. {
  376. return BeginTransaction ();
  377. }
  378. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso)
  379. {
  380. return BeginTransaction (iso);
  381. }
  382. IDbCommand IDbConnection.CreateCommand ()
  383. {
  384. return CreateCommand ();
  385. }
  386. void IDisposable.Dispose ()
  387. {
  388. Dispose (true);
  389. GC.SuppressFinalize (this);
  390. }
  391. ~SqlConnection ()
  392. {
  393. Dispose (false);
  394. }
  395. public
  396. #if NET_2_0
  397. override
  398. #endif // NET_2_0
  399. void Open ()
  400. {
  401. string serverName = "";
  402. if (state == ConnectionState.Open)
  403. throw new InvalidOperationException ("The Connection is already Open (State=Open)");
  404. if (connectionString == null)
  405. throw new InvalidOperationException ("Connection string has not been initialized.");
  406. try {
  407. if (!pooling) {
  408. if(!ParseDataSource (dataSource, out port, out serverName))
  409. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  410. tds = new Tds70 (serverName, port, PacketSize, ConnectionTimeout);
  411. }
  412. else {
  413. if(!ParseDataSource (dataSource, out port, out serverName))
  414. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  415. TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize);
  416. pool = sqlConnectionPools.GetConnectionPool (connectionString, info);
  417. tds = pool.GetConnection ();
  418. }
  419. } catch (TdsTimeoutException e) {
  420. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  421. }catch (TdsInternalException e) {
  422. throw SqlException.FromTdsInternalException (e);
  423. }
  424. tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
  425. tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);
  426. if (!tds.IsConnected) {
  427. try {
  428. tds.Connect (parms);
  429. }
  430. catch {
  431. if (pooling)
  432. pool.ReleaseConnection (tds);
  433. throw;
  434. }
  435. } else if (connectionReset) {
  436. tds.Reset ();
  437. }
  438. disposed = false; // reset this, so using () would call Close ().
  439. ChangeState (ConnectionState.Open);
  440. }
  441. private bool ParseDataSource (string theDataSource, out int thePort, out string theServerName)
  442. {
  443. theServerName = "";
  444. string theInstanceName = "";
  445. if (theDataSource == null)
  446. throw new ArgumentException("Format of initialization string doesnot conform to specifications");
  447. thePort = 1433; // default TCP port for SQL Server
  448. bool success = true;
  449. int idx = 0;
  450. if ((idx = theDataSource.IndexOf (",")) > -1) {
  451. theServerName = theDataSource.Substring (0, idx);
  452. string p = theDataSource.Substring (idx + 1);
  453. thePort = Int32.Parse (p);
  454. }
  455. else if ((idx = theDataSource.IndexOf ("\\")) > -1) {
  456. theServerName = theDataSource.Substring (0, idx);
  457. theInstanceName = theDataSource.Substring (idx + 1);
  458. // do port discovery via UDP port 1434
  459. port = DiscoverTcpPortViaSqlMonitor (theServerName, theInstanceName);
  460. if (port == -1)
  461. success = false;
  462. }
  463. else if (theDataSource == "" || theDataSource == "(local)")
  464. theServerName = "localhost";
  465. else
  466. theServerName = theDataSource;
  467. return success;
  468. }
  469. private bool ConvertIntegratedSecurity (string value)
  470. {
  471. if (value.ToUpper() == "SSPI")
  472. {
  473. return true;
  474. }
  475. return ConvertToBoolean("integrated security", value);
  476. }
  477. private bool ConvertToBoolean(string key, string value)
  478. {
  479. string upperValue = value.ToUpper();
  480. if (upperValue == "TRUE" ||upperValue == "YES")
  481. {
  482. return true;
  483. }
  484. else if (upperValue == "FALSE" || upperValue == "NO")
  485. {
  486. return false;
  487. }
  488. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  489. "Invalid value \"{0}\" for key '{1}'.", value, key));
  490. }
  491. private int ConvertToInt32(string key, string value)
  492. {
  493. try
  494. {
  495. return int.Parse(value);
  496. }
  497. catch (Exception ex)
  498. {
  499. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  500. "Invalid value \"{0}\" for key '{1}'.", value, key));
  501. }
  502. }
  503. private int DiscoverTcpPortViaSqlMonitor(string ServerName, string InstanceName)
  504. {
  505. SqlMonitorSocket msock;
  506. msock = new SqlMonitorSocket (ServerName, InstanceName);
  507. int SqlServerPort = msock.DiscoverTcpPort ();
  508. msock = null;
  509. return SqlServerPort;
  510. }
  511. void SetConnectionString (string connectionString)
  512. {
  513. NameValueCollection parameters = new NameValueCollection ();
  514. SetDefaultConnectionParameters (parameters);
  515. if ((connectionString == null) || (connectionString.Length == 0)) {
  516. this.connectionString = connectionString;
  517. return;
  518. }
  519. connectionString += ";";
  520. bool inQuote = false;
  521. bool inDQuote = false;
  522. bool inName = true;
  523. string name = String.Empty;
  524. string value = String.Empty;
  525. StringBuilder sb = new StringBuilder ();
  526. for (int i = 0; i < connectionString.Length; i += 1) {
  527. char c = connectionString [i];
  528. char peek;
  529. if (i == connectionString.Length - 1)
  530. peek = '\0';
  531. else
  532. peek = connectionString [i + 1];
  533. switch (c) {
  534. case '\'':
  535. if (inDQuote)
  536. sb.Append (c);
  537. else if (peek.Equals (c)) {
  538. sb.Append (c);
  539. i += 1;
  540. }
  541. else
  542. inQuote = !inQuote;
  543. break;
  544. case '"':
  545. if (inQuote)
  546. sb.Append (c);
  547. else if (peek.Equals (c)) {
  548. sb.Append (c);
  549. i += 1;
  550. }
  551. else
  552. inDQuote = !inDQuote;
  553. break;
  554. case ';':
  555. if (inDQuote || inQuote)
  556. sb.Append (c);
  557. else {
  558. if (name != String.Empty && name != null) {
  559. value = sb.ToString ();
  560. SetProperties (name.ToUpper ().Trim() , value);
  561. parameters [name.ToUpper ().Trim ()] = value.Trim ();
  562. }
  563. else if (sb.Length != 0)
  564. throw new ArgumentException ("Format of initialization string doesnot conform to specifications");
  565. inName = true;
  566. name = String.Empty;
  567. value = String.Empty;
  568. sb = new StringBuilder ();
  569. }
  570. break;
  571. case '=':
  572. if (inDQuote || inQuote || !inName)
  573. sb.Append (c);
  574. else if (peek.Equals (c)) {
  575. sb.Append (c);
  576. i += 1;
  577. }
  578. else {
  579. name = sb.ToString ();
  580. sb = new StringBuilder ();
  581. inName = false;
  582. }
  583. break;
  584. case ' ':
  585. if (inQuote || inDQuote)
  586. sb.Append (c);
  587. else if (sb.Length > 0 && !peek.Equals (';'))
  588. sb.Append (c);
  589. break;
  590. default:
  591. sb.Append (c);
  592. break;
  593. }
  594. }
  595. connectionString = connectionString.Substring (0 , connectionString.Length-1);
  596. this.connectionString = connectionString;
  597. this.connStringParameters = parameters;
  598. }
  599. void SetDefaultConnectionParameters (NameValueCollection parameters)
  600. {
  601. parms.Reset ();
  602. dataSource = "";
  603. connectionTimeout= 15;
  604. connectionReset = true;
  605. pooling = true;
  606. maxPoolSize = 100;
  607. minPoolSize = 0;
  608. packetSize = 8192;
  609. parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
  610. parameters["CONNECT TIMEOUT"] = "15";
  611. parameters["CONNECTION LIFETIME"] = "0";
  612. parameters["CONNECTION RESET"] = "true";
  613. parameters["ENLIST"] = "true";
  614. parameters["INTEGRATED SECURITY"] = "false";
  615. parameters["INITIAL CATALOG"] = "";
  616. parameters["MAX POOL SIZE"] = "100";
  617. parameters["MIN POOL SIZE"] = "0";
  618. parameters["NETWORK LIBRARY"] = "dbmssocn";
  619. parameters["PACKET SIZE"] = "8192";
  620. parameters["PERSIST SECURITY INFO"] = "false";
  621. parameters["POOLING"] = "true";
  622. parameters["WORKSTATION ID"] = Dns.GetHostName();
  623. #if NET_2_0
  624. async = false;
  625. parameters ["ASYNCHRONOUS PROCESSING"] = "false";
  626. #endif
  627. }
  628. private void SetProperties (string name , string value)
  629. {
  630. switch (name)
  631. {
  632. case "APP" :
  633. case "APPLICATION NAME" :
  634. parms.ApplicationName = value;
  635. break;
  636. case "ATTACHDBFILENAME" :
  637. case "EXTENDED PROPERTIES" :
  638. case "INITIAL FILE NAME" :
  639. throw new NotImplementedException("Attachable database support is not implemented.");
  640. case "TIMEOUT" :
  641. case "CONNECT TIMEOUT" :
  642. case "CONNECTION TIMEOUT" :
  643. int tmpTimeout = ConvertToInt32 ("connection timeout", value);
  644. if (tmpTimeout < 0)
  645. throw new ArgumentException ("Invalid CONNECTION TIMEOUT .. Must be an integer >=0 ");
  646. else
  647. connectionTimeout = tmpTimeout;
  648. break;
  649. case "CONNECTION LIFETIME" :
  650. break;
  651. case "CONNECTION RESET" :
  652. connectionReset = ConvertToBoolean ("connection reset", value);
  653. break;
  654. case "LANGUAGE" :
  655. case "CURRENT LANGUAGE" :
  656. parms.Language = value;
  657. break;
  658. case "DATA SOURCE" :
  659. case "SERVER" :
  660. case "ADDRESS" :
  661. case "ADDR" :
  662. case "NETWORK ADDRESS" :
  663. dataSource = value;
  664. break;
  665. case "ENCRYPT":
  666. if (ConvertToBoolean("encrypt", value))
  667. {
  668. throw new NotImplementedException("SSL encryption for"
  669. + " data sent between client and server is not"
  670. + " implemented.");
  671. }
  672. break;
  673. case "ENLIST" :
  674. if (!ConvertToBoolean("enlist", value))
  675. {
  676. throw new NotImplementedException("Disabling the automatic"
  677. + " enlistment of connections in the thread's current"
  678. + " transaction context is not implemented.");
  679. }
  680. break;
  681. case "INITIAL CATALOG" :
  682. case "DATABASE" :
  683. parms.Database = value;
  684. break;
  685. case "INTEGRATED SECURITY" :
  686. case "TRUSTED_CONNECTION" :
  687. parms.DomainLogin = ConvertIntegratedSecurity(value);
  688. break;
  689. case "MAX POOL SIZE" :
  690. int tmpMaxPoolSize = ConvertToInt32 ("max pool size" , value);
  691. if (tmpMaxPoolSize < 0)
  692. throw new ArgumentException ("Invalid MAX POOL SIZE. Must be a intger >= 0");
  693. else
  694. maxPoolSize = tmpMaxPoolSize;
  695. break;
  696. case "MIN POOL SIZE" :
  697. int tmpMinPoolSize = ConvertToInt32 ("min pool size" , value);
  698. if (tmpMinPoolSize < 0)
  699. throw new ArgumentException ("Invalid MIN POOL SIZE. Must be a intger >= 0");
  700. else
  701. minPoolSize = tmpMinPoolSize;
  702. break;
  703. #if NET_2_0
  704. case "MULTIPLEACTIVERESULTSETS":
  705. break;
  706. case "ASYNCHRONOUS PROCESSING" :
  707. case "ASYNC" :
  708. async = ConvertToBoolean (name, value);
  709. break;
  710. #endif
  711. case "NET" :
  712. case "NETWORK" :
  713. case "NETWORK LIBRARY" :
  714. if (!value.ToUpper ().Equals ("DBMSSOCN"))
  715. throw new ArgumentException ("Unsupported network library.");
  716. break;
  717. case "PACKET SIZE" :
  718. int tmpPacketSize = ConvertToInt32 ("packet size", value);
  719. if (tmpPacketSize < 512 || tmpPacketSize > 32767)
  720. throw new ArgumentException ("Invalid PACKET SIZE. The integer must be between 512 and 32767");
  721. else
  722. packetSize = tmpPacketSize;
  723. break;
  724. case "PASSWORD" :
  725. case "PWD" :
  726. parms.Password = value;
  727. break;
  728. case "PERSISTSECURITYINFO" :
  729. case "PERSIST SECURITY INFO" :
  730. // FIXME : not implemented
  731. throw new NotImplementedException ();
  732. break;
  733. case "POOLING" :
  734. pooling = ConvertToBoolean("pooling", value);
  735. break;
  736. case "UID" :
  737. case "USER" :
  738. case "USER ID" :
  739. parms.User = value;
  740. break;
  741. case "WSID" :
  742. case "WORKSTATION ID" :
  743. parms.Hostname = value;
  744. break;
  745. default :
  746. throw new ArgumentException("Keyword not supported :"+name);
  747. }
  748. }
  749. static bool IsValidDatabaseName (string database)
  750. {
  751. if ( database == null || database.Trim() == String.Empty || database.Length > 128)
  752. return false ;
  753. if (database[0] == '"' && database[database.Length] == '"')
  754. database = database.Substring (1, database.Length - 2);
  755. else if (Char.IsDigit (database[0]))
  756. return false;
  757. if (database[0] == '_')
  758. return false;
  759. foreach (char c in database.Substring (1, database.Length - 1))
  760. if (!Char.IsLetterOrDigit (c) && c != '_' && c != '-')
  761. return false;
  762. return true;
  763. }
  764. private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
  765. {
  766. if (InfoMessage != null)
  767. InfoMessage (this, value);
  768. }
  769. private void OnStateChange (StateChangeEventArgs value)
  770. {
  771. if (StateChange != null)
  772. StateChange (this, value);
  773. }
  774. private sealed class SqlMonitorSocket : UdpClient
  775. {
  776. // UDP port that the SQL Monitor listens
  777. private static readonly int SqlMonitorUdpPort = 1434;
  778. private static readonly string SqlServerNotExist = "SQL Server does not exist or access denied";
  779. private string server;
  780. private string instance;
  781. internal SqlMonitorSocket (string ServerName, string InstanceName)
  782. : base (ServerName, SqlMonitorUdpPort)
  783. {
  784. server = ServerName;
  785. instance = InstanceName;
  786. }
  787. internal int DiscoverTcpPort ()
  788. {
  789. int SqlServerTcpPort;
  790. Client.Blocking = false;
  791. // send command to UDP 1434 (SQL Monitor) to get
  792. // the TCP port to connect to the MS SQL server
  793. ASCIIEncoding enc = new ASCIIEncoding ();
  794. Byte[] rawrq = new Byte [instance.Length + 1];
  795. rawrq[0] = 4;
  796. enc.GetBytes (instance, 0, instance.Length, rawrq, 1);
  797. int bytes = Send (rawrq, rawrq.Length);
  798. if (!Active)
  799. return -1; // Error
  800. bool result;
  801. result = Client.Poll (100, SelectMode.SelectRead);
  802. if (result == false)
  803. return -1; // Error
  804. if (Client.Available <= 0)
  805. return -1; // Error
  806. IPEndPoint endpoint = new IPEndPoint (Dns.GetHostByName ("localhost").AddressList [0], 0);
  807. Byte [] rawrs;
  808. rawrs = Receive (ref endpoint);
  809. string rs = Encoding.ASCII.GetString (rawrs);
  810. string[] rawtokens = rs.Split (';');
  811. Hashtable data = new Hashtable ();
  812. for (int i = 0; i < rawtokens.Length / 2 && i < 256; i++) {
  813. data [rawtokens [i * 2]] = rawtokens [ i * 2 + 1];
  814. }
  815. if (!data.ContainsKey ("tcp"))
  816. throw new NotImplementedException ("Only TCP/IP is supported.");
  817. SqlServerTcpPort = int.Parse ((string) data ["tcp"]);
  818. Close ();
  819. return SqlServerTcpPort;
  820. }
  821. }
  822. #endregion // Methods
  823. #if NET_2_0
  824. #region Fields Net 2
  825. bool async = false;
  826. #endregion // Fields Net 2
  827. #region Properties Net 2
  828. [DataSysDescription ("Enable Asynchronous processing, 'Asynchrouse Processing=true/false' in the ConnectionString.")]
  829. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  830. internal bool AsyncProcessing {
  831. get { return async; }
  832. }
  833. #endregion // Properties Net 2
  834. #endif // NET_2_0
  835. }
  836. }