SqlConnection.cs 27 KB

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