SqlConnection.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. else if (connectionReset)
  291. tds.ExecProc ("sp_reset_connection");
  292. ChangeState (ConnectionState.Open);
  293. }
  294. void SetConnectionString (string connectionString)
  295. {
  296. connectionString += ";";
  297. NameValueCollection parameters = new NameValueCollection ();
  298. if (connectionString == String.Empty)
  299. return;
  300. bool inQuote = false;
  301. bool inDQuote = false;
  302. string name = String.Empty;
  303. string value = String.Empty;
  304. StringBuilder sb = new StringBuilder ();
  305. foreach (char c in connectionString)
  306. {
  307. switch (c) {
  308. case '\'':
  309. inQuote = !inQuote;
  310. break;
  311. case '"' :
  312. inDQuote = !inDQuote;
  313. break;
  314. case ';' :
  315. if (!inDQuote && !inQuote) {
  316. if (name != String.Empty && name != null) {
  317. value = sb.ToString ();
  318. parameters [name.ToUpper ().Trim ()] = value.Trim ();
  319. }
  320. name = String.Empty;
  321. value = String.Empty;
  322. sb = new StringBuilder ();
  323. }
  324. else
  325. sb.Append (c);
  326. break;
  327. case '=' :
  328. if (!inDQuote && !inQuote) {
  329. name = sb.ToString ();
  330. sb = new StringBuilder ();
  331. }
  332. else
  333. sb.Append (c);
  334. break;
  335. default:
  336. sb.Append (c);
  337. break;
  338. }
  339. }
  340. if (this.ConnectionString == null)
  341. {
  342. SetDefaultConnectionParameters (parameters);
  343. }
  344. SetProperties (parameters);
  345. this.connectionString = connectionString;
  346. }
  347. void SetDefaultConnectionParameters (NameValueCollection parameters)
  348. {
  349. if (null == parameters.Get ("APPLICATION NAME"))
  350. parameters["APPLICATION NAME"] = "Mono SqlClient Data Provider";
  351. if (null == parameters.Get ("CONNECT TIMEOUT") && null == parameters.Get ("CONNECTION TIMEOUT"))
  352. parameters["CONNECT TIMEOUT"] = "15";
  353. if (null == parameters.Get ("CONNECTION LIFETIME"))
  354. parameters["CONNECTION LIFETIME"] = "0";
  355. if (null == parameters.Get ("CONNECTION RESET"))
  356. parameters["CONNECTION RESET"] = "true";
  357. if (null == parameters.Get ("ENLIST"))
  358. parameters["ENLIST"] = "true";
  359. if (null == parameters.Get ("INTEGRATED SECURITY") && null == parameters.Get ("TRUSTED_CONNECTION"))
  360. parameters["INTEGRATED SECURITY"] = "false";
  361. if (null == parameters.Get ("MAX POOL SIZE"))
  362. parameters["MAX POOL SIZE"] = "100";
  363. if (null == parameters.Get ("MIN POOL SIZE"))
  364. parameters["MIN POOL SIZE"] = "0";
  365. if (null == parameters.Get ("NETWORK LIBRARY") && null == parameters.Get ("NET"))
  366. parameters["NETWORK LIBRARY"] = "dbmssocn";
  367. if (null == parameters.Get ("PACKET SIZE"))
  368. parameters["PACKET SIZE"] = "512";
  369. if (null == parameters.Get ("PERSIST SECURITY INFO"))
  370. parameters["PERSIST SECURITY INFO"] = "false";
  371. if (null == parameters.Get ("POOLING"))
  372. parameters["POOLING"] = "true";
  373. if (null == parameters.Get ("WORKSTATION ID"))
  374. parameters["WORKSTATION ID"] = Dns.GetHostByName ("localhost").HostName;
  375. }
  376. private void SetProperties (NameValueCollection parameters)
  377. {
  378. string value;
  379. foreach (string name in parameters) {
  380. value = parameters[name];
  381. switch (name) {
  382. case "APPLICATION NAME" :
  383. parms.ApplicationName = value;
  384. break;
  385. case "ATTACHDBFILENAME" :
  386. case "EXTENDED PROPERTIES" :
  387. case "INITIAL FILE NAME" :
  388. break;
  389. case "CONNECT TIMEOUT" :
  390. case "CONNECTION TIMEOUT" :
  391. connectionTimeout = Int32.Parse (value);
  392. break;
  393. case "CONNECTION LIFETIME" :
  394. break;
  395. case "CONNECTION RESET" :
  396. connectionReset = !(value.ToUpper ().Equals ("FALSE") || value.ToUpper ().Equals ("NO"));
  397. break;
  398. case "CURRENT LANGUAGE" :
  399. parms.Language = value;
  400. break;
  401. case "DATA SOURCE" :
  402. case "SERVER" :
  403. case "ADDRESS" :
  404. case "ADDR" :
  405. case "NETWORK ADDRESS" :
  406. dataSource = value;
  407. break;
  408. case "ENLIST" :
  409. break;
  410. case "INITIAL CATALOG" :
  411. case "DATABASE" :
  412. parms.Database = value;
  413. break;
  414. case "INTEGRATED SECURITY" :
  415. case "TRUSTED_CONNECTION" :
  416. break;
  417. case "MAX POOL SIZE" :
  418. maxPoolSize = Int32.Parse (value);
  419. break;
  420. case "MIN POOL SIZE" :
  421. minPoolSize = Int32.Parse (value);
  422. break;
  423. case "NET" :
  424. case "NETWORK LIBRARY" :
  425. if (!value.ToUpper ().Equals ("DBMSSOCN"))
  426. throw new ArgumentException ("Unsupported network library.");
  427. break;
  428. case "PACKET SIZE" :
  429. packetSize = Int32.Parse (value);
  430. break;
  431. case "PASSWORD" :
  432. case "PWD" :
  433. parms.Password = value;
  434. break;
  435. case "PERSIST SECURITY INFO" :
  436. break;
  437. case "POOLING" :
  438. pooling = !(value.ToUpper ().Equals ("FALSE") || value.ToUpper ().Equals ("NO"));
  439. break;
  440. case "USER ID" :
  441. parms.User = value;
  442. break;
  443. case "WORKSTATION ID" :
  444. parms.Hostname = value;
  445. break;
  446. }
  447. }
  448. }
  449. static bool IsValidDatabaseName (string database)
  450. {
  451. if (database.Length > 32 || database.Length < 1)
  452. return false;
  453. if (database[0] == '"' && database[database.Length] == '"')
  454. database = database.Substring (1, database.Length - 2);
  455. else if (Char.IsDigit (database[0]))
  456. return false;
  457. if (database[0] == '_')
  458. return false;
  459. foreach (char c in database.Substring (1, database.Length - 1))
  460. if (!Char.IsLetterOrDigit (c) && c != '_')
  461. return false;
  462. return true;
  463. }
  464. private void OnSqlInfoMessage (SqlInfoMessageEventArgs value)
  465. {
  466. if (InfoMessage != null)
  467. InfoMessage (this, value);
  468. }
  469. private void OnStateChange (StateChangeEventArgs value)
  470. {
  471. if (StateChange != null)
  472. StateChange (this, value);
  473. }
  474. #endregion // Methods
  475. }
  476. }