SqlConnection.cs 28 KB

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