SqlConnection.cs 23 KB

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