OdbcConnection.cs 16 KB

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