/// <summary>
        /// Use this method to encapsulte a data call method.
        /// </summary>
        /// <param name="runMethod"></param>
        public virtual void InConnected(ConnectThenDelegate runMethod)
        {
            try
            {
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();

                    try
                    {
                        runMethod(connection);
                    }
                    catch (Exception ex)
                    {
                        var helpfulDetails = string.Empty;
                        if (ex.Message.Contains("DataReader associated with this Command"))
                        {
                            helpfulDetails += " (hint: You probably need to specify MultipleActiveResultSets=True in your connection string.) ";
                        }

                        if (ExceptionHandler != null)
                        {
                            ExceptionHandler(new Exception("Failed to run data method (" + runMethod.Method.Name + ")." + helpfulDetails, ex));
                        }
                        else
                        {
                            if (helpfulDetails != string.Empty)
                            {
                                throw new Exception(ex.Message + helpfulDetails, ex);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }

                    connection.Close();
                }
            }
            catch (Exception ex)
            {
                if (ExceptionHandler != null)
                {
                    ExceptionHandler(new Exception("Failed to connect to database.", ex));
                }
                else
                {
                    throw;
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Run a series of commands after connecting to the db.
        /// </summary>
        /// <param name="runMethod">A delegate method that runs your logic commands.</param>
        public static void ConnectThen(ConnectThenDelegate runMethod)
        {
            var db = new VotingInfoDb();

            db.InConnected(runMethod);
        }