OdbcConnection.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. //
  2. // System.Data.Odbc.OdbcConnection
  3. //
  4. // Authors:
  5. // Brian Ritchie ([email protected])
  6. //
  7. // Copyright (C) Brian Ritchie, 2002
  8. //
  9. //
  10. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.ComponentModel;
  32. using System.Data;
  33. using System.Data.Common;
  34. using System.Runtime.InteropServices;
  35. using System.EnterpriseServices;
  36. #if NET_2_0 && !TARGET_JVM
  37. using System.Transactions;
  38. #endif
  39. namespace System.Data.Odbc
  40. {
  41. [DefaultEvent ("InfoMessage")]
  42. #if NET_2_0
  43. public sealed class OdbcConnection : DbConnection, ICloneable
  44. #else
  45. public sealed class OdbcConnection : Component, ICloneable, IDbConnection
  46. #endif //NET_2_0
  47. {
  48. #region Fields
  49. string connectionString;
  50. int connectionTimeout;
  51. internal OdbcTransaction transaction;
  52. IntPtr henv =IntPtr.Zero, hdbc=IntPtr.Zero;
  53. bool disposed;
  54. #endregion
  55. #region Constructors
  56. public OdbcConnection () : this (String.Empty)
  57. {
  58. }
  59. public OdbcConnection (string connectionString)
  60. {
  61. connectionTimeout = 15;
  62. ConnectionString = connectionString;
  63. }
  64. #endregion // Constructors
  65. #region Properties
  66. internal IntPtr hDbc {
  67. get { return hdbc; }
  68. }
  69. [OdbcCategoryAttribute ("DataCategory_Data")]
  70. [DefaultValue ("")]
  71. [OdbcDescriptionAttribute ("Information used to connect to a Data Source")]
  72. [RefreshPropertiesAttribute (RefreshProperties.All)]
  73. [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  74. [RecommendedAsConfigurableAttribute (true)]
  75. public
  76. #if NET_2_0
  77. override
  78. #endif
  79. string ConnectionString {
  80. get {
  81. if (connectionString == null)
  82. return string.Empty;
  83. return connectionString;
  84. }
  85. set { connectionString = value; }
  86. }
  87. [OdbcDescriptionAttribute ("Current connection timeout value, not settable in the ConnectionString")]
  88. [DefaultValue (15)]
  89. #if NET_2_0
  90. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  91. #endif
  92. public
  93. #if NET_2_0
  94. new
  95. #endif // NET_2_0
  96. int ConnectionTimeout {
  97. get {
  98. return connectionTimeout;
  99. }
  100. set {
  101. if (value < 0)
  102. throw new ArgumentException("Timout should not be less than zero.");
  103. connectionTimeout = value;
  104. }
  105. }
  106. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  107. [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
  108. public
  109. #if NET_2_0
  110. override
  111. #endif // NET_2_0
  112. string Database {
  113. get {
  114. if (State == ConnectionState.Closed)
  115. return string.Empty;
  116. return GetInfo (OdbcInfo.DatabaseName);
  117. }
  118. }
  119. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  120. [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
  121. [BrowsableAttribute (false)]
  122. public
  123. #if NET_2_0
  124. override
  125. #endif // NET_2_0
  126. ConnectionState State {
  127. get {
  128. if (hdbc!=IntPtr.Zero)
  129. return ConnectionState.Open;
  130. else
  131. return ConnectionState.Closed;
  132. }
  133. }
  134. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  135. [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
  136. #if NET_2_0
  137. [Browsable (false)]
  138. #endif
  139. public
  140. #if NET_2_0
  141. override
  142. #endif // NET_2_0
  143. string DataSource {
  144. get {
  145. if (State == ConnectionState.Closed)
  146. return string.Empty;
  147. return GetInfo (OdbcInfo.DataSourceName);
  148. }
  149. }
  150. #if NET_2_0
  151. [Browsable (false)]
  152. #endif
  153. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  154. [OdbcDescriptionAttribute ("Current ODBC Driver")]
  155. public string Driver {
  156. get {
  157. if (State == ConnectionState.Closed)
  158. return string.Empty;
  159. return GetInfo (OdbcInfo.DriverName);
  160. }
  161. }
  162. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  163. [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
  164. [BrowsableAttribute (false)]
  165. public
  166. #if NET_2_0
  167. override
  168. #endif // NET_2_0
  169. string ServerVersion {
  170. get {
  171. return GetInfo (OdbcInfo.DbmsVersion);
  172. }
  173. }
  174. #endregion // Properties
  175. #region Methods
  176. public
  177. #if NET_2_0
  178. new
  179. #endif // NET_2_0
  180. OdbcTransaction BeginTransaction ()
  181. {
  182. return BeginTransaction(IsolationLevel.Unspecified);
  183. }
  184. #if ONLY_1_1
  185. IDbTransaction IDbConnection.BeginTransaction ()
  186. {
  187. return (IDbTransaction) BeginTransaction();
  188. }
  189. #endif // ONLY_1_1
  190. #if NET_2_0
  191. protected override DbTransaction BeginDbTransaction (IsolationLevel level)
  192. {
  193. return BeginTransaction (level);
  194. }
  195. #endif
  196. public
  197. #if NET_2_0
  198. new
  199. #endif // NET_2_0
  200. OdbcTransaction BeginTransaction (IsolationLevel level)
  201. {
  202. if (State == ConnectionState.Closed)
  203. throw ExceptionHelper.ConnectionClosed ();
  204. if (transaction == null) {
  205. transaction = new OdbcTransaction (this,level);
  206. return transaction;
  207. } else
  208. throw new InvalidOperationException();
  209. }
  210. #if ONLY_1_1
  211. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel level)
  212. {
  213. return (IDbTransaction) BeginTransaction (level);
  214. }
  215. #endif // ONLY_1_1
  216. public
  217. #if NET_2_0
  218. override
  219. #endif // NET_2_0
  220. void Close ()
  221. {
  222. OdbcReturn ret = OdbcReturn.Error;
  223. if (State == ConnectionState.Open) {
  224. // disconnect
  225. ret = libodbc.SQLDisconnect (hdbc);
  226. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  227. throw new OdbcException (new OdbcError ("SQLDisconnect", OdbcHandleType.Dbc, hdbc));
  228. FreeHandles ();
  229. transaction = null;
  230. RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
  231. }
  232. }
  233. public
  234. #if NET_2_0
  235. new
  236. #endif // NET_2_0
  237. OdbcCommand CreateCommand ()
  238. {
  239. return new OdbcCommand (string.Empty, this, transaction);
  240. }
  241. public
  242. #if NET_2_0
  243. override
  244. #endif // NET_2_0
  245. void ChangeDatabase(string Database)
  246. {
  247. IntPtr ptr = IntPtr.Zero;
  248. OdbcReturn ret = OdbcReturn.Error;
  249. try {
  250. ptr = Marshal.StringToHGlobalAnsi (Database);
  251. ret = libodbc.SQLSetConnectAttr (hdbc, OdbcConnectionAttribute.CurrentCatalog, ptr, Database.Length);
  252. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  253. throw new OdbcException (new OdbcError ("SQLSetConnectAttr", OdbcHandleType.Dbc, hdbc));
  254. } finally {
  255. if (ptr != IntPtr.Zero)
  256. Marshal.FreeCoTaskMem (ptr);
  257. }
  258. }
  259. protected override void Dispose (bool disposing)
  260. {
  261. if (!this.disposed) {
  262. try {
  263. // release the native unmananged resources
  264. this.Close();
  265. this.disposed = true;
  266. } finally {
  267. // call Dispose on the base class
  268. base.Dispose(disposing);
  269. }
  270. }
  271. }
  272. [MonoTODO]
  273. object ICloneable.Clone ()
  274. {
  275. throw new NotImplementedException();
  276. }
  277. #if ONLY_1_1
  278. IDbCommand IDbConnection.CreateCommand ()
  279. {
  280. return (IDbCommand) CreateCommand ();
  281. }
  282. #endif //ONLY_1_1
  283. #if NET_2_0
  284. protected override DbCommand CreateDbCommand ()
  285. {
  286. return CreateCommand ();
  287. }
  288. #endif
  289. public
  290. #if NET_2_0
  291. override
  292. #endif // NET_2_0
  293. void Open ()
  294. {
  295. if (State == ConnectionState.Open)
  296. throw new InvalidOperationException ();
  297. OdbcReturn ret = OdbcReturn.Error;
  298. OdbcException e = null;
  299. try {
  300. // allocate Environment handle
  301. ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
  302. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo)) {
  303. e = new OdbcException (new OdbcError ("SQLAllocHandle"));
  304. MessageHandler (e);
  305. throw e;
  306. }
  307. ret = libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0);
  308. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  309. throw new OdbcException (new OdbcError ("SQLSetEnvAttr", OdbcHandleType.Env, henv));
  310. // allocate connection handle
  311. ret = libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
  312. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  313. throw new OdbcException (new OdbcError ("SQLAllocHandle", OdbcHandleType.Env, henv));
  314. // DSN connection
  315. if (ConnectionString.ToLower ().IndexOf ("dsn=") >= 0)
  316. {
  317. string _uid = string.Empty, _pwd = string.Empty, _dsn = string.Empty;
  318. string [] items = ConnectionString.Split (new char[1]{';'});
  319. foreach (string item in items)
  320. {
  321. string [] parts = item.Split (new char[1] {'='});
  322. switch (parts [0].Trim ().ToLower ())
  323. {
  324. case "dsn":
  325. _dsn = parts [1].Trim ();
  326. break;
  327. case "uid":
  328. _uid = parts [1].Trim ();
  329. break;
  330. case "pwd":
  331. _pwd = parts [1].Trim ();
  332. break;
  333. }
  334. }
  335. ret = libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
  336. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  337. throw new OdbcException (new OdbcError ("SQLConnect", OdbcHandleType.Dbc, hdbc));
  338. }
  339. else
  340. {
  341. // DSN-less Connection
  342. string OutConnectionString = new String (' ',1024);
  343. short OutLen = 0;
  344. ret = libodbc.SQLDriverConnect (hdbc, IntPtr.Zero, ConnectionString, -3,
  345. OutConnectionString, (short) OutConnectionString.Length, ref OutLen, 0);
  346. if ((ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  347. throw new OdbcException (new OdbcError ("SQLDriverConnect", OdbcHandleType.Dbc, hdbc));
  348. }
  349. RaiseStateChange (ConnectionState.Closed, ConnectionState.Open);
  350. } catch {
  351. // free handles if any.
  352. FreeHandles ();
  353. throw;
  354. }
  355. disposed = false;
  356. }
  357. [MonoTODO]
  358. public static void ReleaseObjectPool ()
  359. {
  360. throw new NotImplementedException ();
  361. }
  362. private void FreeHandles ()
  363. {
  364. OdbcReturn ret = OdbcReturn.Error;
  365. if (hdbc != IntPtr.Zero) {
  366. ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Dbc, hdbc);
  367. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  368. throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Dbc, hdbc));
  369. }
  370. hdbc = IntPtr.Zero;
  371. if (henv != IntPtr.Zero) {
  372. ret = libodbc.SQLFreeHandle ((ushort) OdbcHandleType.Env, henv);
  373. if ( (ret != OdbcReturn.Success) && (ret != OdbcReturn.SuccessWithInfo))
  374. throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Env, henv));
  375. }
  376. henv = IntPtr.Zero;
  377. }
  378. #if NET_2_0
  379. public override DataTable GetSchema ()
  380. {
  381. if (State == ConnectionState.Closed)
  382. throw ExceptionHelper.ConnectionClosed ();
  383. return MetaDataCollections.Instance;
  384. }
  385. public override DataTable GetSchema (string collectionName)
  386. {
  387. return GetSchema (collectionName, null);
  388. }
  389. public override DataTable GetSchema (string collectionName, string [] restrictionValues)
  390. {
  391. if (State == ConnectionState.Closed)
  392. throw ExceptionHelper.ConnectionClosed ();
  393. return GetSchema (collectionName, null);
  394. }
  395. [MonoTODO]
  396. public override void EnlistTransaction (Transaction transaction)
  397. {
  398. throw new NotImplementedException ();
  399. }
  400. #endif
  401. [MonoTODO]
  402. public void EnlistDistributedTransaction ( ITransaction transaction)
  403. {
  404. throw new NotImplementedException ();
  405. }
  406. internal string GetInfo (OdbcInfo info)
  407. {
  408. if (State == ConnectionState.Closed)
  409. throw new InvalidOperationException ("The connection is closed.");
  410. OdbcReturn ret = OdbcReturn.Error;
  411. short max_length = 256;
  412. byte [] buffer = new byte [max_length];
  413. short actualLength = 0;
  414. ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
  415. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  416. throw new OdbcException (new OdbcError ("SQLGetInfo",
  417. OdbcHandleType.Dbc,
  418. hdbc));
  419. return System.Text.Encoding.Default.GetString (buffer);
  420. }
  421. private void RaiseStateChange (ConnectionState from, ConnectionState to)
  422. {
  423. #if ONLY_1_1
  424. if (StateChange != null)
  425. StateChange (this, new StateChangeEventArgs (from, to));
  426. #else
  427. base.OnStateChange (new StateChangeEventArgs (from, to));
  428. #endif
  429. }
  430. private OdbcInfoMessageEventArgs CreateOdbcInfoMessageEvent (OdbcErrorCollection errors)
  431. {
  432. return new OdbcInfoMessageEventArgs (errors);
  433. }
  434. private void OnOdbcInfoMessage (OdbcInfoMessageEventArgs e) {
  435. if (InfoMessage != null)
  436. InfoMessage (this, e);
  437. }
  438. #endregion
  439. #region Events and Delegates
  440. #if ONLY_1_1
  441. [OdbcDescription ("DbConnection_StateChange")]
  442. [OdbcCategory ("DataCategory_StateChange")]
  443. public event StateChangeEventHandler StateChange;
  444. #endif // ONLY_1_1
  445. [OdbcDescription ("DbConnection_InfoMessage")]
  446. [OdbcCategory ("DataCategory_InfoMessage")]
  447. public event OdbcInfoMessageEventHandler InfoMessage;
  448. private void MessageHandler (OdbcException e)
  449. {
  450. OnOdbcInfoMessage (CreateOdbcInfoMessageEvent (e.Errors));
  451. }
  452. #endregion
  453. }
  454. }