SqlConnection.cs 27 KB

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