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

/MDXParameter/MDXParameter/SqlHelper.cs

#
C# | 2716 lines | 1112 code | 336 blank | 1268 comment | 553 complexity | 699f42e893910321827f0ea16bcab56b MD5 | raw file
Possible License(s): CC-BY-SA-3.0

Large files files are truncated, but you can click here to view the full 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. namespace Microsoft.ApplicationBlocks.Data
  30. {
  31. /// <summary>
  32. /// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
  33. /// common uses of SqlClient
  34. /// </summary>
  35. internal sealed class SqlHelper
  36. {
  37. #region private utility methods & constructors
  38. // Since this class provides only static methods, make the default constructor private to prevent
  39. // instances from being created with "new SqlHelper()"
  40. private SqlHelper() { }
  41. /// <summary>
  42. /// This method is used to attach array of SqlParameters to a SqlCommand.
  43. ///
  44. /// This method will assign a value of DbNull to any parameter with a direction of
  45. /// InputOutput and a value of null.
  46. ///
  47. /// This behavior will prevent default values from being used, but
  48. /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
  49. /// where the user provided no input value.
  50. /// </summary>
  51. /// <param name="command">The command to which the parameters will be added</param>
  52. /// <param name="commandParameters">An array of SqlParameters to be added to command</param>
  53. private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
  54. {
  55. if (command == null) throw new ArgumentNullException("command");
  56. if (commandParameters != null)
  57. {
  58. foreach (SqlParameter p in commandParameters)
  59. {
  60. if (p != null)
  61. {
  62. // Check for derived output value with no value assigned
  63. if ((p.Direction == ParameterDirection.InputOutput ||
  64. p.Direction == ParameterDirection.Input) &&
  65. (p.Value == null))
  66. {
  67. p.Value = DBNull.Value;
  68. }
  69. command.Parameters.Add(p);
  70. }
  71. }
  72. }
  73. }
  74. /// <summary>
  75. /// This method assigns dataRow column values to an array of SqlParameters
  76. /// </summary>
  77. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  78. /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
  79. private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
  80. {
  81. if ((commandParameters == null) || (dataRow == null))
  82. {
  83. // Do nothing if we get no data
  84. return;
  85. }
  86. int i = 0;
  87. // Set the parameters values
  88. foreach (SqlParameter commandParameter in commandParameters)
  89. {
  90. // Check the parameter name
  91. if (commandParameter.ParameterName == null ||
  92. commandParameter.ParameterName.Length <= 1)
  93. throw new Exception(
  94. string.Format(
  95. "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
  96. i, commandParameter.ParameterName));
  97. if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
  98. commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
  99. i++;
  100. }
  101. }
  102. /// <summary>
  103. /// This method assigns an array of values to an array of SqlParameters
  104. /// </summary>
  105. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  106. /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
  107. private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
  108. {
  109. if ((commandParameters == null) || (parameterValues == null))
  110. {
  111. // Do nothing if we get no data
  112. return;
  113. }
  114. // We must have the same number of values as we pave parameters to put them in
  115. if (commandParameters.Length != parameterValues.Length)
  116. {
  117. throw new ArgumentException("Parameter count does not match Parameter Value count.");
  118. }
  119. // Iterate through the SqlParameters, assigning the values from the corresponding position in the
  120. // value array
  121. for (int i = 0, j = commandParameters.Length; i < j; i++)
  122. {
  123. // If the current array value derives from IDbDataParameter, then assign its Value property
  124. if (parameterValues[i] is IDbDataParameter)
  125. {
  126. IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
  127. if (paramInstance.Value == null)
  128. {
  129. commandParameters[i].Value = DBNull.Value;
  130. }
  131. else
  132. {
  133. commandParameters[i].Value = paramInstance.Value;
  134. }
  135. }
  136. else if (parameterValues[i] == null)
  137. {
  138. commandParameters[i].Value = DBNull.Value;
  139. }
  140. else
  141. {
  142. commandParameters[i].Value = parameterValues[i];
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// This method assigns an array of values to an array of SqlParameters
  148. /// </summary>
  149. /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
  150. /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
  151. private static void UpdateParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
  152. {
  153. if ((commandParameters == null) || (parameterValues == null))
  154. {
  155. // Do nothing if we get no data
  156. return;
  157. }
  158. // We must have the same number of values as we pave parameters to put them in
  159. if (commandParameters.Length != parameterValues.Length)
  160. {
  161. throw new ArgumentException("Parameter count does not match Parameter Value count.");
  162. }
  163. // Iterate through the SqlParameters, assigning the values from the corresponding position in the
  164. // value array
  165. for (int i = 0, j = commandParameters.Length; i < j; i++)
  166. {
  167. //Update the Return Value
  168. if (commandParameters[i].Direction == ParameterDirection.ReturnValue)
  169. {
  170. parameterValues[i] = commandParameters[i].Value;
  171. }
  172. if (commandParameters[i].Direction == ParameterDirection.InputOutput)
  173. parameterValues[i] = commandParameters[i].Value;
  174. }
  175. }
  176. /// <summary>
  177. /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
  178. /// to the provided command
  179. /// </summary>
  180. /// <param name="command">The SqlCommand to be prepared</param>
  181. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  182. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  183. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  184. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  185. /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  186. /// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
  187. private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection)
  188. {
  189. if (command == null) throw new ArgumentNullException("command");
  190. if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText");
  191. // If the provided connection is not open, we will open it
  192. if (connection.State != ConnectionState.Open)
  193. {
  194. mustCloseConnection = true;
  195. connection.Open();
  196. }
  197. else
  198. {
  199. mustCloseConnection = false;
  200. }
  201. // Associate the connection with the command
  202. command.Connection = connection;
  203. // Set the command text (stored procedure name or SQL statement)
  204. command.CommandText = commandText;
  205. // If we were provided a transaction, assign it
  206. if (transaction != null)
  207. {
  208. if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  209. command.Transaction = transaction;
  210. }
  211. // Set the command type
  212. command.CommandType = commandType;
  213. // Attach the command parameters if they are provided
  214. if (commandParameters != null)
  215. {
  216. AttachParameters(command, commandParameters);
  217. }
  218. return;
  219. }
  220. #endregion private utility methods & constructors
  221. #region ExecuteNonQuery
  222. /// <summary>
  223. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
  224. /// the connection string
  225. /// </summary>
  226. /// <remarks>
  227. /// e.g.:
  228. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
  229. /// </remarks>
  230. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  231. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  232. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  233. /// <returns>An int representing the number of rows affected by the command</returns>
  234. internal static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
  235. {
  236. // Pass through the call providing null for the set of SqlParameters
  237. return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
  238. }
  239. /// <summary>
  240. /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
  241. /// using the provided parameters
  242. /// </summary>
  243. /// <remarks>
  244. /// e.g.:
  245. /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  246. /// </remarks>
  247. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  248. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  249. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  250. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  251. /// <returns>An int representing the number of rows affected by the command</returns>
  252. internal static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  253. {
  254. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  255. // Create & open a SqlConnection, and dispose of it after we are done
  256. using (SqlConnection connection = new SqlConnection(connectionString))
  257. {
  258. connection.Open();
  259. // Call the overload that takes a connection in place of the connection string
  260. return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
  261. }
  262. }
  263. /// <summary>
  264. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
  265. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  266. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  267. /// </summary>
  268. /// <remarks>
  269. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  270. ///
  271. /// e.g.:
  272. /// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
  273. /// </remarks>
  274. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  275. /// <param name="spName">The name of the stored prcedure</param>
  276. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  277. /// <returns>An int representing the number of rows affected by the command</returns>
  278. internal static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
  279. {
  280. int intReturn;
  281. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  282. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  283. // If we receive parameter values, we need to figure out where they go
  284. if ((parameterValues != null) && (parameterValues.Length > 0))
  285. {
  286. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  287. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName,true);
  288. // Assign the provided values to these parameters based on parameter order
  289. AssignParameterValues(commandParameters, parameterValues);
  290. // Call the overload that takes an array of SqlParameters
  291. //return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  292. intReturn = ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  293. //Update the array - parameterValues from the new CommandParameters that should have the ReturnValue
  294. UpdateParameterValues(commandParameters, parameterValues);
  295. return intReturn;
  296. }
  297. else
  298. {
  299. // Otherwise we can just call the SP without params
  300. return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
  301. }
  302. }
  303. /// <summary>
  304. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
  305. /// </summary>
  306. /// <remarks>
  307. /// e.g.:
  308. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
  309. /// </remarks>
  310. /// <param name="connection">A valid SqlConnection</param>
  311. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  312. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  313. /// <returns>An int representing the number of rows affected by the command</returns>
  314. internal static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
  315. {
  316. // Pass through the call providing null for the set of SqlParameters
  317. return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
  318. }
  319. /// <summary>
  320. /// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
  321. /// using the provided parameters.
  322. /// </summary>
  323. /// <remarks>
  324. /// e.g.:
  325. /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
  326. /// </remarks>
  327. /// <param name="connection">A valid SqlConnection</param>
  328. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  329. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  330. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  331. /// <returns>An int representing the number of rows affected by the command</returns>
  332. internal static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  333. {
  334. if (connection == null) throw new ArgumentNullException("connection");
  335. // Create a command and prepare it for execution
  336. SqlCommand cmd = new SqlCommand();
  337. bool mustCloseConnection = false;
  338. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  339. // Finally, execute the command
  340. int retval = cmd.ExecuteNonQuery();
  341. // Detach the SqlParameters from the command object, so they can be used again
  342. cmd.Parameters.Clear();
  343. if (mustCloseConnection)
  344. connection.Close();
  345. return retval;
  346. }
  347. /// <summary>
  348. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
  349. /// using the provided parameter values. This method will query the database to discover the parameters for the
  350. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  351. /// </summary>
  352. /// <remarks>
  353. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  354. ///
  355. /// e.g.:
  356. /// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
  357. /// </remarks>
  358. /// <param name="connection">A valid SqlConnection</param>
  359. /// <param name="spName">The name of the stored procedure</param>
  360. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  361. /// <returns>An int representing the number of rows affected by the command</returns>
  362. internal static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
  363. {
  364. if (connection == null) throw new ArgumentNullException("connection");
  365. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  366. // If we receive parameter values, we need to figure out where they go
  367. if ((parameterValues != null) && (parameterValues.Length > 0))
  368. {
  369. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  370. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  371. // Assign the provided values to these parameters based on parameter order
  372. AssignParameterValues(commandParameters, parameterValues);
  373. // Call the overload that takes an array of SqlParameters
  374. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
  375. }
  376. else
  377. {
  378. // Otherwise we can just call the SP without params
  379. return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
  380. }
  381. }
  382. /// <summary>
  383. /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
  384. /// </summary>
  385. /// <remarks>
  386. /// e.g.:
  387. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
  388. /// </remarks>
  389. /// <param name="transaction">A valid SqlTransaction</param>
  390. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  391. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  392. /// <returns>An int representing the number of rows affected by the command</returns>
  393. internal static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
  394. {
  395. // Pass through the call providing null for the set of SqlParameters
  396. return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
  397. }
  398. /// <summary>
  399. /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
  400. /// using the provided parameters.
  401. /// </summary>
  402. /// <remarks>
  403. /// e.g.:
  404. /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  405. /// </remarks>
  406. /// <param name="transaction">A valid SqlTransaction</param>
  407. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  408. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  409. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  410. /// <returns>An int representing the number of rows affected by the command</returns>
  411. internal static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  412. {
  413. if (transaction == null) throw new ArgumentNullException("transaction");
  414. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  415. // Create a command and prepare it for execution
  416. SqlCommand cmd = new SqlCommand();
  417. bool mustCloseConnection = false;
  418. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  419. // Finally, execute the command
  420. int retval = cmd.ExecuteNonQuery();
  421. // Detach the SqlParameters from the command object, so they can be used again
  422. cmd.Parameters.Clear();
  423. return retval;
  424. }
  425. /// <summary>
  426. /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
  427. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  428. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  429. /// </summary>
  430. /// <remarks>
  431. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  432. ///
  433. /// e.g.:
  434. /// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
  435. /// </remarks>
  436. /// <param name="transaction">A valid SqlTransaction</param>
  437. /// <param name="spName">The name of the stored procedure</param>
  438. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  439. /// <returns>An int representing the number of rows affected by the command</returns>
  440. internal static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
  441. {
  442. if (transaction == null) throw new ArgumentNullException("transaction");
  443. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  444. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  445. // If we receive parameter values, we need to figure out where they go
  446. if ((parameterValues != null) && (parameterValues.Length > 0))
  447. {
  448. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  449. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  450. // Assign the provided values to these parameters based on parameter order
  451. AssignParameterValues(commandParameters, parameterValues);
  452. // Call the overload that takes an array of SqlParameters
  453. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
  454. }
  455. else
  456. {
  457. // Otherwise we can just call the SP without params
  458. return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
  459. }
  460. }
  461. #endregion ExecuteNonQuery
  462. #region ExecuteDataset
  463. /// <summary>
  464. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  465. /// the connection string.
  466. /// </summary>
  467. /// <remarks>
  468. /// e.g.:
  469. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
  470. /// </remarks>
  471. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  472. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  473. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  474. /// <returns>A dataset containing the resultset generated by the command</returns>
  475. internal static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
  476. {
  477. // Pass through the call providing null for the set of SqlParameters
  478. return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
  479. }
  480. /// <summary>
  481. /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
  482. /// using the provided parameters.
  483. /// </summary>
  484. /// <remarks>
  485. /// e.g.:
  486. /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  487. /// </remarks>
  488. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  489. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  490. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  491. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  492. /// <returns>A dataset containing the resultset generated by the command</returns>
  493. internal static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  494. {
  495. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  496. // Create & open a SqlConnection, and dispose of it after we are done
  497. using (SqlConnection connection = new SqlConnection(connectionString))
  498. {
  499. connection.Open();
  500. // Call the overload that takes a connection in place of the connection string
  501. return ExecuteDataset(connection, commandType, commandText, commandParameters);
  502. }
  503. }
  504. /// <summary>
  505. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
  506. /// the connection string using the provided parameter values. This method will query the database to discover the parameters for the
  507. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  508. /// </summary>
  509. /// <remarks>
  510. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  511. ///
  512. /// e.g.:
  513. /// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
  514. /// </remarks>
  515. /// <param name="connectionString">A valid connection string for a SqlConnection</param>
  516. /// <param name="spName">The name of the stored procedure</param>
  517. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  518. /// <returns>A dataset containing the resultset generated by the command</returns>
  519. internal static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
  520. {
  521. DataSet dsReturn;
  522. if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
  523. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  524. // If we receive parameter values, we need to figure out where they go
  525. if ((parameterValues != null) && (parameterValues.Length > 0))
  526. {
  527. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  528. //SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); -- Original code from sqlHelper
  529. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName,true ); // Added Parameter true to support ReturnValues
  530. // Assign the provided values to these parameters based on parameter order
  531. AssignParameterValues(commandParameters, parameterValues);
  532. // Call the overload that takes an array of SqlParameters
  533. //return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  534. //Modify code - just store the dataset to dsReturn
  535. dsReturn = ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
  536. //Update the array - parameterValues from the new CommandParameters that should have the ReturnValue
  537. UpdateParameterValues(commandParameters, parameterValues);
  538. }
  539. else
  540. {
  541. // Otherwise we can just call the SP without params
  542. //return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
  543. //Modify code
  544. dsReturn = ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
  545. }
  546. //Modify code
  547. return dsReturn;
  548. }
  549. /// <summary>
  550. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
  551. /// </summary>
  552. /// <remarks>
  553. /// e.g.:
  554. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
  555. /// </remarks>
  556. /// <param name="connection">A valid SqlConnection</param>
  557. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  558. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  559. /// <returns>A dataset containing the resultset generated by the command</returns>
  560. internal static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
  561. {
  562. // Pass through the call providing null for the set of SqlParameters
  563. return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
  564. }
  565. /// <summary>
  566. /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
  567. /// using the provided parameters.
  568. /// </summary>
  569. /// <remarks>
  570. /// e.g.:
  571. /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  572. /// </remarks>
  573. /// <param name="connection">A valid SqlConnection</param>
  574. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  575. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  576. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  577. /// <returns>A dataset containing the resultset generated by the command</returns>
  578. internal static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  579. {
  580. if (connection == null) throw new ArgumentNullException("connection");
  581. // Create a command and prepare it for execution
  582. SqlCommand cmd = new SqlCommand();
  583. bool mustCloseConnection = false;
  584. PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);
  585. // Create the DataAdapter & DataSet
  586. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  587. {
  588. DataSet ds = new DataSet();
  589. // Fill the DataSet using default values for DataTable names, etc
  590. da.Fill(ds);
  591. // Detach the SqlParameters from the command object, so they can be used again
  592. cmd.Parameters.Clear();
  593. if (mustCloseConnection)
  594. connection.Close();
  595. // Return the dataset
  596. return ds;
  597. }
  598. }
  599. /// <summary>
  600. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
  601. /// using the provided parameter values. This method will query the database to discover the parameters for the
  602. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  603. /// </summary>
  604. /// <remarks>
  605. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  606. ///
  607. /// e.g.:
  608. /// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
  609. /// </remarks>
  610. /// <param name="connection">A valid SqlConnection</param>
  611. /// <param name="spName">The name of the stored procedure</param>
  612. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  613. /// <returns>A dataset containing the resultset generated by the command</returns>
  614. internal static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
  615. {
  616. if (connection == null) throw new ArgumentNullException("connection");
  617. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  618. // If we receive parameter values, we need to figure out where they go
  619. if ((parameterValues != null) && (parameterValues.Length > 0))
  620. {
  621. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  622. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
  623. // Assign the provided values to these parameters based on parameter order
  624. AssignParameterValues(commandParameters, parameterValues);
  625. // Call the overload that takes an array of SqlParameters
  626. return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
  627. }
  628. else
  629. {
  630. // Otherwise we can just call the SP without params
  631. return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
  632. }
  633. }
  634. /// <summary>
  635. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
  636. /// </summary>
  637. /// <remarks>
  638. /// e.g.:
  639. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
  640. /// </remarks>
  641. /// <param name="transaction">A valid SqlTransaction</param>
  642. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  643. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  644. /// <returns>A dataset containing the resultset generated by the command</returns>
  645. internal static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
  646. {
  647. // Pass through the call providing null for the set of SqlParameters
  648. return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
  649. }
  650. /// <summary>
  651. /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
  652. /// using the provided parameters.
  653. /// </summary>
  654. /// <remarks>
  655. /// e.g.:
  656. /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
  657. /// </remarks>
  658. /// <param name="transaction">A valid SqlTransaction</param>
  659. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  660. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  661. /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
  662. /// <returns>A dataset containing the resultset generated by the command</returns>
  663. internal static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
  664. {
  665. if (transaction == null) throw new ArgumentNullException("transaction");
  666. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  667. // Create a command and prepare it for execution
  668. SqlCommand cmd = new SqlCommand();
  669. bool mustCloseConnection = false;
  670. PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  671. // Create the DataAdapter & DataSet
  672. using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  673. {
  674. DataSet ds = new DataSet();
  675. // Fill the DataSet using default values for DataTable names, etc
  676. da.Fill(ds);
  677. // Detach the SqlParameters from the command object, so they can be used again
  678. cmd.Parameters.Clear();
  679. // Return the dataset
  680. return ds;
  681. }
  682. }
  683. /// <summary>
  684. /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
  685. /// SqlTransaction using the provided parameter values. This method will query the database to discover the parameters for the
  686. /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
  687. /// </summary>
  688. /// <remarks>
  689. /// This method provides no access to output parameters or the stored procedure's return value parameter.
  690. ///
  691. /// e.g.:
  692. /// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
  693. /// </remarks>
  694. /// <param name="transaction">A valid SqlTransaction</param>
  695. /// <param name="spName">The name of the stored procedure</param>
  696. /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
  697. /// <returns>A dataset containing the resultset generated by the command</returns>
  698. internal static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
  699. {
  700. if (transaction == null) throw new ArgumentNullException("transaction");
  701. if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
  702. if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
  703. // If we receive parameter values, we need to figure out where they go
  704. if ((parameterValues != null) && (parameterValues.Length > 0))
  705. {
  706. // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
  707. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
  708. // Assign the provided values to these parameters based on parameter order
  709. AssignParameterValues(commandParameters, parameterValues);
  710. // Call the overload that takes an array of SqlParameters
  711. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
  712. }
  713. else
  714. {
  715. // Otherwise we can just call the SP without params
  716. return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
  717. }
  718. }
  719. #endregion ExecuteDataset
  720. #region ExecuteReader
  721. /// <summary>
  722. /// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
  723. /// we can set the appropriate CommandBehavior when calling ExecuteReader()
  724. /// </summary>
  725. private enum SqlConnectionOwnership
  726. {
  727. /// <summary>Connection is owned and managed by SqlHelper</summary>
  728. Internal,
  729. /// <summary>Connection is owned and managed by the caller</summary>
  730. External
  731. }
  732. /// <summary>
  733. /// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
  734. /// </summary>
  735. /// <remarks>
  736. /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
  737. ///
  738. /// If the caller provided the connection, we want to leave it to them to manage.
  739. /// </remarks>
  740. /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
  741. /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
  742. /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
  743. /// <param name="commandText">The stored procedure name or T-SQL command</param>
  744. /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
  745. /// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
  746. /// <returns>SqlDataReader containing the results of the command</returns>
  747. private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
  748. {
  749. if (connection == null) throw new ArgumentNullException("connection");
  750. bool mustCloseConnection = false;
  751. // Create a command and prepare it for execution
  752. SqlCommand cmd = new SqlCommand();
  753. try
  754. {
  755. PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
  756. // Create a reader
  757. SqlDataReader dataReader;
  758. // Call ExecuteReader with the appropriate CommandBehavior
  759. if (connectionOwnership == SqlConnectionOwnership.External)
  760. {
  761. dataReader = cmd.ExecuteReader();
  762. }
  763. else
  764. {
  765. dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  766. }
  767. //We need to Close the DataReader in order to get the Return value
  768. //if (dataReader.IsClosed == false)
  769. // dataReader.Close();
  770. // Detach the SqlParameters from the command object, so they can be used again.
  771. // HACK: There is a problem here, the output parameter values are fletched
  772. // when the reader is closed, so if the parameters are detached from the command
  773. // then the SqlReader can´t set its values.
  774. // When this happen, the parameters can´t be used again in other command.
  775. bool canClear = true;
  776. foreach (SqlParameter commandParameter in cmd.Parameters)
  777. {
  778. if (commandParameter.Direction != ParameterDirection.Input)
  779. canClear = false;
  780. }
  781. if (canClear)
  782. {
  783. cmd.Parameters.Clear();
  784. }
  785. return dataReader;
  786. }
  787. catch
  788. {
  789. if (mustCloseConnection)
  790. connection.Close();
  791. throw;
  792. }
  793. }
  794. /// <summary>
  795. /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
  796. /// the connection string.
  797. /// </summary>
  798. /// <remarks>
  799. /// e.g.:
  800. /// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
  801. /// </remarks>
  802. /// <param name="connectionString">A valid connection string for a SqlConnection</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. /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
  806. internal static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
  807. {
  808. // Pass through the call providing null for the set of SqlParameters
  809. return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
  810. }
  811. /// <summary…

Large files files are truncated, but you can click here to view the full file