PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/mcs/class/System.Data.OracleClient/Test/System.Data.OracleClient.jvm/MonoTests.System.Data.Utils/DbTypeParametersCollection.cs

https://bitbucket.org/danipen/mono
C# | 561 lines | 322 code | 57 blank | 182 comment | 27 complexity | 7090045d20a4948cd0de44960001b28d MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  1. //
  2. // Copyright (c) 2006 Mainsoft Co.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining
  5. // a copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to
  9. // permit persons to whom the Software is furnished to do so, subject to
  10. // the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be
  13. // included in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. //
  23. using System;
  24. using System.Data;
  25. using System.Data.OracleClient;
  26. using System.Data.SqlClient;
  27. using CollectionBase = System.Collections.CollectionBase;
  28. using Sys = System;
  29. namespace MonoTests.System.Data.Utils.Data
  30. {
  31. /// <summary>
  32. /// A collection of DbTypeParameters that matches the column of specific a database table
  33. /// </summary>
  34. public class DbTypeParametersCollection : CollectionBase
  35. {
  36. #region Constructors
  37. /// <summary>
  38. /// Default constructor.
  39. /// </summary>
  40. public DbTypeParametersCollection()
  41. {
  42. }
  43. /// <summary>
  44. /// Constructor.
  45. /// Initializes a DbTypeParametersCollection with the specified TableName
  46. /// </summary>
  47. /// <param name="a_sTableName">Specifies the table name to set.</param>
  48. public DbTypeParametersCollection(string a_sTableName)
  49. {
  50. m_sTableName = a_sTableName;
  51. }
  52. #endregion
  53. #region Members
  54. private string m_sTableName;
  55. #endregion
  56. #region Properties & Indexers
  57. public string TableName
  58. {
  59. get
  60. {
  61. return m_sTableName;
  62. }
  63. set
  64. {
  65. m_sTableName = value;
  66. }
  67. }
  68. /// <summary>
  69. /// Gets or sets the DbTypeParameter at the specified index.
  70. /// </summary>
  71. /// <exception cref="ArgumentException">The column name specified by value.DBColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  72. public DbTypeParameter this[int a_iIndex]
  73. {
  74. get
  75. {
  76. return((DbTypeParameter)List[a_iIndex]);
  77. }
  78. set
  79. {
  80. //Check that the collection does not already contain a DbTypeParameter with the same column name.
  81. int l_iIndexOfValueColumnName = this.IndexOf(value.DbColumnName);
  82. if (l_iIndexOfValueColumnName != -1 && l_iIndexOfValueColumnName != a_iIndex)
  83. {
  84. throw new ArgumentException("The column name specified by DbTypeParameter.DBColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.", "value");
  85. }
  86. else
  87. {
  88. List[a_iIndex] = value;
  89. }
  90. }
  91. }
  92. /// <summary>
  93. /// Gets or sets the DbTypeParameter with the specified DBColumnName.
  94. /// </summary>
  95. /// <exception cref="ArgumentException">The column name specified by value.DBColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  96. public DbTypeParameter this[string a_sDBColumnName]
  97. {
  98. get
  99. {
  100. return this[IndexOf(a_sDBColumnName)];
  101. }
  102. set
  103. {
  104. this[IndexOf(a_sDBColumnName)] = value;
  105. }
  106. }
  107. /// <summary>
  108. /// A textual string that conatins the Oracle place holder for parameter ('?') for each of the parameters.
  109. /// </summary>
  110. public string UnnamedParameterPlaceHolderList {
  111. get {
  112. return GetParameterPlaceHolderList("?, ");
  113. }
  114. }
  115. /// <summary>
  116. /// A textual string that conatins the MSSQL place holder for parameter ('@parame_name') for each of the parameters.
  117. /// </summary>
  118. public string NamedParameterPlaceHolderList
  119. {
  120. get
  121. {
  122. return GetParameterPlaceHolderList("{0}, ");
  123. }
  124. }
  125. /// <summary>
  126. /// A string that contains a comma delimited list of all default column names for the parameters held by this collection.
  127. /// </summary>
  128. public string ColumnsList
  129. {
  130. get
  131. {
  132. Sys.Text.StringBuilder l_sbColumnsList = new Sys.Text.StringBuilder();;
  133. foreach (DbTypeParameter l_oCurrent in this)
  134. {
  135. l_sbColumnsList.AppendFormat("{0}, ", l_oCurrent.DbColumnName);
  136. }
  137. //remove last ', ' from values list:
  138. l_sbColumnsList.Remove(l_sbColumnsList.Length -2, 2);
  139. return l_sbColumnsList.ToString();
  140. }
  141. }
  142. /// <summary>
  143. /// A string that contains a comma delimited list of all values of the parameters held by this collection.
  144. /// </summary>
  145. public string ValuesList
  146. {
  147. get
  148. {
  149. Sys.Text.StringBuilder l_sbValuesList = new Sys.Text.StringBuilder();
  150. string l_sCurrentVal = string.Empty;
  151. string l_sCurrentFormatting = string.Empty;
  152. foreach (DbTypeParameter l_oCurrent in this)
  153. {
  154. //Handle types with string representation different then ToString().
  155. l_sCurrentVal = (l_oCurrent.Value != DBNull.Value) ? l_oCurrent.Value.ToString() : "NULL";
  156. if (l_oCurrent.Value is bool)
  157. {
  158. l_sCurrentVal = ((bool)l_oCurrent.Value) ? "1" : "0";
  159. }
  160. //Set the correct foratting according to type.
  161. l_sCurrentFormatting = (l_oCurrent.Value is string) ? "'{0}', " : "{0}, ";
  162. //appent the textual representation.
  163. l_sbValuesList.AppendFormat(l_sCurrentFormatting, l_sCurrentVal);
  164. }
  165. //remove last ', ' from values list:
  166. l_sbValuesList.Remove(l_sbValuesList.Length -2, 2);
  167. return l_sbValuesList.ToString();
  168. }
  169. }
  170. #endregion
  171. #region Methods
  172. #region Public
  173. #region Sys.Collections.CollectionBase implementation
  174. /// <summary>
  175. /// Adds the specified DbTypeParameter to the DbTypeParametersCollection.
  176. /// </summary>
  177. /// <param name="a_oToAdd">The DbTypeParameter to add to the collection. </param>
  178. /// <returns>The index of the new DbTypeParameter object.</returns>
  179. /// <exception cref="ArgumentException">The column name specified by a_oToAdd.DBColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  180. public virtual int Add( DbTypeParameter a_oToAdd )
  181. {
  182. if (this.Contains(a_oToAdd.DbColumnName))
  183. {
  184. throw new ArgumentException("The column name specified by DbTypeParameter.DBColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.", "a_oToAdd");
  185. }
  186. return( List.Add( a_oToAdd ) );
  187. }
  188. /// <summary>
  189. /// Adds a DbTypeParameter with the specified data to the DbTypeParametersCollection.
  190. /// </summary>
  191. /// <param name="a_sColumnName">Specifies the initial column name for the DbTypeParameter.</param>
  192. /// <param name="a_sTypeName">Specifies the initial parameter type Name for the DbTypeParameter.</param>
  193. /// <param name="a_oValue">Specifies the initial value for the DbTypeParameter.</param>
  194. /// <returns>The index of the new DbTypeParameter object.</returns>
  195. /// <exception cref="ArgumentException">The column name specified by a_sColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  196. public virtual int Add(string a_sTypeName, object a_oValue)
  197. {
  198. DbTypeParameter l_oToAdd = new DbTypeParameter(a_sTypeName, a_oValue);
  199. return this.Add(l_oToAdd);
  200. }
  201. /// <summary>
  202. /// Adds a DbTypeParameter with the specified data to the DbTypeParametersCollection.
  203. /// </summary>
  204. /// <param name="a_sColumnName">Specifies the initial column name for the DbTypeParameter.</param>
  205. /// <param name="a_sTypeName">Specifies the initial parameter type Name for the DbTypeParameter.</param>
  206. /// <param name="a_oValue">Specifies the initial value for the DbTypeParameter.</param>
  207. /// <param name="a_iSize">Specifies the initial size for the DbTypeParameter</param>
  208. /// <returns>The index of the new DbTypeParameter object.</returns>
  209. /// <exception cref="ArgumentException">The column name specified by a_sColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  210. public virtual int Add(string a_sTypeName, object a_oValue, int a_iSize)
  211. {
  212. DbTypeParameter l_oToAdd = new DbTypeParameter(a_sTypeName, a_oValue, a_iSize);
  213. return this.Add(l_oToAdd);
  214. }
  215. /// <summary>
  216. /// Gets the location of the DbTypeParameter object in the collection.
  217. /// </summary>
  218. /// <param name="a_oToFind">The DbTypeParameter object to locate. </param>
  219. /// <returns>The zero-based location of the DbTypeParameter in the collection, if found; otherwise, -1.</returns>
  220. public virtual int IndexOf( DbTypeParameter a_oToFind)
  221. {
  222. return( List.IndexOf( a_oToFind ) );
  223. }
  224. /// <summary>
  225. /// Gets the location of the DbTypeParameter object in the collection.
  226. /// </summary>
  227. /// <param name="a_oToFind">The DbTypeParameter object to locate. </param>
  228. /// <returns>The zero-based location of the DbTypeParameter in the collection, if found; otherwise, -1.</returns>
  229. public virtual int IndexOf( string a_sColumnName )
  230. {
  231. for (int i=0; i<List.Count; i++)
  232. {
  233. if (this[i].DbColumnName.ToUpper() == a_sColumnName.ToUpper())
  234. {
  235. return i;
  236. }
  237. }
  238. //Didn't find such DbTypeParameter:
  239. return-1;
  240. }
  241. /// <summary>
  242. /// Determines whether the DbTypeParametersCollection contains a specific DbTypeParameter.
  243. /// </summary>
  244. /// <param name="a_oToFind">The DbTypeParameter to locate in the DbTypeParametersCollection</param>
  245. /// <returns>true if the DbTypeParametersCollection contains the specified DbTypeParameter; otherwise, false.</returns>
  246. public virtual bool Contains( DbTypeParameter a_oToFind )
  247. {
  248. // If a_oToFind is not of type DbTypeParameter, this will return false.
  249. return( List.Contains( a_oToFind ) );
  250. }
  251. /// <summary>
  252. /// Determines whether the DbTypeParametersCollection contains a DbTypeParameter with specific column name (DBColumnName).
  253. /// </summary>
  254. /// <param name="a_sToFind">The column name to locate in the DbTypeParametersCollection</param>
  255. /// <returns>true if the DbTypeParametersCollection contains a DbTypeParameter with specific column name; otherwise, false.</returns>
  256. public virtual bool Contains( string a_sToFind )
  257. {
  258. return (this.IndexOf(a_sToFind) > -1);
  259. }
  260. /// <summary>
  261. /// Creates an array of OracleParameters based on the contents of this collection.
  262. /// </summary>
  263. /// <returns>An array of OracleParameters based on the contents of this collection</returns>
  264. public virtual OracleParameter[] ToOracleParameterArray()
  265. {
  266. OracleParameter[] l_oParams = new OracleParameter[this.Count];
  267. for (int i=0; i<this.Count; i++)
  268. {
  269. l_oParams[i] = new OracleParameter(this[i].ParameterName, this[i].Value);
  270. }
  271. return l_oParams;
  272. }
  273. /// <summary>
  274. /// Creates an array of SqlParameters based on the contents of this collection.
  275. /// </summary>
  276. /// <returns>An array of SqlParameters based on the contents of this collection</returns>
  277. public virtual SqlParameter[] ToSqlParameterArray()
  278. {
  279. SqlParameter[] l_oParams = new SqlParameter[this.Count];
  280. for (int i=0; i<this.Count; i++)
  281. {
  282. l_oParams[i] = new SqlParameter(this[i].ParameterName, this[i].Value);
  283. }
  284. return l_oParams;
  285. }
  286. /// <summary>
  287. /// Creates an array of objects based on the contents of this collection.
  288. /// </summary>
  289. /// <returns>An array of objects that contains all values of parameters in this collection</returns>
  290. public virtual object[] ToValuesArray()
  291. {
  292. object[] l_oParams = new object[this.Count];
  293. for (int i=0; i<this.Count; i++)
  294. {
  295. l_oParams[i] = this[i].Value;
  296. }
  297. return l_oParams;
  298. }
  299. #endregion
  300. #region Execute methods
  301. /// <summary>
  302. /// Builds and execute an INSERT command according to the DbTypeParameters in this collection, and the TableName property.
  303. /// </summary>
  304. /// <param name="a_sUniqueId">A unique identifier for the inserted row.</param>
  305. /// <returns>The number of inserted rows (usually 1).</returns>
  306. public virtual int ExecuteInsert(string a_sUniqueId)
  307. {
  308. int l_iRecordsInserted;
  309. OracleCommand l_cmdInsert = new OracleCommand();
  310. l_cmdInsert.Connection = new OracleConnection(ConnectedDataProvider.ConnectionString);
  311. l_cmdInsert.CommandText = GetInsertCommandText(a_sUniqueId);
  312. AddInsertCommandParameters(l_cmdInsert.Parameters);
  313. try
  314. {
  315. if (l_cmdInsert.Connection.State != ConnectionState.Open)
  316. {
  317. l_cmdInsert.Connection.Open();
  318. }
  319. // Sys.Console.WriteLine(l_cmdInsert.CommandText);
  320. l_iRecordsInserted = l_cmdInsert.ExecuteNonQuery();
  321. }
  322. finally
  323. {
  324. l_cmdInsert.Connection.Close();
  325. }
  326. return l_iRecordsInserted;
  327. }
  328. /// <summary>
  329. /// Builds and executes an DELETE command according to the UniqueId parameter, and the TableName property.
  330. /// </summary>
  331. /// <param name="a_sUniqueId">The criteria for deleting.</param>
  332. /// <returns>The number of deleted rows.</returns>
  333. public virtual int ExecuteDelete(string a_sUniqueId)
  334. {
  335. return DbTypeParametersCollection.ExecuteDelete(this.TableName, a_sUniqueId);
  336. }
  337. /// <summary>
  338. /// Builds and executes an DELETE command according to the given TableName & UniqueId parameters.
  339. /// </summary>
  340. /// <param name="a_sTableName">The table to delete from.</param>
  341. /// <param name="a_sUniqueId">The criteria for deleting.</param>
  342. /// <returns>The number of deleted rows.</returns>
  343. public static int ExecuteDelete(string a_sTableName, string a_sUniqueId)
  344. {
  345. #if !TARGET_JVM
  346. return 0;
  347. #endif
  348. int l_iRecordsDeleted;
  349. OracleCommand l_cmdDelete = new OracleCommand();
  350. l_cmdDelete.Connection = new OracleConnection(ConnectedDataProvider.ConnectionString);
  351. l_cmdDelete.CommandText = String.Format("DELETE FROM {0} WHERE ID='{1}'", a_sTableName, a_sUniqueId);
  352. try
  353. {
  354. if (l_cmdDelete.Connection.State != ConnectionState.Open)
  355. {
  356. l_cmdDelete.Connection.Open();
  357. }
  358. l_iRecordsDeleted = l_cmdDelete.ExecuteNonQuery();
  359. }
  360. finally
  361. {
  362. l_cmdDelete.Connection.Close();
  363. }
  364. return l_iRecordsDeleted;
  365. }
  366. /// <summary>
  367. /// Executes a select command that selects all columns specified by this collection,
  368. /// from the table specified by this collections TableName property,
  369. /// filtered by the given unique id.
  370. /// The select command is executed using ExecuteReader.
  371. /// </summary>
  372. /// <param name="a_sUniqueId">The unique id to use as rows filter.</param>
  373. /// <param name="a_oReader">Reader that holds the results of the select command.</param>
  374. /// <param name="a_oConnection">A connection object that serves the reader a_oReader for retrivieng data.</param>
  375. /// <remarks>
  376. /// While the OracleDataReader is in use, the associated OracleConnection is open and busy serving the OracleDataReader.
  377. /// While in this state, no other operations can be performed on the OracleConnection other than closing it.
  378. /// This is the case until the Close method of the OracleDataReader is called.
  379. /// It is the users responsibility to close the OracleConnection explicitly when it is no longer needed.
  380. /// </remarks>
  381. public virtual void ExecuteSelectReader(string a_sUniqueId, out OracleDataReader a_oReader, out OracleConnection a_oConnection)
  382. {
  383. OracleCommand l_cmdSelect = BuildSelectCommand(a_sUniqueId);
  384. l_cmdSelect.Connection.Open();
  385. a_oConnection = l_cmdSelect.Connection;
  386. a_oReader = l_cmdSelect.ExecuteReader();
  387. }
  388. /// <summary>
  389. /// Executes a select command that selects all columns specified by this collection,
  390. /// from the table specified by this collections TableName property,
  391. /// filtered by the given unique id.
  392. /// The select command is executed using ExecuteScalar.
  393. /// </summary>
  394. /// <param name="a_sUniqueId">The unique id to use as rows filter.</param>
  395. /// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
  396. public virtual object ExecuteSelectScalar(string a_sUniqueId)
  397. {
  398. object l_oReturnValue = null;
  399. OracleCommand l_cmdSelect = BuildSelectCommand(a_sUniqueId);
  400. try
  401. {
  402. l_cmdSelect.Connection.Open();
  403. l_oReturnValue = l_cmdSelect.ExecuteScalar();
  404. }
  405. finally
  406. {
  407. if (l_cmdSelect.Connection.State != ConnectionState.Closed)
  408. {
  409. l_cmdSelect.Connection.Close();
  410. }
  411. }
  412. return l_oReturnValue;
  413. }
  414. #endregion
  415. #endregion
  416. #region Callbacks
  417. //All these methods are callbacks, that ensure type safty of elements within the base.List.
  418. protected override void OnInsert( int index, Object value )
  419. {
  420. if ( value.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  421. throw new ArgumentException( "value must be of type DbTypeParameter.", "value" );
  422. }
  423. protected override void OnRemove( int index, Object value )
  424. {
  425. if ( value.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  426. throw new ArgumentException( "value must be of type DbTypeParameter.", "value" );
  427. }
  428. protected override void OnSet( int index, Object oldValue, Object newValue )
  429. {
  430. if ( newValue.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  431. throw new ArgumentException( "newValue must be of type DbTypeParameter.", "newValue" );
  432. }
  433. protected override void OnValidate( Object value )
  434. {
  435. if ( value.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  436. throw new ArgumentException( "value must be of type DbTypeParameter." );
  437. }
  438. #endregion
  439. #region Private
  440. /// <summary>
  441. /// Create a SQL text for an INSERT command with parameters ('?' notation).
  442. /// The command uses the table specified in the TableName property,
  443. /// and uses the columns specified in this parameters collection.
  444. /// </summary>
  445. /// <param name="a_sUniqueId">The Unique id for the row to be inserted.</param>
  446. private string GetInsertCommandText(string a_sUniqueId)
  447. {
  448. string l_sCmd = string.Empty;
  449. string l_sColumnsList = ColumnsList;
  450. string l_sValuesList = NamedParameterPlaceHolderList;
  451. l_sCmd = String.Format("INSERT INTO {0} (ID, {1}) VALUES ('{2}', {3})", m_sTableName, l_sColumnsList, a_sUniqueId, l_sValuesList);
  452. return l_sCmd;
  453. }
  454. /// <summary>
  455. /// Builds an OracleParametersCollection for an INSERT command, according to the DbTypeParameters in this collection.
  456. /// </summary>
  457. /// <param name="a_oParams">The OracleParameterCollection to be filled.</param>
  458. private void AddInsertCommandParameters(OracleParameterCollection a_oParams)
  459. {
  460. foreach (DbTypeParameter l_oCurrent in this)
  461. {
  462. a_oParams.Add(l_oCurrent.ParameterName, l_oCurrent.Value);
  463. }
  464. }
  465. /// <summary>
  466. /// Create a command object for a SELECT command .
  467. /// The command uses the table specified in the TableName property,
  468. /// and uses the columns specified in this parameters collection.
  469. /// </summary>
  470. /// <remarks>The ID column is not included in the selected columns of this command.</remarks>
  471. /// <returns>An OracleCommand for selecting the columns specified in this collection, from the table specified in the TableName property. </returns>
  472. private OracleCommand BuildSelectCommand(string a_sUniqueId)
  473. {
  474. string l_sColumnsList = ColumnsList;
  475. string l_sCmdTxt;
  476. OracleConnection l_oConnection = new OracleConnection(ConnectedDataProvider.ConnectionString);
  477. OracleCommand l_cmdSelect = new OracleCommand();
  478. //Build the command's text.
  479. l_sCmdTxt = string.Format("SELECT {0} FROM {1} WHERE ID='{2}'", l_sColumnsList, this.TableName, a_sUniqueId);
  480. //Build the command object.
  481. l_cmdSelect.CommandText = l_sCmdTxt;
  482. l_cmdSelect.Connection = l_oConnection;
  483. return l_cmdSelect;
  484. }
  485. /// <summary>
  486. /// Create a string that conatins a place holder for each of the parameters.
  487. /// </summary>
  488. /// <param name="a_sSormatting">The format for each parameter in the list (defined in String.Format())</param>
  489. /// <returns>A string that conatins a place holder for each of the parameters.</returns>
  490. private string GetParameterPlaceHolderList(string a_sSormatting)
  491. {
  492. Sys.Text.StringBuilder l_sbValuesList = new Sys.Text.StringBuilder();;
  493. foreach (DbTypeParameter l_oCurrent in this)
  494. {
  495. l_sbValuesList.AppendFormat(a_sSormatting, l_oCurrent.ParameterName);
  496. }
  497. //remove last ', ' from values list:
  498. l_sbValuesList.Remove(l_sbValuesList.Length -2, 2);
  499. return l_sbValuesList.ToString();
  500. }
  501. #endregion
  502. #endregion
  503. }
  504. }