OdbcConnection.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. #if NET_2_0
  77. [SettingsBindableAttribute (true)]
  78. #else
  79. [RecommendedAsConfigurableAttribute (true)]
  80. #endif
  81. public
  82. #if NET_2_0
  83. override
  84. #endif
  85. string ConnectionString {
  86. get {
  87. return connectionString;
  88. }
  89. set {
  90. connectionString = value;
  91. }
  92. }
  93. [OdbcDescriptionAttribute ("Current connection timeout value, not settable in the ConnectionString")]
  94. [DefaultValue (15)]
  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. [MonoTODO]
  139. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  140. [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
  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. [MonoTODO]
  151. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  152. [OdbcDescriptionAttribute ("Current ODBC Driver")]
  153. public string Driver {
  154. get {
  155. return GetInfo (OdbcInfo.DriverName);
  156. }
  157. }
  158. [MonoTODO]
  159. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  160. [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
  161. [BrowsableAttribute (false)]
  162. public
  163. #if NET_2_0
  164. override
  165. #endif // NET_2_0
  166. string ServerVersion {
  167. get {
  168. return GetInfo (OdbcInfo.DbmsVersion);
  169. }
  170. }
  171. #endregion // Properties
  172. #region Methods
  173. public
  174. #if NET_2_0
  175. new
  176. #endif // NET_2_0
  177. OdbcTransaction BeginTransaction ()
  178. {
  179. return BeginTransaction(IsolationLevel.Unspecified);
  180. }
  181. #if ONLY_1_1
  182. IDbTransaction IDbConnection.BeginTransaction ()
  183. {
  184. return (IDbTransaction) BeginTransaction();
  185. }
  186. #endif // ONLY_1_1
  187. #if NET_2_0
  188. protected override DbTransaction BeginDbTransaction (IsolationLevel level)
  189. {
  190. return BeginTransaction (level);
  191. }
  192. #endif
  193. public
  194. #if NET_2_0
  195. new
  196. #endif // NET_2_0
  197. OdbcTransaction BeginTransaction (IsolationLevel level)
  198. {
  199. if (transaction==null)
  200. {
  201. transaction=new OdbcTransaction(this,level);
  202. return transaction;
  203. }
  204. else
  205. throw new InvalidOperationException();
  206. }
  207. #if ONLY_1_1
  208. IDbTransaction IDbConnection.BeginTransaction (IsolationLevel level)
  209. {
  210. return (IDbTransaction) BeginTransaction(level);
  211. }
  212. #endif // ONLY_1_1
  213. public
  214. #if NET_2_0
  215. override
  216. #endif // NET_2_0
  217. void Close ()
  218. {
  219. OdbcReturn ret = OdbcReturn.Error;
  220. if (State == ConnectionState.Open) {
  221. // disconnect
  222. ret = libodbc.SQLDisconnect (hdbc);
  223. if ( (ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  224. throw new OdbcException (new OdbcError ("SQLDisconnect", OdbcHandleType.Dbc,hdbc));
  225. FreeHandles ();
  226. transaction = null;
  227. RaiseStateChange (ConnectionState.Open, ConnectionState.Closed);
  228. }
  229. }
  230. public
  231. #if NET_2_0
  232. new
  233. #endif // NET_2_0
  234. OdbcCommand CreateCommand ()
  235. {
  236. return new OdbcCommand("", this, transaction);
  237. }
  238. [MonoTODO]
  239. public
  240. #if NET_2_0
  241. override
  242. #endif // NET_2_0
  243. void ChangeDatabase(string Database)
  244. {
  245. IntPtr ptr = IntPtr.Zero;
  246. OdbcReturn ret = OdbcReturn.Error;
  247. try {
  248. ptr = Marshal.StringToHGlobalAnsi (Database);
  249. ret = libodbc.SQLSetConnectAttr (hdbc, OdbcConnectionAttribute.CurrentCatalog, ptr, Database.Length);
  250. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  251. throw new OdbcException (new OdbcError ("SQLSetConnectAttr", OdbcHandleType.Dbc, hdbc));
  252. } finally {
  253. if (ptr != IntPtr.Zero)
  254. Marshal.FreeCoTaskMem (ptr);
  255. }
  256. }
  257. protected override void Dispose (bool disposing)
  258. {
  259. if (!this.disposed) {
  260. try
  261. {
  262. // release the native unmananged resources
  263. this.Close();
  264. this.disposed = true;
  265. }
  266. finally
  267. {
  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. try {
  300. // allocate Environment handle
  301. ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
  302. if ( (ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  303. throw new OdbcException (new OdbcError ("SQLAllocHandle"));
  304. ret=libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0);
  305. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  306. throw new OdbcException (new OdbcError ("SQLSetEnvAttr", OdbcHandleType.Env,henv));
  307. // allocate connection handle
  308. ret=libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
  309. if ( (ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  310. throw new OdbcException (new OdbcError ("SQLAllocHandle",OdbcHandleType.Env,henv));
  311. // DSN connection
  312. if (ConnectionString.ToLower().IndexOf("dsn=")>=0)
  313. {
  314. string _uid="", _pwd="", _dsn="";
  315. string[] items=ConnectionString.Split(new char[1]{';'});
  316. foreach (string item in items)
  317. {
  318. string[] parts=item.Split(new char[1] {'='});
  319. switch (parts[0].Trim().ToLower())
  320. {
  321. case "dsn":
  322. _dsn=parts[1].Trim();
  323. break;
  324. case "uid":
  325. _uid=parts[1].Trim();
  326. break;
  327. case "pwd":
  328. _pwd=parts[1].Trim();
  329. break;
  330. }
  331. }
  332. ret=libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
  333. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  334. throw new OdbcException(new OdbcError("SQLConnect",OdbcHandleType.Dbc,hdbc));
  335. }
  336. else
  337. {
  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 (Exception) {
  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. [MonoTODO]
  376. public void EnlistDistributedTransaction ( ITransaction transaction)
  377. {
  378. throw new NotImplementedException ();
  379. }
  380. internal string GetInfo (OdbcInfo info)
  381. {
  382. if (State == ConnectionState.Closed)
  383. throw new InvalidOperationException ("The connection is closed.");
  384. OdbcReturn ret = OdbcReturn.Error;
  385. short max_length = 256;
  386. byte [] buffer = new byte [max_length];
  387. short actualLength = 0;
  388. ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
  389. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  390. throw new OdbcException (new OdbcError ("SQLGetInfo",
  391. OdbcHandleType.Dbc,
  392. hdbc));
  393. return System.Text.Encoding.Default.GetString (buffer);
  394. }
  395. private void RaiseStateChange (ConnectionState from, ConnectionState to)
  396. {
  397. #if ONLY_1_1
  398. if (StateChange != null)
  399. StateChange (this, new StateChangeEventArgs (from, to));
  400. #else
  401. base.OnStateChange (new StateChangeEventArgs (from, to));
  402. #endif
  403. }
  404. #endregion
  405. #region Events and Delegates
  406. #if ONLY_1_1
  407. [OdbcDescription ("DbConnection_StateChange")]
  408. [OdbcCategory ("DataCategory_StateChange")]
  409. public event StateChangeEventHandler StateChange;
  410. #endif // ONLY_1_1
  411. [OdbcDescription ("DbConnection_InfoMessage")]
  412. [OdbcCategory ("DataCategory_InfoMessage")]
  413. public event OdbcInfoMessageEventHandler InfoMessage;
  414. #endregion
  415. }
  416. }