//===============================================================================
// This file is based on the Microsoft Data Access Application Block for .NET
// For more information please go to 
// http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
//
//===============================================================================using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;namespace Thinkbank.Utility.DataAccess
{
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance, scalable best practices for 
/// common uses of SqlClient
/// </summary>
    public sealed class SqlHelper
    {
        #region private utility methods & constructors        // Since this class provides only static methods, make the default constructor private to prevent 
        // instances from being created with "new SqlHelper()"
        private SqlHelper() {}        /// <summary>
        /// This method is used to attach array of SqlParameters to a SqlCommand.
        /// 
        /// This method will assign a value of DbNull to any parameter with a direction of
        /// InputOutput and a value of null.  
        /// 
        /// This behavior will prevent default values from being used, but
        /// this will be the less common case than an intended pure output parameter (derived as InputOutput)
        /// where the user provided no input value.
        /// </summary>
        /// <param name="command">The command to which the parameters will be added</param>
        /// <param name="commandParameters">An array of SqlParameters to be added to command</param>
        private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
        {
if( command == null ) throw new ArgumentNullException( "command" );
if( commandParameters != null )
{
foreach (SqlParameter p in commandParameters)
{
if( p != null )
{
// Check for derived output value with no value assigned
if ( ( p.Direction == ParameterDirection.InputOutput || 
p.Direction == ParameterDirection.Input ) && 
(p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
}
        }        /// <summary>
        /// This method assigns dataRow column values to an array of SqlParameters
        /// </summary>
        /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
        /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values</param>
        private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
        {
            if ((commandParameters == null) || (dataRow == null)) 
            {
                // Do nothing if we get no data
                return;
            } int i = 0;
            // Set the parameters values
            foreach(SqlParameter commandParameter in commandParameters)
            {
// Check the parameter name
if( commandParameter.ParameterName == null || 
commandParameter.ParameterName.Length <= 1 )
throw new Exception( 
string.Format( 
"Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.", 
i, commandParameter.ParameterName ) );
                if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
                    commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
i++;
            }
        }        /// <summary>
        /// This method assigns an array of values to an array of SqlParameters
        /// </summary>
        /// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
        /// <param name="parameterValues">Array of objects holding the values to be assigned</param>
        private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
        {
            if ((commandParameters == null) || (parameterValues == null)) 
            {

解决方案 »

  1.   

           // Do nothing if we get no data
                    return;
                }            // We must have the same number of values as we pave parameters to put them in
                if (commandParameters.Length != parameterValues.Length)
                {
                    throw new ArgumentException("Parameter count does not match Parameter Value count.");
                }            // Iterate through the SqlParameters, assigning the values from the corresponding position in the 
                // value array
                for (int i = 0, j = commandParameters.Length; i < j; i++)
                {
                    // If the current array value derives from IDbDataParameter, then assign its Value property
    if (parameterValues[i] is IDbDataParameter)
    {
    IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
    if( paramInstance.Value == null )
    {
    commandParameters[i].Value = DBNull.Value; 
    }
    else
    {
    commandParameters[i].Value = paramInstance.Value;
    }
    }
    else if (parameterValues[i] == null)
    {
    commandParameters[i].Value = DBNull.Value;
    }
    else
    {
    commandParameters[i].Value = parameterValues[i];
    }
                }
            }        /// <summary>
            /// This method opens (if necessary) and assigns a connection, transaction, command type and parameters 
            /// to the provided command
            /// </summary>
            /// <param name="command">The SqlCommand to be prepared</param>
            /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
            /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
            /// <param name="mustCloseConnection"><c>true</c> if the connection was opened by the method, otherwose is false.</param>
            private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection )
            {
    if( command == null ) throw new ArgumentNullException( "command" );
    if( commandText == null || commandText.Length == 0 ) throw new ArgumentNullException( "commandText" );            // If the provided connection is not open, we will open it
    if (connection.State != ConnectionState.Open)
    {
    mustCloseConnection = true;
    connection.Open();
    }
    else
    {
    mustCloseConnection = false;
    }            // Associate the connection with the command
                command.Connection = connection;            // Set the command text (stored procedure name or SQL statement)
                command.CommandText = commandText;            // If we were provided a transaction, assign it
                if (transaction != null)
                {
    if( transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
                    command.Transaction = transaction;
                }            // Set the command type
                command.CommandType = commandType;            // Attach the command parameters if they are provided
                if (commandParameters != null)
                {
                    AttachParameters(command, commandParameters);
                }
                return;
            }        #endregion private utility methods & constructors        #region ExecuteNonQuery        /// <summary>
            /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in 
            /// the connection string
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
      

  2.   

     /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
            /// using the provided parameters
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );            // Create & open a SqlConnection, and dispose of it after we are done
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();                // Call the overload that takes a connection in place of the connection string
                    return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in 
            /// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored prcedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
      

  3.   

        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );            // Create a command and prepare it for execution
                SqlCommand cmd = new SqlCommand();
    bool mustCloseConnection = false;
                PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
        
                // Finally, execute the command
                int retval = cmd.ExecuteNonQuery();
        
                // Detach the SqlParameters from the command object, so they can be used again
                cmd.Parameters.Clear();
    if( mustCloseConnection )
    connection.Close();
                return retval;
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection 
            /// using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
    public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
      

  4.   


    // Create a command and prepare it for execution
    SqlCommand cmd = new SqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
        
    // Finally, execute the command
    int retval = cmd.ExecuteNonQuery();
        
    // Detach the SqlParameters from the command object, so they can be used again
    cmd.Parameters.Clear();
    return retval;
    }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified 
            /// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" ); // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
                }
            }        #endregion ExecuteNonQuery        #region ExecuteDataset        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
            /// the connection string. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );            // Create & open a SqlConnection, and dispose of it after we are done
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();                // Call the overload that takes a connection in place of the connection string
                    return ExecuteDataset(connection, commandType, commandText, commandParameters);
                }
      

  5.   

           }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in 
            /// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

    // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
            }

            /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
    public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
    if( connection == null ) throw new ArgumentNullException( "connection" ); // Create a command and prepare it for execution
    SqlCommand cmd = new SqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
        
    // Create the DataAdapter & DataSet
    using( SqlDataAdapter da = new SqlDataAdapter(cmd) )
    {
    DataSet ds = new DataSet(); // Fill the DataSet using default values for DataTable names, etc
    da.Fill(ds);

    // Detach the SqlParameters from the command object, so they can be used again
    cmd.Parameters.Clear(); if( mustCloseConnection )
    connection.Close(); // Return the dataset
    return ds;
    }
    }

            /// <summary>
      

  6.   

           /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
            }

            /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
    public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" ); // Create a command and prepare it for execution
    SqlCommand cmd = new SqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
        
    // Create the DataAdapter & DataSet
    using( SqlDataAdapter da = new SqlDataAdapter(cmd) )
    {
    DataSet ds = new DataSet(); // Fill the DataSet using default values for DataTable names, etc
    da.Fill(ds);
        
    // Detach the SqlParameters from the command object, so they can be used again
    cmd.Parameters.Clear(); // Return the dataset
    return ds;
    }
    }

            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified 
            /// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
      

  7.   

            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

    // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
                }
            }        #endregion ExecuteDataset

            #region ExecuteReader        /// <summary>
            /// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
            /// we can set the appropriate CommandBehavior when calling ExecuteReader()
            /// </summary>
            private enum SqlConnectionOwnership
            {
                /// <summary>Connection is owned and managed by SqlHelper</summary>
                Internal, 
                /// <summary>Connection is owned and managed by the caller</summary>
                External
            }        /// <summary>
            /// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
            /// </summary>
            /// <res>
            /// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
            /// 
            /// If the caller provided the connection, we want to leave it to them to manage.
            /// </res>
            /// <param name="connection">A valid SqlConnection, on which to execute this command</param>
            /// <param name="transaction">A valid SqlTransaction, or 'null'</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
            /// <param name="connectionOwnership">Indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
            /// <returns>SqlDataReader containing the results of the command</returns>
            private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" ); bool mustCloseConnection = false;
                // Create a command and prepare it for execution
                SqlCommand cmd = new SqlCommand();
    try
    {
    PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );

    // Create a reader
    SqlDataReader dataReader; // Call ExecuteReader with the appropriate CommandBehavior
    if (connectionOwnership == SqlConnectionOwnership.External)
    {
    dataReader = cmd.ExecuteReader();
    }
    else
    {
    dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    }

    // Detach the SqlParameters from the command object, so they can be used again.
    // HACK: There is a problem here, the output parameter values are fletched 
    // when the reader is closed, so if the parameters are detached from the command
    // then the SqlReader can磘 set its values. 
    // When this happen, the parameters can磘 be used again in other command.
    bool canClear = true;
    foreach(SqlParameter commandParameter in cmd.Parameters)
    {
    if (commandParameter.Direction != ParameterDirection.Input)
    canClear = false;
    }
      

  8.   

                
    if (canClear)
    {
    cmd.Parameters.Clear();
    } return dataReader;
    }
    catch
    {
    if( mustCloseConnection )
    connection.Close();
    throw;
    }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
            /// the connection string. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
                SqlConnection connection = null;
                try
                {
    connection = new SqlConnection(connectionString);
    connection.Open();                // Call the private overload that takes an internally owned connection in place of the connection string
                    return ExecuteReader(connection, null, commandType, commandText, commandParameters,SqlConnectionOwnership.Internal);
                }
                catch
                {
                    // If we fail to return the SqlDatReader, we need to close the connection ourselves
                    if( connection != null ) connection.Close();
                    throw;
                }
                
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in 
            /// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36);
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

    // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);                AssignParameterValues(commandParameters, parameterValues);                return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
      

  9.   

                  return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
                // Pass through the call to the private overload using a null transaction value and an externally owned connection
                return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36);
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);                AssignParameterValues(commandParameters, parameterValues);                return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteReader(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///   SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
      

  10.   

            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" ); // Pass through to private overload, indicating that the connection is owned by the caller
                return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
            /// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36);
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);                AssignParameterValues(commandParameters, parameterValues);                return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
                }
            }        #endregion ExecuteReader        #region ExecuteScalar

            /// <summary>
            /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in 
            /// the connection string. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
                // Create & open a SqlConnection, and dispose of it after we are done
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();                // Call the overload that takes a connection in place of the connection string
                    return ExecuteScalar(connection, commandType, commandText, commandParameters);
                }
            }
      

  11.   


            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in 
            /// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36);
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

    // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
    if( connection == null ) throw new ArgumentNullException( "connection" ); // Create a command and prepare it for execution
    SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false;
    PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );
        
    // Execute the command & return the results
    object retval = cmd.ExecuteScalar();
        
    // Detach the SqlParameters from the command object, so they can be used again
    cmd.Parameters.Clear(); if( mustCloseConnection )
    connection.Close(); return retval;
    }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection 
            /// using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
      

  12.   

          ///  int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36);
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
    public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" ); // Create a command and prepare it for execution
    SqlCommand cmd = new SqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
        
    // Execute the command & return the results
    object retval = cmd.ExecuteScalar();
        
    // Detach the SqlParameters from the command object, so they can be used again
    cmd.Parameters.Clear();
    return retval;
    }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified
            /// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36);
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
      

  13.   

               if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // PPull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
                }
            }        #endregion ExecuteScalar         #region ExecuteXmlReader
            /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
            /// <returns>An XmlReader containing the resultset generated by the command</returns>
            public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An XmlReader containing the resultset generated by the command</returns>
            public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" ); bool mustCloseConnection = false;
    // Create a command and prepare it for execution
                SqlCommand cmd = new SqlCommand();
    try
    {
    PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );

    // Create the DataAdapter & DataSet
    XmlReader retval = cmd.ExecuteXmlReader();

    // Detach the SqlParameters from the command object, so they can be used again
    cmd.Parameters.Clear(); return retval;
    }
    catch
    {
    if( mustCloseConnection )
    connection.Close();
    throw;
    }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36);
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="spName">The name of the stored procedure using "FOR XML AUTO"</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>An XmlReader containing the resultset generated by the command</returns>
            public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
      

  14.   

               {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders");
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
            /// <returns>An XmlReader containing the resultset generated by the command</returns>
            public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
            {
                // Pass through the call providing null for the set of SqlParameters
                return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command using "FOR XML AUTO"</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <returns>An XmlReader containing the resultset generated by the command</returns>
    public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
    {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" ); // Create a command and prepare it for execution
    SqlCommand cmd = new SqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );

    // Create the DataAdapter & DataSet
    XmlReader retval = cmd.ExecuteXmlReader();

    // Detach the SqlParameters from the command object, so they can be used again
    cmd.Parameters.Clear();
    return retval;
    }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified 
            /// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36);
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else 
                {
      

  15.   

    // Otherwise we can just call the SP without params
                    return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
                }
            }        #endregion ExecuteXmlReader        #region FillDataset
            /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in 
            /// the connection string. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)</param>
            public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
                
    // Create & open a SqlConnection, and dispose of it after we are done
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();                // Call the overload that takes a connection in place of the connection string
                    FillDataset(connection, commandType, commandText, dataSet, tableNames);
                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>
            public static void FillDataset(string connectionString, CommandType commandType,
                string commandText, DataSet dataSet, string[] tableNames,
                params SqlParameter[] commandParameters)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
                // Create & open a SqlConnection, and dispose of it after we are done
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();                // Call the overload that takes a connection in place of the connection string
                    FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in 
            /// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, 24);
            /// </res>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>    
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            public static void FillDataset(string connectionString, string spName,
                DataSet dataSet, string[] tableNames,
                params object[] parameterValues)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
                // Create & open a SqlConnection, and dispose of it after we are done
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();                // Call the overload that takes a connection in place of the connection string
                    FillDataset (connection, spName, dataSet, tableNames, parameterValues);
      

  16.   

                }
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>    
            public static void FillDataset(SqlConnection connection, CommandType commandType, 
                string commandText, DataSet dataSet, string[] tableNames)
            {
                FillDataset(connection, commandType, commandText, dataSet, tableNames, null);
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            public static void FillDataset(SqlConnection connection, CommandType commandType, 
                string commandText, DataSet dataSet, string[] tableNames,
                params SqlParameter[] commandParameters)
            {
                FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters);
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  FillDataset(conn, "GetOrders", ds, new string[] {"orders"}, 24, 36);
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            public static void FillDataset(SqlConnection connection, string spName, 
                DataSet dataSet, string[] tableNames,
                params object[] parameterValues)
            {
                if ( connection == null ) throw new ArgumentNullException( "connection" );
    if (dataSet == null ) throw new ArgumentNullException( "dataSet" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" ); // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames);
                }    
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction. 
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"});
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
      

  17.   

            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>
            public static void FillDataset(SqlTransaction transaction, CommandType commandType, 
                string commandText,
                DataSet dataSet, string[] tableNames)
            {
                FillDataset (transaction, commandType, commandText, dataSet, tableNames, null);    
            }        /// <summary>
            /// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
            public static void FillDataset(SqlTransaction transaction, CommandType commandType, 
                string commandText, DataSet dataSet, string[] tableNames,
                params SqlParameter[] commandParameters)
            {
                FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters);
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified 
            /// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <res>
            /// This method provides no access to output parameters or the stored procedure's return value parameter.
            /// 
            /// e.g.:  
            ///  FillDataset(trans, "GetOrders", ds, new string[]{"orders"}, 24, 36);
            /// </res>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>
            /// <param name="parameterValues">An array of objects to be assigned as the input values of the stored procedure</param>
            public static void FillDataset(SqlTransaction transaction, string spName,
                DataSet dataSet, string[] tableNames,
                params object[] parameterValues) 
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( dataSet == null ) throw new ArgumentNullException( "dataSet" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If we receive parameter values, we need to figure out where they go
                if ((parameterValues != null) && (parameterValues.Length > 0)) 
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);                // Assign the provided values to these parameters based on parameter order
                    AssignParameterValues(commandParameters, parameterValues);                // Call the overload that takes an array of SqlParameters
                    FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
                }
                else 
                {
    // Otherwise we can just call the SP without params
                    FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames);
                }    
            }        /// <summary>
            /// Private helper method that execute a SqlCommand (that returns a resultset) against the specified SqlTransaction and SqlConnection
            /// using the provided parameters.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  FillDataset(conn, trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24));
            /// </res>
            /// <param name="connection">A valid SqlConnection</param>
            /// <param name="transaction">A valid SqlTransaction</param>
            /// <param name="commandType">The CommandType (stored procedure, text, etc.)</param>
            /// <param name="commandText">The stored procedure name or T-SQL command</param>
            /// <param name="dataSet">A dataset wich will contain the resultset generated by the command</param>
            /// <param name="tableNames">This array will be used to create table mappings allowing the DataTables to be referenced
            /// by a user defined name (probably the actual table name)
            /// </param>
            /// <param name="commandParameters">An array of SqlParamters used to execute the command</param>
    private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType, 
    string commandText, DataSet dataSet, string[] tableNames,
      

  18.   

    params SqlParameter[] commandParameters)
    {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( dataSet == null ) throw new ArgumentNullException( "dataSet" ); // Create a command and prepare it for execution
    SqlCommand command = new SqlCommand();
    bool mustCloseConnection = false;
    PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection );
        
    // Create the DataAdapter & DataSet
    using( SqlDataAdapter dataAdapter = new SqlDataAdapter(command) )
    {
                    
    // Add the table mappings specified by the user
    if (tableNames != null && tableNames.Length > 0)
    {
    string tableName = "Table";
    for (int index=0; index < tableNames.Length; index++)
    {
    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" );
    dataAdapter.TableMappings.Add(tableName, tableNames[index]);
    tableName += (index + 1).ToString();
    }
    }
                    
    // Fill the DataSet using default values for DataTable names, etc
    dataAdapter.Fill(dataSet); // Detach the SqlParameters from the command object, so they can be used again
    command.Parameters.Clear();
    } if( mustCloseConnection )
    connection.Close();
    }
    #endregion
            
            #region UpdateDataset
            /// <summary>
            /// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
            /// </res>
            /// <param name="insertCommand">A valid transact-SQL statement or stored procedure to insert new records into the data source</param>
            /// <param name="deleteCommand">A valid transact-SQL statement or stored procedure to delete records from the data source</param>
            /// <param name="updateCommand">A valid transact-SQL statement or stored procedure used to update records in the data source</param>
            /// <param name="dataSet">The DataSet used to update the data source</param>
            /// <param name="tableName">The DataTable used to update the data source.</param>
            public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName)
            {
    if( insertCommand == null ) throw new ArgumentNullException( "insertCommand" );
    if( deleteCommand == null ) throw new ArgumentNullException( "deleteCommand" );
    if( updateCommand == null ) throw new ArgumentNullException( "updateCommand" );
    if( tableName == null || tableName.Length == 0 ) throw new ArgumentNullException( "tableName" );             // Create a SqlDataAdapter, and dispose of it after we are done
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
                {
                    // Set the data adapter commands
                    dataAdapter.UpdateCommand = updateCommand;
                    dataAdapter.InsertCommand = insertCommand;
                    dataAdapter.DeleteCommand = deleteCommand;                // Update the dataset changes in the data source
                    dataAdapter.Update (dataSet, tableName);                 // Commit all the changes made to the DataSet
                    dataSet.AcceptChanges();
                }
            }
            #endregion        #region CreateCommand
            /// <summary>
            /// Simplify the creation of a Sql command object by allowing
            /// a stored procedure and optional parameters to be provided
            /// </summary>
            /// <res>
            /// e.g.:  
            ///  SqlCommand command = CreateCommand(conn, "AddCustomer", "CustomerID", "CustomerName");
            /// </res>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="sourceColumns">An array of string to be assigned as the source columns of the stored procedure parameters</param>
            /// <returns>A valid SqlCommand object</returns>
            public static SqlCommand CreateCommand(SqlConnection connection, string spName, params string[] sourceColumns) 
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // Create a SqlCommand
                SqlCommand cmd = new SqlCommand( spName, connection );
                cmd.CommandType = CommandType.StoredProcedure;            // If we receive parameter values, we need to figure out where they go
                if ((sourceColumns != null) && (sourceColumns.Length > 0)) 
                {
      

  19.   

                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);                // Assign the provided source columns to these parameters based on parameter order
                    for (int index=0; index < sourceColumns.Length; index++)
                        commandParameters[index].SourceColumn = sourceColumns[index];                // Attach the discovered parameters to the SqlCommand object
                    AttachParameters (cmd, commandParameters);
                }            return cmd;
            }
            #endregion        #region ExecuteNonQueryTypedParams
            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in 
            /// the connection string using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
            /// </summary>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQueryTypedParams(String connectionString, String spName, DataRow dataRow)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

    // If the row has values, the store procedure parameters must be initialized
                if (dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                                    
                    return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection 
            /// using the dataRow column values as the stored procedure's parameters values.  
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
            /// </summary>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQueryTypedParams(SqlConnection connection, String spName, DataRow dataRow)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if (dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                                    
                    return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
            /// SqlTransaction using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
            /// </summary>
            /// <param name="transaction">A valid SqlTransaction object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An int representing the number of rows affected by the command</returns>
            public static int ExecuteNonQueryTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // Sf the row has values, the store procedure parameters must be initialized
                if (dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
      

  20.   

                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                                    
                    return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
                }
            }
            #endregion        #region ExecuteDatasetTypedParams
            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in 
            /// the connection string using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
            /// </summary>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDatasetTypedParams(string connectionString, String spName, DataRow dataRow)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            //If the row has values, the store procedure parameters must be initialized
                if ( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the dataRow column values as the store procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
            /// </summary>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDatasetTypedParams(SqlConnection connection, String spName, DataRow dataRow)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction 
            /// using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on row values.
            /// </summary>
            /// <param name="transaction">A valid SqlTransaction object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>A dataset containing the resultset generated by the command</returns>
            public static DataSet ExecuteDatasetTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
      

  21.   

                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
                }
            }        #endregion        #region ExecuteReaderTypedParams
            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in 
            /// the connection string using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReaderTypedParams(String connectionString, String spName, DataRow dataRow)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

    // If the row has values, the store procedure parameters must be initialized
                if ( dataRow != null && dataRow.ItemArray.Length > 0 )
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
                }
            }                
            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName);
                }
            }
            
            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction 
            /// using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="transaction">A valid SqlTransaction object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>A SqlDataReader containing the resultset generated by the command</returns>
            public static SqlDataReader ExecuteReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0 )
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
      

  22.   

                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
                }
            }
            #endregion        #region ExecuteScalarTypedParams
            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in 
            /// the connection string using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="connectionString">A valid connection string for a SqlConnection</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalarTypedParams(String connectionString, String spName, DataRow dataRow)
            {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );

    // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection 
            /// using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalarTypedParams(SqlConnection connection, String spName, DataRow dataRow)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
            /// using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="transaction">A valid SqlTransaction object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
            public static object ExecuteScalarTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
      

  23.   

                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
                }
            }
            #endregion        #region ExecuteXmlReaderTypedParams
            /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection 
            /// using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An XmlReader containing the resultset generated by the command</returns>
            public static XmlReader ExecuteXmlReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
                }
            }        /// <summary>
            /// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlTransaction 
            /// using the dataRow column values as the stored procedure's parameters values.
            /// This method will query the database to discover the parameters for the 
            /// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
            /// </summary>
            /// <param name="transaction">A valid SqlTransaction object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="dataRow">The dataRow used to hold the stored procedure's parameter values.</param>
            /// <returns>An XmlReader containing the resultset generated by the command</returns>
            public static XmlReader ExecuteXmlReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow)
            {
    if( transaction == null ) throw new ArgumentNullException( "transaction" );
    if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            // If the row has values, the store procedure parameters must be initialized
                if( dataRow != null && dataRow.ItemArray.Length > 0)
                {
                    // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
                    SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);
                    
                    // Set the parameters values
                    AssignParameterValues(commandParameters, dataRow);
                    
                    return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
                }
                else
                {
                    return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
                }
            }
            #endregion    } /// <summary>
    /// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
    /// ability to discover parameters for stored procedures at run-time.
    /// </summary>
    public sealed class SqlHelperParameterCache
    {
    #region private methods, variables, and constructors //Since this class provides only static methods, make the default constructor private to prevent 
    //instances from being created with "new SqlHelperParameterCache()"
    private SqlHelperParameterCache() {} private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());        /// <summary>
            /// Resolve at run time the appropriate set of SqlParameters for a stored procedure
            /// </summary>
            /// <param name="connection">A valid SqlConnection object</param>
      

  24.   

            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="includeReturnValueParameter">Whether or not to include their return value parameter</param>
            /// <returns>The parameter array discovered.</returns>
    private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
    {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" ); SqlCommand cmd = new SqlCommand(spName, connection);
    cmd.CommandType = CommandType.StoredProcedure; connection.Open();
    SqlCommandBuilder.DeriveParameters(cmd);
    connection.Close(); if (!includeReturnValueParameter) 
    {
    cmd.Parameters.RemoveAt(0);
    }
                    
    SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count]; cmd.Parameters.CopyTo(discoveredParameters, 0); // Init the parameters with a DBNull value
    foreach (SqlParameter discoveredParameter in discoveredParameters)
    {
    discoveredParameter.Value = DBNull.Value;
    }
    return discoveredParameters;
    } /// <summary>
    /// Deep copy of cached SqlParameter array
    /// </summary>
    /// <param name="originalParameters"></param>
    /// <returns></returns>
    private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
    {
    SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length]; for (int i = 0, j = originalParameters.Length; i < j; i++)
    {
    clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
    } return clonedParameters;
    } #endregion private methods, variables, and constructors #region caching functions /// <summary>
    /// Add parameter array to the cache
    /// </summary>
    /// <param name="connectionString">A valid connection string for a SqlConnection</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <param name="commandParameters">An array of SqlParamters to be cached</param>
    public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
    {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( commandText == null || commandText.Length == 0 ) throw new ArgumentNullException( "commandText" ); string hashKey = connectionString + ":" + commandText; paramCache[hashKey] = commandParameters;
    } /// <summary>
    /// Retrieve a parameter array from the cache
    /// </summary>
    /// <param name="connectionString">A valid connection string for a SqlConnection</param>
    /// <param name="commandText">The stored procedure name or T-SQL command</param>
    /// <returns>An array of SqlParamters</returns>
    public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
    {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( commandText == null || commandText.Length == 0 ) throw new ArgumentNullException( "commandText" ); string hashKey = connectionString + ":" + commandText; SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[];
    if (cachedParameters == null)
    {
    return null;
    }
    else
    {
    return CloneParameters(cachedParameters);
    }
    } #endregion caching functions #region Parameter Discovery Functions /// <summary>
    /// Retrieves the set of SqlParameters appropriate for the stored procedure
    /// </summary>
      

  25.   

    /// <res>
    /// This method will query the database for this information, and then store it in a cache for future requests.
    /// </res>
    /// <param name="connectionString">A valid connection string for a SqlConnection</param>
    /// <param name="spName">The name of the stored procedure</param>
    /// <returns>An array of SqlParameters</returns>
    public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
    {
    return GetSpParameterSet(connectionString, spName, false);
    } /// <summary>
    /// Retrieves the set of SqlParameters appropriate for the stored procedure
    /// </summary>
    /// <res>
    /// This method will query the database for this information, and then store it in a cache for future requests.
    /// </res>
    /// <param name="connectionString">A valid connection string for a SqlConnection</param>
    /// <param name="spName">The name of the stored procedure</param>
    /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
    /// <returns>An array of SqlParameters</returns>
    public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
    {
    if( connectionString == null || connectionString.Length == 0 ) throw new ArgumentNullException( "connectionString" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            using(SqlConnection connection = new SqlConnection(connectionString))
                {
                    return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
                }
    }        /// <summary>
            /// Retrieves the set of SqlParameters appropriate for the stored procedure
            /// </summary>
            /// <res>
            /// This method will query the database for this information, and then store it in a cache for future requests.
            /// </res>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <returns>An array of SqlParameters</returns>
            internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName)
            {
                return GetSpParameterSet(connection, spName, false);
            }        /// <summary>
            /// Retrieves the set of SqlParameters appropriate for the stored procedure
            /// </summary>
            /// <res>
            /// This method will query the database for this information, and then store it in a cache for future requests.
            /// </res>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
            /// <returns>An array of SqlParameters</returns>
            internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
                using (SqlConnection clonedConnection = (SqlConnection)((ICloneable)connection).Clone())
                {
                    return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter);
                }
            }        /// <summary>
            /// Retrieves the set of SqlParameters appropriate for the stored procedure
            /// </summary>
            /// <param name="connection">A valid SqlConnection object</param>
            /// <param name="spName">The name of the stored procedure</param>
            /// <param name="includeReturnValueParameter">A bool value indicating whether the return value parameter should be included in the results</param>
            /// <returns>An array of SqlParameters</returns>
            private static SqlParameter[] GetSpParameterSetInternal(SqlConnection connection, string spName, bool includeReturnValueParameter)
            {
    if( connection == null ) throw new ArgumentNullException( "connection" );
    if( spName == null || spName.Length == 0 ) throw new ArgumentNullException( "spName" );            string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter":"");            SqlParameter[] cachedParameters;
            
                cachedParameters = paramCache[hashKey] as SqlParameter[];
                if (cachedParameters == null)
                {
                    SqlParameter[] spParameters = DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
            paramCache[hashKey] = spParameters;
                    cachedParameters = spParameters;
                }
            
                return CloneParameters(cachedParameters);
            }
            
    #endregion Parameter Discovery Functions }
    }
      

  26.   

    /////////////////////////BLL--UserBLL///////////////////////////////////////////////////
    using System;
    using Thinkbank.TRMS.Common;
    using Thinkbank.TRMS.IDAL;
    using Thinkbank.TRMS.DALFactory;
    using Thinkbank.TRMS.Model;namespace Thinkbank.TRMS.BLL
    {
    /// <summary>
    /// UserBLL 的摘要说明。
    /// </summary>
    public class UserBLL
    {
    private static readonly IUserDAL userDAL = Thinkbank.TRMS.DALFactory.DataAccess.CreateUserDAL(); /// <summary>
    /// 根据指定的用户ID取得用户信息
    /// </summary>
    /// <param name="userID">用户的ID值</param>
    /// <returns></returns>
    public Thinkbank.TRMS.Model.UserInfo GetUser(int userID)
    {
    if(userID < 1)
    return null;

    return userDAL.GetUser(userID);
    } /// <summary>
    /// 根据指定的登录名和口令取得用户信息
    /// </summary>
    /// <param name="loginName"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public Thinkbank.TRMS.Model.UserInfo GetUser(string loginName, string password)
    {
    if((loginName == string.Empty) || (password == string.Empty))
    return null; return userDAL.GetUser(loginName, password);
    } /// <summary>
    /// 取得所有用户
    /// </summary>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetAllUsers(string sortExpress)
    {
    if(sortExpress == string.Empty)
    return null; return userDAL.GetAllUsers(sortExpress);
    } /// <summary>
    /// 根据登录名取得用户
    /// </summary>
    /// <param name="loginName">登录名</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetUsersByLoginName(string loginName, string sortExpress)
    {
    if((loginName == string.Empty) || (sortExpress == string.Empty))
    return null; return userDAL.GetUsersByLoginName(loginName,sortExpress);
    } /// <summary>
    /// 根据用户姓名取得用户
    /// </summary>
    /// <param name="userName">用户姓名</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetUsersByUserName(string userName, string sortExpress)
    {
    if((userName == string.Empty) || (sortExpress == string.Empty))
    return null; return userDAL.GetUsersByUserName(userName,sortExpress);
    } /// <summary>
    /// 根据角色取得用户
    /// </summary>
    /// <param name="roleID">角色ID</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetUsersByRoleID(int roleID, string sortExpress)
    {
    if((roleID < 1) || (sortExpress == string.Empty))
    return null; return userDAL.GetUsersByRoleID(roleID,sortExpress);
    } /// <summary>
    /// 插入一个用户
    /// </summary>
      

  27.   

    /// <param name="user">用户信息</param>
    /// <returns>成功则返回true ,失败则返回false</returns>
    public ReturnInfo Insert(Thinkbank.TRMS.Model.UserInfo user)
    {
    if(user == null)
    return new ReturnInfo(false, "用户信息为空!"); if(userDAL.IsExistUser(user.LoginName))
    return new ReturnInfo(false, "登名名(" + user.LoginName + ")已经存在!"); return userDAL.Insert(user);
    } /// <summary>
    /// 更新一个用户
    /// </summary>
    /// <param name="user">用户信息</param>
    /// <returns>成功则返回true ,失败则返回false</returns>>
    public ReturnInfo Update(Thinkbank.TRMS.Model.UserInfo user)
    {
    if(user == null)
    return new ReturnInfo(false, "用户信息为空!"); return userDAL.Update(user);
    } /// <summary>
    /// 删除一个用户
    /// </summary>
    /// <param name="userID">用户的ID值</param>
    /// <returns>成功则返回true ,失败则返回false</returns>
    public ReturnInfo Delete(int operatorID, int userID)
    {
    if(userID < 1)
    return new ReturnInfo(false,"用户ID值非法!"); if(operatorID == userID)  
    return new ReturnInfo(false,"您不能删除自己!"); return userDAL.Delete(userID);
    } /// <summary>
    /// 删除一批用户
    /// </summary>
    /// <param name="userIDs">删除用户的ID的集合</param>
    /// <returns>成功返回 true;失败返回 false</returns>
    public ReturnInfo Delete(int operatorID, int[] userIDs)
    {
    if((userIDs == null) || (userIDs.Length == 0))
    return new ReturnInfo(false,"用户ID值非法!"); for(int i=0; i<userIDs.Length; i++)
    if(operatorID == userIDs[i])
    return new ReturnInfo(false,"您不能删除自己!");

    return userDAL.Delete(userIDs);
    } /// <summary>
    /// 更新指定用户的密码
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="oldPassword">旧密码</param>
    /// <param name="newPassword">新密码</param>
    /// <returns>返回值信息</returns>
    public ReturnInfo UpdatePassord(int userID, string oldPassword, string newPassword)
    {
    if((userID < 1)||(oldPassword == string.Empty)||(newPassword == string.Empty))
    return new ReturnInfo(false, "用户ID、或输入的密码无效!");

    if(userDAL.GetUserPassword(userID) == oldPassword)
    {
    return userDAL.ChangeUserPassword(userID,newPassword);
    }
    else
    {
    return new ReturnInfo(false, "旧密码输入错误!");
    }
    } /// <summary>
    /// 检查用户权限
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="rightID">权限ID</param>
    /// <returns>true 有权限, false 无权限</returns>
    public bool CheckRight(int userID, int rightID)
    {
    if((userID <1) || (rightID <1))
    return false;

    return userDAL.CheckRight(userID, rightID);
    } /// <summary>
    /// 检查用户权限
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="rightID">权限ID的集合</param>
    /// <returns>true 有权限, false 无权限</returns>
    public bool CheckRight(int userID, int[] rightIDs)
    {
    if((userID <1) || (rightIDs.Length <0))
    return false;

    return userDAL.CheckRight(userID, rightIDs);
    }
    }
    }
      

  28.   

    ////////////////////////DataFactory--DataAccess////////////////////////////////////
    using System;
    using System.Reflection;
    using Thinkbank.TRMS.IDAL;
    using Thinkbank.TRMS.Common;namespace Thinkbank.TRMS.DALFactory
    {
    /// <summary>
    /// DataAccess 的摘要说明。
    /// </summary>
    public sealed class DataAccess
    {
    public DataAccess()
    {
    } public static IUserDAL CreateUserDAL() 
    {
    string className = TRMSConfiguration.DALNameSpace + ".UserDAL";
    return (IUserDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IRoleDAL CreateRoleDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".RoleDAL";
    return (IRoleDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IRightDAL CreateRightDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".RightDAL";
    return (IRightDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IResearchResourceLevelDAL CreateResearchResourceLevelDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".ResearchResourceLevelDAL";
    return (IResearchResourceLevelDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IAuditingDAL CreateAuditingDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".AuditingDAL";
    return (IAuditingDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IResearchResourceTypeDAL CreateResearchResourceTypeDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".ResearchResourceTypeDAL";
    return (IResearchResourceTypeDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IAssessDAL CreateAssessDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".AssessDAL";
    return (IAssessDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    }

    public static IAssessDetailDAL CreateAssessDetailDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".AssessDetailDAL";
    return (IAssessDetailDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IDownloadDetailDAL CreateDownloadDetailDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".DownloadDetailDAL";
    return (IDownloadDetailDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IDownloadDAL CreateDownloadDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".DownloadDAL";
    return (IDownloadDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    } public static IUploadDAL CreateUploadDAL()
    {
    string className = TRMSConfiguration.DALNameSpace + ".UploadDAL";
    return (IUploadDAL)Assembly.Load(TRMSConfiguration.DALAssembly).CreateInstance(className);
    }
    }
    }
      

  29.   

    ///////////////////////////////////////IDAL--UserDAL///////////////////////////////////////////
    using System;
    using System.Data;
    using Thinkbank.TRMS.Model;
    using Thinkbank.TRMS.Common;namespace Thinkbank.TRMS.IDAL
    {
    /// <summary>
    /// IUser 的摘要说明。
    /// </summary>
    public interface IUserDAL
    {
    /// <summary>
    /// 根据用户ID取用户信息
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <returns>取得的用户信息</returns>
    UserInfo GetUser(int userID); /// <summary>
    /// 根据用户的登录名和口令取用户信息
    /// </summary>
    /// <param name="loginName">用户的登录名</param>
    /// <param name="password">用户的口令</param>
    /// <returns>取得的用户信息</returns>
    UserInfo GetUser(string loginName, string password); /// <summary>
    /// 取所有用户
    /// </summary>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    DataSet GetAllUsers(string sortExpress);

    /// <summary>
    /// 根据登录名取用户数据集
    /// </summary>
    /// <param name="loginName">登录名</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    DataSet GetUsersByLoginName(string loginName, string sortExpress); /// <summary>
    /// 根据用户名取用户数据集
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    DataSet GetUsersByUserName(string userName, string sortExpress); /// <summary>
    /// 根据角色ID取用户数据集
    /// </summary>
    /// <param name="roleID">角色ID</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    DataSet GetUsersByRoleID(int roleID, string sortExpress);

    /// <summary>
    /// 添加一个新的用户
    /// </summary>
    /// <param name="user">用户信息</param>
    /// <returns>操作的返回信息</returns>
    ReturnInfo Insert(UserInfo user); /// <summary>
    /// 修改一个用户的信息
    /// </summary>
    /// <param name="user">新设的用户信息</param>
    /// <returns>操作的返回信息</returns>
    ReturnInfo Update(UserInfo user); /// <summary>
    /// 删除一个指定的用户
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <returns>操作的返回信息</returns>
    ReturnInfo Delete(int userID); /// <summary>
    /// 删除一批用户
    /// </summary>
    /// <param name="userIDs">用户ID的集合</param>
    /// <returns>操作的返回信息</returns>
    ReturnInfo Delete(int[] userIDs); /// <summary>
    /// 取用户密码
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <returns>取得的用户密码</returns>
    string GetUserPassword(int userID); /// <summary>
    /// 修改用户密码
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="newPassword">新密码</param>
    /// <returns>操作的返回信息</returns>
    ReturnInfo ChangeUserPassword(int userID, string newPassword); /// <summary>
    /// 判断是否存在指定登录名的用户
    /// </summary>
    /// <param name="loginName">登录名</param>
    /// <returns>存在则返回true,否则返回false</returns>
    bool IsExistUser(string loginName); /// <summary>
    /// 检查用户的权限
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="rightID">权限ID</param>
    /// <returns>如果用户具有该权限则返回true,否则返回false</returns>
    bool CheckRight(int userID, int rightID); /// <summary>
    /// 检查用户的权限
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="rightIDs">一组权限</param>
    /// <returns>如果用户具有该组权限中的一个则返回true,否则返回false</returns>
    bool CheckRight(int userID, int[] rightIDs);
    }
    }
      

  30.   

    /////////////////////////////////Model--UserInfo////////////////////////
    using System;
    using System.Collections;namespace Thinkbank.TRMS.Model
    {
    /// <summary>
    /// 用户信息类。
    /// </summary>
    public class UserInfo
    {
    private int _userID;
    private string _loginName;
    private string _password;
    private string _userName;
    private string _userDesc;
    private int _userStatus;
    private string _email;
    private string _phoneNum;
    private string _mobileNum;
    private string _department;
    private ArrayList _roleIDs; /// <summary>
    /// 默认构造函数
    /// </summary>
    public UserInfo(){} /// <summary>
    /// 带有指定参数的构造函数
    /// </summary>
    public UserInfo(int userID, string loginName, string password, string userName, string userDesc,
    int userStatus, string email, string phoneNum, string mobileNum, string department, ArrayList roleIDs)
    {
    _userID = userID;
    _loginName = loginName;
    _password = password;
    _userName = userName;
    _userDesc = userDesc;
    _userStatus = userStatus;
    _email = email;
    _phoneNum = phoneNum;
    _mobileNum = mobileNum;
    _department = department;
    _roleIDs = roleIDs;
    } /// <summary>
    /// 用户ID
    /// </summary>
    public int UserID
    {
    set
    {
    _userID = value;
    }
    get
    {
    return _userID;
    }
    } /// <summary>
    /// 登录名
    /// </summary>
    public string LoginName
    {
    set
    {
    _loginName = value;
    }
    get
    {
    return _loginName;
    }
    } /// <summary>
    /// 口令
    /// </summary>
    public string Password
    {
    set
    {
    _password = value;
    }
    get
    {
    return _password;
    }
    } /// <summary>
    /// 用户姓名
    /// </summary>
    public string UserName
    {
    set
    {
    _userName = value;
    }
      

  31.   

    ///////////////////////////SqlDAL --UserDAL//////////////////////////
    using System;
    using System.Data;
    using System.Text;
    using System.Data.SqlClient;
    using System.Collections;
    using Thinkbank.TRMS.IDAL;
    using Thinkbank.TRMS.Common;
    using Thinkbank.Utility.DataAccess;
    using Thinkbank.TRMS.Model;namespace Thinkbank.TRMS.SqlDAL
    {
    /// <summary>
    /// UserDAL 的摘要说明。
    /// </summary>
    public class UserDAL : IUserDAL
    {
    #region 常量定义
    private const string SQL_SELECT_USER               = "SELECT UserID,LoginName,Password,UserName,UserDesc,UserStatus,Email,PhoneNum,MobileNum,Department FROM trms_users WHERE UserID = @UserID";
    private const string SQL_SELECT_USER_2             = "SELECT UserID,LoginName,Password,UserName,UserDesc,UserStatus,Email,PhoneNum,MobileNum,Department FROM trms_users WHERE (LoginName = @LoginName) AND (Password = @Password)";
    private const string SQL_SELECT_USER_ROLE          = "SELECT RoleID From trms_user_role WHERE UserID = @UserID";
    private const string SQL_SELECT_USERS              = "SELECT UserID,LoginName,Password,UserName,UserDesc,UserStatus,Email,PhoneNum,MobileNum,Department FROM trms_users";
    private const string SQL_SELECT_USERS_2            = "SELECT UserID,LoginName,Password,UserName,UserDesc,UserStatus,Email,PhoneNum,MobileNum,Department FROM trms_users WHERE UserID IN(SELECT UserID From trms_user_role WHERE RoleID=@RoleID)"; private const string SQL_INSERT_USER               = "INSERT INTO trms_users(LoginName,Password,UserName,UserDesc,UserStatus,Email,PhoneNum,MobileNum,Department) VALUES(@LoginName,@Password,@UserName,@UserDesc,@UserStatus,@Email,@PhoneNum,@MobileNum,@Department)";
    private const string SQL_UPDATE_USER               = "UPDATE trms_users SET UserName=@UserName,UserDesc=@UserDesc,UserStatus=@UserStatus,Email=@Email,PhoneNum=@PhoneNum,MobileNum=@MobileNum,Department=@Department WHERE UserID=@UserID";
    private const string SQL_DELETE_USER               = "DELETE FROM trms_users WHERE UserID=@UserID";
    private const string SQL_DELETE_USER_2             = "DELETE FROM trms_users";

    private const string SQL_INSERT_USER_ROLE          = "INSERT INTO trms_user_role VALUES";
    private const string SQL_DELETE_USER_ROLE          = "DELETE FROM trms_user_role WHERE UserID=@UserID";
    private const string SQL_DELETE_USER_ROLE_2        = "DELETE FROM trms_user_role";

    private const string SQL_UPDATE_PASSWORD           = "UPDATE trms_users SET Password=@Password WHERE UserID=@UserID";
    private const string SQL_IS_EXIST_USER             = "SELECT Count(*) FROM trms_users Where LoginName=@LoginName";
    private const string SQL_IS_EXIST_USER_2           = "SELECT Count(*) FROM trms_user_role Where RoleID=@RoleID";
    private const string SQL_CHECK_RIGHT               = "SELECT Count(*) FROM trms_user_role A,trms_role_right B WHERE (A.RoleID = B.RoleID) AND (A.UserID = @UserID) AND (B.RightID = @RightID)";
    private const string SQL_CHECK_RIGHT_2             = "SELECT Count(*) FROM trms_user_role A,trms_role_right B WHERE (A.RoleID = B.RoleID) AND (A.UserID = @UserID)"; private const string PARM_USER_ID                  = "@UserID";
    private const string PARM_LOGIN_NAME               = "@LoginName";
    private const string PARM_PASSWORD                 = "@Password";
    private const string PARM_USER_NAME                = "@UserName";
    private const string PARM_USER_DESC                = "@UserDesc";
    private const string PARM_USER_STATUS              = "@UserStatus";
    private const string PARM_EMAIL                    = "@Email";
    private const string PARM_PHONE_NUM                = "@PhoneNum";
    private const string PARM_MOBILE_NUM               = "@MobileNum";
    private const string PARM_DEPARTMENT               = "@Department";
    private const string PARM_ROLE_ID                  = "@RoleID";
    private const string PARM_RIGHT_ID                 = "@RightID";
    #endregion

    #region 内部成员
    /// <summary>
    /// 取得连接对象
    /// </summary>
    /// <param name="connectionString">连接字符串</param>
    /// <returns>连接对象</returns>
    private SqlConnection GetConnection(string connectionString)
    {
    SqlConnection connection = new SqlConnection(connectionString);
    connection.Open(); return connection;
    }
    #endregion #region IUserDAL 成员 /// <summary>
    /// 根据用户ID取用户信息
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <returns>取得的用户信息</returns>
    public Thinkbank.TRMS.Model.UserInfo GetUser(int userID)
    {
    UserInfo user = null;
    ArrayList roleIDs = null; SqlParameter parm = new SqlParameter(PARM_USER_ID,SqlDbType.Int);
    parm.Value = userID; //取得该用户的角色信息
    using(SqlDataReader rdr = SqlHelper.ExecuteReader(TRMSConfiguration.ConnectionString, CommandType.Text, SQL_SELECT_USER_ROLE, parm))
    {
    roleIDs = new ArrayList();
    while(rdr.Read())
    {
    roleIDs.Add(rdr.GetInt32(0));
    }
    } //取得该用户的信息
    using(SqlDataReader rdr2 = SqlHelper.ExecuteReader(TRMSConfiguration.ConnectionString, CommandType.Text, SQL_SELECT_USER, parm))
    {
    if(rdr2.Read())
    {
    user = new UserInfo(rdr2.GetInt32(0),rdr2.GetString(1),rdr2.GetString(2),rdr2.GetString(3),rdr2.GetString(4),rdr2.GetInt32(5),rdr2.GetString(6),rdr2.GetString(7),rdr2.GetString(8),rdr2.GetString(9),roleIDs);
    }
      

  32.   

    else
    {
    user = null;
    }
    }
     
    return user;
    } /// <summary>
    /// 根据用户的登录名和口令取用户信息
    /// </summary>
    /// <param name="loginName">用户的登录名</param>
    /// <param name="password">用户的口令</param>
    /// <returns>取得的用户信息</returns>
    public Thinkbank.TRMS.Model.UserInfo GetUser(string loginName, string password)
    {
    UserInfo user = null; SqlParameter[] parms = new SqlParameter[2];
    parms[0] = new SqlParameter(PARM_LOGIN_NAME,SqlDbType.VarChar,16);
    parms[0].Value = loginName;
    parms[1] = new SqlParameter(PARM_PASSWORD,SqlDbType.VarChar,64);
    parms[1].Value = password; //取得该用户的信息
    using(SqlDataReader rdr2 = SqlHelper.ExecuteReader(TRMSConfiguration.ConnectionString, CommandType.Text, SQL_SELECT_USER_2, parms))
    {
    if(rdr2.Read())
    {
    user = new UserInfo(rdr2.GetInt32(0),rdr2.GetString(1),rdr2.GetString(2),rdr2.GetString(3),rdr2.GetString(4),rdr2.GetInt32(5),rdr2.GetString(6),rdr2.GetString(7),rdr2.GetString(8),rdr2.GetString(9),null);
    }
    else
    {
    user = null;
    }
    }
     
    return user;
    } /// <summary>
    /// 取所有用户
    /// </summary>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetAllUsers(string sortExpress)
    {
    StringBuilder strSQL = new StringBuilder();
    strSQL.Append(SQL_SELECT_USERS);
    strSQL.Append(" ORDER BY ").Append(sortExpress); DataSet ds = new DataSet();
    SqlHelper.FillDataset(TRMSConfiguration.ConnectionString, CommandType.Text, strSQL.ToString(),ds,new string[]{"trms_users"},null);
    return ds;
    } /// <summary>
    /// 根据登录名取用户数据集
    /// </summary>
    /// <param name="loginName">登录名</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetUsersByLoginName(string loginName, string sortExpress)
    {
    StringBuilder strSQL = new StringBuilder();
    strSQL.Append(SQL_SELECT_USERS);
    strSQL.Append(" WHERE LoginName LIKE '%" + loginName + "%'");
    strSQL.Append(" ORDER BY ").Append(sortExpress); DataSet ds = new DataSet();
    SqlHelper.FillDataset(TRMSConfiguration.ConnectionString, CommandType.Text, strSQL.ToString(),ds,new string[]{"trms_users"},null);
    return ds;
    }

    /// <summary>
    /// 根据用户名取用户数据集
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetUsersByUserName(string userName, string sortExpress)
    {
    StringBuilder strSQL = new StringBuilder();
    strSQL.Append(SQL_SELECT_USERS);
    strSQL.Append(" WHERE UserName LIKE '%" + userName + "%'");
    strSQL.Append(" ORDER BY ").Append(sortExpress); DataSet ds = new DataSet();
    SqlHelper.FillDataset(TRMSConfiguration.ConnectionString, CommandType.Text, strSQL.ToString(),ds,new string[]{"trms_users"},null);
    return ds;
    }

    /// <summary>
    /// 根据角色ID取用户数据集
    /// </summary>
    /// <param name="roleID">角色ID</param>
    /// <param name="sortExpress">排序表达式</param>
    /// <returns>取得的用户数据集</returns>
    public System.Data.DataSet GetUsersByRoleID(int roleID, string sortExpress)
      

  33.   

    {
    StringBuilder strSQL = new StringBuilder(); strSQL.Append(SQL_SELECT_USERS_2).Append(" ORDER BY ").Append(sortExpress);
    SqlParameter parm = new SqlParameter(PARM_ROLE_ID, roleID); DataSet ds = new DataSet();
    SqlHelper.FillDataset(TRMSConfiguration.ConnectionString, CommandType.Text, strSQL.ToString(),ds,new string[]{"trms_users"},parm);
    return ds;
    } /// <summary>
    /// 添加一个新的用户
    /// </summary>
    /// <param name="user">用户信息</param>
    /// <returns>操作的返回信息</returns>
    public ReturnInfo Insert(Thinkbank.TRMS.Model.UserInfo user)
    {
    StringBuilder strSQL = new StringBuilder();

    int parmCount = 9 + user.RoleIDs.Count;
    SqlParameter[] parms = new SqlParameter[parmCount]; //准备添加用户的Sql语句和参数
    strSQL.Append(SQL_INSERT_USER).Append("; "); parms[0] = new SqlParameter(PARM_LOGIN_NAME,SqlDbType.VarChar,16);
    parms[0].Value = user.LoginName;
    parms[1] = new SqlParameter(PARM_PASSWORD,SqlDbType.VarChar,64);
    parms[1].Value = user.Password;
    parms[2] = new SqlParameter(PARM_USER_NAME,SqlDbType.VarChar,40);
    parms[2].Value = user.UserName;
    parms[3] = new SqlParameter(PARM_USER_DESC,SqlDbType.VarChar,200);
    parms[3].Value = user.UserDesc;
    parms[4] = new SqlParameter(PARM_USER_STATUS,SqlDbType.Int);
    parms[4].Value = user.UserStatus;
    parms[5] = new SqlParameter(PARM_EMAIL,SqlDbType.VarChar,80);
    parms[5].Value = user.Email;
    parms[6] = new SqlParameter(PARM_PHONE_NUM,SqlDbType.VarChar,20);
    parms[6].Value = user.PhoneNum;
    parms[7] = new SqlParameter(PARM_MOBILE_NUM,SqlDbType.VarChar,20);
    parms[7].Value = user.MobileNum;
    parms[8] = new SqlParameter(PARM_DEPARTMENT,SqlDbType.VarChar,40);
    parms[8].Value = user.Department; //准备添加用户角色的Sql语句和参数
    int num;
    strSQL.Append("DECLARE @NewID int; SELECT @NewID = @@IDENTITY; ");
    for(int i=0; i<user.RoleIDs.Count; i++)
    {
    num = i+1;
    strSQL.Append(SQL_INSERT_USER_ROLE).Append("(@NewID, @RoleID" + num.ToString() + "); ");
    parms[9+i] = new SqlParameter(PARM_ROLE_ID + num.ToString(), SqlDbType.Int);
    parms[9+i].Value = user.RoleIDs[i];
    }

    //执行命令成功则返回true,失败则返回false
    SqlConnection connection = null;
    try
    {
    connection = GetConnection(TRMSConfiguration.ConnectionString);
    using(SqlTransaction trans = connection.BeginTransaction())
    {
    try
    {
    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSQL.ToString(), parms);
    trans.Commit();
    }
    catch(Exception ex)
    {
    trans.Rollback();
    throw ex;
    }
    }
    }
    catch
    {
    return new ReturnInfo(false,"系统操作数据库失败!");
    }
    finally
    {
    if(connection != null)
    connection.Dispose();
    } return new ReturnInfo(true, null);
    } /// <summary>
    /// 修改一个用户的信息
    /// </summary>
    /// <param name="user">新设的用户信息</param>
    /// <returns>操作的返回信息</returns>
    public ReturnInfo Update(Thinkbank.TRMS.Model.UserInfo user)
    {
    StringBuilder strSQL = new StringBuilder();

    int parmCount = 8 + user.RoleIDs.Count;
    SqlParameter[] parms = new SqlParameter[parmCount];
      

  34.   


    //准备更新用户和删除用户角色的Sql语句和参数
    strSQL.Append(SQL_UPDATE_USER).Append("; ");
    strSQL.Append(SQL_DELETE_USER_ROLE).Append("; "); parms[0] = new SqlParameter(PARM_USER_NAME,SqlDbType.VarChar,40);
    parms[0].Value = user.UserName;
    parms[1] = new SqlParameter(PARM_USER_DESC,SqlDbType.VarChar,200);
    parms[1].Value = user.UserDesc;
    parms[2] = new SqlParameter(PARM_USER_STATUS,SqlDbType.Int);
    parms[2].Value = user.UserStatus;
    parms[3] = new SqlParameter(PARM_EMAIL,SqlDbType.VarChar,80);
    parms[3].Value = user.Email;
    parms[4] = new SqlParameter(PARM_PHONE_NUM,SqlDbType.VarChar,20);
    parms[4].Value = user.PhoneNum;
    parms[5] = new SqlParameter(PARM_MOBILE_NUM,SqlDbType.VarChar,20);
    parms[5].Value = user.MobileNum;
    parms[6] = new SqlParameter(PARM_DEPARTMENT,SqlDbType.VarChar,40);
    parms[6].Value = user.Department;
    parms[7] = new SqlParameter(PARM_USER_ID,SqlDbType.Int);
    parms[7].Value = user.UserID; //准备添加用户角色的Sql语句和参数
    int num;
    for(int i=0; i<user.RoleIDs.Count; i++)
    {
    num = i+1;
    strSQL.Append(SQL_INSERT_USER_ROLE).Append("(@UserID, @RoleID" + num.ToString() + "); ");
    parms[8+i] = new SqlParameter(PARM_ROLE_ID + num.ToString(), SqlDbType.Int);
    parms[8+i].Value = user.RoleIDs[i];
    }

    //执行命令成功则返回true,失败则返回false
    SqlConnection connection = null;
    try
    {
    connection = GetConnection(TRMSConfiguration.ConnectionString);
    using(SqlTransaction trans = connection.BeginTransaction())
    {
    try
    {
    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSQL.ToString(), parms);
    trans.Commit();
    }
    catch(Exception ex)
    {
    trans.Rollback();
    throw ex;
    }
    }
    }
    catch
    {
    return new ReturnInfo(false,"系统操作数据库失败!");
    }
    finally
    {
    if(connection != null)
    connection.Dispose();
    } return new ReturnInfo(true,null);
    } /// <summary>
    /// 删除一个指定的用户
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <returns>操作的返回信息</returns>
    public ReturnInfo Delete(int userID)
    {
    StringBuilder strSQL = new StringBuilder(); strSQL.Append(SQL_DELETE_USER_ROLE).Append("; ");
    strSQL.Append(SQL_DELETE_USER).Append("; "); SqlParameter parm = new SqlParameter(PARM_USER_ID,SqlDbType.Int);
    parm.Value = userID;

    //执行命令成功则返回true,失败则返回false
    SqlConnection connection = null;
    try
    {
    connection = GetConnection(TRMSConfiguration.ConnectionString);
    using(SqlTransaction trans = connection.BeginTransaction())
    {
    try
    {
    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSQL.ToString(), parm);
    trans.Commit();
    }
    catch(Exception ex)
    {
    trans.Rollback();
    throw ex;
    }
    }
    }
    catch
    {
    return new ReturnInfo(false,"系统操作数据库失败");
      

  35.   

    }
    finally
    {
    if(connection != null)
    connection.Dispose();
    } return new ReturnInfo(true,null);
    } /// <summary>
    /// 删除一批用户
    /// </summary>
    /// <param name="userIDs">用户ID的集合</param>
    /// <returns>操作的返回信息</returns>
    public ReturnInfo Delete(int[] userIDs)
    {
    StringBuilder strSQL = new StringBuilder(); int len = userIDs.Length;
    string strUserIDs = string.Empty;
    for(int i=0; i<len; i++)
    {
    if(i != 0)
    strUserIDs += ",";
    strUserIDs += userIDs[i].ToString();
    } strSQL.Append(SQL_DELETE_USER_ROLE_2).Append(" WHERE UserID IN(" + strUserIDs + "); ");
    strSQL.Append(SQL_DELETE_USER_2).Append(" WHERE UserID IN(" + strUserIDs + "); ");
    //执行命令成功则返回true,失败则返回false
    SqlConnection connection = null;
    try
    {
    connection = GetConnection(TRMSConfiguration.ConnectionString);
    using(SqlTransaction trans = connection.BeginTransaction())
    {
    try
    {
    SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSQL.ToString(), null);
    trans.Commit();
    }
    catch(Exception ex)
    {
    trans.Rollback();
    throw ex;
    }
    }
    }
    catch
    {
    return new ReturnInfo(false,"系统操作数据库失败!");
    }
    finally
    {
    if(connection != null)
    connection.Dispose();
    } return new ReturnInfo(true,null);
    } /// <summary>
    /// 取用户密码
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <returns>取得的用户密码</returns>
    public string GetUserPassword(int userID)
    {
    string pwd = null; SqlParameter parm = new SqlParameter(PARM_USER_ID,SqlDbType.Int);
    parm.Value = userID; //取得该用户的信息
    using(SqlDataReader rdr = SqlHelper.ExecuteReader(TRMSConfiguration.ConnectionString, CommandType.Text, SQL_SELECT_USER, parm))
    {
    if(rdr.Read())
    {
    pwd = rdr.GetString(2).ToString();
    }
    else
    {
    pwd = null;
    }
    }
     
    return pwd;
    } /// <summary>
    /// 修改用户密码
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="newPassword">新密码</param>
    /// <returns>操作的返回信息</returns>
    public ReturnInfo ChangeUserPassword(int userID, string newPassword)
    {
      

  36.   

    StringBuilder strSQL = new StringBuilder(); //准备更新用户和删除用户角色的Sql语句和参数
    strSQL.Append(SQL_UPDATE_PASSWORD);

    SqlParameter[] parms = new SqlParameter[2];
    parms[0] = new SqlParameter(PARM_PASSWORD,SqlDbType.VarChar,64);
    parms[0].Value = newPassword;
    parms[1] = new SqlParameter(PARM_USER_ID,SqlDbType.Int);
    parms[1].Value = userID;

    //执行命令成功则返回true,失败则返回false
    SqlConnection connection = null;
    try
    {
    connection = GetConnection(TRMSConfiguration.ConnectionString);
    SqlHelper.ExecuteNonQuery(connection, CommandType.Text, strSQL.ToString(), parms);
    }
    catch
    {
    return new ReturnInfo(false, "系统操作数据库失败!");
    }
    finally
    {
    if(connection != null)
    connection.Dispose();
    } return new ReturnInfo(true,null);
    } /// <summary>
    /// 判断是否存在指定登录名的用户
    /// </summary>
    /// <param name="loginName">登录名</param>
    /// <returns>存在则返回true,否则返回false</returns>
    public bool IsExistUser(string loginName)
    {
    StringBuilder strSQL = new StringBuilder(); strSQL.Append(SQL_IS_EXIST_USER); SqlParameter parm = new SqlParameter(PARM_LOGIN_NAME, SqlDbType.VarChar, 16);
    parm.Value = loginName; object obj = SqlHelper.ExecuteScalar(TRMSConfiguration.ConnectionString,CommandType.Text,strSQL.ToString(),parm);
    int count = Convert.ToInt32(obj); if(count>0)
    return true;
    else
    return false;
    } /// <summary>
    /// 检查用户的权限
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="rightID">权限ID</param>
    /// <returns>如果用户具有该权限则返回true,否则返回false</returns>
    public bool CheckRight(int userID, int rightID)
    {
    StringBuilder strSQL = new StringBuilder(); strSQL.Append(SQL_CHECK_RIGHT); SqlParameter[] parms = new SqlParameter[2];
    parms[0] = new SqlParameter(PARM_USER_ID,SqlDbType.Int);
    parms[0].Value = userID;
    parms[1] = new SqlParameter(PARM_RIGHT_ID,SqlDbType.Int);
    parms[1].Value = rightID;

    object obj = SqlHelper.ExecuteScalar(TRMSConfiguration.ConnectionString, CommandType.Text, strSQL.ToString(), parms);
    int RecordCount = Convert.ToInt32(obj); if(RecordCount > 0)
    return true;
    else
    return false;

    } /// <summary>
    /// 检查用户的权限
    /// </summary>
    /// <param name="userID">用户ID</param>
    /// <param name="rightIDs">一组权限</param>
    /// <returns>如果用户具有该组权限中的一个则返回true,否则返回false</returns>
    public bool CheckRight(int userID, int[] rightIDs)
    {
    StringBuilder strSQL = new StringBuilder(); strSQL.Append(SQL_CHECK_RIGHT_2); SqlParameter parm = new SqlParameter(PARM_USER_ID,SqlDbType.Int);
    parm.Value = userID; int len = rightIDs.Length;
    string strRightIDs = string.Empty;
    for(int i=0; i<len; i++)
      

  37.   

    {
    if(i != 0)
    strRightIDs += ",";
    strRightIDs += rightIDs[i].ToString();
    }
    strSQL.Append(" AND (RightID IN(" + strRightIDs + "))"); object obj = SqlHelper.ExecuteScalar(TRMSConfiguration.ConnectionString, CommandType.Text, strSQL.ToString(), parm);
    int RecordCount = Convert.ToInt32(obj); if(RecordCount > 0)
    return true;
    else
    return false;
    } #endregion
    }
    }
      

  38.   

    ////////////////////////////////Common--TRMSConfiguration//////////////////////////////
    using System;
    using System.Configuration;
    using Thinkbank.Utility.CryptTo;namespace Thinkbank.TRMS.Common
    {
    /// <summary>
    /// TBOAConfiguration 的摘要说明。
    /// </summary>
    public class TRMSConfiguration
    {
    public TRMSConfiguration()
    {
    } /// <summary>
    /// 连接字符串
    /// </summary>
    public static string ConnectionString = ConfigurationSettings.AppSettings["TRMS.Core.ConnectionString"];
    public static string ConnectionString1 = ConfigurationSettings.AppSettings["TRS.Core.ConnectionString"]; /// <summary>
    /// 数据访问层程序集
    /// </summary>
    public static string DALAssembly = ConfigurationSettings.AppSettings["TRMS.Core.DALAssembly"]; /// <summary>
    /// 数据访问层命名空间
    /// </summary>
    public static string DALNameSpace = ConfigurationSettings.AppSettings["TRMS.Core.DALNameSpace"]; /// <summary>
    /// 系统Session 和 Cookie的前缀
    /// </summary>
    public static string Prefix = ConfigurationSettings.AppSettings["TRMS.Core.Prefix"]; /// <summary>
    /// 系统日志的源
    /// </summary>
    public static string LogSource = ConfigurationSettings.AppSettings["TRMS.Core.LogSource"]; /// <summary>
    /// 加密使用的Key
    /// </summary>
    public static string Secret = ConfigurationSettings.AppSettings["TRMS.Core.Secret"]; /// <summary>
    /// 3DES加密使用的Key
    /// </summary>
    public static string TripleDESKey = CryptTo.GenerateKey(Secret); /// <summary>
    /// 用来保存用户Cookie的名称
    /// </summary>
    public static string LoginCookieName = ConfigurationSettings.AppSettings["TRMS.Core.LoginCookieName"]; /// <summary>
    /// 登录页面的地址
    /// </summary>
    public static string LoginPageURL = ConfigurationSettings.AppSettings["TRMS.Core.LoginPage"]; /// <summary>
    /// 页面缓存时间(单位:秒)
    /// </summary>
    public static string PageExpires = ConfigurationSettings.AppSettings["TRMS.Core.PageExpires"];
    }
    }
      

  39.   

        关于让WPF软件界面支持全球化和本地化
                                              周银辉
    有朋友询问如何让WPF应用能够提供多语言支持(中文,英文,日文.....),我的建议是:(1)抛弃WinForm时代的资源存储方式 (2)利用WPF的动态资源特性.
    下面简单介绍一下并打造一个简单的DEMO:1,语言资源文件怎样存储
    我们知道以前(WPF以前)我们将界面上的各国语言分别存储在.resx类型的文件中,然后利用ResourceManager来得到相应资源并根据当地的CultureInfo来给界面文本赋值.这是可行的.但在WPF中存在的一个问题是:我们必须为每个控件在后台代码中来Code这些逻辑,因为XAML是找不到.resx类型中的资源的.但WPF中绝大多数界面元素都是在XAML中定义的这是一件很麻烦的事情.所以我们应该抛弃这样的做法.
    WPF中的资源继承了以前的多种存储形式,但可以在XAML和C#(或其他)中通行的有两中,一个是Content,一个是Resource,前者是"内容",既是松散的资源链接,后者是被编译并嵌入的资源,注意,你在设置资源文件属性的时候会发现还有一个很让人混淆的Embedded Resource,这也是内嵌的资源,但其被压缩为二进制形式,既和以前WinForm的内嵌资源相同,Resource和Embedded Resource在编码上的区别是前者可以通过Uri找到,这是XAML需要的方式,后者可以通过Stream找到,这可以通过编写c#代码来查找资源.
    所以,在这里看来Content是我们保存语言资源的良好方式,由于其是松散的资源链接,所以为应用程序添加新的语言包时就可以不重新编译了,只需将对象的语言文件拷贝到指定的文件夹即可.2,界面元素如何链接到语言文本
    这是StaticResource 和 DynamicResource要做的事情,比如:
    <Button Content="{DynamicResource OK}"/>至于是使用StaticResource 还是DynamicResource,这取决于你是否要在运行时动态切换,如果仅仅是软件启动的时候才切换语言StaticResource就可以了.3,OK 实战一下:
    3.1 新建项目,并在项目中新建一个Lang文件夹用于保存我们的语言文件3.2 在Lang文件夹中,新建"ResourceDictionary(WPF)",命名为"DefaultLanguage.xaml",并将其BuildAction设置为Page,这是一个默认语言资源文件,其将被编译(而不是松散链接,这样可以确保在软件语言包丢失或没有某国家或地区的对应语言包时可以有一种默认的界面语言):我们这里采用英文作为默认语言:
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib">  <sys:String x:Key="OK">
        OK
      </sys:String>  <sys:String x:Key="Cancel">
        Cancel
      </sys:String>
      
    </ResourceDictionary>然后,我们添加另一国语言,比如中文,在Lang文件夹中,新建"ResourceDictionary(WPF)",命名为"zh-CN.xaml",并将其BuildAction设置为Content,将CopyToOutputDirctory设置为"if new",这样,我们的中文语言文件为将被拷贝到应用程序目录下的Lang目录下,其他的非默认语言的语言文件都应该采取这种方式.
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:sys="clr-namespace:System;assembly=mscorlib">  <sys:String x:Key="OK">
        确定
      </sys:String>  <sys:String x:Key="Cancel">
        取消
      </sys:String></ResourceDictionary>
    3.3 为了让编码人员在设计器(比如VS,Blend)中所见即所得地看到界面文本,我们应该将默认语言资源加入到应用程序的资源列表中:
    <Application x:Class="LangDemo.App"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml"
        >
      
      <Application.Resources>
        <ResourceDictionary>
          <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="lang\DefaultLanguage.xaml"/>
          </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
      </Application.Resources>
      
    </Application>
    这样我们就可以在设计器中使用这些资源了:我们可以看到由于我们加载的默认语言是英文,设计器中我们的窗口界面上显示的是对应的英文文本.3.4 软件启动时加载对应的本地化的语言:public partial class App : Application
        {        protected override void OnStartup(StartupEventArgs e)
            {
                base.OnStartup(e);
                LoadLanguage();
            }        private void LoadLanguage()
            {
                CultureInfo currentCultureInfo = CultureInfo.CurrentCulture;            ResourceDictionary langRd = null;            try
                {
                    langRd =
                        Application.LoadComponent(
                                 new Uri(@"Lang\" + currentCultureInfo.Name + ".xaml", UriKind.Relative))
                        as ResourceDictionary;
                }
                catch
                {
                }            if (langRd != null)
                {
                    if (this.Resources.MergedDictionaries.Count > 0)
                    {
                        this.Resources.MergedDictionaries.Clear();
                    }
                    this.Resources.MergedDictionaries.Add(langRd);
                }           
            }
        }
      

  40.   

    ///////////////////////calendar--NcCalendar.cs/////////////////////
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ComponentModel;
    using System.Globalization;
    using System.Collections.ObjectModel;namespace TestMainWindow
    {
        public class NcCalendar : ObservableCollection<NcCalendarWeek>, INotifyPropertyChanged
        {
            #region 字段定义
            private int mYear;
            private int mMonth;
            private NcCalendarDay mCurrent = NcCalendarDay.Empty;        #endregion
            #region 事件定义
            public event EventHandler SelectedChanged;
            public event EventHandler CurrentChanged;
            #endregion
            #region 构造函数
            public NcCalendar() : this(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day) { }
            public NcCalendar(DateTime date) : this(date.Year, date.Month, date.Day) { }
            public NcCalendar(int year, int month) : this(year, month, 1) { }
            public NcCalendar(int year, int month, int day) { BuildCalendar(year, month, day); }
            #endregion
            #region 属性定义
            public int Year
            {
                get { return mYear; }
                set
                {
                    int day = (mCurrent != null) ? day = mCurrent.Day : 1;
                    if (BuildCalendar(value, mMonth, day)) OnPropertyChanged(new PropertyChangedEventArgs("Year"));
                }
            }
            public int Month
            {
                get { return mMonth; }
                set
                {
                    int day = (mCurrent != null) ? day = mCurrent.Day : 1;
                    if (BuildCalendar(mYear, value, day)) OnPropertyChanged(new PropertyChangedEventArgs("Month"));
                }
            }
            public int Day
            {
                get { return mCurrent.Day; }
                set { if (BuildCalendar(mYear, mMonth, value)) OnPropertyChanged(new PropertyChangedEventArgs("Day")); }
            }        public NcCalendarDay Current
            {
                get { return mCurrent; }
                set
                {
                    if (value == null || value == NcCalendarDay.Empty || value == mCurrent || value.Value.Date == mCurrent.Value.Date) return;
                    bool setOK = false;
                    foreach (NcCalendarWeek week in this)
                    {
                        foreach (NcCalendarDay one in week)
                        {
                            if (one.IsEmpty) continue;
                            if (one.Value.Date == value.Value.Date)
                            {
                                mCurrent = one;
                                setOK = true;
                                OnPropertyChanged(new PropertyChangedEventArgs("Day"));
                                this.OnSelectedChanged(new EventArgs());
                                break;
                            }
                        }
                        if (setOK) break;
                    }
                }
            }
            #endregion        #region 方法定义
            public void SetValue(DateTime date) { BuildCalendar(date); }
            /// <summary>
            /// 向后一年
            /// </summary>
            public void NextYear() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddYears(1));
                    return;
                }            int newYear = mYear + 1;
                int newMonth = mMonth;
                int newDay = (mCurrent==null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime maxDate = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime.Date;
                if (newYear > maxDate.Year) return;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear) newMonth = maxMonthOfYear;
                int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay); 
            }
            /// <summary>
            /// 向前一年
            /// </summary>
            public void PreviousYear() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddYears(-1));
                    return;
                }            int newYear = mYear - 1;
                int newMonth = mMonth;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime minDate = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime.Date;
                if (newYear < minDate.Year) return;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear) newMonth = maxMonthOfYear;
                int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);
            }
            /// <summary>
            /// 向后一个月
            /// </summary>
            public void NextMonth() 
            {
                if (mCurrent.Year ==mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddMonths(1));
                    return;
                }
                int newYear = mYear;
                int newMonth = mMonth + 1;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear)
                {
                    newYear++;
                    DateTime maxDate = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime.Date;
                    if (newYear > maxDate.Year)
                        return;
                    newMonth = 1;
                }            int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);
            }
            /// <summary>
            /// 向前一个月
            /// </summary>
            public void PreviousMonth() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddMonths(-1));
                    return;
                }            int newYear = mYear;
                int newMonth = mMonth - 1;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime minDate = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime.Date;
                if (newMonth < 1)
                {
                    newYear = newYear - 1;
                    if (newYear < minDate.Year) return;
                    newMonth = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                }            int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);        }
     
      

  41.   

    ///////////////////////calendar--NcCalendar.cs/////////////////////
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ComponentModel;
    using System.Globalization;
    using System.Collections.ObjectModel;namespace TestMainWindow
    {
        public class NcCalendar : ObservableCollection<NcCalendarWeek>, INotifyPropertyChanged
        {
            #region 字段定义
            private int mYear;
            private int mMonth;
            private NcCalendarDay mCurrent = NcCalendarDay.Empty;        #endregion
            #region 事件定义
            public event EventHandler SelectedChanged;
            public event EventHandler CurrentChanged;
            #endregion
            #region 构造函数
            public NcCalendar() : this(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day) { }
            public NcCalendar(DateTime date) : this(date.Year, date.Month, date.Day) { }
            public NcCalendar(int year, int month) : this(year, month, 1) { }
            public NcCalendar(int year, int month, int day) { BuildCalendar(year, month, day); }
            #endregion
            #region 属性定义
            public int Year
            {
                get { return mYear; }
                set
                {
                    int day = (mCurrent != null) ? day = mCurrent.Day : 1;
                    if (BuildCalendar(value, mMonth, day)) OnPropertyChanged(new PropertyChangedEventArgs("Year"));
                }
            }
            public int Month
            {
                get { return mMonth; }
                set
                {
                    int day = (mCurrent != null) ? day = mCurrent.Day : 1;
                    if (BuildCalendar(mYear, value, day)) OnPropertyChanged(new PropertyChangedEventArgs("Month"));
                }
            }
            public int Day
            {
                get { return mCurrent.Day; }
                set { if (BuildCalendar(mYear, mMonth, value)) OnPropertyChanged(new PropertyChangedEventArgs("Day")); }
            }        public NcCalendarDay Current
            {
                get { return mCurrent; }
                set
                {
                    if (value == null || value == NcCalendarDay.Empty || value == mCurrent || value.Value.Date == mCurrent.Value.Date) return;
                    bool setOK = false;
                    foreach (NcCalendarWeek week in this)
                    {
                        foreach (NcCalendarDay one in week)
                        {
                            if (one.IsEmpty) continue;
                            if (one.Value.Date == value.Value.Date)
                            {
                                mCurrent = one;
                                setOK = true;
                                OnPropertyChanged(new PropertyChangedEventArgs("Day"));
                                this.OnSelectedChanged(new EventArgs());
                                break;
                            }
                        }
                        if (setOK) break;
                    }
                }
            }
            #endregion        #region 方法定义
            public void SetValue(DateTime date) { BuildCalendar(date); }
            /// <summary>
            /// 向后一年
            /// </summary>
            public void NextYear() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddYears(1));
                    return;
                }            int newYear = mYear + 1;
                int newMonth = mMonth;
                int newDay = (mCurrent==null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime maxDate = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime.Date;
                if (newYear > maxDate.Year) return;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear) newMonth = maxMonthOfYear;
                int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay); 
            }
            /// <summary>
            /// 向前一年
            /// </summary>
            public void PreviousYear() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddYears(-1));
                    return;
                }            int newYear = mYear - 1;
                int newMonth = mMonth;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime minDate = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime.Date;
                if (newYear < minDate.Year) return;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear) newMonth = maxMonthOfYear;
                int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);
            }
            /// <summary>
            /// 向后一个月
            /// </summary>
            public void NextMonth() 
            {
                if (mCurrent.Year ==mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddMonths(1));
                    return;
                }
                int newYear = mYear;
                int newMonth = mMonth + 1;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear)
                {
                    newYear++;
                    DateTime maxDate = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime.Date;
                    if (newYear > maxDate.Year)
                        return;
                    newMonth = 1;
                }            int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);
            }
            /// <summary>
            /// 向前一个月
            /// </summary>
            public void PreviousMonth() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddMonths(-1));
                    return;
                }            int newYear = mYear;
                int newMonth = mMonth - 1;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime minDate = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime.Date;
                if (newMonth < 1)
                {
                    newYear = newYear - 1;
                    if (newYear < minDate.Year) return;
                    newMonth = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                }            int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);        }
     
      

  42.   

    //////////////////////////NcCalendarControl.cs//////////////////////////////
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;namespace TestMainWindow
    {
        public class NcCalendarControl : Control
        {
            #region 构造函数
            static NcCalendarControl()
            {
                DefaultStyleKeyProperty.OverrideMetadata(typeof(NcCalendarControl), new FrameworkPropertyMetadata(typeof(NcCalendarControl)));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(PreviousYear, OnPreviousYear));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(PreviousMonth, OnPreviousMonth));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(NextYear, OnNextYear));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(NextMonth, OnNextMonth));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(Today, OnToday));
            }
            public NcCalendarControl() 
            {
                this.SetValue(ItemsProperty, new NcCalendar(DateTime.Now));
                Items.SelectedChanged += new EventHandler(Items_SelectedChanged);
            }
            #endregion        #region 属性定义
            /// <summary>
            /// 本月的"周"集合 
            /// </summary>
            public NcCalendar Items
            {
                get { return (NcCalendar)GetValue(ItemsProperty); }
                set { SetValue(ItemsProperty, value); }
            }
            public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(NcCalendar), typeof(NcCalendarControl), new UIPropertyMetadata(new NcCalendar(DateTime.Now)));        #region Changeable
            /// <summary>
            /// 是否能够通过按钮改变年、月。
            /// </summary>
            public static readonly DependencyProperty ChangeableProperty = DependencyProperty.Register("Changeable", typeof(bool), typeof(NcCalendarControl), new FrameworkPropertyMetadata(true));
            /// <summary>
            /// 获取或设置Changeable
            /// </summary>
            public bool Changeable
            {
                get { return (bool)base.GetValue(NcCalendarControl.ChangeableProperty); }
                set { base.SetValue(NcCalendarControl.ChangeableProperty, value); }
            }
            #endregion        #region ShowHeader
            /// <summary>
            /// 是否显示月历头。
            /// </summary>
            public static readonly DependencyProperty ShowHeaderProperty = DependencyProperty.Register("ShowHeader", typeof(bool), typeof(NcCalendarControl), new FrameworkPropertyMetadata(true));
            /// <summary>
            /// 获取或设置ShowHeader
            /// </summary>
            public bool ShowHeader
            {
                get { return (bool)base.GetValue(NcCalendarControl.ShowHeaderProperty); }
                set { base.SetValue(NcCalendarControl.ShowHeaderProperty, value); }
            }
            #endregion        #region ShowWeekTitle
            /// <summary>
            /// 是否显示周标签。
            /// </summary>
            public static readonly DependencyProperty ShowWeekTitleProperty = DependencyProperty.Register("ShowWeekTitle", typeof(bool), typeof(NcCalendarControl), new FrameworkPropertyMetadata(true));
            /// <summary>
            /// 获取或设置ShowWeekTitle
            /// </summary>
            public bool ShowWeekTitle
            {
                get { return (bool)base.GetValue(NcCalendarControl.ShowWeekTitleProperty); }
                set { base.SetValue(NcCalendarControl.ShowWeekTitleProperty, value); }
            }
            #endregion        #region CurrentDay
            /// <summary>
            /// 获取CurrentDay标识
            /// </summary>
            public static readonly DependencyPropertyKey CurrentDayPropertyKey = DependencyProperty.RegisterReadOnly("CurrentDay", typeof(DateTime), typeof(NcCalendarControl), new FrameworkPropertyMetadata(DateTime.Now.Date));
            /// <summary>
            /// 获取CurrentDay属性
            /// </summary>
            public static readonly DependencyProperty CurrentDayProperty = CurrentDayPropertyKey.DependencyProperty;
            /// <summary>
            /// 获取CurrentDay
            /// </summary>
            public DateTime CurrentDay { get { return (DateTime)base.GetValue(NcCalendarControl.CurrentDayProperty); } }
            #endregion
            #endregion        #region 事件定义
            /// <summary>
            /// 选项改变事件。
            /// </summary>
            public static readonly RoutedEvent SelectedChangedEvent = EventManager.RegisterRoutedEvent("SelectedChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NcCalendarControl));
            public event RoutedEventHandler SelectedChanged
            {
                add { AddHandler(SelectedChangedEvent, value); }
                remove { RemoveHandler(SelectedChangedEvent, value); }
            }
            void RaiseSelectedChangedEvent()
            {
                RoutedEventArgs args = new RoutedEventArgs(SelectedChangedEvent,this);
                RaiseEvent(args);
            }
            #endregion        #region 命令定义
       
      

  43.   

    //////////////////NcCalendar.cs//////////////////////
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ComponentModel;
    using System.Globalization;
    using System.Collections.ObjectModel;namespace TestMainWindow
    {
        public class NcCalendar : ObservableCollection<NcCalendarWeek>, INotifyPropertyChanged
        {
            #region 字段定义
            private int mYear;
            private int mMonth;
            private NcCalendarDay mCurrent = NcCalendarDay.Empty;        #endregion
            #region 事件定义
            public event EventHandler SelectedChanged;
            public event EventHandler CurrentChanged;
            #endregion
            #region 构造函数
            public NcCalendar() : this(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day) { }
            public NcCalendar(DateTime date) : this(date.Year, date.Month, date.Day) { }
            public NcCalendar(int year, int month) : this(year, month, 1) { }
            public NcCalendar(int year, int month, int day) { BuildCalendar(year, month, day); }
            #endregion
            #region 属性定义
            public int Year
            {
                get { return mYear; }
                set
                {
                    int day = (mCurrent != null) ? day = mCurrent.Day : 1;
                    if (BuildCalendar(value, mMonth, day)) OnPropertyChanged(new PropertyChangedEventArgs("Year"));
                }
            }
            public int Month
            {
                get { return mMonth; }
                set
                {
                    int day = (mCurrent != null) ? day = mCurrent.Day : 1;
                    if (BuildCalendar(mYear, value, day)) OnPropertyChanged(new PropertyChangedEventArgs("Month"));
                }
            }
            public int Day
            {
                get { return mCurrent.Day; }
                set { if (BuildCalendar(mYear, mMonth, value)) OnPropertyChanged(new PropertyChangedEventArgs("Day")); }
            }        public NcCalendarDay Current
            {
                get { return mCurrent; }
                set
                {
                    if (value == null || value == NcCalendarDay.Empty || value == mCurrent || value.Value.Date == mCurrent.Value.Date) return;
                    bool setOK = false;
                    foreach (NcCalendarWeek week in this)
                    {
                        foreach (NcCalendarDay one in week)
                        {
                            if (one.IsEmpty) continue;
                            if (one.Value.Date == value.Value.Date)
                            {
                                mCurrent = one;
                                setOK = true;
                                OnPropertyChanged(new PropertyChangedEventArgs("Day"));
                                this.OnSelectedChanged(new EventArgs());
                                break;
                            }
                        }
                        if (setOK) break;
                    }
                }
            }
            #endregion        #region 方法定义
            public void SetValue(DateTime date) { BuildCalendar(date); }
            /// <summary>
            /// 向后一年
            /// </summary>
            public void NextYear() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddYears(1));
                    return;
                }            int newYear = mYear + 1;
                int newMonth = mMonth;
                int newDay = (mCurrent==null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime maxDate = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime.Date;
                if (newYear > maxDate.Year) return;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear) newMonth = maxMonthOfYear;
                int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay); 
            }
            /// <summary>
            /// 向前一年
            /// </summary>
            public void PreviousYear() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddYears(-1));
                    return;
                }            int newYear = mYear - 1;
                int newMonth = mMonth;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime minDate = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime.Date;
                if (newYear < minDate.Year) return;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear) newMonth = maxMonthOfYear;
                int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);
            }
            /// <summary>
            /// 向后一个月
            /// </summary>
            public void NextMonth() 
            {
                if (mCurrent.Year ==mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddMonths(1));
                    return;
                }
                int newYear = mYear;
                int newMonth = mMonth + 1;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                if (newMonth > maxMonthOfYear)
                {
                    newYear++;
                    DateTime maxDate = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime.Date;
                    if (newYear > maxDate.Year)
                        return;
                    newMonth = 1;
                }            int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);
            }
            /// <summary>
            /// 向前一个月
            /// </summary>
            public void PreviousMonth() 
            {
                if (mCurrent.Year == mYear && mCurrent.Month == mMonth)
                {
                    BuildCalendar(mCurrent.Value.AddMonths(-1));
                    return;
                }            int newYear = mYear;
                int newMonth = mMonth - 1;
                int newDay = (mCurrent == null || mCurrent == NcCalendarDay.Empty) ? DateTime.Now.Day : mCurrent.Value.Day;            DateTime minDate = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime.Date;
                if (newMonth < 1)
                {
                    newYear = newYear - 1;
                    if (newYear < minDate.Year) return;
                    newMonth = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(newYear);
                }            int maxDayOfMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(newYear, newMonth);
                if (newDay > maxDayOfMonth) newDay = maxDayOfMonth;            BuildCalendar(newYear, newMonth, newDay);        }
          
      

  44.   

     /// <summary>
            /// 转到今天
            /// </summary>
            public void Today() { BuildCalendar(DateTime.Now.Date); }
            /// <summary>
            /// 设置“当前日”
            /// </summary>
            /// <param name="day"></param>
            /// <returns></returns>
            private bool setDay(int day)
            {
                foreach (NcCalendarWeek week in this)
                {
                    foreach (NcCalendarDay one in week)
                    {
                        if (!one.IsEmpty && one.Day == day)
                        {
                            if (mCurrent != null) mCurrent.IsCurrent = false;
                            mCurrent = one;
                            OnPropertyChanged(new PropertyChangedEventArgs("Current"));
                            OnPropertyChanged(new PropertyChangedEventArgs("Day"));
                            one.OnPropertyChanged("IsCurrent");
                            this.OnSelectedChanged(new EventArgs());
                            return true;
                        }
                        else
                        {
                            mCurrent = null;
                            this.OnPropertyChanged(new PropertyChangedEventArgs("IsCurrent"));
                        }
                    }
                }
                return false;
            }        private bool BuildCalendar(DateTime date) { if (date != null)  return BuildCalendar(date.Year, date.Month, date.Day); return false; }
            /// <summary>
            /// 创建月历视图数据
            /// </summary>
            /// <param name="year"></param>
            /// <param name="month"></param>
            /// <param name="day"></param>
            /// <returns></returns>
            private bool BuildCalendar(int year, int month, int day)
            {
                if (mCurrent != null)
                {
                    // 年、月、日均没有变化,不作任何改变
                    if (year == mCurrent.Year && month == mCurrent.Month && day == mCurrent.Day) return true;
                    // 年、月没有变化,不需要重建日期列表,定位当前日期
                    if (year == mCurrent.Year && month == mCurrent.Month) return setDay(day);
                }            DateTime minDate = CultureInfo.CurrentCulture.Calendar.MinSupportedDateTime.Date;
                DateTime maxDate = CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime.Date;
                int maxMonthOfYear = CultureInfo.CurrentCulture.Calendar.GetMonthsInYear(year);
                // 方案1:年月日不符合范围限定时,返回False
                if (year < minDate.Year || year > maxDate.Year || month < 1 || month > maxMonthOfYear) return false;            // 方案2:年月日不符合范围限定时,规范到合理范围内
                //if (year < minDate.Year) year = minDate.Year;
                //if (year > maxDate.Year) year = maxDate.Year;
                //if (month < 1) month = 1;
                //if (month > maxMonthOfYear) month = maxMonthOfYear;
                DateTime firstDay = new DateTime(year, month, 1);
                int emptyDays = (int)firstDay.DayOfWeek;            int days = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month);
                int weeks = (int)Math.Ceiling(((float)days) / 7);            if (day < 1 || day > days) day = (mCurrent != null) ? mCurrent.Day : 1;            this.Clear();            int dayOfWeekCount = 0;
                int weekCount = 0;
                NcCalendarWeek week = new NcCalendarWeek();
                NcCalendarDay item = NcCalendarDay.Empty;
                if (emptyDays > 0)
                {
                    for (int i = emptyDays; i > 0; i--)
                    {
                        item = new NcCalendarDay(firstDay.AddDays(-i));
                        item.Owner = this;
                        item.IsPreviousMonth = true;
                        week.Add(item);  //添加"上个月"的日期
                        dayOfWeekCount++;
                    }
                }            NcCalendarDay currentDayTo = null;
                for (int i = 1; i <= days; i++)
                {
                    item = new NcCalendarDay(new DateTime(year, month, i));
                    item.Owner = this;
                    week.Add(item);
                    dayOfWeekCount++;
                    if (dayOfWeekCount >= 7)
                    {
                        dayOfWeekCount = 0;
                        weekCount++;
                        this.Add(week);
                        week = new NcCalendarWeek();
                    }
                    if (i == day) currentDayTo = item;
                }
                firstDay = item.Value.Date;    // 借用firstDay变量
                if (dayOfWeekCount > 0)
                {
                    for (int i = dayOfWeekCount; i < 7; i++)
                    {
                        item = new NcCalendarDay(firstDay.AddDays(i - dayOfWeekCount + 1));
                        item.IsNextMonth = true;
                        item.Owner = this;
                        week.Add(item);  //添加"下个月"的日期
                    }
                    if (dayOfWeekCount < 7) this.Add(week);
                }            //if (this.mCurrent == null || this.mCurrent != currentDayTo)
                if (this.mCurrent == null)
                {
                    this.mCurrent = currentDayTo;
                    this.OnSelectedChanged(new EventArgs());
                }            mYear = year;
                mMonth = month;            OnPropertyChanged(new PropertyChangedEventArgs("Day"));
                OnPropertyChanged(new PropertyChangedEventArgs("Month"));
                OnPropertyChanged(new PropertyChangedEventArgs("Year"));            return true;
            }
            #endregion        protected internal virtual void OnSelectedChanged(EventArgs e) { if (this.SelectedChanged != null) this.SelectedChanged(this, e); }
            protected internal virtual void OnCurrentChanged(EventArgs e) { if (this.CurrentChanged != null) this.CurrentChanged(this, e); }
        }
        public class NcCalendarWeek : ObservableCollection<NcCalendarDay>, INotifyPropertyChanged { }}
      

  45.   

    ////////////////NcCalendarControl.cs///////////////////////
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;namespace TestMainWindow
    {
        public class NcCalendarControl : Control
        {
            #region 构造函数
            static NcCalendarControl()
            {
                DefaultStyleKeyProperty.OverrideMetadata(typeof(NcCalendarControl), new FrameworkPropertyMetadata(typeof(NcCalendarControl)));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(PreviousYear, OnPreviousYear));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(PreviousMonth, OnPreviousMonth));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(NextYear, OnNextYear));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(NextMonth, OnNextMonth));
                CommandManager.RegisterClassCommandBinding(typeof(NcCalendarControl), new CommandBinding(Today, OnToday));
            }
            public NcCalendarControl() 
            {
                this.SetValue(ItemsProperty, new NcCalendar(DateTime.Now));
                Items.SelectedChanged += new EventHandler(Items_SelectedChanged);
            }
            #endregion        #region 属性定义
            /// <summary>
            /// 本月的"周"集合 
            /// </summary>
            public NcCalendar Items
            {
                get { return (NcCalendar)GetValue(ItemsProperty); }
                set { SetValue(ItemsProperty, value); }
            }
            public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(NcCalendar), typeof(NcCalendarControl), new UIPropertyMetadata(new NcCalendar(DateTime.Now)));        #region Changeable
            /// <summary>
            /// 是否能够通过按钮改变年、月。
            /// </summary>
            public static readonly DependencyProperty ChangeableProperty = DependencyProperty.Register("Changeable", typeof(bool), typeof(NcCalendarControl), new FrameworkPropertyMetadata(true));
            /// <summary>
            /// 获取或设置Changeable
            /// </summary>
            public bool Changeable
            {
                get { return (bool)base.GetValue(NcCalendarControl.ChangeableProperty); }
                set { base.SetValue(NcCalendarControl.ChangeableProperty, value); }
            }
            #endregion        #region ShowHeader
            /// <summary>
            /// 是否显示月历头。
            /// </summary>
            public static readonly DependencyProperty ShowHeaderProperty = DependencyProperty.Register("ShowHeader", typeof(bool), typeof(NcCalendarControl), new FrameworkPropertyMetadata(true));
            /// <summary>
            /// 获取或设置ShowHeader
            /// </summary>
            public bool ShowHeader
            {
                get { return (bool)base.GetValue(NcCalendarControl.ShowHeaderProperty); }
                set { base.SetValue(NcCalendarControl.ShowHeaderProperty, value); }
            }
            #endregion        #region ShowWeekTitle
            /// <summary>
            /// 是否显示周标签。
            /// </summary>
            public static readonly DependencyProperty ShowWeekTitleProperty = DependencyProperty.Register("ShowWeekTitle", typeof(bool), typeof(NcCalendarControl), new FrameworkPropertyMetadata(true));
            /// <summary>
            /// 获取或设置ShowWeekTitle
            /// </summary>
            public bool ShowWeekTitle
            {
                get { return (bool)base.GetValue(NcCalendarControl.ShowWeekTitleProperty); }
                set { base.SetValue(NcCalendarControl.ShowWeekTitleProperty, value); }
            }
            #endregion        #region CurrentDay
            /// <summary>
            /// 获取CurrentDay标识
            /// </summary>
            public static readonly DependencyPropertyKey CurrentDayPropertyKey = DependencyProperty.RegisterReadOnly("CurrentDay", typeof(DateTime), typeof(NcCalendarControl), new FrameworkPropertyMetadata(DateTime.Now.Date));
            /// <summary>
            /// 获取CurrentDay属性
            /// </summary>
            public static readonly DependencyProperty CurrentDayProperty = CurrentDayPropertyKey.DependencyProperty;
            /// <summary>
            /// 获取CurrentDay
            /// </summary>
            public DateTime CurrentDay { get { return (DateTime)base.GetValue(NcCalendarControl.CurrentDayProperty); } }
            #endregion
            #endregion        #region 事件定义
            /// <summary>
            /// 选项改变事件。
            /// </summary>
            public static readonly RoutedEvent SelectedChangedEvent = EventManager.RegisterRoutedEvent("SelectedChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NcCalendarControl));
            public event RoutedEventHandler SelectedChanged
            {
                add { AddHandler(SelectedChangedEvent, value); }
                remove { RemoveHandler(SelectedChangedEvent, value); }
            }
            void RaiseSelectedChangedEvent()
            {
                RoutedEventArgs args = new RoutedEventArgs(SelectedChangedEvent,this);
                RaiseEvent(args);
            }
            #endregion
      

  46.   

           #region 命令定义
            #region PreviousYear
            /// <summary>
            /// 月历视图向前移动一年命令。
            /// </summary>
            public static RoutedUICommand PreviousYear { get { return mPreviousYear; } }
            private static RoutedUICommand mPreviousYear = new RoutedUICommand("PreviousYear", "PreviousYear", typeof(NcCalendarControl));        private static void OnPreviousYear(object sender, ExecutedRoutedEventArgs e)
            {
                NcCalendarControl calendar = sender as NcCalendarControl;
                if (calendar == null) return;
                calendar.Items.PreviousYear();
            }
            #endregion
            #region NextYear
            /// <summary>
            /// 月历视图向后移动一年命令。
            /// </summary>
            public static RoutedUICommand NextYear { get { return mNextYear; } }
            private static RoutedUICommand mNextYear = new RoutedUICommand("NextYear", "NextYear", typeof(NcCalendarControl));        private static void OnNextYear(object sender, ExecutedRoutedEventArgs e)
            {
                NcCalendarControl calendar = sender as NcCalendarControl;
                if (calendar == null) return;
                calendar.Items.NextYear();
            }
            #endregion
            #region PreviousMonth
            /// <summary>
            /// 月历视图向前移动一月命令。
            /// </summary>
            public static RoutedUICommand PreviousMonth { get { return mPreviousMonth; } }
            private static RoutedUICommand mPreviousMonth = new RoutedUICommand("PreviousMonth", "PreviousMonth", typeof(NcCalendarControl));        private static void OnPreviousMonth(object sender, ExecutedRoutedEventArgs e)
            {
                NcCalendarControl calendar = sender as NcCalendarControl;
                if (calendar == null) return;
                calendar.Items.PreviousMonth();
            }
            #endregion
            #region NextMonth
            /// <summary>
            /// 月历视图向后移动一月命令。
            /// </summary>
            public static RoutedUICommand NextMonth { get { return mNextMonth; } }
            private static RoutedUICommand mNextMonth = new RoutedUICommand("NextMonth", "NextMonth", typeof(NcCalendarControl));        private static void OnNextMonth(object sender, ExecutedRoutedEventArgs e)
            {
                NcCalendarControl calendar = sender as NcCalendarControl;
                if (calendar == null) return;
                calendar.Items.NextMonth();
            }
            #endregion
            #region Today
            /// <summary>
            /// 转到今天命令。
            /// </summary>
            public static RoutedUICommand Today { get { return mToday; } }
            private static RoutedUICommand mToday = new RoutedUICommand("Today", "Today", typeof(NcCalendarControl));
            private static void OnToday(object sender, ExecutedRoutedEventArgs e)
            {
                NcCalendarControl calendar = sender as NcCalendarControl;
                if (calendar == null) return;
                calendar.Items.Today();
                DateTime dt = calendar.CurrentDay.Date;
                // 依赖于XAML中的控件,需要改进 ??????????????????????????
                List<RadioButton> rbList = new List<RadioButton>();
                calendar.FindRadioButton(calendar, rbList);
                foreach(RadioButton one in rbList )
                {
                    NcCalendarDay day = one.DataContext as NcCalendarDay;
                    if (day != null && day.Value.Date == dt.Date)
                    {
                        one.Focus();
                        break;
                    }
                }
            }
            /// <summary>
            /// 查找视图中的“天”按钮。
            /// </summary>
            /// <param name="parent"></param>
            /// <param name="rbList"></param>
            private void FindRadioButton(DependencyObject parent, List<RadioButton> rbList)
            {
                int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < childrenCount; i++)
                {
                    DependencyObject obj = VisualTreeHelper.GetChild(parent, i);
                    if (obj.GetType() == typeof(RadioButton))
                    {
                        RadioButton rb = obj as RadioButton;
                        if (rb != null) rbList.Add(rb);                    //NcCalendarDay day = rb.Content as NcCalendarDay;
                        //if (day != null && day.Value.Date == dt.Date)
                        //{
                        //    rb.Focus();
                        //    break;
                        //}
                    }
                    else
                        FindRadioButton(obj, rbList);
                }        }
            #endregion
            #endregion        /// <summary>
            /// 设置控件的当前日期。如果日期不在当前显示的月份,当前日历视图将变为指定日期所在的月份视图。
            /// </summary>
            /// <param name="date">日期。</param>
            public void SetValue(DateTime date) { if (date != null) Items.SetValue(date); }        /// <summary>
            /// 选项改变事件。
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Items_SelectedChanged(object sender, EventArgs e)
            {
                if (Items.Current == null || Items.Current == NcCalendarDay.Empty) return;
                DateTime dt = Items.Current.Value;
                this.SetValue(NcCalendarControl.CurrentDayPropertyKey, dt);
                RaiseSelectedChangedEvent();
            }
        }
    }