2
0

SqlConnection.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. //
  2. // System.Data.SqlClient.SqlConnection.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. // Tim Coleman ([email protected])
  8. //
  9. // (C) Ximian, Inc 2002
  10. // (C) Daniel Morgan 2002
  11. // Copyright (C) Tim Coleman, 2002
  12. //
  13. using Mono.Data.Tds;
  14. using Mono.Data.Tds.Protocol;
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Specialized;
  18. using System.ComponentModel;
  19. using System.Data;
  20. using System.Data.Common;
  21. using System.EnterpriseServices;
  22. using System.Net;
  23. using System.Text;
  24. using System.Xml;
  25. namespace System.Data.SqlClient {
  26. [DefaultEvent ("InfoMessage")]
  27. public sealed class SqlConnection : Component, IDbConnection, ICloneable
  28. {
  29. #region Fields
  30. bool disposed = false;
  31. // The set of SQL connection pools
  32. static Hashtable SqlConnectionPools = new Hashtable ();
  33. // The current connection pool
  34. SqlConnectionPool pool;
  35. // The connection string that identifies this connection
  36. string connectionString = null;
  37. // The transaction object for the current transaction
  38. SqlTransaction transaction = null;
  39. // Connection parameters
  40. TdsConnectionParameters parms = new TdsConnectionParameters ();
  41. bool connectionReset;
  42. bool pooling;
  43. string dataSource;
  44. int connectionTimeout;
  45. int minPoolSize;
  46. int maxPoolSize;
  47. int packetSize;
  48. int port = 1433;
  49. // The current state
  50. ConnectionState state = ConnectionState.Closed;
  51. SqlDataReader dataReader = null;
  52. XmlReader xmlReader = null;
  53. // The TDS object
  54. ITds tds;
  55. #endregion // Fields
  56. #region Constructors
  57. public SqlConnection ()
  58. : this (String.Empty)
  59. {
  60. }
  61. public SqlConnection (string connectionString)
  62. {
  63. ConnectionString = connectionString;
  64. }
  65. #endregion // Constructors
  66. #region Properties
  67. [DataCategory ("Data")]
  68. [DataSysDescription ("Information used to connect to a DataSource, such as 'Data Source=x;Initial Catalog=x;Integrated Security=SSPI'.")]
  69. [DefaultValue ("")]
  70. [RecommendedAsConfigurable (true)]
  71. [RefreshProperties (RefreshProperties.All)]
  72. public string ConnectionString {
  73. get { return connectionString; }
  74. set { SetConnectionString (value); }
  75. }
  76. [DataSysDescription ("Current connection timeout value, 'Connect Timeout=X' in the ConnectionString.")]
  77. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  78. public int ConnectionTimeout {
  79. get { return connectionTimeout; }
  80. }
  81. [DataSysDescription ("Current SQL Server database, 'Initial Catalog=X' in the ConnectionString.")]
  82. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  83. public string Database {
  84. get { return tds.Database; }
  85. }
  86. internal SqlDataReader DataReader {
  87. get { return dataReader; }
  88. set { dataReader = value; }
  89. }
  90. [DataSysDescription ("Current SqlServer that the connection is opened to, 'Data Source=X' in the ConnectionString.")]
  91. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  92. public string DataSource {
  93. get { return dataSource; }
  94. }
  95. [DataSysDescription ("Network packet size, 'Packet Size=x' in the ConnectionString.")]
  96. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  97. public int PacketSize {
  98. get { return packetSize; }
  99. }
  100. [Browsable (false)]
  101. [DataSysDescription ("Version of the SQL Server accessed by the SqlConnection.")]
  102. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  103. public string ServerVersion {
  104. get { return tds.ServerVersion; }
  105. }
  106. [Browsable (false)]
  107. [DataSysDescription ("The ConnectionState indicating whether the connection is open or closed.")]
  108. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  109. public ConnectionState State {
  110. get { return state; }
  111. }
  112. internal ITds Tds {
  113. get { return tds; }
  114. }
  115. internal SqlTransaction Transaction {
  116. get { return transaction; }
  117. set { transaction = value; }
  118. }
  119. [DataSysDescription ("Workstation Id, 'Workstation Id=x' in the ConnectionString.")]
  120. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  121. public string WorkstationId {
  122. get { return parms.Hostname; }
  123. }
  124. internal XmlReader XmlReader {
  125. get { return xmlReader; }
  126. set { xmlReader = value; }
  127. }
  128. #endregion // Properties
  129. #region Events
  130. [DataCategory ("InfoMessage")]
  131. [DataSysDescription ("Event triggered when messages arrive from the DataSource.")]
  132. public event SqlInfoMessageEventHandler InfoMessage;
  133. [DataCategory ("StateChange")]
  134. [DataSysDescription ("Event triggered when the connection changes state.")]
  135. public event StateChangeEventHandler StateChange;
  136. #endregion // Events
  137. #region Delegates
  138. private void ErrorHandler (object sender, TdsInternalErrorMessageEventArgs e)
  139. {
  140. throw new SqlException (e.Class, e.LineNumber, e.Message, e.Number, e.Procedure, e.Server, "Mono SqlClient Data Provider", e.State);
  141. }
  142. private void MessageHandler (object sender, TdsInternalInfoMessageEventArgs e)
  143. {
  144. OnSqlInfoMessage (CreateSqlInfoMessageEvent (e.Errors));
  145. }
  146. #endregion // Delegates
  147. #region Methods
  148. public SqlTransaction BeginTransaction ()
  149. {
  150. return BeginTransaction (IsolationLevel.ReadCommitted, String.Empty);
  151. }
  152. public SqlTransaction BeginTransaction (IsolationLevel iso)
  153. {
  154. return BeginTransaction (iso, String.Empty);
  155. }
  156. public SqlTransaction BeginTransaction (string transactionName)
  157. {
  158. return BeginTransaction (IsolationLevel.ReadCommitted, transactionName);
  159. }
  160. public SqlTransaction BeginTransaction (IsolationLevel iso, string transactionName)
  161. {
  162. if (state == ConnectionState.Closed)
  163. throw new InvalidOperationException ("The connection is not open.");
  164. if (transaction != null)
  165. throw new InvalidOperationException ("SqlConnection does not support parallel transactions.");
  166. string isolevel = String.Empty;
  167. switch (iso) {
  168. case IsolationLevel.Chaos:
  169. isolevel = "CHAOS";
  170. break;
  171. case IsolationLevel.ReadCommitted:
  172. isolevel = "READ COMMITTED";
  173. break;
  174. case IsolationLevel.ReadUncommitted:
  175. isolevel = "READ UNCOMMITTED";
  176. break;
  177. case IsolationLevel.RepeatableRead:
  178. isolevel = "REPEATABLE READ";
  179. break;
  180. case IsolationLevel.Serializable:
  181. isolevel = "SERIALIZABLE";
  182. break;
  183. }
  184. tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0};BEGIN TRANSACTION {1}", isolevel, transactionName));
  185. transaction = new SqlTransaction (this, iso);
  186. return transaction;
  187. }
  188. public void ChangeDatabase (string database)
  189. {
  190. if (!IsValidDatabaseName (database))
  191. throw new ArgumentException (String.Format ("The database name {0} is not valid."));
  192. if (state != ConnectionState.Open)
  193. throw new InvalidOperationException ("The connection is not open.");
  194. tds.Execute (String.Format ("use {0}", database));
  195. }
  196. private void ChangeState (ConnectionState currentState)
  197. {
  198. ConnectionState originalState = state;
  199. state = currentState;
  200. OnStateChange (CreateStateChangeEvent (originalState, currentState));
  201. }
  202. public void Close ()
  203. {
  204. if (transaction != null && transaction.IsOpen)
  205. transaction.Rollback ();
  206. if (pooling)
  207. pool.ReleaseConnection (tds);
  208. else
  209. tds.Disconnect ();
  210. tds.TdsErrorMessage -= new TdsInternalErrorMessageEventHandler (ErrorHandler);
  211. tds.TdsInfoMessage -= new TdsInternalInfoMessageEventHandler (MessageHandler);
  212. ChangeState (ConnectionState.Closed);
  213. }
  214. public SqlCommand CreateCommand ()
  215. {
  216. SqlCommand command = new SqlCommand ();
  217. command.Connection = this;
  218. return command;
  219. }
  220. private SqlInfoMessageEventArgs CreateSqlInfoMessageEvent (TdsInternalErrorCollection errors)
  221. {
  222. return new SqlInfoMessageEventArgs (errors);
  223. }
  224. private StateChangeEventArgs CreateStateChangeEvent (ConnectionState originalState, ConnectionState currentState)
  225. {
  226. return new StateChangeEventArgs (originalState, currentState);
  227. }
  228. protected override void Dispose (bool disposing)
  229. {
  230. if (!disposed) {
  231. if (disposing) {
  232. if (State == ConnectionState.Open)
  233. Close ();
  234. parms = null;
  235. dataSource = null;
  236. }
  237. base.Dispose (disposing);
  238. disposed = true;
  239. }
  240. }
  241. [MonoTODO ("Not sure what this means at present.")]
  242. public void EnlistDistributedTransaction (ITransaction transaction)
  243. {
  244. throw new NotImplementedException ();
  245. }
  246. object ICloneable.Clone ()
  247. {
  248. return new SqlConnection (ConnectionString);
  249. }
  250. IDbTransaction IDbConnection.BeginTransaction ()
  251. {
  252. return BeginTransaction ();
  253. }
  254. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso)
  255. {
  256. return BeginTransaction (iso);
  257. }
  258. IDbCommand IDbConnection.CreateCommand ()
  259. {
  260. return CreateCommand ();
  261. }
  262. void IDisposable.Dispose ()
  263. {
  264. Dispose (true);
  265. GC.SuppressFinalize (this);
  266. }
  267. public void Open ()
  268. {
  269. if (connectionString == null)
  270. throw new InvalidOperationException ("Connection string has not been initialized.");
  271. try {
  272. if (!pooling)
  273. tds = new Tds70 (DataSource, port, PacketSize, ConnectionTimeout);
  274. else {
  275. pool = (SqlConnectionPool) SqlConnectionPools [connectionString];
  276. if (pool == null) {
  277. pool = new SqlConnectionPool (dataSource, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize);
  278. SqlConnectionPools [connectionString] = pool;
  279. }
  280. tds = pool.AllocateConnection ();
  281. }
  282. }
  283. catch (TdsTimeoutException e) {
  284. throw SqlException.FromTdsInternalException ((TdsInternalException) e);
  285. }
  286. tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
  287. tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);
  288. if (!tds.IsConnected)
  289. tds.Connect (parms);
  290. /* Not sure ebout removing these 2 lines.
  291. * The command that gets to the sql server is just
  292. * 'sp_reset_connection' and it fails.
  293. * Either remove them definitely or fix it
  294. else if (connectionReset)
  295. tds.ExecProc ("sp_reset_connection");
  296. */
  297. ChangeState (ConnectionState.Open);
  298. }
  299. void SetConnectionString (string connectionString)
  300. {
  301. connectionString += ";";
  302. NameValueCollection parameters = new NameValueCollection ();
  303. if (connectionString == String.Empty)
  304. return;
  305. bool inQuote = false;
  306. bool inDQuote = false;
  307. string name = String.Empty;
  308. string value = String.Empty;
  309. StringBuilder sb = new StringBuilder ();
  310. foreach (char c in connectionString)
  311. {
  312. switch (c) {
  313. case '\'':
  314. inQuote = !inQuote;
  315. break;
  316. case '"' :
  317. inDQuote = !inDQuote;
  318. break;
  319. case ';' :
  320. if (!inDQuote && !inQuote) {
  321. if (name != String.Empty && name != null) {
  322. value = sb.ToString ();
  323. parameters [name.ToUpper ().Trim ()] = value.Trim ();
  324. }
  325. name = String.Empty;
  326. value = String.Empty;
  327. sb = new StringBuilder ();
  328. }
  329. else
  330. sb.Append (c);
  331. break;
  332. case '=' :
  333. if (!inDQuote && !inQuote) {
  334. name = sb.ToString ();
  335. sb = new StringBuilder ();
  336. }
  337. else
  338. sb.Append (c);
  339. break;
  340. default:
  341. sb.Append (c);
  342. break;
  343. }
  344. }
  345. if (this.ConnectionString == null)
  346. {
  347. SetDefaultConnectionParameters (parameters);
  348. }
  349. SetProperties (parameters);
  350. this.connectionString = connectionString;
  351. }
  352. void SetDefaultConnectionParameters (NameValueCollection parameters)
  353. {
  354. if (null == parameters.Get ("APPLICATION NAME"))
  355. parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
  356. if (null == parameters.Get ("CONNECT TIMEOUT") && null == parameters.Get ("CONNECTION TIMEOUT"))
  357. parameters["CONNECT TIMEOUT"] = "15";
  358. if (null == parameters.Get ("CONNECTION LIFETIME"))
  359. parameters["CONNECTION LIFETIME"] = "0";
  360. if (null == parameters.Get ("CONNECTION RESET"))
  361. parameters["CONNECTION RESET"] = "true";
  362. if (null == parameters.Get ("ENLIST"))
  363. parameters["ENLIST"] = "true";
  364. if (null == parameters.Get ("INTEGRATED SECURITY") && null == parameters.Get ("TRUSTED_CONNECTION"))
  365. parameters["INTEGRATED SECURITY"] = "false";
  366. if (null == parameters.Get ("MAX POOL SIZE"))
  367. parameters["MAX POOL SIZE"] = "100";
  368. if (null == parameters.Get ("MIN POOL SIZE"))
  369. parameters["MIN POOL SIZE"] = "0";
  370. if (null == parameters.Get ("NETWORK LIBRARY") && null == parameters.Get ("NET"))
  371. parameters["NETWORK LIBRARY"] = "dbmssocn";
  372. if (null == parameters.Get ("PACKET SIZE"))
  373. parameters["PACKET SIZE"] = "512";
  374. if (null == parameters.Get ("PERSIST SECURITY INFO"))
  375. parameters["PERSIST SECURITY INFO"] = "false";
  376. if (null == parameters.Get ("POOLING"))
  377. parameters["POOLING"] = "true";
  378. if (null == parameters.Get ("WORKSTATION ID"))
  379. parameters["WORKSTATION ID"] = Dns.GetHostByName ("localhost").HostName;
  380. }
  381. private void SetProperties (NameValueCollection parameters)
  382. {
  383. string value;
  384. foreach (string name in parameters) {
  385. value = parameters[name];
  386. switch (name) {
  387. case "APPLICATION NAME" :
  388. parms.ApplicationName = value;
  389. break;
  390. case "ATTACHDBFILENAME" :
  391. case "EXTENDED PROPERTIES" :
  392. case "INITIAL FILE NAME" :
  393. break;
  394. case "CONNECT TIMEOUT" :
  395. case "CONNECTION TIMEOUT" :
  396. connectionTimeout = Int32.Parse (value);
  397. break;
  398. case "CONNECTION LIFETIME" :
  399. break;
  400. case "CONNECTION RESET" :
  401. connectionReset = !(value.ToUpper ().Equals ("FALSE") || value.ToUpper ().Equals ("NO"));
  402. break;
  403. case "CURRENT LANGUAGE" :
  404. parms.Language = value;
  405. break;
  406. case "DATA SOURCE" :
  407. case "SERVER" :
  408. case "ADDRESS" :
  409. case "ADDR" :
  410. case "NETWORK ADDRESS" :
  411. dataSource = value;
  412. break;
  413. case "ENLIST" :
  414. break;
  415. case "INITIAL CATALOG" :
  416. case "DATABASE" :
  417. parms.Database = value;
  418. break;
  419. case "INTEGRATED SECURITY" :
  420. case "TRUSTED_CONNECTION" :
  421. break;
  422. case "MAX POOL SIZE" :
  423. maxPoolSize = Int32.Parse (value);
  424. break;
  425. case "MIN POOL SIZE" :
  426. minPoolSize = Int32.Parse (value);
  427. break;
  428. case "NET" :
  429. case "NETWORK LIBRARY" :
  430. if (!value.ToUpper ().Equals ("DBMSSOCN"))
  431. throw new ArgumentException ("Unsupported network library.");
  432. break;
  433. case "PACKET SIZE" :
  434. packetSize = Int32.Parse (value);
  435. break;
  436. case "PASSWORD" :
  437. case "PWD" :
  438. parms.Password = value;
  439. break;
  440. case "PERSIST SECURITY INFO" :
  441. break;
  442. case "POOLING" :
  443. pooling = !(value.ToUpper ().Equals ("FALSE") || value.ToUpper ().Equals ("NO"));
  444. break;
  445. case "USER ID" :
  446. parms.User = value;
  447. break;
  448. case "WORKSTATION ID" :
  449. parms.Hostname = value;
  450. break;
  451. }
  452. }
  453. }
  454. static bool IsValidDatabaseName (string database)
  455. {
  456. if (database.Length > 32 || database.Length < 1)
  457. return false;
  458. if (database[0] == '"' && database[database.Length] == '"')
  459. database = database.Substring (1, database.Length - 2);
  460. else if (Char.IsDigit (database[0]))
  461. return false;
  462. if (database[0] == '_')
  463. return false;
  464. foreach (char c in database.Substring (1, database.Length - 1))
  465. if (!Char.IsLetterOrDigit (c) && c != '_')
  466. return false;
  467. return true;
  468. }
  469. private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
  470. {
  471. if (InfoMessage != null)
  472. InfoMessage (this, value);
  473. }
  474. private void OnStateChange (StateChangeEventArgs value)
  475. {
  476. if (StateChange != null)
  477. StateChange (this, value);
  478. }
  479. #endregion // Methods
  480. }
  481. }