PageRenderTime 35ms CodeModel.GetById 13ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 1ms

/BlogEngine/DotNetSlave.BusinessLogic/Providers/DbConnectionHelper.cs

#
C# | 199 lines | 111 code | 29 blank | 59 comment | 9 complexity | fa48cd681908e1bfcdf12038adb43fc4 MD5 | raw file
  1using System;
  2using System.Collections.Generic;
  3using System.Configuration;
  4using System.Configuration.Provider;
  5using System.Data;
  6using System.Data.Common;
  7using System.Linq;
  8using System.Text;
  9
 10namespace BlogEngine.Core.Providers
 11{
 12    /// <summary>
 13    /// Helper class for working with DbConnections.
 14    /// </summary>
 15    /// <remarks>
 16    /// 
 17    /// This class is meant to reduce the amount of repeated code in database provider classes by pulling all the common actions
 18    /// into one spot. This should remove the many repetitive null checks on connections/parameters.
 19    /// 
 20    /// This class handles the creation of DbConnection, setting its connection string, and opening the connection if possible.
 21    /// 
 22    /// Usage is simple:
 23    /// using(var helper = new ConnectionHelper(provider)) {
 24    ///     if (helper.HasConnection) {
 25    ///         // do stuff
 26    ///     }
 27    /// }
 28    /// 
 29    /// Note: This class throws a NullReferenceException if its Provider.CreateParameter() method returns a null object.
 30    /// All of the methods in the DbBlogProvider class require parameterized queries, and previously each parameter
 31    /// created was being checked for null before proceeding. It's better to fail fast in this instance, to help creaters
 32    /// of custom implementations figure out what's wrong.
 33    /// 
 34    /// </remarks>
 35    public sealed class DbConnectionHelper : IDisposable
 36    {
 37
 38        #region "Constructors"
 39
 40        /// <summary>
 41        /// Creates a new DbConnectionHelper instance from the given ConnectionStringSettings.
 42        /// </summary>
 43        /// <param name="settings"></param>
 44        public DbConnectionHelper(ConnectionStringSettings settings) : this(settings.ProviderName, settings.ConnectionString)
 45        {
 46        }
 47
 48        /// <summary>
 49        /// Creates a new DbConnectionHelper instance from the given provider name and database connection string..
 50        /// </summary>
 51        /// <param name="providerName"></param>
 52        /// <param name="connectionString"></param>
 53        public DbConnectionHelper(string providerName, string connectionString)
 54        {
 55            this._dbProvFactory = DbProviderFactories.GetFactory(providerName);
 56            this._connection = this._dbProvFactory.CreateConnection();
 57
 58            this._hasConnection = (this._connection != null);
 59            if (this._hasConnection)
 60            {
 61                this._connection.ConnectionString = connectionString;
 62                this._connection.Open();
 63            }
 64        }
 65
 66        #endregion
 67
 68        #region "Properties"
 69
 70        /// <summary>
 71        /// Returns the DbConnection of this instance.
 72        /// </summary>
 73        public DbConnection Connection
 74        {
 75            get { return this._connection; }
 76        }
 77        private DbConnection _connection;
 78
 79        /// <summary>
 80        /// Gets whether the Connection of this ConnectionHelper instance is null.
 81        /// </summary>
 82        public bool HasConnection
 83        {
 84            get { return this._hasConnection; }
 85        }
 86
 87        private bool _hasConnection;
 88
 89        /// <summary>
 90        /// Gets the DbProviderFactory used by this ConnectionHelper instance.
 91        /// </summary>
 92        public DbProviderFactory Provider
 93        {
 94            get { return this._dbProvFactory; }
 95        }
 96        private DbProviderFactory _dbProvFactory;
 97
 98        #endregion
 99
100        #region "Methods"
101
102        private void CheckDisposed()
103        {
104            if (this.isDisposed)
105            {
106                throw new ObjectDisposedException("ConnectionHelper");
107            }
108        }
109
110        /// <summary>
111        /// Uses this ConnectionHelper instance's connection to create and return a new DbCommand instance.
112        /// </summary>
113        /// <returns></returns>
114        public DbCommand CreateCommand()
115        {
116            this.CheckDisposed();
117            return this.Connection.CreateCommand();
118        }
119
120        /// <summary>
121        /// Users this ConnectionHelper instance's connection to create and return a new DbCommand with the given command text. CommandType is automatically set to CommandType.Text.
122        /// </summary>
123        /// <param name="commandText"></param>
124        /// <returns></returns>
125        public DbCommand CreateTextCommand(string commandText)
126        {
127            var command = this.CreateCommand();
128            command.CommandText = commandText;
129            command.CommandType = CommandType.Text;
130
131            return command;
132        }
133
134
135        /// <summary>
136        /// Uses this ConnectionHelper's Provider to create a DbParameter instance with the given parameter name and value.
137        /// </summary>
138        /// <param name="parameterName">The name of the parameter.</param>
139        /// <param name="value">The value of the parameter.</param>
140        /// <returns></returns>
141        public DbParameter CreateParameter(string parameterName, object value)
142        {
143            this.CheckDisposed();
144
145            var param = this.Provider.CreateParameter();
146
147            if (param == null)
148            {
149                throw new NullReferenceException("DbBlogProvider");
150            }
151            else
152            {
153                param.ParameterName = parameterName;
154                param.Value = value;
155                return param;
156            }
157
158        }
159
160        #endregion
161
162        #region "IDisposable"
163
164        private bool isDisposed;
165
166        private void Dispose(bool disposing)
167        {
168            try
169            {
170                if (!this.isDisposed && disposing)
171                {
172                    if (this._connection != null)
173                    {
174                        this._connection.Dispose();
175                    }
176                }
177            }
178            finally
179            {
180                this._dbProvFactory = null;
181                this._connection = null;
182                this._hasConnection = false;
183                this.isDisposed = true;
184            }
185        }
186
187        /// <summary>
188        /// Disposes this DbConnectionHelper and its underlying connection.
189        /// </summary>
190        public void Dispose()
191        {
192            this.Dispose(true);
193            GC.SuppressFinalize(this);
194        }
195
196        #endregion
197
198    }
199}