SqlConnection.cs 28 KB

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