SqlConnection.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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. }
  409. catch (TdsTimeoutException e) {
  410. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  411. }
  412. tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
  413. tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);
  414. if (!tds.IsConnected) {
  415. try {
  416. tds.Connect (parms);
  417. }
  418. catch {
  419. if (pooling)
  420. pool.ReleaseConnection (tds);
  421. throw;
  422. }
  423. }
  424. /* Not sure ebout removing these 2 lines.
  425. * The command that gets to the sql server is just
  426. * 'sp_reset_connection' and it fails.
  427. * Either remove them definitely or fix it
  428. else if (connectionReset)
  429. tds.ExecProc ("sp_reset_connection");
  430. */
  431. disposed = false; // reset this, so using () would call Close ().
  432. ChangeState (ConnectionState.Open);
  433. }
  434. private bool ParseDataSource (string theDataSource, out int thePort, out string theServerName)
  435. {
  436. theServerName = "";
  437. string theInstanceName = "";
  438. if ((theDataSource == null) || (theServerName == null)
  439. || theDataSource == "")
  440. throw new ArgumentException("Format of initialization string doesnot conform to specifications");
  441. thePort = 1433; // default TCP port for SQL Server
  442. bool success = true;
  443. int idx = 0;
  444. if ((idx = theDataSource.IndexOf (",")) > -1) {
  445. theServerName = theDataSource.Substring (0, idx);
  446. string p = theDataSource.Substring (idx + 1);
  447. thePort = Int32.Parse (p);
  448. }
  449. else if ((idx = theDataSource.IndexOf ("\\")) > -1) {
  450. theServerName = theDataSource.Substring (0, idx);
  451. theInstanceName = theDataSource.Substring (idx + 1);
  452. // do port discovery via UDP port 1434
  453. port = DiscoverTcpPortViaSqlMonitor (theServerName, theInstanceName);
  454. if (port == -1)
  455. success = false;
  456. }
  457. else {
  458. theServerName = theDataSource;
  459. }
  460. if(theServerName.Equals("(local)"))
  461. theServerName = "localhost";
  462. return success;
  463. }
  464. private bool ConvertIntegratedSecurity (string value)
  465. {
  466. if (value.ToUpper() == "SSPI")
  467. {
  468. return true;
  469. }
  470. return ConvertToBoolean("integrated security", value);
  471. }
  472. private bool ConvertToBoolean(string key, string value)
  473. {
  474. string upperValue = value.ToUpper();
  475. if (upperValue == "TRUE" ||upperValue == "YES")
  476. {
  477. return true;
  478. }
  479. else if (upperValue == "FALSE" || upperValue == "NO")
  480. {
  481. return false;
  482. }
  483. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  484. "Invalid value \"{0}\" for key '{1}'.", value, key));
  485. }
  486. private int ConvertToInt32(string key, string value)
  487. {
  488. try
  489. {
  490. return int.Parse(value);
  491. }
  492. catch (Exception ex)
  493. {
  494. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  495. "Invalid value \"{0}\" for key '{1}'.", value, key));
  496. }
  497. }
  498. private int DiscoverTcpPortViaSqlMonitor(string ServerName, string InstanceName)
  499. {
  500. SqlMonitorSocket msock;
  501. msock = new SqlMonitorSocket (ServerName, InstanceName);
  502. int SqlServerPort = msock.DiscoverTcpPort ();
  503. msock = null;
  504. return SqlServerPort;
  505. }
  506. void SetConnectionString (string connectionString)
  507. {
  508. if (( connectionString == null)||( connectionString.Length == 0)) {
  509. this.connectionString = null;
  510. return;
  511. }
  512. NameValueCollection parameters = new NameValueCollection ();
  513. connectionString += ";";
  514. SetDefaultConnectionParameters (parameters);
  515. bool inQuote = false;
  516. bool inDQuote = false;
  517. bool inName = true;
  518. string name = String.Empty;
  519. string value = String.Empty;
  520. StringBuilder sb = new StringBuilder ();
  521. for (int i = 0; i < connectionString.Length; i += 1) {
  522. char c = connectionString [i];
  523. char peek;
  524. if (i == connectionString.Length - 1)
  525. peek = '\0';
  526. else
  527. peek = connectionString [i + 1];
  528. switch (c) {
  529. case '\'':
  530. if (inDQuote)
  531. sb.Append (c);
  532. else if (peek.Equals (c)) {
  533. sb.Append (c);
  534. i += 1;
  535. }
  536. else
  537. inQuote = !inQuote;
  538. break;
  539. case '"':
  540. if (inQuote)
  541. sb.Append (c);
  542. else if (peek.Equals (c)) {
  543. sb.Append (c);
  544. i += 1;
  545. }
  546. else
  547. inDQuote = !inDQuote;
  548. break;
  549. case ';':
  550. if (inDQuote || inQuote)
  551. sb.Append (c);
  552. else {
  553. if (name != String.Empty && name != null) {
  554. value = sb.ToString ();
  555. parameters [name.ToUpper ().Trim ()] = value.Trim ();
  556. }
  557. inName = true;
  558. name = String.Empty;
  559. value = String.Empty;
  560. sb = new StringBuilder ();
  561. }
  562. break;
  563. case '=':
  564. if (inDQuote || inQuote || !inName)
  565. sb.Append (c);
  566. else if (peek.Equals (c)) {
  567. sb.Append (c);
  568. i += 1;
  569. }
  570. else {
  571. name = sb.ToString ();
  572. sb = new StringBuilder ();
  573. inName = false;
  574. }
  575. break;
  576. case ' ':
  577. if (inQuote || inDQuote)
  578. sb.Append (c);
  579. else if (sb.Length > 0 && !peek.Equals (';'))
  580. sb.Append (c);
  581. break;
  582. default:
  583. sb.Append (c);
  584. break;
  585. }
  586. }
  587. SetProperties (parameters);
  588. this.connectionString = connectionString;
  589. this.connStringParameters = parameters;
  590. }
  591. void SetDefaultConnectionParameters (NameValueCollection parameters)
  592. {
  593. if (null == parameters.Get ("APPLICATION NAME") && null == parameters.Get ("APP"))
  594. parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
  595. if (null == parameters.Get ("TIMEOUT") && null == parameters.Get ("CONNECT TIMEOUT") && null == parameters.Get ("CONNECTION TIMEOUT"))
  596. parameters["CONNECT TIMEOUT"] = "15";
  597. if (null == parameters.Get ("CONNECTION LIFETIME"))
  598. parameters["CONNECTION LIFETIME"] = "0";
  599. if (null == parameters.Get ("CONNECTION RESET"))
  600. parameters["CONNECTION RESET"] = "true";
  601. if (null == parameters.Get ("ENLIST"))
  602. parameters["ENLIST"] = "true";
  603. if (null == parameters.Get ("INTEGRATED SECURITY") && null == parameters.Get ("TRUSTED_CONNECTION"))
  604. parameters["INTEGRATED SECURITY"] = "false";
  605. if (null == parameters.Get ("MAX POOL SIZE"))
  606. parameters["MAX POOL SIZE"] = "100";
  607. if (null == parameters.Get ("MIN POOL SIZE"))
  608. parameters["MIN POOL SIZE"] = "0";
  609. if (null == parameters.Get ("NETWORK LIBRARY") && null == parameters.Get ("NET") && null == parameters.Get ("NETWORK"))
  610. parameters["NETWORK LIBRARY"] = "dbmssocn";
  611. if (null == parameters.Get ("PACKET SIZE"))
  612. parameters["PACKET SIZE"] = "512";
  613. if (null == parameters.Get ("PERSIST SECURITY INFO") && null == parameters.Get ("PERSISTSECURITYINFO"))
  614. parameters["PERSIST SECURITY INFO"] = "false";
  615. if (null == parameters.Get ("POOLING"))
  616. parameters["POOLING"] = "true";
  617. if (null == parameters.Get ("WORKSTATION ID") && null == parameters.Get ("WSID"))
  618. parameters["WORKSTATION ID"] = Dns.GetHostName();
  619. }
  620. private void SetProperties (NameValueCollection parameters)
  621. {
  622. foreach (string name in parameters) {
  623. string value = parameters[name];
  624. switch (name) {
  625. case "APP" :
  626. case "APPLICATION NAME" :
  627. parms.ApplicationName = value;
  628. break;
  629. case "ATTACHDBFILENAME" :
  630. case "EXTENDED PROPERTIES" :
  631. case "INITIAL FILE NAME" :
  632. throw new NotImplementedException("Attachable database support is not implemented.");
  633. case "TIMEOUT" :
  634. case "CONNECT TIMEOUT" :
  635. case "CONNECTION TIMEOUT" :
  636. connectionTimeout = ConvertToInt32 ("connection timeout", value);
  637. break;
  638. case "CONNECTION LIFETIME" :
  639. break;
  640. case "CONNECTION RESET" :
  641. connectionReset = ConvertToBoolean ("connection reset", value);
  642. break;
  643. case "LANGUAGE" :
  644. case "CURRENT LANGUAGE" :
  645. parms.Language = value;
  646. break;
  647. case "DATA SOURCE" :
  648. case "SERVER" :
  649. case "ADDRESS" :
  650. case "ADDR" :
  651. case "NETWORK ADDRESS" :
  652. dataSource = value;
  653. break;
  654. case "ENCRYPT":
  655. if (ConvertToBoolean("encrypt", value))
  656. {
  657. throw new NotImplementedException("SSL encryption for"
  658. + " data sent between client and server is not"
  659. + " implemented.");
  660. }
  661. break;
  662. case "ENLIST" :
  663. if (!ConvertToBoolean("enlist", value))
  664. {
  665. throw new NotImplementedException("Disabling the automatic"
  666. + " enlistment of connections in the thread's current"
  667. + " transaction context is not implemented.");
  668. }
  669. break;
  670. case "INITIAL CATALOG" :
  671. case "DATABASE" :
  672. parms.Database = value;
  673. break;
  674. case "INTEGRATED SECURITY" :
  675. case "TRUSTED_CONNECTION" :
  676. parms.DomainLogin = ConvertIntegratedSecurity(value);
  677. break;
  678. case "MAX POOL SIZE" :
  679. maxPoolSize = ConvertToInt32 ("max pool size", value);
  680. break;
  681. case "MIN POOL SIZE" :
  682. minPoolSize = ConvertToInt32 ("min pool size", value);
  683. break;
  684. #if NET_2_0
  685. case "MULTIPLEACTIVERESULTSETS":
  686. break;
  687. #endif
  688. case "NET" :
  689. case "NETWORK" :
  690. case "NETWORK LIBRARY" :
  691. if (!value.ToUpper ().Equals ("DBMSSOCN"))
  692. throw new ArgumentException ("Unsupported network library.");
  693. break;
  694. case "PACKET SIZE" :
  695. packetSize = ConvertToInt32 ("packet size", value);
  696. break;
  697. case "PASSWORD" :
  698. case "PWD" :
  699. parms.Password = value;
  700. break;
  701. case "PERSISTSECURITYINFO" :
  702. case "PERSIST SECURITY INFO" :
  703. // FIXME : not implemented
  704. break;
  705. case "POOLING" :
  706. pooling = ConvertToBoolean("pooling", value);
  707. break;
  708. case "UID" :
  709. case "USER" :
  710. case "USER ID" :
  711. parms.User = value;
  712. break;
  713. case "WSID" :
  714. case "WORKSTATION ID" :
  715. parms.Hostname = value;
  716. break;
  717. default :
  718. throw new ArgumentException("Keyword not supported :"+name);
  719. }
  720. }
  721. }
  722. static bool IsValidDatabaseName (string database)
  723. {
  724. if (database.Length > 32 || database.Length < 1)
  725. return false;
  726. if (database[0] == '"' && database[database.Length] == '"')
  727. database = database.Substring (1, database.Length - 2);
  728. else if (Char.IsDigit (database[0]))
  729. return false;
  730. if (database[0] == '_')
  731. return false;
  732. foreach (char c in database.Substring (1, database.Length - 1))
  733. if (!Char.IsLetterOrDigit (c) && c != '_')
  734. return false;
  735. return true;
  736. }
  737. private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
  738. {
  739. if (InfoMessage != null)
  740. InfoMessage (this, value);
  741. }
  742. private void OnStateChange (StateChangeEventArgs value)
  743. {
  744. if (StateChange != null)
  745. StateChange (this, value);
  746. }
  747. private sealed class SqlMonitorSocket : UdpClient
  748. {
  749. // UDP port that the SQL Monitor listens
  750. private static readonly int SqlMonitorUdpPort = 1434;
  751. private static readonly string SqlServerNotExist = "SQL Server does not exist or access denied";
  752. private string server;
  753. private string instance;
  754. internal SqlMonitorSocket (string ServerName, string InstanceName)
  755. : base (ServerName, SqlMonitorUdpPort)
  756. {
  757. server = ServerName;
  758. instance = InstanceName;
  759. }
  760. internal int DiscoverTcpPort ()
  761. {
  762. int SqlServerTcpPort;
  763. Client.Blocking = false;
  764. // send command to UDP 1434 (SQL Monitor) to get
  765. // the TCP port to connect to the MS SQL server
  766. ASCIIEncoding enc = new ASCIIEncoding ();
  767. Byte[] rawrq = new Byte [instance.Length + 1];
  768. rawrq[0] = 4;
  769. enc.GetBytes (instance, 0, instance.Length, rawrq, 1);
  770. int bytes = Send (rawrq, rawrq.Length);
  771. if (!Active)
  772. return -1; // Error
  773. bool result;
  774. result = Client.Poll (100, SelectMode.SelectRead);
  775. if (result == false)
  776. return -1; // Error
  777. if (Client.Available <= 0)
  778. return -1; // Error
  779. IPEndPoint endpoint = new IPEndPoint (Dns.GetHostByName ("localhost").AddressList [0], 0);
  780. Byte [] rawrs;
  781. rawrs = Receive (ref endpoint);
  782. string rs = Encoding.ASCII.GetString (rawrs);
  783. string[] rawtokens = rs.Split (';');
  784. Hashtable data = new Hashtable ();
  785. for (int i = 0; i < rawtokens.Length / 2 && i < 256; i++) {
  786. data [rawtokens [i * 2]] = rawtokens [ i * 2 + 1];
  787. }
  788. if (!data.ContainsKey ("tcp"))
  789. throw new NotImplementedException ("Only TCP/IP is supported.");
  790. SqlServerTcpPort = int.Parse ((string) data ["tcp"]);
  791. Close ();
  792. return SqlServerTcpPort;
  793. }
  794. }
  795. #endregion // Methods
  796. }
  797. }