OdbcConnection.cs 14 KB

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