SqlConnection.cs 25 KB

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