PageRenderTime 63ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/Crab.DataModel/Utility/SqlHelper.cs

#
C# | 2811 lines | 1164 code | 314 blank | 1333 comment | 578 complexity | 8ba69f7e429327802591626d3ac5b2ae MD5 | raw file
  1. // ===============================================================================
  2. // Microsoft Data Access Application Block for .NET
  3. // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
  4. //
  5. // SQLHelper.cs
  6. //
  7. // This file contains the implementations of the SqlHelper and SqlHelperParameterCache
  8. // classes.
  9. //
  10. // For more information see the Data Access Application Block Implementation Overview.
  11. // ===============================================================================
  12. // Release history
  13. // VERSION DESCRIPTION
  14. // 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods
  15. //
  16. // ===============================================================================
  17. // Copyright (C) 2000-2001 Microsoft Corporation
  18. // All rights reserved.
  19. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
  20. // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
  21. // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
  22. // FITNESS FOR A PARTICULAR PURPOSE.
  23. // ==============================================================================
  24. using System;
  25. using System.Data;
  26. using System.Xml;
  27. using System.Data.SqlClient;
  28. using System.Collections;
  29. using System.IO;
  30. using System.Configuration;
  31. namespace Crab.DataModel.Utility
  32. {
  33. /// <summary>
  34. /// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
  35. /// common uses of SqlClient
  36. /// </summary>
  37. public sealed class SqlHelper
  38. {
  39. #region private utility methods & constructors
  40. // Since this class provides only static methods, make the default constructor private to prevent
  41. // instances from being created with "new SqlHelper()"
  42. private SqlHelper() { }
  43. /// <summary>
  44. /// This method is used to attach array of SqlParameters to a SqlCommand.
  45. ///
  46. /// This method will assign a value of DbNull to any parameter with a direction of
  47. /// InputOutput and a value of null.
  48. ///
  49. /// This behavior will prevent default values from being used, but
  50. /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
  51. /// where the user provided no input value.
  52. /// </summary>
  53. /// <param name="command">The command to which the parameters will be added</param>
  54. /// <param name="commandParameters">An array of SqlParameters to be added to command</param>
  55. private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
  56. {
  57. if (command == null) throw new ArgumentNullException("command");
  58. if (commandParameters != null)
  59. {
  60. foreach (SqlParameter p in commandParameters)
  61. {
  62. if (p != null)
  63. {
  64. // Check for derived output value with no value assigned
  65. if ((p.Direction == ParameterDirection.InputOutput ||
  66. p.Direction == ParameterDirection.Input) &&
  67. (p.Value == null))
  68. {
  69. p.Value = DBNull.Value;
  70. }
  71. command.Parameters.Add(p);
  72. }
  73. }
  74. }
  75. }
  76. /// <summary>
  77. /// This method assigns dataRow column values to an array of SqlParameters
  78. /// </summary>
  79. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  80. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
  81. private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
  82. {
  83. if ((commandParameters == null) || (dataRow == null))
  84. {
  85. // Do nothing if we get no data
  86. return;
  87. }
  88. int i = 0;
  89. // Set the parameters values
  90. foreach (SqlParameter commandParameter in commandParameters)
  91. {
  92. // Check the parameter name
  93. if (commandParameter.ParameterName == null ||
  94. commandParameter.ParameterName.Length <= 1)
  95. throw new Exception(
  96. string.Format(
  97. "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
  98. i, commandParameter.ParameterName));
  99. if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
  100. commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
  101. i++;
  102. }
  103. }
  104. /// <summary>
  105. /// This method assigns an array of values to an array of SqlParameters
  106. /// </summary>
  107. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  108. /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
  109. private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
  110. {
  111. if ((commandParameters == null) || (parameterValues == null))
  112. {
  113. // Do nothing if we get no data
  114. return;
  115. }
  116. // We must have the same number of values as we pave parameters to put them in
  117. if (commandParameters.Length != parameterValues.Length)
  118. {
  119. throw new ArgumentException("Parameter count does not match Parameter Value count.");
  120. }
  121. // Iterate through the SqlParameters, assigning the values from the corresponding position in the
  122. // value array
  123. for (int i = 0, j = commandParameters.Length; i < j; i++)
  124. {
  125. // If the current array value derives from IDbDataParameter, then assign its Value property
  126. if (parameterValues[i] is IDbDataParameter)
  127. {
  128. IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
  129. if (paramInstance.Value == null)
  130. {
  131. commandParameters[i].Value = DBNull.Value;
  132. }
  133. else
  134. {
  135. commandParameters[i].Value = paramInstance.Value;
  136. }
  137. }
  138. else if (parameterValues[i] == null)
  139. {
  140. commandParameters[i].Value = DBNull.Value;
  141. }
  142. else
  143. {
  144. commandParameters[i].Value = parameterValues[i];
  145. }
  146. }
  147. }
  148. /// <summary>
  149. /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
  150. /// to the provided command
  151. /// </summary>
  152. /// <param name="command">The SqlCommand to be prepared</param>
  153. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  154. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  155. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  156. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  157. /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  158. /// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
  159. private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection)
  160. {
  161. if (command == null) throw new ArgumentNullException("command");
  162. if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
  163. // If the provided connection is not open, we will open it
  164. if (connection.State != ConnectionState.Open)
  165. {
  166. mustCloseConnection = true;
  167. connection.Open();
  168. }
  169. else
  170. {
  171. mustCloseConnection = false;
  172. }
  173. // Associate the connection with the command
  174. command.Connection = connection;
  175. // Set the command text (stored procedure name or SQL statement)
  176. command.CommandText = commandText;
  177. // If we were provided a transaction, assign it
  178. if (transaction != null)
  179. {
  180. if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  181. command.Transaction = transaction;
  182. }
  183. // Set the command type
  184. command.CommandType = commandType;
  185. // Attach the command parameters if they are provided
  186. if (commandParameters != null)
  187. {
  188. AttachParameters(command, commandParameters);
  189. }
  190. return;
  191. }
  192. #endregion private utility methods & constructors
  193. #region ExecuteNonQuery
  194. /// <summary>
  195. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
  196. /// the connection string
  197. /// </summary>
  198. /// <remarks>
  199. /// e.g.:
  200. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
  201. /// </remarks>
  202. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  203. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  204. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  205. /// <returns>An int representing the number of rows affected by the command</returns>
  206. public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
  207. {
  208. // Pass through the call providing null for the set of SqlParameters
  209. return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
  210. }
  211. /// <summary>
  212. /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
  213. /// using the provided parameters
  214. /// </summary>
  215. /// <remarks>
  216. /// e.g.:
  217. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  218. /// </remarks>
  219. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  220. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  221. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  222. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  223. /// <returns>An int representing the number of rows affected by the command</returns>
  224. public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  225. {
  226. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  227. // Create & open a SqlConnection, and dispose of it after we are done
  228. using (SqlConnection connection = new SqlConnection(connectionString))
  229. {
  230. connection.Open();
  231. // Call the overload that takes a connection in place of the connection string
  232. return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
  233. }
  234. }
  235. /// <summary>
  236. /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
  237. /// using the provided parameters
  238. /// </summary>
  239. /// <remarks>
  240. /// e.g.:
  241. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  242. /// </remarks>
  243. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  244. /// <param name="spName">The stored procedure name</param>
  245. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  246. /// <returns>An int representing the number of rows affected by the command</returns>
  247. public static int ExecuteNonQuery(string connectionString, string spName, params SqlParameter[] commandParameters)
  248. {
  249. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  250. // Create & open a SqlConnection, and dispose of it after we are done
  251. using (SqlConnection connection = new SqlConnection(connectionString))
  252. {
  253. connection.Open();
  254. // Call the overload that takes a connection in place of the connection string
  255. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  256. }
  257. }
  258. /// <summary>
  259. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
  260. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  261. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  262. /// </summary>
  263. /// <remarks>
  264. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  265. ///
  266. /// e.g.:
  267. /// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
  268. /// </remarks>
  269. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  270. /// <param name="spName">The name of the stored prcedure</param>
  271. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  272. /// <returns>An int representing the number of rows affected by the command</returns>
  273. public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
  274. {
  275. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  276. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  277. // If we receive parameter values, we need to figure out where they go
  278. if ((parameterValues != null) && (parameterValues.Length > 0))
  279. {
  280. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  281. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  282. // Assign the provided values to these parameters based on parameter order
  283. AssignParameterValues(commandParameters, parameterValues);
  284. // Call the overload that takes an array of SqlParameters
  285. return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  286. }
  287. else
  288. {
  289. // Otherwise we can just call the SP without params
  290. return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
  291. }
  292. }
  293. /// <summary>
  294. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
  295. /// </summary>
  296. /// <remarks>
  297. /// e.g.:
  298. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
  299. /// </remarks>
  300. /// <param name="connection">A valid SqlConnection</param>
  301. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  302. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  303. /// <returns>An int representing the number of rows affected by the command</returns>
  304. public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
  305. {
  306. // Pass through the call providing null for the set of SqlParameters
  307. return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
  308. }
  309. /// <summary>
  310. /// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
  311. /// using the provided parameters.
  312. /// </summary>
  313. /// <remarks>
  314. /// e.g.:
  315. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  316. /// </remarks>
  317. /// <param name="connection">A valid SqlConnection</param>
  318. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  319. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  320. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  321. /// <returns>An int representing the number of rows affected by the command</returns>
  322. public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  323. {
  324. if (connection == null) throw new ArgumentNullException("connection");
  325. // Create a command and prepare it for execution
  326. SqlCommand cmd = new SqlCommand();
  327. bool mustCloseConnection = false;
  328. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  329. // Finally, execute the command
  330. int retval = cmd.ExecuteNonQuery();
  331. // Detach the SqlParameters from the command object, so they can be used again
  332. cmd.Parameters.Clear();
  333. if (mustCloseConnection)
  334. connection.Close();
  335. return retval;
  336. }
  337. /// <summary>
  338. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
  339. /// using the provided parameter values. This method will query the database to discover the parameters for the
  340. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  341. /// </summary>
  342. /// <remarks>
  343. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  344. ///
  345. /// e.g.:
  346. /// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
  347. /// </remarks>
  348. /// <param name="connection">A valid SqlConnection</param>
  349. /// <param name="spName">The name of the stored procedure</param>
  350. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  351. /// <returns>An int representing the number of rows affected by the command</returns>
  352. public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
  353. {
  354. if (connection == null) throw new ArgumentNullException("connection");
  355. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  356. // If we receive parameter values, we need to figure out where they go
  357. if ((parameterValues != null) && (parameterValues.Length > 0))
  358. {
  359. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  360. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  361. // Assign the provided values to these parameters based on parameter order
  362. AssignParameterValues(commandParameters, parameterValues);
  363. // Call the overload that takes an array of SqlParameters
  364. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  365. }
  366. else
  367. {
  368. // Otherwise we can just call the SP without params
  369. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
  370. }
  371. }
  372. /// <summary>
  373. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
  374. /// </summary>
  375. /// <remarks>
  376. /// e.g.:
  377. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
  378. /// </remarks>
  379. /// <param name="transaction">A valid SqlTransaction</param>
  380. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  381. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  382. /// <returns>An int representing the number of rows affected by the command</returns>
  383. public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
  384. {
  385. // Pass through the call providing null for the set of SqlParameters
  386. return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
  387. }
  388. /// <summary>
  389. /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
  390. /// using the provided parameters.
  391. /// </summary>
  392. /// <remarks>
  393. /// e.g.:
  394. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  395. /// </remarks>
  396. /// <param name="transaction">A valid SqlTransaction</param>
  397. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  398. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  399. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  400. /// <returns>An int representing the number of rows affected by the command</returns>
  401. public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  402. {
  403. if (transaction == null) throw new ArgumentNullException("transaction");
  404. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  405. // Create a command and prepare it for execution
  406. SqlCommand cmd = new SqlCommand();
  407. bool mustCloseConnection = false;
  408. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  409. // Finally, execute the command
  410. int retval = cmd.ExecuteNonQuery();
  411. // Detach the SqlParameters from the command object, so they can be used again
  412. cmd.Parameters.Clear();
  413. return retval;
  414. }
  415. /// <summary>
  416. /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
  417. /// using the provided parameters.
  418. /// </summary>
  419. /// <remarks>
  420. /// e.g.:
  421. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  422. /// </remarks>
  423. /// <param name="transaction">A valid SqlTransaction</param>
  424. /// <param name="spName">The stored procedure name</param>
  425. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  426. /// <returns>An int representing the number of rows affected by the command</returns>
  427. public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params SqlParameter[] commandParameters)
  428. {
  429. if (transaction == null) throw new ArgumentNullException("transaction");
  430. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  431. // Create a command and prepare it for execution
  432. SqlCommand cmd = new SqlCommand();
  433. bool mustCloseConnection = false;
  434. PrepareCommand(cmd, transaction.Connection, transaction, CommandType.StoredProcedure, spName, commandParameters, out mustCloseConnection);
  435. // Finally, execute the command
  436. int retval = cmd.ExecuteNonQuery();
  437. // Detach the SqlParameters from the command object, so they can be used again
  438. cmd.Parameters.Clear();
  439. return retval;
  440. }
  441. /// <summary>
  442. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
  443. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  444. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  445. /// </summary>
  446. /// <remarks>
  447. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  448. ///
  449. /// e.g.:
  450. /// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
  451. /// </remarks>
  452. /// <param name="transaction">A valid SqlTransaction</param>
  453. /// <param name="spName">The name of the stored procedure</param>
  454. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  455. /// <returns>An int representing the number of rows affected by the command</returns>
  456. public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
  457. {
  458. if (transaction == null) throw new ArgumentNullException("transaction");
  459. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  460. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  461. // If we receive parameter values, we need to figure out where they go
  462. if ((parameterValues != null) && (parameterValues.Length > 0))
  463. {
  464. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  465. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  466. // Assign the provided values to these parameters based on parameter order
  467. AssignParameterValues(commandParameters, parameterValues);
  468. // Call the overload that takes an array of SqlParameters
  469. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
  470. }
  471. else
  472. {
  473. // Otherwise we can just call the SP without params
  474. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
  475. }
  476. }
  477. #endregion ExecuteNonQuery
  478. #region ExecuteDataset
  479. /// <summary>
  480. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  481. /// the connection string.
  482. /// </summary>
  483. /// <remarks>
  484. /// e.g.:
  485. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
  486. /// </remarks>
  487. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  488. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  489. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  490. /// <returns>A dataset containing the resultset generated by the command</returns>
  491. public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
  492. {
  493. // Pass through the call providing null for the set of SqlParameters
  494. return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
  495. }
  496. /// <summary>
  497. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  498. /// using the provided parameters.
  499. /// </summary>
  500. /// <remarks>
  501. /// e.g.:
  502. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  503. /// </remarks>
  504. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  505. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  506. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  507. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  508. /// <returns>A dataset containing the resultset generated by the command</returns>
  509. public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  510. {
  511. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  512. // Create & open a SqlConnection, and dispose of it after we are done
  513. using (SqlConnection connection = new SqlConnection(connectionString))
  514. {
  515. connection.Open();
  516. // Call the overload that takes a connection in place of the connection string
  517. return ExecuteDataset(connection, commandType, commandText, commandParameters);
  518. }
  519. }
  520. /// <summary>
  521. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  522. /// using the provided parameters.
  523. /// </summary>
  524. /// <remarks>
  525. /// e.g.:
  526. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  527. /// </remarks>
  528. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  529. /// <param name="spName">The stored procedure name </param>
  530. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  531. /// <returns>A dataset containing the resultset generated by the command</returns>
  532. public static DataSet ExecuteDataset(string connectionString, string spName, params SqlParameter[] commandParameters)
  533. {
  534. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  535. // Create & open a SqlConnection, and dispose of it after we are done
  536. using (SqlConnection connection = new SqlConnection(connectionString))
  537. {
  538. connection.Open();
  539. // Call the overload that takes a connection in place of the connection string
  540. return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  541. }
  542. }
  543. /// <summary>
  544. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  545. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  546. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  547. /// </summary>
  548. /// <remarks>
  549. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  550. ///
  551. /// e.g.:
  552. /// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
  553. /// </remarks>
  554. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  555. /// <param name="spName">The name of the stored procedure</param>
  556. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  557. /// <returns>A dataset containing the resultset generated by the command</returns>
  558. public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
  559. {
  560. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  561. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  562. // If we receive parameter values, we need to figure out where they go
  563. if ((parameterValues != null) && (parameterValues.Length > 0))
  564. {
  565. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  566. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  567. // Assign the provided values to these parameters based on parameter order
  568. AssignParameterValues(commandParameters, parameterValues);
  569. // Call the overload that takes an array of SqlParameters
  570. return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  571. }
  572. else
  573. {
  574. // Otherwise we can just call the SP without params
  575. return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
  576. }
  577. }
  578. /// <summary>
  579. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  580. /// </summary>
  581. /// <remarks>
  582. /// e.g.:
  583. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
  584. /// </remarks>
  585. /// <param name="connection">A valid SqlConnection</param>
  586. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  587. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  588. /// <returns>A dataset containing the resultset generated by the command</returns>
  589. public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
  590. {
  591. // Pass through the call providing null for the set of SqlParameters
  592. return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
  593. }
  594. /// <summary>
  595. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  596. /// using the provided parameters.
  597. /// </summary>
  598. /// <remarks>
  599. /// e.g.:
  600. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  601. /// </remarks>
  602. /// <param name="connection">A valid SqlConnection</param>
  603. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  604. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  605. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  606. /// <returns>A dataset containing the resultset generated by the command</returns>
  607. public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  608. {
  609. if (connection == null) throw new ArgumentNullException("connection");
  610. // Create a command and prepare it for execution
  611. SqlCommand cmd = new SqlCommand();
  612. bool mustCloseConnection = false;
  613. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  614. // Create the DataAdapter & DataSet
  615. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  616. {
  617. DataSet ds = new DataSet();
  618. // Fill the DataSet using default values for DataTable names, etc
  619. da.Fill(ds);
  620. // Detach the SqlParameters from the command object, so they can be used again
  621. cmd.Parameters.Clear();
  622. if (mustCloseConnection)
  623. connection.Close();
  624. // Return the dataset
  625. return ds;
  626. }
  627. }
  628. /// <summary>
  629. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  630. /// using the provided parameter values. This method will query the database to discover the parameters for the
  631. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  632. /// </summary>
  633. /// <remarks>
  634. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  635. ///
  636. /// e.g.:
  637. /// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
  638. /// </remarks>
  639. /// <param name="connection">A valid SqlConnection</param>
  640. /// <param name="spName">The name of the stored procedure</param>
  641. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  642. /// <returns>A dataset containing the resultset generated by the command</returns>
  643. public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
  644. {
  645. if (connection == null) throw new ArgumentNullException("connection");
  646. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  647. // If we receive parameter values, we need to figure out where they go
  648. if ((parameterValues != null) && (parameterValues.Length > 0))
  649. {
  650. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  651. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  652. // Assign the provided values to these parameters based on parameter order
  653. AssignParameterValues(commandParameters, parameterValues);
  654. // Call the overload that takes an array of SqlParameters
  655. return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  656. }
  657. else
  658. {
  659. // Otherwise we can just call the SP without params
  660. return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
  661. }
  662. }
  663. /// <summary>
  664. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  665. /// </summary>
  666. /// <remarks>
  667. /// e.g.:
  668. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
  669. /// </remarks>
  670. /// <param name="transaction">A valid SqlTransaction</param>
  671. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  672. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  673. /// <returns>A dataset containing the resultset generated by the command</returns>
  674. public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
  675. {
  676. // Pass through the call providing null for the set of SqlParameters
  677. return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
  678. }
  679. /// <summary>
  680. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  681. /// using the provided parameters.
  682. /// </summary>
  683. /// <remarks>
  684. /// e.g.:
  685. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  686. /// </remarks>
  687. /// <param name="transaction">A valid SqlTransaction</param>
  688. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  689. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  690. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  691. /// <returns>A dataset containing the resultset generated by the command</returns>
  692. public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  693. {
  694. if (transaction == null) throw new ArgumentNullException("transaction");
  695. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  696. // Create a command and prepare it for execution
  697. SqlCommand cmd = new SqlCommand();
  698. bool mustCloseConnection = false;
  699. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  700. // Create the DataAdapter & DataSet
  701. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  702. {
  703. DataSet ds = new DataSet();
  704. // Fill the DataSet using default values for DataTable names, etc
  705. da.Fill(ds);
  706. // Detach the SqlParameters from the command object, so they can be used again
  707. cmd.Parameters.Clear();
  708. // Return the dataset
  709. return ds;
  710. }
  711. }
  712. /// <summary>
  713. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  714. /// using the provided parameters.
  715. /// </summary>
  716. /// <remarks>
  717. /// e.g.:
  718. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  719. /// </remarks>
  720. /// <param name="transaction">A valid SqlTransaction</param>
  721. /// <param name="spName">The stored procedure name </param>
  722. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  723. /// <returns>A dataset containing the resultset generated by the command</returns>
  724. public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params SqlParameter[] commandParameters)
  725. {
  726. if (transaction == null) throw new ArgumentNullException("transaction");
  727. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  728. // Create a command and prepare it for execution
  729. SqlCommand cmd = new SqlCommand();
  730. bool mustCloseConnection = false;
  731. PrepareCommand(cmd, transaction.Connection, transaction, CommandType.StoredProcedure, spName, commandParameters, out mustCloseConnection);
  732. // Create the DataAdapter & DataSet
  733. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  734. {
  735. DataSet ds = new DataSet();
  736. // Fill the DataSet using default values for DataTable names, etc
  737. da.Fill(ds);
  738. // Detach the SqlParameters from the command object, so they can be used again
  739. cmd.Parameters.Clear();
  740. // Return the dataset
  741. return ds;
  742. }
  743. }
  744. /// <summary>
  745. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  746. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  747. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  748. /// </summary>
  749. /// <remarks>
  750. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  751. ///
  752. /// e.g.:
  753. /// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
  754. /// </remarks>
  755. /// <param name="transaction">A valid SqlTransaction</param>
  756. /// <param name="spName">The name of the stored procedure</param>
  757. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  758. /// <returns>A dataset containing the resultset generated by the command</returns>
  759. public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
  760. {
  761. if (transaction == null) throw new ArgumentNullException("transaction");
  762. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  763. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  764. // If we receive parameter values, we need to figure out where they go
  765. if ((parameterValues != null) && (parameterValues.Length > 0))
  766. {
  767. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  768. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  769. // Assign the provided values to these parameters based on parameter order
  770. AssignParameterValues(commandParameters, parameterValues);
  771. // Call the overload that takes an array of SqlParameters
  772. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
  773. }
  774. else
  775. {
  776. // Otherwise we can just call the SP without params
  777. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
  778. }
  779. }
  780. #endregion ExecuteDataset
  781. #region ExecuteReader
  782. /// <summary>
  783. /// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
  784. /// we can set the appropriate CommandBehavior when calling ExecuteReader()
  785. /// </summary>
  786. private enum SqlConnectionOwnership
  787. {
  788. /// <summary>Connection is owned and managed by SqlHelper</summary>
  789. Internal,
  790. /// <summary>Connection is owned and managed by the caller</summary>
  791. External
  792. }
  793. /// <summary>
  794. /// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
  795. /// </summary>
  796. /// <remarks>
  797. /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
  798. ///
  799. /// If the caller provided the connection, we want to leave it to them to manage.
  800. /// </remarks>
  801. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  802. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  803. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  804. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  805. /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  806. /// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
  807. /// <returns>SqlDataReader containing the results of the command</returns>
  808. private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
  809. {
  810. if (connection == null) throw new ArgumentNullException("connection");
  811. bool mustCloseConnection = false;
  812. // Create a command and prepare it for execution
  813. SqlCommand cmd = new SqlCommand();
  814. try
  815. {
  816. PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  817. // Create a reader
  818. SqlDataReader dataReader;
  819. // Call ExecuteReader with the appropriate CommandBehavior
  820. if (connectionOwnership == SqlConnectionOwnership.External)
  821. {
  822. dataReader = cmd.ExecuteReader();
  823. }
  824. else
  825. {
  826. dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  827. }
  828. // Detach the SqlParameters from the command object, so they can be used again.
  829. // HACK: There is a problem here, the output parameter values are fletched
  830. // when the reader is closed, so if the parameters are detached from the command
  831. // then the SqlReader can´t set its values.
  832. // When this happen, the parameters can´t be used again in other command.
  833. bool canClear = true;
  834. foreach (SqlParameter commandParameter in cmd.Parameters)
  835. {
  836. if (commandParameter.Direction != ParameterDirection.Input)
  837. canClear = false;
  838. }
  839. if (canClear)
  840. {
  841. cmd.Parameters.Clear();
  842. }
  843. return dataReader;
  844. }
  845. catch
  846. {
  847. if (mustCloseConnection)
  848. connection.Close();
  849. throw;
  850. }
  851. }
  852. /// <summary>
  853. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  854. /// the connection string.
  855. /// </summary>
  856. /// <remarks>
  857. /// e.g.:
  858. /// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
  859. /// </remarks>
  860. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  861. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  862. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  863. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  864. public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
  865. {
  866. // Pass through the call providing null for the set of SqlParameters
  867. return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
  868. }
  869. /// <summary>
  870. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  871. /// using the provided parameters.
  872. /// </summary>
  873. /// <remarks>
  874. /// e.g.:
  875. /// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  876. /// </remarks>
  877. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  878. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  879. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  880. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  881. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  882. public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  883. {
  884. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  885. SqlConnection connection = null;
  886. try
  887. {
  888. connection = new SqlConnection(connectionString);
  889. connection.Open();
  890. // Call the private overload that takes an internally owned connection in place of the connection string
  891. return ExecuteReader(connection, null, commandType, commandText, commandParameters, SqlConnectionOwnership.Internal);
  892. }
  893. catch
  894. {
  895. // If we fail to return the SqlDatReader, we need to close the connection ourselves
  896. if (connection != null) connection.Close();
  897. throw;
  898. }
  899. }
  900. /// <summary>
  901. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  902. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  903. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  904. /// </summary>
  905. /// <remarks>
  906. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  907. ///
  908. /// e.g.:
  909. /// SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36);
  910. /// </remarks>
  911. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  912. /// <param name="spName">The name of the stored procedure</param>
  913. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  914. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  915. public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
  916. {
  917. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  918. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  919. // If we receive parameter values, we need to figure out where they go
  920. if ((parameterValues != null) && (parameterValues.Length > 0))
  921. {
  922. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  923. AssignParameterValues(commandParameters, parameterValues);
  924. return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  925. }
  926. else
  927. {
  928. // Otherwise we can just call the SP without params
  929. return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
  930. }
  931. }
  932. /// <summary>
  933. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  934. /// </summary>
  935. /// <remarks>
  936. /// e.g.:
  937. /// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
  938. /// </remarks>
  939. /// <param name="connection">A valid SqlConnection</param>
  940. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  941. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  942. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  943. public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
  944. {
  945. // Pass through the call providing null for the set of SqlParameters
  946. return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
  947. }
  948. /// <summary>
  949. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  950. /// using the provided parameters.
  951. /// </summary>
  952. /// <remarks>
  953. /// e.g.:
  954. /// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  955. /// </remarks>
  956. /// <param name="connection">A valid SqlConnection</param>
  957. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  958. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  959. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  960. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  961. public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  962. {
  963. // Pass through the call to the private overload using a null transaction value and an externally owned connection
  964. return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
  965. }
  966. /// <summary>
  967. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  968. /// using the provided parameter values. This method will query the database to discover the parameters for the
  969. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  970. /// </summary>
  971. /// <remarks>
  972. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  973. ///
  974. /// e.g.:
  975. /// SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36);
  976. /// </remarks>
  977. /// <param name="connection">A valid SqlConnection</param>
  978. /// <param name="spName">The name of the stored procedure</param>
  979. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  980. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  981. public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
  982. {
  983. if (connection == null) throw new ArgumentNullException("connection");
  984. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  985. // If we receive parameter values, we need to figure out where they go
  986. if ((parameterValues != null) && (parameterValues.Length > 0))
  987. {
  988. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  989. AssignParameterValues(commandParameters, parameterValues);
  990. return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  991. }
  992. else
  993. {
  994. // Otherwise we can just call the SP without params
  995. return ExecuteReader(connection, CommandType.StoredProcedure, spName);
  996. }
  997. }
  998. /// <summary>
  999. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  1000. /// </summary>
  1001. /// <remarks>
  1002. /// e.g.:
  1003. /// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
  1004. /// </remarks>
  1005. /// <param name="transaction">A valid SqlTransaction</param>
  1006. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1007. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1008. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  1009. public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
  1010. {
  1011. // Pass through the call providing null for the set of SqlParameters
  1012. return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
  1013. }
  1014. /// <summary>
  1015. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  1016. /// using the provided parameters.
  1017. /// </summary>
  1018. /// <remarks>
  1019. /// e.g.:
  1020. /// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  1021. /// </remarks>
  1022. /// <param name="transaction">A valid SqlTransaction</param>
  1023. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1024. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1025. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1026. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  1027. public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1028. {
  1029. if (transaction == null) throw new ArgumentNullException("transaction");
  1030. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1031. // Pass through to private overload, indicating that the connection is owned by the caller
  1032. return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
  1033. }
  1034. /// <summary>
  1035. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  1036. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1037. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1038. /// </summary>
  1039. /// <remarks>
  1040. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1041. ///
  1042. /// e.g.:
  1043. /// SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36);
  1044. /// </remarks>
  1045. /// <param name="transaction">A valid SqlTransaction</param>
  1046. /// <param name="spName">The name of the stored procedure</param>
  1047. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1048. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  1049. public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
  1050. {
  1051. if (transaction == null) throw new ArgumentNullException("transaction");
  1052. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1053. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1054. // If we receive parameter values, we need to figure out where they go
  1055. if ((parameterValues != null) && (parameterValues.Length > 0))
  1056. {
  1057. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1058. AssignParameterValues(commandParameters, parameterValues);
  1059. return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  1060. }
  1061. else
  1062. {
  1063. // Otherwise we can just call the SP without params
  1064. return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
  1065. }
  1066. }
  1067. #endregion ExecuteReader
  1068. #region ExecuteScalar
  1069. /// <summary>
  1070. /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in
  1071. /// the connection string.
  1072. /// </summary>
  1073. /// <remarks>
  1074. /// e.g.:
  1075. /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
  1076. /// </remarks>
  1077. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1078. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1079. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1080. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1081. public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
  1082. {
  1083. // Pass through the call providing null for the set of SqlParameters
  1084. return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
  1085. }
  1086. /// <summary>
  1087. /// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string
  1088. /// using the provided parameters.
  1089. /// </summary>
  1090. /// <remarks>
  1091. /// e.g.:
  1092. /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1093. /// </remarks>
  1094. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1095. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1096. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1097. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1098. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1099. public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1100. {
  1101. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1102. // Create & open a SqlConnection, and dispose of it after we are done
  1103. using (SqlConnection connection = new SqlConnection(connectionString))
  1104. {
  1105. connection.Open();
  1106. // Call the overload that takes a connection in place of the connection string
  1107. return ExecuteScalar(connection, commandType, commandText, commandParameters);
  1108. }
  1109. }
  1110. /// <summary>
  1111. /// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string
  1112. /// using the provided parameters.
  1113. /// </summary>
  1114. /// <remarks>
  1115. /// e.g.:
  1116. /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1117. /// </remarks>
  1118. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1119. /// <param name="spName">The stored procedure name</param>
  1120. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1121. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1122. public static object ExecuteScalar(string connectionString, string spName, params SqlParameter[] commandParameters)
  1123. {
  1124. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1125. // Create & open a SqlConnection, and dispose of it after we are done
  1126. using (SqlConnection connection = new SqlConnection(connectionString))
  1127. {
  1128. connection.Open();
  1129. // Call the overload that takes a connection in place of the connection string
  1130. return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
  1131. }
  1132. }
  1133. /// <summary>
  1134. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in
  1135. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  1136. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1137. /// </summary>
  1138. /// <remarks>
  1139. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1140. ///
  1141. /// e.g.:
  1142. /// int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36);
  1143. /// </remarks>
  1144. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1145. /// <param name="spName">The name of the stored procedure</param>
  1146. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1147. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1148. public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
  1149. {
  1150. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1151. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1152. // If we receive parameter values, we need to figure out where they go
  1153. if ((parameterValues != null) && (parameterValues.Length > 0))
  1154. {
  1155. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1156. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  1157. // Assign the provided values to these parameters based on parameter order
  1158. AssignParameterValues(commandParameters, parameterValues);
  1159. // Call the overload that takes an array of SqlParameters
  1160. return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  1161. }
  1162. else
  1163. {
  1164. // Otherwise we can just call the SP without params
  1165. return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
  1166. }
  1167. }
  1168. /// <summary>
  1169. /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection.
  1170. /// </summary>
  1171. /// <remarks>
  1172. /// e.g.:
  1173. /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
  1174. /// </remarks>
  1175. /// <param name="connection">A valid SqlConnection</param>
  1176. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1177. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1178. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1179. public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
  1180. {
  1181. // Pass through the call providing null for the set of SqlParameters
  1182. return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
  1183. }
  1184. /// <summary>
  1185. /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
  1186. /// using the provided parameters.
  1187. /// </summary>
  1188. /// <remarks>
  1189. /// e.g.:
  1190. /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1191. /// </remarks>
  1192. /// <param name="connection">A valid SqlConnection</param>
  1193. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1194. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1195. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1196. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1197. public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1198. {
  1199. if (connection == null) throw new ArgumentNullException("connection");
  1200. // Create a command and prepare it for execution
  1201. SqlCommand cmd = new SqlCommand();
  1202. bool mustCloseConnection = false;
  1203. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  1204. // Execute the command & return the results
  1205. object retval = cmd.ExecuteScalar();
  1206. // Detach the SqlParameters from the command object, so they can be used again
  1207. cmd.Parameters.Clear();
  1208. if (mustCloseConnection)
  1209. connection.Close();
  1210. return retval;
  1211. }
  1212. /// <summary>
  1213. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
  1214. /// using the provided parameter values. This method will query the database to discover the parameters for the
  1215. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1216. /// </summary>
  1217. /// <remarks>
  1218. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1219. ///
  1220. /// e.g.:
  1221. /// int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36);
  1222. /// </remarks>
  1223. /// <param name="connection">A valid SqlConnection</param>
  1224. /// <param name="spName">The name of the stored procedure</param>
  1225. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1226. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1227. public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
  1228. {
  1229. if (connection == null) throw new ArgumentNullException("connection");
  1230. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1231. // If we receive parameter values, we need to figure out where they go
  1232. if ((parameterValues != null) && (parameterValues.Length > 0))
  1233. {
  1234. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1235. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1236. // Assign the provided values to these parameters based on parameter order
  1237. AssignParameterValues(commandParameters, parameterValues);
  1238. // Call the overload that takes an array of SqlParameters
  1239. return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
  1240. }
  1241. else
  1242. {
  1243. // Otherwise we can just call the SP without params
  1244. return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
  1245. }
  1246. }
  1247. /// <summary>
  1248. /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction.
  1249. /// </summary>
  1250. /// <remarks>
  1251. /// e.g.:
  1252. /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
  1253. /// </remarks>
  1254. /// <param name="transaction">A valid SqlTransaction</param>
  1255. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1256. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1257. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1258. public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
  1259. {
  1260. // Pass through the call providing null for the set of SqlParameters
  1261. return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
  1262. }
  1263. /// <summary>
  1264. /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
  1265. /// using the provided parameters.
  1266. /// </summary>
  1267. /// <remarks>
  1268. /// e.g.:
  1269. /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1270. /// </remarks>
  1271. /// <param name="transaction">A valid SqlTransaction</param>
  1272. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1273. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1274. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1275. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1276. public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1277. {
  1278. if (transaction == null) throw new ArgumentNullException("transaction");
  1279. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1280. // Create a command and prepare it for execution
  1281. SqlCommand cmd = new SqlCommand();
  1282. bool mustCloseConnection = false;
  1283. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  1284. // Execute the command & return the results
  1285. object retval = cmd.ExecuteScalar();
  1286. // Detach the SqlParameters from the command object, so they can be used again
  1287. cmd.Parameters.Clear();
  1288. return retval;
  1289. }
  1290. /// <summary>
  1291. /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
  1292. /// using the provided parameters.
  1293. /// </summary>
  1294. /// <remarks>
  1295. /// e.g.:
  1296. /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
  1297. /// </remarks>
  1298. /// <param name="transaction">A valid SqlTransaction</param>
  1299. /// <param name="spName">The stored procedure name or T-SQL command</param>
  1300. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1301. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1302. public static object ExecuteScalar(SqlTransaction transaction, string spName, params SqlParameter[] commandParameters)
  1303. {
  1304. if (transaction == null) throw new ArgumentNullException("transaction");
  1305. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1306. // Create a command and prepare it for execution
  1307. SqlCommand cmd = new SqlCommand();
  1308. bool mustCloseConnection = false;
  1309. PrepareCommand(cmd, transaction.Connection, transaction, CommandType.StoredProcedure, spName, commandParameters, out mustCloseConnection);
  1310. // Execute the command & return the results
  1311. object retval = cmd.ExecuteScalar();
  1312. // Detach the SqlParameters from the command object, so they can be used again
  1313. cmd.Parameters.Clear();
  1314. return retval;
  1315. }
  1316. /// <summary>
  1317. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified
  1318. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1319. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1320. /// </summary>
  1321. /// <remarks>
  1322. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1323. ///
  1324. /// e.g.:
  1325. /// int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36);
  1326. /// </remarks>
  1327. /// <param name="transaction">A valid SqlTransaction</param>
  1328. /// <param name="spName">The name of the stored procedure</param>
  1329. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1330. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  1331. public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
  1332. {
  1333. if (transaction == null) throw new ArgumentNullException("transaction");
  1334. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1335. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1336. // If we receive parameter values, we need to figure out where they go
  1337. if ((parameterValues != null) && (parameterValues.Length > 0))
  1338. {
  1339. // PPull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1340. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1341. // Assign the provided values to these parameters based on parameter order
  1342. AssignParameterValues(commandParameters, parameterValues);
  1343. // Call the overload that takes an array of SqlParameters
  1344. return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
  1345. }
  1346. else
  1347. {
  1348. // Otherwise we can just call the SP without params
  1349. return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
  1350. }
  1351. }
  1352. #endregion ExecuteScalar
  1353. #region ExecuteXmlReader
  1354. /// <summary>
  1355. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  1356. /// </summary>
  1357. /// <remarks>
  1358. /// e.g.:
  1359. /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders");
  1360. /// </remarks>
  1361. /// <param name="connection">A valid SqlConnection</param>
  1362. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1363. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1364. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1365. public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
  1366. {
  1367. // Pass through the call providing null for the set of SqlParameters
  1368. return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
  1369. }
  1370. /// <summary>
  1371. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  1372. /// using the provided parameters.
  1373. /// </summary>
  1374. /// <remarks>
  1375. /// e.g.:
  1376. /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  1377. /// </remarks>
  1378. /// <param name="connection">A valid SqlConnection</param>
  1379. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1380. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1381. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1382. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1383. public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1384. {
  1385. if (connection == null) throw new ArgumentNullException("connection");
  1386. bool mustCloseConnection = false;
  1387. // Create a command and prepare it for execution
  1388. SqlCommand cmd = new SqlCommand();
  1389. try
  1390. {
  1391. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  1392. // Create the DataAdapter & DataSet
  1393. XmlReader retval = cmd.ExecuteXmlReader();
  1394. // Detach the SqlParameters from the command object, so they can be used again
  1395. cmd.Parameters.Clear();
  1396. return retval;
  1397. }
  1398. catch
  1399. {
  1400. if (mustCloseConnection)
  1401. connection.Close();
  1402. throw;
  1403. }
  1404. }
  1405. /// <summary>
  1406. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  1407. /// using the provided parameter values. This method will query the database to discover the parameters for the
  1408. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1409. /// </summary>
  1410. /// <remarks>
  1411. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1412. ///
  1413. /// e.g.:
  1414. /// XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36);
  1415. /// </remarks>
  1416. /// <param name="connection">A valid SqlConnection</param>
  1417. /// <param name="spName">The name of the stored procedure using "FOR XML AUTO"</param>
  1418. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1419. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1420. public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues)
  1421. {
  1422. if (connection == null) throw new ArgumentNullException("connection");
  1423. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1424. // If we receive parameter values, we need to figure out where they go
  1425. if ((parameterValues != null) && (parameterValues.Length > 0))
  1426. {
  1427. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1428. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1429. // Assign the provided values to these parameters based on parameter order
  1430. AssignParameterValues(commandParameters, parameterValues);
  1431. // Call the overload that takes an array of SqlParameters
  1432. return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  1433. }
  1434. else
  1435. {
  1436. // Otherwise we can just call the SP without params
  1437. return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
  1438. }
  1439. }
  1440. /// <summary>
  1441. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  1442. /// </summary>
  1443. /// <remarks>
  1444. /// e.g.:
  1445. /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders");
  1446. /// </remarks>
  1447. /// <param name="transaction">A valid SqlTransaction</param>
  1448. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1449. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1450. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1451. public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
  1452. {
  1453. // Pass through the call providing null for the set of SqlParameters
  1454. return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
  1455. }
  1456. /// <summary>
  1457. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  1458. /// using the provided parameters.
  1459. /// </summary>
  1460. /// <remarks>
  1461. /// e.g.:
  1462. /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  1463. /// </remarks>
  1464. /// <param name="transaction">A valid SqlTransaction</param>
  1465. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1466. /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
  1467. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1468. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  1469. public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1470. {
  1471. if (transaction == null) throw new ArgumentNullException("transaction");
  1472. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1473. // Create a command and prepare it for execution
  1474. SqlCommand cmd = new SqlCommand();
  1475. bool mustCloseConnection = false;
  1476. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  1477. // Create the DataAdapter & DataSet
  1478. XmlReader retval = cmd.ExecuteXmlReader();
  1479. // Detach the SqlParameters from the command object, so they can be used again
  1480. cmd.Parameters.Clear();
  1481. return retval;
  1482. }
  1483. /// <summary>
  1484. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  1485. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1486. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1487. /// </summary>
  1488. /// <remarks>
  1489. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1490. ///
  1491. /// e.g.:
  1492. /// XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36);
  1493. /// </remarks>
  1494. /// <param name="transaction">A valid SqlTransaction</param>
  1495. /// <param name="spName">The name of the stored procedure</param>
  1496. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1497. /// <returns>A dataset containing the resultset generated by the command</returns>
  1498. public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues)
  1499. {
  1500. if (transaction == null) throw new ArgumentNullException("transaction");
  1501. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1502. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1503. // If we receive parameter values, we need to figure out where they go
  1504. if ((parameterValues != null) && (parameterValues.Length > 0))
  1505. {
  1506. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1507. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1508. // Assign the provided values to these parameters based on parameter order
  1509. AssignParameterValues(commandParameters, parameterValues);
  1510. // Call the overload that takes an array of SqlParameters
  1511. return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  1512. }
  1513. else
  1514. {
  1515. // Otherwise we can just call the SP without params
  1516. return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
  1517. }
  1518. }
  1519. public static XmlReader ExecuteXmlReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  1520. {
  1521. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1522. SqlConnection connection = null;
  1523. try
  1524. {
  1525. connection = new SqlConnection(connectionString);
  1526. connection.Open();
  1527. // Call the private overload that takes an internally owned connection in place of the connection string
  1528. return ExecuteXmlReader(connection, commandType, commandText, commandParameters);
  1529. }
  1530. catch
  1531. {
  1532. // If we fail to return the XmlReader, we need to close the connection ourselves
  1533. if (connection != null) connection.Close();
  1534. throw;
  1535. }
  1536. }
  1537. #endregion ExecuteXmlReader
  1538. #region FillDataset
  1539. /// <summary>
  1540. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  1541. /// the connection string.
  1542. /// </summary>
  1543. /// <remarks>
  1544. /// e.g.:
  1545. /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
  1546. /// </remarks>
  1547. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1548. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1549. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1550. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1551. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1552. /// by a user defined name (probably the actual table name)</param>
  1553. public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
  1554. {
  1555. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1556. if (dataSet == null) throw new ArgumentNullException("dataSet");
  1557. // Create & open a SqlConnection, and dispose of it after we are done
  1558. using (SqlConnection connection = new SqlConnection(connectionString))
  1559. {
  1560. connection.Open();
  1561. // Call the overload that takes a connection in place of the connection string
  1562. FillDataset(connection, commandType, commandText, dataSet, tableNames);
  1563. }
  1564. }
  1565. /// <summary>
  1566. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  1567. /// using the provided parameters.
  1568. /// </summary>
  1569. /// <remarks>
  1570. /// e.g.:
  1571. /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1572. /// </remarks>
  1573. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1574. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1575. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1576. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1577. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1578. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1579. /// by a user defined name (probably the actual table name)
  1580. /// </param>
  1581. public static void FillDataset(string connectionString, CommandType commandType,
  1582. string commandText, DataSet dataSet, string[] tableNames,
  1583. params SqlParameter[] commandParameters)
  1584. {
  1585. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1586. if (dataSet == null) throw new ArgumentNullException("dataSet");
  1587. // Create & open a SqlConnection, and dispose of it after we are done
  1588. using (SqlConnection connection = new SqlConnection(connectionString))
  1589. {
  1590. connection.Open();
  1591. // Call the overload that takes a connection in place of the connection string
  1592. FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters);
  1593. }
  1594. }
  1595. /// <summary>
  1596. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  1597. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  1598. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1599. /// </summary>
  1600. /// <remarks>
  1601. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1602. ///
  1603. /// e.g.:
  1604. /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, 24);
  1605. /// </remarks>
  1606. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1607. /// <param name="spName">The name of the stored procedure</param>
  1608. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1609. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1610. /// by a user defined name (probably the actual table name)
  1611. /// </param>
  1612. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1613. public static void FillDataset(string connectionString, string spName,
  1614. DataSet dataSet, string[] tableNames,
  1615. params object[] parameterValues)
  1616. {
  1617. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1618. if (dataSet == null) throw new ArgumentNullException("dataSet");
  1619. // Create & open a SqlConnection, and dispose of it after we are done
  1620. using (SqlConnection connection = new SqlConnection(connectionString))
  1621. {
  1622. connection.Open();
  1623. // Call the overload that takes a connection in place of the connection string
  1624. FillDataset(connection, spName, dataSet, tableNames, parameterValues);
  1625. }
  1626. }
  1627. /// <summary>
  1628. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  1629. /// </summary>
  1630. /// <remarks>
  1631. /// e.g.:
  1632. /// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
  1633. /// </remarks>
  1634. /// <param name="connection">A valid SqlConnection</param>
  1635. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1636. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1637. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1638. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1639. /// by a user defined name (probably the actual table name)
  1640. /// </param>
  1641. public static void FillDataset(SqlConnection connection, CommandType commandType,
  1642. string commandText, DataSet dataSet, string[] tableNames)
  1643. {
  1644. FillDataset(connection, commandType, commandText, dataSet, tableNames, null);
  1645. }
  1646. /// <summary>
  1647. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  1648. /// using the provided parameters.
  1649. /// </summary>
  1650. /// <remarks>
  1651. /// e.g.:
  1652. /// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1653. /// </remarks>
  1654. /// <param name="connection">A valid SqlConnection</param>
  1655. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1656. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1657. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1658. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1659. /// by a user defined name (probably the actual table name)
  1660. /// </param>
  1661. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1662. public static void FillDataset(SqlConnection connection, CommandType commandType,
  1663. string commandText, DataSet dataSet, string[] tableNames,
  1664. params SqlParameter[] commandParameters)
  1665. {
  1666. FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters);
  1667. }
  1668. /// <summary>
  1669. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  1670. /// using the provided parameter values. This method will query the database to discover the parameters for the
  1671. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1672. /// </summary>
  1673. /// <remarks>
  1674. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1675. ///
  1676. /// e.g.:
  1677. /// FillDataset(conn, "GetOrders", ds, new string[] {"orders"}, 24, 36);
  1678. /// </remarks>
  1679. /// <param name="connection">A valid SqlConnection</param>
  1680. /// <param name="spName">The name of the stored procedure</param>
  1681. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1682. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1683. /// by a user defined name (probably the actual table name)
  1684. /// </param>
  1685. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1686. public static void FillDataset(SqlConnection connection, string spName,
  1687. DataSet dataSet, string[] tableNames,
  1688. params object[] parameterValues)
  1689. {
  1690. if (connection == null) throw new ArgumentNullException("connection");
  1691. if (dataSet == null) throw new ArgumentNullException("dataSet");
  1692. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1693. // If we receive parameter values, we need to figure out where they go
  1694. if ((parameterValues != null) && (parameterValues.Length > 0))
  1695. {
  1696. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1697. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1698. // Assign the provided values to these parameters based on parameter order
  1699. AssignParameterValues(commandParameters, parameterValues);
  1700. // Call the overload that takes an array of SqlParameters
  1701. FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
  1702. }
  1703. else
  1704. {
  1705. // Otherwise we can just call the SP without params
  1706. FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames);
  1707. }
  1708. }
  1709. /// <summary>
  1710. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  1711. /// </summary>
  1712. /// <remarks>
  1713. /// e.g.:
  1714. /// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
  1715. /// </remarks>
  1716. /// <param name="transaction">A valid SqlTransaction</param>
  1717. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1718. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1719. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1720. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1721. /// by a user defined name (probably the actual table name)
  1722. /// </param>
  1723. public static void FillDataset(SqlTransaction transaction, CommandType commandType,
  1724. string commandText,
  1725. DataSet dataSet, string[] tableNames)
  1726. {
  1727. FillDataset(transaction, commandType, commandText, dataSet, tableNames, null);
  1728. }
  1729. /// <summary>
  1730. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  1731. /// using the provided parameters.
  1732. /// </summary>
  1733. /// <remarks>
  1734. /// e.g.:
  1735. /// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1736. /// </remarks>
  1737. /// <param name="transaction">A valid SqlTransaction</param>
  1738. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1739. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1740. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1741. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1742. /// by a user defined name (probably the actual table name)
  1743. /// </param>
  1744. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1745. public static void FillDataset(SqlTransaction transaction, CommandType commandType,
  1746. string commandText, DataSet dataSet, string[] tableNames,
  1747. params SqlParameter[] commandParameters)
  1748. {
  1749. FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters);
  1750. }
  1751. /// <summary>
  1752. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  1753. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  1754. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  1755. /// </summary>
  1756. /// <remarks>
  1757. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  1758. ///
  1759. /// e.g.:
  1760. /// FillDataset(trans, "GetOrders", ds, new string[]{"orders"}, 24, 36);
  1761. /// </remarks>
  1762. /// <param name="transaction">A valid SqlTransaction</param>
  1763. /// <param name="spName">The name of the stored procedure</param>
  1764. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1765. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1766. /// by a user defined name (probably the actual table name)
  1767. /// </param>
  1768. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  1769. public static void FillDataset(SqlTransaction transaction, string spName,
  1770. DataSet dataSet, string[] tableNames,
  1771. params object[] parameterValues)
  1772. {
  1773. if (transaction == null) throw new ArgumentNullException("transaction");
  1774. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1775. if (dataSet == null) throw new ArgumentNullException("dataSet");
  1776. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1777. // If we receive parameter values, we need to figure out where they go
  1778. if ((parameterValues != null) && (parameterValues.Length > 0))
  1779. {
  1780. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1781. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1782. // Assign the provided values to these parameters based on parameter order
  1783. AssignParameterValues(commandParameters, parameterValues);
  1784. // Call the overload that takes an array of SqlParameters
  1785. FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
  1786. }
  1787. else
  1788. {
  1789. // Otherwise we can just call the SP without params
  1790. FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames);
  1791. }
  1792. }
  1793. /// <summary>
  1794. /// Private helper method that execute a SqlCommand (that returns a resultset) against the specified SqlTransaction and SqlConnection
  1795. /// using the provided parameters.
  1796. /// </summary>
  1797. /// <remarks>
  1798. /// e.g.:
  1799. /// FillDataset(conn, trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
  1800. /// </remarks>
  1801. /// <param name="connection">A valid SqlConnection</param>
  1802. /// <param name="transaction">A valid SqlTransaction</param>
  1803. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  1804. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  1805. /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
  1806. /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
  1807. /// by a user defined name (probably the actual table name)
  1808. /// </param>
  1809. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  1810. private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType,
  1811. string commandText, DataSet dataSet, string[] tableNames,
  1812. params SqlParameter[] commandParameters)
  1813. {
  1814. if (connection == null) throw new ArgumentNullException("connection");
  1815. if (dataSet == null) throw new ArgumentNullException("dataSet");
  1816. // Create a command and prepare it for execution
  1817. SqlCommand command = new SqlCommand();
  1818. bool mustCloseConnection = false;
  1819. PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  1820. // Create the DataAdapter & DataSet
  1821. using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
  1822. {
  1823. // Add the table mappings specified by the user
  1824. if (tableNames != null && tableNames.Length > 0)
  1825. {
  1826. string tableName = "Table";
  1827. for (int index = 0; index < tableNames.Length; index++)
  1828. {
  1829. if (tableNames[index] == null || tableNames[index].Length == 0) throw new ArgumentException("The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames");
  1830. dataAdapter.TableMappings.Add(tableName, tableNames[index]);
  1831. tableName += (index + 1).ToString();
  1832. }
  1833. }
  1834. // Fill the DataSet using default values for DataTable names, etc
  1835. dataAdapter.Fill(dataSet);
  1836. // Detach the SqlParameters from the command object, so they can be used again
  1837. command.Parameters.Clear();
  1838. }
  1839. if (mustCloseConnection)
  1840. connection.Close();
  1841. }
  1842. #endregion
  1843. #region UpdateDataset
  1844. /// <summary>
  1845. /// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
  1846. /// </summary>
  1847. /// <remarks>
  1848. /// e.g.:
  1849. /// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
  1850. /// </remarks>
  1851. /// <param name="insertCommand">A valid transact-SQL statement or stored procedure to insert new records into the data source</param>
  1852. /// <param name="deleteCommand">A valid transact-SQL statement or stored procedure to delete records from the data source</param>
  1853. /// <param name="updateCommand">A valid transact-SQL statement or stored procedure used to update records in the data source</param>
  1854. /// <param name="dataSet">The DataSet used to update the data source</param>
  1855. /// <param name="tableName">The DataTable used to update the data source.</param>
  1856. public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName)
  1857. {
  1858. if (insertCommand == null) throw new ArgumentNullException("insertCommand");
  1859. if (deleteCommand == null) throw new ArgumentNullException("deleteCommand");
  1860. if (updateCommand == null) throw new ArgumentNullException("updateCommand");
  1861. if (tableName == null || tableName.Length == 0) throw new ArgumentNullException("tableName");
  1862. // Create a SqlDataAdapter, and dispose of it after we are done
  1863. using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
  1864. {
  1865. // Set the data adapter commands
  1866. dataAdapter.UpdateCommand = updateCommand;
  1867. dataAdapter.InsertCommand = insertCommand;
  1868. dataAdapter.DeleteCommand = deleteCommand;
  1869. // Update the dataset changes in the data source
  1870. dataAdapter.Update(dataSet, tableName);
  1871. // Commit all the changes made to the DataSet
  1872. dataSet.AcceptChanges();
  1873. }
  1874. }
  1875. #endregion
  1876. #region CreateCommand
  1877. /// <summary>
  1878. /// Simplify the creation of a Sql command object by allowing
  1879. /// a stored procedure and optional parameters to be provided
  1880. /// </summary>
  1881. /// <remarks>
  1882. /// e.g.:
  1883. /// SqlCommand command = CreateCommand(conn, "AddCustomer", "CustomerID", "CustomerName");
  1884. /// </remarks>
  1885. /// <param name="connection">A valid SqlConnection object</param>
  1886. /// <param name="spName">The name of the stored procedure</param>
  1887. /// <param name="sourceColumns">An array of string to be assigned as the source columns of the stored procedure parameters</param>
  1888. /// <returns>A valid SqlCommand object</returns>
  1889. public static SqlCommand CreateCommand(SqlConnection connection, string spName, params string[] sourceColumns)
  1890. {
  1891. if (connection == null) throw new ArgumentNullException("connection");
  1892. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1893. // Create a SqlCommand
  1894. SqlCommand cmd = new SqlCommand(spName, connection);
  1895. cmd.CommandType = CommandType.StoredProcedure;
  1896. // If we receive parameter values, we need to figure out where they go
  1897. if ((sourceColumns != null) && (sourceColumns.Length > 0))
  1898. {
  1899. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1900. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1901. // Assign the provided source columns to these parameters based on parameter order
  1902. for (int index = 0; index < sourceColumns.Length; index++)
  1903. commandParameters[index].SourceColumn = sourceColumns[index];
  1904. // Attach the discovered parameters to the SqlCommand object
  1905. AttachParameters(cmd, commandParameters);
  1906. }
  1907. return cmd;
  1908. }
  1909. #endregion
  1910. #region ExecuteNonQueryTypedParams
  1911. /// <summary>
  1912. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
  1913. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  1914. /// This method will query the database to discover the parameters for the
  1915. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  1916. /// </summary>
  1917. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  1918. /// <param name="spName">The name of the stored procedure</param>
  1919. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  1920. /// <returns>An int representing the number of rows affected by the command</returns>
  1921. public static int ExecuteNonQueryTypedParams(String connectionString, String spName, DataRow dataRow)
  1922. {
  1923. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  1924. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1925. // If the row has values, the store procedure parameters must be initialized
  1926. if (dataRow != null && dataRow.ItemArray.Length > 0)
  1927. {
  1928. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1929. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  1930. // Set the parameters values
  1931. AssignParameterValues(commandParameters, dataRow);
  1932. return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  1933. }
  1934. else
  1935. {
  1936. return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
  1937. }
  1938. }
  1939. /// <summary>
  1940. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
  1941. /// using the dataRow column values as the stored procedure's parameters values.
  1942. /// This method will query the database to discover the parameters for the
  1943. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  1944. /// </summary>
  1945. /// <param name="connection">A valid SqlConnection object</param>
  1946. /// <param name="spName">The name of the stored procedure</param>
  1947. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  1948. /// <returns>An int representing the number of rows affected by the command</returns>
  1949. public static int ExecuteNonQueryTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  1950. {
  1951. if (connection == null) throw new ArgumentNullException("connection");
  1952. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1953. // If the row has values, the store procedure parameters must be initialized
  1954. if (dataRow != null && dataRow.ItemArray.Length > 0)
  1955. {
  1956. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1957. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  1958. // Set the parameters values
  1959. AssignParameterValues(commandParameters, dataRow);
  1960. return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  1961. }
  1962. else
  1963. {
  1964. return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
  1965. }
  1966. }
  1967. /// <summary>
  1968. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
  1969. /// SqlTransaction using the dataRow column values as the stored procedure's parameters values.
  1970. /// This method will query the database to discover the parameters for the
  1971. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  1972. /// </summary>
  1973. /// <param name="transaction">A valid SqlTransaction object</param>
  1974. /// <param name="spName">The name of the stored procedure</param>
  1975. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  1976. /// <returns>An int representing the number of rows affected by the command</returns>
  1977. public static int ExecuteNonQueryTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  1978. {
  1979. if (transaction == null) throw new ArgumentNullException("transaction");
  1980. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  1981. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  1982. // Sf the row has values, the store procedure parameters must be initialized
  1983. if (dataRow != null && dataRow.ItemArray.Length > 0)
  1984. {
  1985. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  1986. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  1987. // Set the parameters values
  1988. AssignParameterValues(commandParameters, dataRow);
  1989. return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
  1990. }
  1991. else
  1992. {
  1993. return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
  1994. }
  1995. }
  1996. #endregion
  1997. #region ExecuteDatasetTypedParams
  1998. /// <summary>
  1999. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  2000. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  2001. /// This method will query the database to discover the parameters for the
  2002. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  2003. /// </summary>
  2004. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2005. /// <param name="spName">The name of the stored procedure</param>
  2006. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2007. /// <returns>A dataset containing the resultset generated by the command</returns>
  2008. public static DataSet ExecuteDatasetTypedParams(string connectionString, String spName, DataRow dataRow)
  2009. {
  2010. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  2011. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2012. //If the row has values, the store procedure parameters must be initialized
  2013. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2014. {
  2015. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2016. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  2017. // Set the parameters values
  2018. AssignParameterValues(commandParameters, dataRow);
  2019. return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  2020. }
  2021. else
  2022. {
  2023. return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
  2024. }
  2025. }
  2026. /// <summary>
  2027. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  2028. /// using the dataRow column values as the store procedure's parameters values.
  2029. /// This method will query the database to discover the parameters for the
  2030. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  2031. /// </summary>
  2032. /// <param name="connection">A valid SqlConnection object</param>
  2033. /// <param name="spName">The name of the stored procedure</param>
  2034. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2035. /// <returns>A dataset containing the resultset generated by the command</returns>
  2036. public static DataSet ExecuteDatasetTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2037. {
  2038. if (connection == null) throw new ArgumentNullException("connection");
  2039. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2040. // If the row has values, the store procedure parameters must be initialized
  2041. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2042. {
  2043. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2044. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2045. // Set the parameters values
  2046. AssignParameterValues(commandParameters, dataRow);
  2047. return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  2048. }
  2049. else
  2050. {
  2051. return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
  2052. }
  2053. }
  2054. /// <summary>
  2055. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
  2056. /// using the dataRow column values as the stored procedure's parameters values.
  2057. /// This method will query the database to discover the parameters for the
  2058. /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
  2059. /// </summary>
  2060. /// <param name="transaction">A valid SqlTransaction object</param>
  2061. /// <param name="spName">The name of the stored procedure</param>
  2062. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2063. /// <returns>A dataset containing the resultset generated by the command</returns>
  2064. public static DataSet ExecuteDatasetTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2065. {
  2066. if (transaction == null) throw new ArgumentNullException("transaction");
  2067. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  2068. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2069. // If the row has values, the store procedure parameters must be initialized
  2070. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2071. {
  2072. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2073. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2074. // Set the parameters values
  2075. AssignParameterValues(commandParameters, dataRow);
  2076. return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2077. }
  2078. else
  2079. {
  2080. return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
  2081. }
  2082. }
  2083. #endregion
  2084. #region ExecuteReaderTypedParams
  2085. /// <summary>
  2086. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  2087. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  2088. /// This method will query the database to discover the parameters for the
  2089. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2090. /// </summary>
  2091. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2092. /// <param name="spName">The name of the stored procedure</param>
  2093. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2094. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  2095. public static SqlDataReader ExecuteReaderTypedParams(String connectionString, String spName, DataRow dataRow)
  2096. {
  2097. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  2098. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2099. // If the row has values, the store procedure parameters must be initialized
  2100. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2101. {
  2102. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2103. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  2104. // Set the parameters values
  2105. AssignParameterValues(commandParameters, dataRow);
  2106. return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  2107. }
  2108. else
  2109. {
  2110. return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
  2111. }
  2112. }
  2113. /// <summary>
  2114. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  2115. /// using the dataRow column values as the stored procedure's parameters values.
  2116. /// This method will query the database to discover the parameters for the
  2117. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2118. /// </summary>
  2119. /// <param name="connection">A valid SqlConnection object</param>
  2120. /// <param name="spName">The name of the stored procedure</param>
  2121. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2122. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  2123. public static SqlDataReader ExecuteReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2124. {
  2125. if (connection == null) throw new ArgumentNullException("connection");
  2126. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2127. // If the row has values, the store procedure parameters must be initialized
  2128. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2129. {
  2130. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2131. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2132. // Set the parameters values
  2133. AssignParameterValues(commandParameters, dataRow);
  2134. return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  2135. }
  2136. else
  2137. {
  2138. return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName);
  2139. }
  2140. }
  2141. /// <summary>
  2142. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
  2143. /// using the dataRow column values as the stored procedure's parameters values.
  2144. /// This method will query the database to discover the parameters for the
  2145. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2146. /// </summary>
  2147. /// <param name="transaction">A valid SqlTransaction object</param>
  2148. /// <param name="spName">The name of the stored procedure</param>
  2149. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2150. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  2151. public static SqlDataReader ExecuteReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2152. {
  2153. if (transaction == null) throw new ArgumentNullException("transaction");
  2154. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  2155. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2156. // If the row has values, the store procedure parameters must be initialized
  2157. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2158. {
  2159. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2160. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2161. // Set the parameters values
  2162. AssignParameterValues(commandParameters, dataRow);
  2163. return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2164. }
  2165. else
  2166. {
  2167. return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
  2168. }
  2169. }
  2170. #endregion
  2171. #region ExecuteScalarTypedParams
  2172. /// <summary>
  2173. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in
  2174. /// the connection string using the dataRow column values as the stored procedure's parameters values.
  2175. /// This method will query the database to discover the parameters for the
  2176. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2177. /// </summary>
  2178. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2179. /// <param name="spName">The name of the stored procedure</param>
  2180. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2181. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  2182. public static object ExecuteScalarTypedParams(String connectionString, String spName, DataRow dataRow)
  2183. {
  2184. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  2185. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2186. // If the row has values, the store procedure parameters must be initialized
  2187. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2188. {
  2189. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2190. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
  2191. // Set the parameters values
  2192. AssignParameterValues(commandParameters, dataRow);
  2193. return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  2194. }
  2195. else
  2196. {
  2197. return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
  2198. }
  2199. }
  2200. /// <summary>
  2201. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
  2202. /// using the dataRow column values as the stored procedure's parameters values.
  2203. /// This method will query the database to discover the parameters for the
  2204. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2205. /// </summary>
  2206. /// <param name="connection">A valid SqlConnection object</param>
  2207. /// <param name="spName">The name of the stored procedure</param>
  2208. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2209. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  2210. public static object ExecuteScalarTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2211. {
  2212. if (connection == null) throw new ArgumentNullException("connection");
  2213. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2214. // If the row has values, the store procedure parameters must be initialized
  2215. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2216. {
  2217. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2218. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2219. // Set the parameters values
  2220. AssignParameterValues(commandParameters, dataRow);
  2221. return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
  2222. }
  2223. else
  2224. {
  2225. return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
  2226. }
  2227. }
  2228. /// <summary>
  2229. /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
  2230. /// using the dataRow column values as the stored procedure's parameters values.
  2231. /// This method will query the database to discover the parameters for the
  2232. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2233. /// </summary>
  2234. /// <param name="transaction">A valid SqlTransaction object</param>
  2235. /// <param name="spName">The name of the stored procedure</param>
  2236. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2237. /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
  2238. public static object ExecuteScalarTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2239. {
  2240. if (transaction == null) throw new ArgumentNullException("transaction");
  2241. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  2242. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2243. // If the row has values, the store procedure parameters must be initialized
  2244. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2245. {
  2246. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2247. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2248. // Set the parameters values
  2249. AssignParameterValues(commandParameters, dataRow);
  2250. return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2251. }
  2252. else
  2253. {
  2254. return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
  2255. }
  2256. }
  2257. #endregion
  2258. #region ExecuteXmlReaderTypedParams
  2259. /// <summary>
  2260. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  2261. /// using the dataRow column values as the stored procedure's parameters values.
  2262. /// This method will query the database to discover the parameters for the
  2263. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2264. /// </summary>
  2265. /// <param name="connection">A valid SqlConnection object</param>
  2266. /// <param name="spName">The name of the stored procedure</param>
  2267. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2268. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  2269. public static XmlReader ExecuteXmlReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
  2270. {
  2271. if (connection == null) throw new ArgumentNullException("connection");
  2272. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2273. // If the row has values, the store procedure parameters must be initialized
  2274. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2275. {
  2276. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2277. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  2278. // Set the parameters values
  2279. AssignParameterValues(commandParameters, dataRow);
  2280. return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
  2281. }
  2282. else
  2283. {
  2284. return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
  2285. }
  2286. }
  2287. /// <summary>
  2288. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction
  2289. /// using the dataRow column values as the stored procedure's parameters values.
  2290. /// This method will query the database to discover the parameters for the
  2291. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  2292. /// </summary>
  2293. /// <param name="transaction">A valid SqlTransaction object</param>
  2294. /// <param name="spName">The name of the stored procedure</param>
  2295. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
  2296. /// <returns>An XmlReader containing the resultset generated by the command</returns>
  2297. public static XmlReader ExecuteXmlReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
  2298. {
  2299. if (transaction == null) throw new ArgumentNullException("transaction");
  2300. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  2301. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2302. // If the row has values, the store procedure parameters must be initialized
  2303. if (dataRow != null && dataRow.ItemArray.Length > 0)
  2304. {
  2305. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  2306. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  2307. // Set the parameters values
  2308. AssignParameterValues(commandParameters, dataRow);
  2309. return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
  2310. }
  2311. else
  2312. {
  2313. return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
  2314. }
  2315. }
  2316. #endregion
  2317. }
  2318. /// <summary>
  2319. /// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
  2320. /// ability to discover parameters for stored procedures at run-time.
  2321. /// </summary>
  2322. public sealed class SqlHelperParameterCache
  2323. {
  2324. #region private methods, variables, and constructors
  2325. //Since this class provides only static methods, make the default constructor private to prevent
  2326. //instances from being created with "new SqlHelperParameterCache()"
  2327. private SqlHelperParameterCache() { }
  2328. private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());
  2329. /// <summary>
  2330. /// Resolve at run time the appropriate set of SqlParameters for a stored procedure
  2331. /// </summary>
  2332. /// <param name="connection">A valid SqlConnection object</param>
  2333. /// <param name="spName">The name of the stored procedure</param>
  2334. /// <param name="includeReturnValueParameter">Whether or not to include their return value parameter</param>
  2335. /// <returns>The parameter array discovered.</returns>
  2336. private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
  2337. {
  2338. if (connection == null) throw new ArgumentNullException("connection");
  2339. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2340. SqlCommand cmd = new SqlCommand(spName, connection);
  2341. cmd.CommandType = CommandType.StoredProcedure;
  2342. connection.Open();
  2343. SqlCommandBuilder.DeriveParameters(cmd);
  2344. connection.Close();
  2345. if (!includeReturnValueParameter)
  2346. {
  2347. cmd.Parameters.RemoveAt(0);
  2348. }
  2349. SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];
  2350. cmd.Parameters.CopyTo(discoveredParameters, 0);
  2351. // Init the parameters with a DBNull value
  2352. foreach (SqlParameter discoveredParameter in discoveredParameters)
  2353. {
  2354. discoveredParameter.Value = DBNull.Value;
  2355. }
  2356. return discoveredParameters;
  2357. }
  2358. /// <summary>
  2359. /// Deep copy of cached SqlParameter array
  2360. /// </summary>
  2361. /// <param name="originalParameters"></param>
  2362. /// <returns></returns>
  2363. private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
  2364. {
  2365. SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];
  2366. for (int i = 0, j = originalParameters.Length; i < j; i++)
  2367. {
  2368. clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
  2369. }
  2370. return clonedParameters;
  2371. }
  2372. #endregion private methods, variables, and constructors
  2373. #region caching functions
  2374. /// <summary>
  2375. /// Add parameter array to the cache
  2376. /// </summary>
  2377. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2378. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  2379. /// <param name="commandParameters">An array of SqlParamters to be cached</param>
  2380. public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
  2381. {
  2382. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  2383. if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
  2384. string hashKey = connectionString + ":" + commandText;
  2385. paramCache[hashKey] = commandParameters;
  2386. }
  2387. /// <summary>
  2388. /// Retrieve a parameter array from the cache
  2389. /// </summary>
  2390. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2391. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  2392. /// <returns>An array of SqlParamters</returns>
  2393. public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
  2394. {
  2395. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  2396. if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
  2397. string hashKey = connectionString + ":" + commandText;
  2398. SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[];
  2399. if (cachedParameters == null)
  2400. {
  2401. return null;
  2402. }
  2403. else
  2404. {
  2405. return CloneParameters(cachedParameters);
  2406. }
  2407. }
  2408. #endregion caching functions
  2409. #region Parameter Discovery Functions
  2410. /// <summary>
  2411. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2412. /// </summary>
  2413. /// <remarks>
  2414. /// This method will query the database for this information, and then store it in a cache for future requests.
  2415. /// </remarks>
  2416. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2417. /// <param name="spName">The name of the stored procedure</param>
  2418. /// <returns>An array of SqlParameters</returns>
  2419. public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
  2420. {
  2421. return GetSpParameterSet(connectionString, spName, false);
  2422. }
  2423. /// <summary>
  2424. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2425. /// </summary>
  2426. /// <remarks>
  2427. /// This method will query the database for this information, and then store it in a cache for future requests.
  2428. /// </remarks>
  2429. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  2430. /// <param name="spName">The name of the stored procedure</param>
  2431. /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
  2432. /// <returns>An array of SqlParameters</returns>
  2433. public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
  2434. {
  2435. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  2436. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2437. using (SqlConnection connection = new SqlConnection(connectionString))
  2438. {
  2439. return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
  2440. }
  2441. }
  2442. /// <summary>
  2443. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2444. /// </summary>
  2445. /// <remarks>
  2446. /// This method will query the database for this information, and then store it in a cache for future requests.
  2447. /// </remarks>
  2448. /// <param name="connection">A valid SqlConnection object</param>
  2449. /// <param name="spName">The name of the stored procedure</param>
  2450. /// <returns>An array of SqlParameters</returns>
  2451. internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
  2452. {
  2453. return GetSpParameterSet(connection, spName, false);
  2454. }
  2455. /// <summary>
  2456. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2457. /// </summary>
  2458. /// <remarks>
  2459. /// This method will query the database for this information, and then store it in a cache for future requests.
  2460. /// </remarks>
  2461. /// <param name="connection">A valid SqlConnection object</param>
  2462. /// <param name="spName">The name of the stored procedure</param>
  2463. /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
  2464. /// <returns>An array of SqlParameters</returns>
  2465. internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
  2466. {
  2467. if (connection == null) throw new ArgumentNullException("connection");
  2468. using (SqlConnection clonedConnection = (SqlConnection)((ICloneable)connection).Clone())
  2469. {
  2470. return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter);
  2471. }
  2472. }
  2473. /// <summary>
  2474. /// Retrieves the set of SqlParameters appropriate for the stored procedure
  2475. /// </summary>
  2476. /// <param name="connection">A valid SqlConnection object</param>
  2477. /// <param name="spName">The name of the stored procedure</param>
  2478. /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
  2479. /// <returns>An array of SqlParameters</returns>
  2480. private static SqlParameter[] GetSpParameterSetInternal(SqlConnection connection, string spName, bool includeReturnValueParameter)
  2481. {
  2482. if (connection == null) throw new ArgumentNullException("connection");
  2483. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  2484. string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");
  2485. SqlParameter[] cachedParameters;
  2486. cachedParameters = paramCache[hashKey] as SqlParameter[];
  2487. if (cachedParameters == null)
  2488. {
  2489. SqlParameter[] spParameters = DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
  2490. paramCache[hashKey] = spParameters;
  2491. cachedParameters = spParameters;
  2492. }
  2493. return CloneParameters(cachedParameters);
  2494. }
  2495. #endregion Parameter Discovery Functions
  2496. }
  2497. }