SqlConnection.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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 TdsConnectionPoolManager sqlConnectionPools = new TdsConnectionPoolManager (TdsVersion.tds70);
  37. // The current connection pool
  38. TdsConnectionPool 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. if (iso == IsolationLevel.Chaos)
  172. throw new ArgumentException ("Invalid IsolationLevel parameter: must be ReadCommitted, ReadUncommitted, RepeatableRead, or Serializable.");
  173. string isolevel = String.Empty;
  174. switch (iso) {
  175. case IsolationLevel.ReadCommitted:
  176. isolevel = "READ COMMITTED";
  177. break;
  178. case IsolationLevel.ReadUncommitted:
  179. isolevel = "READ UNCOMMITTED";
  180. break;
  181. case IsolationLevel.RepeatableRead:
  182. isolevel = "REPEATABLE READ";
  183. break;
  184. case IsolationLevel.Serializable:
  185. isolevel = "SERIALIZABLE";
  186. break;
  187. }
  188. tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0};BEGIN TRANSACTION {1}", isolevel, transactionName));
  189. transaction = new SqlTransaction (this, iso);
  190. return transaction;
  191. }
  192. public void ChangeDatabase (string database)
  193. {
  194. if (!IsValidDatabaseName (database))
  195. throw new ArgumentException (String.Format ("The database name {0} is not valid."));
  196. if (state != ConnectionState.Open)
  197. throw new InvalidOperationException ("The connection is not open.");
  198. tds.Execute (String.Format ("use {0}", database));
  199. }
  200. private void ChangeState (ConnectionState currentState)
  201. {
  202. ConnectionState originalState = state;
  203. state = currentState;
  204. OnStateChange (CreateStateChangeEvent (originalState, currentState));
  205. }
  206. public void Close ()
  207. {
  208. if (transaction != null && transaction.IsOpen)
  209. transaction.Rollback ();
  210. if (dataReader != null || xmlReader != null) {
  211. if(tds != null) tds.SkipToEnd ();
  212. dataReader = null;
  213. xmlReader = null;
  214. }
  215. if (pooling)
  216. if(pool != null) pool.ReleaseConnection (tds);
  217. else
  218. if(tds != null) tds.Disconnect ();
  219. if(tds != null) {
  220. tds.TdsErrorMessage -= new TdsInternalErrorMessageEventHandler (ErrorHandler);
  221. tds.TdsInfoMessage -= new TdsInternalInfoMessageEventHandler (MessageHandler);
  222. }
  223. ChangeState (ConnectionState.Closed);
  224. }
  225. public SqlCommand CreateCommand ()
  226. {
  227. SqlCommand command = new SqlCommand ();
  228. command.Connection = this;
  229. return command;
  230. }
  231. private SqlInfoMessageEventArgs CreateSqlInfoMessageEvent (TdsInternalErrorCollection errors)
  232. {
  233. return new SqlInfoMessageEventArgs (errors);
  234. }
  235. private StateChangeEventArgs CreateStateChangeEvent (ConnectionState originalState, ConnectionState currentState)
  236. {
  237. return new StateChangeEventArgs (originalState, currentState);
  238. }
  239. protected override void Dispose (bool disposing)
  240. {
  241. if (!disposed) {
  242. if (disposing) {
  243. if (State == ConnectionState.Open)
  244. Close ();
  245. parms = null;
  246. dataSource = null;
  247. }
  248. base.Dispose (disposing);
  249. disposed = true;
  250. }
  251. }
  252. [MonoTODO ("Not sure what this means at present.")]
  253. public void EnlistDistributedTransaction (ITransaction transaction)
  254. {
  255. throw new NotImplementedException ();
  256. }
  257. object ICloneable.Clone ()
  258. {
  259. return new SqlConnection (ConnectionString);
  260. }
  261. IDbTransaction IDbConnection.BeginTransaction ()
  262. {
  263. return BeginTransaction ();
  264. }
  265. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso)
  266. {
  267. return BeginTransaction (iso);
  268. }
  269. IDbCommand IDbConnection.CreateCommand ()
  270. {
  271. return CreateCommand ();
  272. }
  273. void IDisposable.Dispose ()
  274. {
  275. Dispose (true);
  276. GC.SuppressFinalize (this);
  277. }
  278. public void Open ()
  279. {
  280. string serverName = "";
  281. if (connectionString == null)
  282. throw new InvalidOperationException ("Connection string has not been initialized.");
  283. try {
  284. if (!pooling) {
  285. if(!ParseDataSource (dataSource, out port, out serverName))
  286. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  287. tds = new Tds70 (serverName, port, PacketSize, ConnectionTimeout);
  288. }
  289. else {
  290. if(!ParseDataSource (dataSource, out port, out serverName))
  291. throw new SqlException(20, 0, "SQL Server does not exist or access denied.", 17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
  292. TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize);
  293. pool = sqlConnectionPools.GetConnectionPool (connectionString, info);
  294. tds = pool.GetConnection ();
  295. }
  296. }
  297. catch (TdsTimeoutException e) {
  298. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  299. }
  300. tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
  301. tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);
  302. if (!tds.IsConnected) {
  303. try {
  304. tds.Connect (parms);
  305. }
  306. catch {
  307. if (pooling)
  308. pool.ReleaseConnection (tds);
  309. throw;
  310. }
  311. }
  312. /* Not sure ebout removing these 2 lines.
  313. * The command that gets to the sql server is just
  314. * 'sp_reset_connection' and it fails.
  315. * Either remove them definitely or fix it
  316. else if (connectionReset)
  317. tds.ExecProc ("sp_reset_connection");
  318. */
  319. ChangeState (ConnectionState.Open);
  320. }
  321. private bool ParseDataSource (string theDataSource, out int thePort, out string theServerName)
  322. {
  323. theServerName = "";
  324. string theInstanceName = "";
  325. thePort = 1433; // default TCP port for SQL Server
  326. bool success = true;
  327. int idx = 0;
  328. if ((idx = theDataSource.IndexOf (",")) > -1) {
  329. theServerName = theDataSource.Substring (0, idx);
  330. string p = theDataSource.Substring (idx + 1);
  331. thePort = Int32.Parse (p);
  332. }
  333. else if ((idx = theDataSource.IndexOf ("\\")) > -1) {
  334. theServerName = theDataSource.Substring (0, idx);
  335. theInstanceName = theDataSource.Substring (idx + 1);
  336. // do port discovery via UDP port 1434
  337. port = DiscoverTcpPortViaSqlMonitor (theServerName, theInstanceName);
  338. if (port == -1)
  339. success = false;
  340. }
  341. else {
  342. theServerName = theDataSource;
  343. }
  344. if(theServerName.Equals("(local)"))
  345. theServerName = "localhost";
  346. return success;
  347. }
  348. private int DiscoverTcpPortViaSqlMonitor(string ServerName, string InstanceName)
  349. {
  350. SqlMonitorSocket msock;
  351. msock = new SqlMonitorSocket (ServerName, InstanceName);
  352. int SqlServerPort = msock.DiscoverTcpPort ();
  353. msock = null;
  354. return SqlServerPort;
  355. }
  356. void SetConnectionString (string connectionString)
  357. {
  358. NameValueCollection parameters = new NameValueCollection ();
  359. if (connectionString.Length == 0)
  360. return;
  361. connectionString += ";";
  362. bool inQuote = false;
  363. bool inDQuote = false;
  364. bool inName = true;
  365. string name = String.Empty;
  366. string value = String.Empty;
  367. StringBuilder sb = new StringBuilder ();
  368. for (int i = 0; i < connectionString.Length; i += 1) {
  369. char c = connectionString [i];
  370. char peek;
  371. if (i == connectionString.Length - 1)
  372. peek = '\0';
  373. else
  374. peek = connectionString [i + 1];
  375. switch (c) {
  376. case '\'':
  377. if (inDQuote)
  378. sb.Append (c);
  379. else if (peek.Equals (c)) {
  380. sb.Append (c);
  381. i += 1;
  382. }
  383. else
  384. inQuote = !inQuote;
  385. break;
  386. case '"':
  387. if (inQuote)
  388. sb.Append (c);
  389. else if (peek.Equals (c)) {
  390. sb.Append (c);
  391. i += 1;
  392. }
  393. else
  394. inDQuote = !inDQuote;
  395. break;
  396. case ';':
  397. if (inDQuote || inQuote)
  398. sb.Append (c);
  399. else {
  400. if (name != String.Empty && name != null) {
  401. value = sb.ToString ();
  402. parameters [name.ToUpper ().Trim ()] = value.Trim ();
  403. }
  404. inName = true;
  405. name = String.Empty;
  406. value = String.Empty;
  407. sb = new StringBuilder ();
  408. }
  409. break;
  410. case '=':
  411. if (inDQuote || inQuote || !inName)
  412. sb.Append (c);
  413. else if (peek.Equals (c)) {
  414. sb.Append (c);
  415. i += 1;
  416. }
  417. else {
  418. name = sb.ToString ();
  419. sb = new StringBuilder ();
  420. inName = false;
  421. }
  422. break;
  423. case ' ':
  424. if (inQuote || inDQuote)
  425. sb.Append (c);
  426. else if (sb.Length > 0 && !peek.Equals (';'))
  427. sb.Append (c);
  428. break;
  429. default:
  430. sb.Append (c);
  431. break;
  432. }
  433. }
  434. if (this.ConnectionString == null)
  435. {
  436. SetDefaultConnectionParameters (parameters);
  437. }
  438. SetProperties (parameters);
  439. this.connectionString = connectionString;
  440. }
  441. void SetDefaultConnectionParameters (NameValueCollection parameters)
  442. {
  443. if (null == parameters.Get ("APPLICATION NAME"))
  444. parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
  445. if (null == parameters.Get ("CONNECT TIMEOUT") && null == parameters.Get ("CONNECTION TIMEOUT"))
  446. parameters["CONNECT TIMEOUT"] = "15";
  447. if (null == parameters.Get ("CONNECTION LIFETIME"))
  448. parameters["CONNECTION LIFETIME"] = "0";
  449. if (null == parameters.Get ("CONNECTION RESET"))
  450. parameters["CONNECTION RESET"] = "true";
  451. if (null == parameters.Get ("ENLIST"))
  452. parameters["ENLIST"] = "true";
  453. if (null == parameters.Get ("INTEGRATED SECURITY") && null == parameters.Get ("TRUSTED_CONNECTION"))
  454. parameters["INTEGRATED SECURITY"] = "false";
  455. if (null == parameters.Get ("MAX POOL SIZE"))
  456. parameters["MAX POOL SIZE"] = "100";
  457. if (null == parameters.Get ("MIN POOL SIZE"))
  458. parameters["MIN POOL SIZE"] = "0";
  459. if (null == parameters.Get ("NETWORK LIBRARY") && null == parameters.Get ("NET"))
  460. parameters["NETWORK LIBRARY"] = "dbmssocn";
  461. if (null == parameters.Get ("PACKET SIZE"))
  462. parameters["PACKET SIZE"] = "512";
  463. if (null == parameters.Get ("PERSIST SECURITY INFO"))
  464. parameters["PERSIST SECURITY INFO"] = "false";
  465. if (null == parameters.Get ("POOLING"))
  466. parameters["POOLING"] = "true";
  467. if (null == parameters.Get ("WORKSTATION ID"))
  468. parameters["WORKSTATION ID"] = Dns.GetHostName();
  469. }
  470. private void SetProperties (NameValueCollection parameters)
  471. {
  472. string value;
  473. string upperValue;
  474. foreach (string name in parameters) {
  475. value = parameters[name];
  476. upperValue = value.ToUpper ();
  477. switch (name) {
  478. case "APPLICATION NAME" :
  479. parms.ApplicationName = value;
  480. break;
  481. case "ATTACHDBFILENAME" :
  482. case "EXTENDED PROPERTIES" :
  483. case "INITIAL FILE NAME" :
  484. break;
  485. case "CONNECT TIMEOUT" :
  486. case "CONNECTION TIMEOUT" :
  487. connectionTimeout = Int32.Parse (value);
  488. break;
  489. case "CONNECTION LIFETIME" :
  490. break;
  491. case "CONNECTION RESET" :
  492. connectionReset = !(upperValue.Equals ("FALSE") || upperValue.Equals ("NO"));
  493. break;
  494. case "CURRENT LANGUAGE" :
  495. parms.Language = value;
  496. break;
  497. case "DATA SOURCE" :
  498. case "SERVER" :
  499. case "ADDRESS" :
  500. case "ADDR" :
  501. case "NETWORK ADDRESS" :
  502. dataSource = value;
  503. break;
  504. case "ENLIST" :
  505. break;
  506. case "INITIAL CATALOG" :
  507. case "DATABASE" :
  508. parms.Database = value;
  509. break;
  510. case "INTEGRATED SECURITY" :
  511. case "TRUSTED_CONNECTION" :
  512. parms.DomainLogin = upperValue.Equals ("TRUE") || upperValue.Equals ("YES") || upperValue.Equals ("SSPI");
  513. break;
  514. case "MAX POOL SIZE" :
  515. maxPoolSize = Int32.Parse (value);
  516. break;
  517. case "MIN POOL SIZE" :
  518. minPoolSize = Int32.Parse (value);
  519. break;
  520. #if NET_1_2
  521. case "MULTIPLEACTIVERESULTSETS":
  522. break;
  523. #endif
  524. case "NET" :
  525. case "NETWORK LIBRARY" :
  526. if (!value.ToUpper ().Equals ("DBMSSOCN"))
  527. throw new ArgumentException ("Unsupported network library.");
  528. break;
  529. case "PACKET SIZE" :
  530. packetSize = Int32.Parse (value);
  531. break;
  532. case "PASSWORD" :
  533. case "PWD" :
  534. parms.Password = value;
  535. break;
  536. case "PERSIST SECURITY INFO" :
  537. break;
  538. case "POOLING" :
  539. pooling = !(value.ToUpper ().Equals ("FALSE") || value.ToUpper ().Equals ("NO"));
  540. break;
  541. case "UID" :
  542. case "USER ID" :
  543. parms.User = value;
  544. break;
  545. case "WORKSTATION ID" :
  546. parms.Hostname = value;
  547. break;
  548. }
  549. }
  550. }
  551. static bool IsValidDatabaseName (string database)
  552. {
  553. if (database.Length > 32 || database.Length < 1)
  554. return false;
  555. if (database[0] == '"' && database[database.Length] == '"')
  556. database = database.Substring (1, database.Length - 2);
  557. else if (Char.IsDigit (database[0]))
  558. return false;
  559. if (database[0] == '_')
  560. return false;
  561. foreach (char c in database.Substring (1, database.Length - 1))
  562. if (!Char.IsLetterOrDigit (c) && c != '_')
  563. return false;
  564. return true;
  565. }
  566. private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
  567. {
  568. if (InfoMessage != null)
  569. InfoMessage (this, value);
  570. }
  571. private void OnStateChange (StateChangeEventArgs value)
  572. {
  573. if (StateChange != null)
  574. StateChange (this, value);
  575. }
  576. private sealed class SqlMonitorSocket : UdpClient
  577. {
  578. // UDP port that the SQL Monitor listens
  579. private static readonly int SqlMonitorUdpPort = 1434;
  580. private static readonly string SqlServerNotExist = "SQL Server does not exist or access denied";
  581. private string server;
  582. private string instance;
  583. internal SqlMonitorSocket (string ServerName, string InstanceName)
  584. : base (ServerName, SqlMonitorUdpPort)
  585. {
  586. server = ServerName;
  587. instance = InstanceName;
  588. }
  589. internal int DiscoverTcpPort ()
  590. {
  591. int SqlServerTcpPort;
  592. Client.Blocking = false;
  593. // send command to UDP 1434 (SQL Monitor) to get
  594. // the TCP port to connect to the MS SQL server
  595. ASCIIEncoding enc = new ASCIIEncoding ();
  596. Byte[] rawrq = new Byte [instance.Length + 1];
  597. rawrq[0] = 4;
  598. enc.GetBytes (instance, 0, instance.Length, rawrq, 1);
  599. int bytes = Send (rawrq, rawrq.Length);
  600. if (!Active)
  601. return -1; // Error
  602. bool result;
  603. result = Client.Poll (100, SelectMode.SelectRead);
  604. if (result == false)
  605. return -1; // Error
  606. if (Client.Available <= 0)
  607. return -1; // Error
  608. IPEndPoint endpoint = new IPEndPoint (Dns.GetHostByName ("localhost").AddressList [0], 0);
  609. Byte [] rawrs;
  610. rawrs = Receive (ref endpoint);
  611. string rs = Encoding.ASCII.GetString (rawrs);
  612. string[] rawtokens = rs.Split (';');
  613. Hashtable data = new Hashtable ();
  614. for (int i = 0; i < rawtokens.Length / 2 && i < 256; i++) {
  615. data [rawtokens [i * 2]] = rawtokens [ i * 2 + 1];
  616. }
  617. if (!data.ContainsKey ("tcp"))
  618. throw new NotImplementedException ("Only TCP/IP is supported.");
  619. SqlServerTcpPort = int.Parse ((string) data ["tcp"]);
  620. Close ();
  621. return SqlServerTcpPort;
  622. }
  623. }
  624. #endregion // Methods
  625. }
  626. }