SqlConnection.cs 27 KB

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