PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/danipen/mono
C# | 559 lines | 321 code | 56 blank | 182 comment | 27 complexity | 8649325ba4bb66cd397bed2466d7a011 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.OleDb;
  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 OleDb place holder for parameter ('?') for each of the parameters.
  109. /// </summary>
  110. public string OleDbParameterPlaceHolderList
  111. {
  112. get
  113. {
  114. return GetParameterPlaceHolderList("?, ");
  115. }
  116. }
  117. /// <summary>
  118. /// A textual string that conatins the MSSQL place holder for parameter ('@parame_name') for each of the parameters.
  119. /// </summary>
  120. public string SqlParameterPlaceHolderList
  121. {
  122. get
  123. {
  124. return GetParameterPlaceHolderList("{0}, ");
  125. }
  126. }
  127. /// <summary>
  128. /// A string that contains a comma delimited list of all default column names for the parameters held by this collection.
  129. /// </summary>
  130. public string ColumnsList
  131. {
  132. get
  133. {
  134. Sys.Text.StringBuilder l_sbColumnsList = new Sys.Text.StringBuilder();;
  135. foreach (DbTypeParameter l_oCurrent in this)
  136. {
  137. l_sbColumnsList.AppendFormat("{0}, ", l_oCurrent.DbColumnName);
  138. }
  139. //remove last ', ' from values list:
  140. l_sbColumnsList.Remove(l_sbColumnsList.Length -2, 2);
  141. return l_sbColumnsList.ToString();
  142. }
  143. }
  144. /// <summary>
  145. /// A string that contains a comma delimited list of all values of the parameters held by this collection.
  146. /// </summary>
  147. public string ValuesList
  148. {
  149. get
  150. {
  151. Sys.Text.StringBuilder l_sbValuesList = new Sys.Text.StringBuilder();
  152. string l_sCurrentVal = string.Empty;
  153. string l_sCurrentFormatting = string.Empty;
  154. foreach (DbTypeParameter l_oCurrent in this)
  155. {
  156. //Handle types with string representation different then ToString().
  157. l_sCurrentVal = (l_oCurrent.Value != DBNull.Value) ? l_oCurrent.Value.ToString() : "NULL";
  158. if (l_oCurrent.Value is bool)
  159. {
  160. l_sCurrentVal = ((bool)l_oCurrent.Value) ? "1" : "0";
  161. }
  162. //Set the correct foratting according to type.
  163. l_sCurrentFormatting = (l_oCurrent.Value is string) ? "'{0}', " : "{0}, ";
  164. //appent the textual representation.
  165. l_sbValuesList.AppendFormat(l_sCurrentFormatting, l_sCurrentVal);
  166. }
  167. //remove last ', ' from values list:
  168. l_sbValuesList.Remove(l_sbValuesList.Length -2, 2);
  169. return l_sbValuesList.ToString();
  170. }
  171. }
  172. #endregion
  173. #region Methods
  174. #region Public
  175. #region Sys.Collections.CollectionBase implementation
  176. /// <summary>
  177. /// Adds the specified DbTypeParameter to the DbTypeParametersCollection.
  178. /// </summary>
  179. /// <param name="a_oToAdd">The DbTypeParameter to add to the collection. </param>
  180. /// <returns>The index of the new DbTypeParameter object.</returns>
  181. /// <exception cref="ArgumentException">The column name specified by a_oToAdd.DBColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  182. public virtual int Add( DbTypeParameter a_oToAdd )
  183. {
  184. if (this.Contains(a_oToAdd.DbColumnName))
  185. {
  186. throw new ArgumentException("The column name specified by DbTypeParameter.DBColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.", "a_oToAdd");
  187. }
  188. return( List.Add( a_oToAdd ) );
  189. }
  190. /// <summary>
  191. /// Adds a DbTypeParameter with the specified data to the DbTypeParametersCollection.
  192. /// </summary>
  193. /// <param name="a_sColumnName">Specifies the initial column name for the DbTypeParameter.</param>
  194. /// <param name="a_sTypeName">Specifies the initial parameter type Name for the DbTypeParameter.</param>
  195. /// <param name="a_oValue">Specifies the initial value for the DbTypeParameter.</param>
  196. /// <returns>The index of the new DbTypeParameter object.</returns>
  197. /// <exception cref="ArgumentException">The column name specified by a_sColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  198. public virtual int Add(string a_sTypeName, object a_oValue)
  199. {
  200. DbTypeParameter l_oToAdd = new DbTypeParameter(a_sTypeName, a_oValue);
  201. return this.Add(l_oToAdd);
  202. }
  203. /// <summary>
  204. /// Adds a DbTypeParameter with the specified data to the DbTypeParametersCollection.
  205. /// </summary>
  206. /// <param name="a_sColumnName">Specifies the initial column name for the DbTypeParameter.</param>
  207. /// <param name="a_sTypeName">Specifies the initial parameter type Name for the DbTypeParameter.</param>
  208. /// <param name="a_oValue">Specifies the initial value for the DbTypeParameter.</param>
  209. /// <param name="a_iSize">Specifies the initial size for the DbTypeParameter</param>
  210. /// <returns>The index of the new DbTypeParameter object.</returns>
  211. /// <exception cref="ArgumentException">The column name specified by a_sColumnName already exist in other DbTypeParameter in the DbTypeParametersCollection.</exception>
  212. public virtual int Add(string a_sTypeName, object a_oValue, int a_iSize)
  213. {
  214. DbTypeParameter l_oToAdd = new DbTypeParameter(a_sTypeName, a_oValue, a_iSize);
  215. return this.Add(l_oToAdd);
  216. }
  217. /// <summary>
  218. /// Gets the location of the DbTypeParameter object in the collection.
  219. /// </summary>
  220. /// <param name="a_oToFind">The DbTypeParameter object to locate. </param>
  221. /// <returns>The zero-based location of the DbTypeParameter in the collection, if found; otherwise, -1.</returns>
  222. public virtual int IndexOf( DbTypeParameter a_oToFind)
  223. {
  224. return( List.IndexOf( a_oToFind ) );
  225. }
  226. /// <summary>
  227. /// Gets the location of the DbTypeParameter object in the collection.
  228. /// </summary>
  229. /// <param name="a_oToFind">The DbTypeParameter object to locate. </param>
  230. /// <returns>The zero-based location of the DbTypeParameter in the collection, if found; otherwise, -1.</returns>
  231. public virtual int IndexOf( string a_sColumnName )
  232. {
  233. for (int i=0; i<List.Count; i++)
  234. {
  235. if (this[i].DbColumnName.ToUpper() == a_sColumnName.ToUpper())
  236. {
  237. return i;
  238. }
  239. }
  240. //Didn't find such DbTypeParameter:
  241. return-1;
  242. }
  243. /// <summary>
  244. /// Determines whether the DbTypeParametersCollection contains a specific DbTypeParameter.
  245. /// </summary>
  246. /// <param name="a_oToFind">The DbTypeParameter to locate in the DbTypeParametersCollection</param>
  247. /// <returns>true if the DbTypeParametersCollection contains the specified DbTypeParameter; otherwise, false.</returns>
  248. public virtual bool Contains( DbTypeParameter a_oToFind )
  249. {
  250. // If a_oToFind is not of type DbTypeParameter, this will return false.
  251. return( List.Contains( a_oToFind ) );
  252. }
  253. /// <summary>
  254. /// Determines whether the DbTypeParametersCollection contains a DbTypeParameter with specific column name (DBColumnName).
  255. /// </summary>
  256. /// <param name="a_sToFind">The column name to locate in the DbTypeParametersCollection</param>
  257. /// <returns>true if the DbTypeParametersCollection contains a DbTypeParameter with specific column name; otherwise, false.</returns>
  258. public virtual bool Contains( string a_sToFind )
  259. {
  260. return (this.IndexOf(a_sToFind) > -1);
  261. }
  262. /// <summary>
  263. /// Creates an array of OleDbParameters based on the contents of this collection.
  264. /// </summary>
  265. /// <returns>An array of OleDbParameters based on the contents of this collection</returns>
  266. public virtual OleDbParameter[] ToOleDbParameterArray()
  267. {
  268. OleDbParameter[] l_oParams = new OleDbParameter[this.Count];
  269. for (int i=0; i<this.Count; i++)
  270. {
  271. l_oParams[i] = new OleDbParameter(this[i].ParameterName, this[i].Value);
  272. }
  273. return l_oParams;
  274. }
  275. /// <summary>
  276. /// Creates an array of SqlParameters based on the contents of this collection.
  277. /// </summary>
  278. /// <returns>An array of SqlParameters based on the contents of this collection</returns>
  279. public virtual SqlParameter[] ToSqlParameterArray()
  280. {
  281. SqlParameter[] l_oParams = new SqlParameter[this.Count];
  282. for (int i=0; i<this.Count; i++)
  283. {
  284. l_oParams[i] = new SqlParameter(this[i].ParameterName, this[i].Value);
  285. }
  286. return l_oParams;
  287. }
  288. /// <summary>
  289. /// Creates an array of objects based on the contents of this collection.
  290. /// </summary>
  291. /// <returns>An array of objects that contains all values of parameters in this collection</returns>
  292. public virtual object[] ToValuesArray()
  293. {
  294. object[] l_oParams = new object[this.Count];
  295. for (int i=0; i<this.Count; i++)
  296. {
  297. l_oParams[i] = this[i].Value;
  298. }
  299. return l_oParams;
  300. }
  301. #endregion
  302. #region Execute methods
  303. /// <summary>
  304. /// Builds and execute an INSERT command according to the DbTypeParameters in this collection, and the TableName property.
  305. /// </summary>
  306. /// <param name="a_sUniqueId">A unique identifier for the inserted row.</param>
  307. /// <returns>The number of inserted rows (usually 1).</returns>
  308. public virtual int ExecuteInsert(string a_sUniqueId)
  309. {
  310. int l_iRecordsInserted;
  311. OleDbCommand l_cmdInsert = new OleDbCommand();
  312. l_cmdInsert.Connection = new OleDbConnection(ConnectedDataProvider.ConnectionString);
  313. l_cmdInsert.CommandText = GetInsertCommandText(a_sUniqueId);
  314. AddInsertCommandParameters(l_cmdInsert.Parameters);
  315. try
  316. {
  317. if (l_cmdInsert.Connection.State != ConnectionState.Open)
  318. {
  319. l_cmdInsert.Connection.Open();
  320. }
  321. // Sys.Console.WriteLine(l_cmdInsert.CommandText);
  322. l_iRecordsInserted = l_cmdInsert.ExecuteNonQuery();
  323. }
  324. finally
  325. {
  326. l_cmdInsert.Connection.Close();
  327. }
  328. return l_iRecordsInserted;
  329. }
  330. /// <summary>
  331. /// Builds and executes an DELETE command according to the UniqueId parameter, and the TableName property.
  332. /// </summary>
  333. /// <param name="a_sUniqueId">The criteria for deleting.</param>
  334. /// <returns>The number of deleted rows.</returns>
  335. public virtual int ExecuteDelete(string a_sUniqueId)
  336. {
  337. return DbTypeParametersCollection.ExecuteDelete(this.TableName, a_sUniqueId);
  338. }
  339. /// <summary>
  340. /// Builds and executes an DELETE command according to the given TableName & UniqueId parameters.
  341. /// </summary>
  342. /// <param name="a_sTableName">The table to delete from.</param>
  343. /// <param name="a_sUniqueId">The criteria for deleting.</param>
  344. /// <returns>The number of deleted rows.</returns>
  345. public static int ExecuteDelete(string a_sTableName, string a_sUniqueId)
  346. {
  347. int l_iRecordsDeleted;
  348. OleDbCommand l_cmdDelete = new OleDbCommand();
  349. l_cmdDelete.Connection = new OleDbConnection(ConnectedDataProvider.ConnectionString);
  350. l_cmdDelete.CommandText = String.Format("DELETE FROM {0} WHERE ID='{1}'", a_sTableName, a_sUniqueId);
  351. try
  352. {
  353. if (l_cmdDelete.Connection.State != ConnectionState.Open)
  354. {
  355. l_cmdDelete.Connection.Open();
  356. }
  357. l_iRecordsDeleted = l_cmdDelete.ExecuteNonQuery();
  358. }
  359. finally
  360. {
  361. l_cmdDelete.Connection.Close();
  362. }
  363. return l_iRecordsDeleted;
  364. }
  365. /// <summary>
  366. /// Executes a select command that selects all columns specified by this collection,
  367. /// from the table specified by this collections TableName property,
  368. /// filtered by the given unique id.
  369. /// The select command is executed using ExecuteReader.
  370. /// </summary>
  371. /// <param name="a_sUniqueId">The unique id to use as rows filter.</param>
  372. /// <param name="a_oReader">Reader that holds the results of the select command.</param>
  373. /// <param name="a_oConnection">A connection object that serves the reader a_oReader for retrivieng data.</param>
  374. /// <remarks>
  375. /// While the OleDbDataReader is in use, the associated OleDbConnection is open and busy serving the OleDbDataReader.
  376. /// While in this state, no other operations can be performed on the OleDbConnection other than closing it.
  377. /// This is the case until the Close method of the OleDbDataReader is called.
  378. /// It is the users responsibility to close the OleDbConnection explicitly when it is no longer needed.
  379. /// </remarks>
  380. public virtual void ExecuteSelectReader(string a_sUniqueId, out OleDbDataReader a_oReader, out OleDbConnection a_oConnection)
  381. {
  382. OleDbCommand l_cmdSelect = BuildSelectCommand(a_sUniqueId);
  383. l_cmdSelect.Connection.Open();
  384. a_oConnection = l_cmdSelect.Connection;
  385. a_oReader = l_cmdSelect.ExecuteReader();
  386. }
  387. /// <summary>
  388. /// Executes a select command that selects all columns specified by this collection,
  389. /// from the table specified by this collections TableName property,
  390. /// filtered by the given unique id.
  391. /// The select command is executed using ExecuteScalar.
  392. /// </summary>
  393. /// <param name="a_sUniqueId">The unique id to use as rows filter.</param>
  394. /// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
  395. public virtual object ExecuteSelectScalar(string a_sUniqueId)
  396. {
  397. object l_oReturnValue = null;
  398. OleDbCommand l_cmdSelect = BuildSelectCommand(a_sUniqueId);
  399. try
  400. {
  401. l_cmdSelect.Connection.Open();
  402. l_oReturnValue = l_cmdSelect.ExecuteScalar();
  403. }
  404. finally
  405. {
  406. if (l_cmdSelect.Connection.State != ConnectionState.Closed)
  407. {
  408. l_cmdSelect.Connection.Close();
  409. }
  410. }
  411. return l_oReturnValue;
  412. }
  413. #endregion
  414. #endregion
  415. #region Callbacks
  416. //All these methods are callbacks, that ensure type safty of elements within the base.List.
  417. protected override void OnInsert( int index, Object value )
  418. {
  419. if ( value.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  420. throw new ArgumentException( "value must be of type DbTypeParameter.", "value" );
  421. }
  422. protected override void OnRemove( int index, Object value )
  423. {
  424. if ( value.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  425. throw new ArgumentException( "value must be of type DbTypeParameter.", "value" );
  426. }
  427. protected override void OnSet( int index, Object oldValue, Object newValue )
  428. {
  429. if ( newValue.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  430. throw new ArgumentException( "newValue must be of type DbTypeParameter.", "newValue" );
  431. }
  432. protected override void OnValidate( Object value )
  433. {
  434. if ( value.GetType() != Type.GetType("MonoTests.System.Data.Utils.Data.DbTypeParameter") )
  435. throw new ArgumentException( "value must be of type DbTypeParameter." );
  436. }
  437. #endregion
  438. #region Private
  439. /// <summary>
  440. /// Create a SQL text for an INSERT command with parameters ('?' notation).
  441. /// The command uses the table specified in the TableName property,
  442. /// and uses the columns specified in this parameters collection.
  443. /// </summary>
  444. /// <param name="a_sUniqueId">The Unique id for the row to be inserted.</param>
  445. private string GetInsertCommandText(string a_sUniqueId)
  446. {
  447. string l_sCmd = string.Empty;
  448. string l_sColumnsList = ColumnsList;
  449. string l_sValuesList = OleDbParameterPlaceHolderList;
  450. l_sCmd = String.Format("INSERT INTO {0} (ID, {1}) VALUES ('{2}', {3})", m_sTableName, l_sColumnsList, a_sUniqueId, l_sValuesList);
  451. return l_sCmd;
  452. }
  453. /// <summary>
  454. /// Builds an OleDbParametersCollection for an INSERT command, according to the DbTypeParameters in this collection.
  455. /// </summary>
  456. /// <param name="a_oParams">The OleDbParameterCollection to be filled.</param>
  457. private void AddInsertCommandParameters(OleDbParameterCollection a_oParams)
  458. {
  459. foreach (DbTypeParameter l_oCurrent in this)
  460. {
  461. a_oParams.Add(l_oCurrent.ParameterName, l_oCurrent.Value);
  462. }
  463. }
  464. /// <summary>
  465. /// Create a command object for a SELECT command .
  466. /// The command uses the table specified in the TableName property,
  467. /// and uses the columns specified in this parameters collection.
  468. /// </summary>
  469. /// <remarks>The ID column is not included in the selected columns of this command.</remarks>
  470. /// <returns>An OleDbCommand for selecting the columns specified in this collection, from the table specified in the TableName property. </returns>
  471. private OleDbCommand BuildSelectCommand(string a_sUniqueId)
  472. {
  473. string l_sColumnsList = ColumnsList;
  474. string l_sCmdTxt;
  475. OleDbConnection l_oConnection = new OleDbConnection(ConnectedDataProvider.ConnectionString);
  476. OleDbCommand l_cmdSelect = new OleDbCommand();
  477. //Build the command's text.
  478. l_sCmdTxt = string.Format("SELECT {0} FROM {1} WHERE ID='{2}'", l_sColumnsList, this.TableName, a_sUniqueId);
  479. //Build the command object.
  480. l_cmdSelect.CommandText = l_sCmdTxt;
  481. l_cmdSelect.Connection = l_oConnection;
  482. return l_cmdSelect;
  483. }
  484. /// <summary>
  485. /// Create a string that conatins a place holder for each of the parameters.
  486. /// </summary>
  487. /// <param name="a_sSormatting">The format for each parameter in the list (defined in String.Format())</param>
  488. /// <returns>A string that conatins a place holder for each of the parameters.</returns>
  489. private string GetParameterPlaceHolderList(string a_sSormatting)
  490. {
  491. Sys.Text.StringBuilder l_sbValuesList = new Sys.Text.StringBuilder();;
  492. foreach (DbTypeParameter l_oCurrent in this)
  493. {
  494. l_sbValuesList.AppendFormat(a_sSormatting, l_oCurrent.ParameterName);
  495. }
  496. //remove last ', ' from values list:
  497. l_sbValuesList.Remove(l_sbValuesList.Length -2, 2);
  498. return l_sbValuesList.ToString();
  499. }
  500. #endregion
  501. #endregion
  502. }
  503. }