SqlConnection.cs 19 KB

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