Example #1
0
        /// <summary>
        /// execute a string back to the database using group names from regex to supply to the stored procedures
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="command"></param>
        /// <param name="source">raw line that will be parsed via regex</param>
        /// <param name="regex"></param>
        /// <param name="regexNotFoundOrValueIsNull">if the parameter cannot find group this is method called for the value of the parameter</param>
        /// <returns></returns>
        public static T ExecuteWithRegex <T>(this d.SqlClient.SqlCommand command, string source, System.Text.RegularExpressions.Regex regex,
                                             Func <string, object> regexNotFoundOrValueIsNull = null)
            where T : class, IBattleAxe, new()
        {
            var outputParameters = new T();

            if (regex.TrySetSqlCommandParameterValues(source, command, regexNotFoundOrValueIsNull))
            {
                try
                {
                    if (command.IsConnectionOpen())
                    {
                        command.ExecuteNonQuery();
                        command.Connection.Close();
                        foreach (d.IDbDataParameter parameter in command.Parameters)
                        {
                            if (parameter.Direction == d.ParameterDirection.InputOutput || parameter.Direction == d.ParameterDirection.Output)
                            {
                                var field = parameter.ParameterName.Replace("@", "");
                                outputParameters[field] = parameter.Value;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string formatted = string.Format("Execution of 'ExecuteWithRegex' SqlCommand:{0}, ErrorMessage:{1}", command.CommandText, ex.Message);
                    throw new Exception(formatted);
                }
                finally {
                    command.Connection.Close();
                }
            }
            else
            {
                string formatted = string.Format("Failed to 'ExecuteWithRegex' SqlCommand:{0}", command.CommandText);
                throw new Exception(formatted);
            }
            return(outputParameters);
        }