OdbcConnection.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. #if NET_2_0
  36. using System.Data.ProviderBase;
  37. #endif // NET_2_0
  38. using System.EnterpriseServices;
  39. namespace System.Data.Odbc
  40. {
  41. [DefaultEvent("InfoMessage")]
  42. #if NET_2_0
  43. public sealed class OdbcConnection : DbConnectionBase, ICloneable
  44. #else
  45. public sealed class OdbcConnection : Component, ICloneable, IDbConnection
  46. #endif //NET_2_0
  47. {
  48. #region Fields
  49. #if ONLY_1_1
  50. string connectionString;
  51. #endif //ONLY_1_1
  52. int connectionTimeout;
  53. internal OdbcTransaction transaction;
  54. IntPtr henv=IntPtr.Zero, hdbc=IntPtr.Zero;
  55. bool disposed = false;
  56. #endregion
  57. #region Constructors
  58. public OdbcConnection () : this (String.Empty)
  59. {
  60. }
  61. public OdbcConnection (string connectionString)
  62. {
  63. Init (connectionString);
  64. }
  65. private void Init (string connectionString)
  66. {
  67. connectionTimeout = 15;
  68. ConnectionString = connectionString;
  69. }
  70. #if NET_2_0
  71. internal OdbcConnection (OdbcConnectionFactory factory)
  72. : base ( (DbConnectionFactory) factory)
  73. {
  74. Init (String.Empty);
  75. }
  76. #endif //NET_2_0
  77. #endregion // Constructors
  78. #region Properties
  79. internal IntPtr hDbc
  80. {
  81. get { return hdbc; }
  82. }
  83. #if ONLY_1_1
  84. [OdbcCategoryAttribute ("DataCategory_Data")]
  85. [DefaultValue ("")]
  86. [OdbcDescriptionAttribute ("Information used to connect to a Data Source")]
  87. [RefreshPropertiesAttribute (RefreshProperties.All)]
  88. [EditorAttribute ("Microsoft.VSDesigner.Data.Odbc.Design.OdbcConnectionStringEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  89. [RecommendedAsConfigurableAttribute (true)]
  90. public string ConnectionString {
  91. get {
  92. return connectionString;
  93. }
  94. set {
  95. connectionString = value;
  96. }
  97. }
  98. #endif // ONLY_1_1
  99. [OdbcDescriptionAttribute ("Current connection timeout value, not settable in the ConnectionString")]
  100. [DefaultValue (15)]
  101. public
  102. #if NET_2_0
  103. new
  104. #endif // NET_2_0
  105. int ConnectionTimeout {
  106. get {
  107. return connectionTimeout;
  108. }
  109. set {
  110. if (value < 0) {
  111. throw new ArgumentException("Timout should not be less than zero.");
  112. }
  113. connectionTimeout = value;
  114. }
  115. }
  116. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  117. [OdbcDescriptionAttribute ("Current data source Catlog value, 'Database=X' in the ConnectionString")]
  118. public
  119. #if NET_2_0
  120. override
  121. #endif // NET_2_0
  122. string Database {
  123. get {
  124. return GetInfo (OdbcInfo.DatabaseName);
  125. }
  126. }
  127. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  128. [OdbcDescriptionAttribute ("The ConnectionState indicating whether the connection is open or closed")]
  129. [BrowsableAttribute (false)]
  130. public
  131. #if NET_2_0
  132. override
  133. #endif // NET_2_0
  134. ConnectionState State
  135. {
  136. get {
  137. if (hdbc!=IntPtr.Zero) {
  138. return ConnectionState.Open;
  139. }
  140. else
  141. return ConnectionState.Closed;
  142. }
  143. }
  144. [MonoTODO]
  145. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  146. [OdbcDescriptionAttribute ("Current data source, 'Server=X' in the ConnectionString")]
  147. public
  148. #if NET_2_0
  149. override
  150. #endif // NET_2_0
  151. string DataSource {
  152. get {
  153. return GetInfo (OdbcInfo.DataSourceName);
  154. }
  155. }
  156. [MonoTODO]
  157. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  158. [OdbcDescriptionAttribute ("Current ODBC Driver")]
  159. public string Driver {
  160. get {
  161. return GetInfo (OdbcInfo.DriverName);
  162. }
  163. }
  164. [MonoTODO]
  165. [DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
  166. [OdbcDescriptionAttribute ("Version of the product accessed by the ODBC Driver")]
  167. [BrowsableAttribute (false)]
  168. public
  169. #if NET_2_0
  170. override
  171. #endif // NET_2_0
  172. string ServerVersion {
  173. get {
  174. return GetInfo (OdbcInfo.DbmsVersion);
  175. }
  176. }
  177. #endregion // Properties
  178. #region Methods
  179. public
  180. #if NET_2_0
  181. new
  182. #endif // NET_2_0
  183. OdbcTransaction BeginTransaction ()
  184. {
  185. return BeginTransaction(IsolationLevel.Unspecified);
  186. }
  187. #if ONLY_1_1
  188. IDbTransaction IDbConnection.BeginTransaction ()
  189. {
  190. return (IDbTransaction) BeginTransaction();
  191. }
  192. #endif // ONLY_1_1
  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. OnStateChange (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. public
  285. #if NET_2_0
  286. override
  287. #endif // NET_2_0
  288. void Open ()
  289. {
  290. if (State == ConnectionState.Open)
  291. throw new InvalidOperationException ();
  292. OdbcReturn ret = OdbcReturn.Error;
  293. try {
  294. // allocate Environment handle
  295. ret = libodbc.SQLAllocHandle (OdbcHandleType.Env, IntPtr.Zero, ref henv);
  296. if ( (ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  297. throw new OdbcException (new OdbcError ("SQLAllocHandle"));
  298. ret=libodbc.SQLSetEnvAttr (henv, OdbcEnv.OdbcVersion, (IntPtr) libodbc.SQL_OV_ODBC3 , 0);
  299. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  300. throw new OdbcException (new OdbcError ("SQLSetEnvAttr", OdbcHandleType.Env,henv));
  301. // allocate connection handle
  302. ret=libodbc.SQLAllocHandle (OdbcHandleType.Dbc, henv, ref hdbc);
  303. if ( (ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  304. throw new OdbcException (new OdbcError ("SQLAllocHandle",OdbcHandleType.Env,henv));
  305. // DSN connection
  306. if (ConnectionString.ToLower().IndexOf("dsn=")>=0)
  307. {
  308. string _uid="", _pwd="", _dsn="";
  309. string[] items=ConnectionString.Split(new char[1]{';'});
  310. foreach (string item in items)
  311. {
  312. string[] parts=item.Split(new char[1] {'='});
  313. switch (parts[0].Trim().ToLower())
  314. {
  315. case "dsn":
  316. _dsn=parts[1].Trim();
  317. break;
  318. case "uid":
  319. _uid=parts[1].Trim();
  320. break;
  321. case "pwd":
  322. _pwd=parts[1].Trim();
  323. break;
  324. }
  325. }
  326. ret=libodbc.SQLConnect(hdbc, _dsn, -3, _uid, -3, _pwd, -3);
  327. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  328. throw new OdbcException(new OdbcError("SQLConnect",OdbcHandleType.Dbc,hdbc));
  329. }
  330. else
  331. {
  332. // DSN-less Connection
  333. string OutConnectionString=new String(' ',1024);
  334. short OutLen=0;
  335. ret=libodbc.SQLDriverConnect(hdbc, IntPtr.Zero, ConnectionString, -3,
  336. OutConnectionString, (short) OutConnectionString.Length, ref OutLen, 0);
  337. if ((ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  338. throw new OdbcException(new OdbcError("SQLDriverConnect",OdbcHandleType.Dbc,hdbc));
  339. }
  340. OnStateChange (ConnectionState.Closed, ConnectionState.Open);
  341. } catch (Exception) {
  342. // free handles if any.
  343. FreeHandles ();
  344. throw;
  345. }
  346. disposed = false;
  347. }
  348. [MonoTODO]
  349. public static void ReleaseObjectPool ()
  350. {
  351. throw new NotImplementedException ();
  352. }
  353. private void FreeHandles ()
  354. {
  355. OdbcReturn ret = OdbcReturn.Error;
  356. if (hdbc != IntPtr.Zero) {
  357. ret = libodbc.SQLFreeHandle ( (ushort) OdbcHandleType.Dbc, hdbc);
  358. if ( (ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  359. throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Dbc,hdbc));
  360. }
  361. hdbc = IntPtr.Zero;
  362. if (henv != IntPtr.Zero) {
  363. ret = libodbc.SQLFreeHandle ( (ushort) OdbcHandleType.Env, henv);
  364. if ( (ret!=OdbcReturn.Success) && (ret!=OdbcReturn.SuccessWithInfo))
  365. throw new OdbcException (new OdbcError ("SQLFreeHandle", OdbcHandleType.Env,henv));
  366. }
  367. henv = IntPtr.Zero;
  368. }
  369. [MonoTODO]
  370. public
  371. #if NET_2_0
  372. override
  373. #endif // NET_2_0
  374. void EnlistDistributedTransaction ( ITransaction transaction) {
  375. throw new NotImplementedException ();
  376. }
  377. internal string GetInfo (OdbcInfo info)
  378. {
  379. if (State == ConnectionState.Closed)
  380. throw new InvalidOperationException ("The connection is closed.");
  381. OdbcReturn ret = OdbcReturn.Error;
  382. short max_length = 256;
  383. byte [] buffer = new byte [max_length];
  384. short actualLength = 0;
  385. ret = libodbc.SQLGetInfo (hdbc, info, buffer, max_length, ref actualLength);
  386. if (ret != OdbcReturn.Success && ret != OdbcReturn.SuccessWithInfo)
  387. throw new OdbcException (new OdbcError ("SQLGetInfo",
  388. OdbcHandleType.Dbc,
  389. hdbc));
  390. return System.Text.Encoding.Default.GetString (buffer);
  391. }
  392. #if ONLY_1_1
  393. private void OnStateChange (ConnectionState from, ConnectionState to)
  394. {
  395. if (StateChange != null)
  396. StateChange (this, new StateChangeEventArgs (from, to));
  397. }
  398. #endif // ONLY_1_1
  399. #endregion
  400. #region Events and Delegates
  401. #if ONLY_1_1
  402. [OdbcDescription ("DbConnection_StateChange")]
  403. [OdbcCategory ("DataCategory_StateChange")]
  404. public event StateChangeEventHandler StateChange;
  405. #endif // ONLY_1_1
  406. [OdbcDescription ("DbConnection_InfoMessage")]
  407. [OdbcCategory ("DataCategory_InfoMessage")]
  408. public event OdbcInfoMessageEventHandler InfoMessage;
  409. #endregion
  410. }
  411. }