2
0

SqlConnection.cs 23 KB

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