コード例 #1
0
        /// <summary>
        /// Executes the current collection of registered commands
        /// </summary>
        /// <remarks>
        /// Opens the connection, begins a transaction, initializes all command, then executes each command.  Finally commits transaction.
        /// Upon failure, transaction is rolled-back.  Null commands automatically return 1 for execution.
        /// </remarks>
        /// <returns>List of integers returned from each registered command</returns>
        public List <int> Execute()
        {
            List <int> retVal = new List <int>();

            using (Microsoft.Data.SqlClient.SqlConnection conn = new Microsoft.Data.SqlClient.SqlConnection(_ConnectionString))
            {
                conn.Open();
                Microsoft.Data.SqlClient.SqlTransaction trans = conn.BeginTransaction();
                try
                {
                    int initialized = _Commands.Count;
                    for (int i = 0; i < initialized; i++)
                    {
                        if (_Commands[i] != null)
                        {
                            _Commands[i].Initialize(conn, trans);
                        }
                    }
                    for (int i = 0; i < _Commands.Count; i++)
                    {
                        if (_Commands[i] != null)
                        {
                            //  This following line allows for chaining.
                            //  in other words, a executing command can add more commands.
                            if (i >= initialized)
                            {
                                _Commands[i].Initialize(conn, trans);
                            }
                            retVal.Add(_Commands[i].Execute());
                        }
                        else
                        {
                            retVal.Add(1);
                        }
                    }
                    trans.Commit();
                }
                catch (Exception)
                {
                    try { trans.Rollback(); } catch (Exception) { }
                    throw;
                }
                finally
                {
                    _Commands.Clear();
                }
            }
            return(retVal);
        }