OdbcConnection.cs 15 KB

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