Share Pastebin
Guest
Public paste!

jeffreyabecker

By: a guest | Jul 2nd, 2009 | Syntax: C# | Size: 7.77 KB | Hits: 28 | Expires: Never
Copy text to clipboard
  1. /*
  2. ** 02/06/2009
  3. **
  4. ** The author disclaims copyright to this source code.  In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. **    May you do good and not evil.
  8. **    May you find forgiveness for yourself and forgive others.
  9. **    May you share freely, never taking more than you give.
  10. **
  11. **
  12. */
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Data;
  18. using System.Data.SqlClient;
  19.  
  20. namespace JB.DbExample
  21. {
  22.     public class DbParameter
  23.     {
  24.         public string Name { get; set; }
  25.         public object Value { get; set; }
  26.     }
  27.  
  28.     public interface IDbManager : IDisposable
  29.     {
  30.         /// <summary>
  31.         /// Executes a procedure returning the results as a DataSet
  32.         /// </summary>
  33.         /// <param name="procName">The name of the stored procedure</param>
  34.         /// <param name="args">the argument name/value pairs for the procedure</param>
  35.         /// <returns>the resuts as a data set</returns>
  36.         DataSet Exec(string procName, params DbParameter[] args);
  37.  
  38.         /// <summary>
  39.         /// Executes some sql returning the results as a DataSet
  40.         /// </summary>
  41.         /// <param name="sql">the sql to be executed</param>
  42.         /// <param name="args">the argument name/value pairs for the sql</param>
  43.         /// <returns>the resuts as a data set</returns>
  44.         DataSet ExecDynamicSql(string sql, params DbParameter[] args);
  45.  
  46.         /// <summary>
  47.         /// Executes a stored procedure and returns a single result
  48.         /// </summary>
  49.         /// <typeparam name="T">The type of the result</typeparam>
  50.         /// <param name="procName">the name of hte procedure</param>
  51.         /// <param name="args">the argument name/value pairs for the procedure</param>
  52.         /// <returns></returns>
  53.         T Scalar<T>(string procName, params DbParameter[] args);
  54.  
  55.         /// <summary>
  56.         /// Executes some sql returning a single result
  57.         /// </summary>
  58.         /// <typeparam name="T">The type of the result</typeparam>
  59.         /// <param name="sql">the sql to be executed</param>
  60.         /// <param name="args">the argument name/value pairs for the sql</param>
  61.         /// <returns></returns>
  62.         T ScalarDynamicSql<T>(string sql, params DbParameter[] args);
  63.  
  64.         /// <summary>
  65.         /// Begins a transaction.
  66.         /// </summary>
  67.         void Begin();
  68.  
  69.         /// <summary>
  70.         /// Commits a transaction.
  71.         /// </summary>
  72.         void Commit();
  73.         /// <summary>
  74.         /// Rolls a transaction back.
  75.         /// </summary>
  76.         void Rollback();
  77.     }
  78.  
  79.     public static class DbManagerExtensions
  80.     {
  81.         private static DbParameter[] GetArgsFromObject(object obj)
  82.         {
  83.             List<DbParameter> parameters = new List<DbParameter>();
  84.             foreach (var propertyInfo in obj.GetType().GetProperties())
  85.             {
  86.                 parameters.Add(new DbParameter() { Name = propertyInfo.Name, Value = propertyInfo.GetValue(obj, null) });
  87.             }
  88.             return parameters.ToArray();
  89.         }
  90.         public static DataSet Exec(this IDbManager db, string procName, object argsDict)
  91.         {
  92.             return db.Exec(procName, GetArgsFromObject(argsDict));
  93.         }
  94.         public static DataSet ExecDynamicSql(this IDbManager db, string sql, object argsDict)
  95.         {
  96.             return db.ExecDynamicSql(sql, GetArgsFromObject(argsDict));
  97.         }
  98.         public static object Scalar(this IDbManager db, string procName, object argsDict)
  99.         {
  100.             return db.Scalar(procName, GetArgsFromObject(argsDict));
  101.         }
  102.         public static object ScalarDynamicSql(this IDbManager db, string sql, object argsDict)
  103.         {
  104.             return db.ScalarDynamicSql(sql, GetArgsFromObject(argsDict));
  105.         }
  106.     }
  107.  
  108.     public class DbManagerFactory
  109.     {
  110.         public static IDbManager GetDbManager(string connectionStringName)
  111.         {
  112.             return new SqlDbManager(System.Configuration.ConfigurationManager.ConnectionStrings[connectionStringName]);
  113.         }
  114.        
  115.         // this is the actual implementation of IDbManager.  It should never be instantiated outside the factory class
  116.         private class SqlDbManager : IDbManager
  117.         {
  118.             string _connectionString;
  119.             SqlConnection _conn;
  120.             SqlTransaction _trans;
  121.  
  122.             public SqlDbManager(string connectionString)
  123.             {
  124.                 _connectionString = connectionString;
  125.             }
  126.  
  127.             private SqlConnection GetConnection()
  128.             {
  129.                 if (_conn == null)
  130.                 {
  131.                     _conn = new SqlConnection(_connectionString);
  132.                     _conn.Open();
  133.                 }
  134.                 return _conn;
  135.             }
  136.  
  137.             public DataSet Exec(string procName, params DbParameter[] args)
  138.             {
  139.                 SqlCommand cmd = new SqlCommand(procName, GetConnection());
  140.                 cmd.CommandType = CommandType.StoredProcedure;
  141.                 foreach (DbParameter p in args)
  142.                 {
  143.                     cmd.Parameters.AddWithValue(p.Name, p.Value);
  144.                 }
  145.                 DataSet ds = new DataSet();
  146.                 SqlDataAdapter adp = new SqlDataAdapter(cmd);
  147.                 adp.Fill(ds);
  148.                 return ds;
  149.             }
  150.  
  151.             public DataSet ExecDynamicSql(string sql, params DbParameter[] args)
  152.             {
  153.                 SqlCommand cmd = new SqlCommand(sql, GetConnection());
  154.                 cmd.CommandType = CommandType.Text;
  155.                 foreach (DbParameter p in args)
  156.                 {
  157.                     cmd.Parameters.AddWithValue(p.Name, p.Value);
  158.                 }
  159.                 DataSet ds = new DataSet();
  160.                 SqlDataAdapter adp = new SqlDataAdapter(cmd);
  161.                 adp.Fill(ds);
  162.                 return ds;
  163.             }
  164.  
  165.             public T Scalar<T>(string procName, params DbParameter[] args)
  166.             {
  167.                 DataSet ds = Exec(procName, args);
  168.                 return ds.Tables[0].Rows[0].Field<T>(0);
  169.             }
  170.  
  171.             public T ScalarDynamicSql<T>(string sql, params DbParameter[] args)
  172.             {
  173.                 DataSet ds = ExecDynamicSql(sql, args);
  174.                 return ds.Tables[0].Rows[0].Field<T>(0);
  175.             }
  176.  
  177.  
  178.  
  179.             public void Begin()
  180.             {
  181.                 if (_trans != null)
  182.                 {
  183.                     throw new DataException("Attempted to begin a transaction with one already pending.");
  184.                 }
  185.                 SqlConnection conn = GetConnection();
  186.                 _trans = conn.BeginTransaction();
  187.             }
  188.  
  189.             public void Commit()
  190.             {
  191.                 if (_trans == null)
  192.                     throw new DataException("Attempted to commit without a pending transaction.");
  193.                 _trans.Commit();
  194.                 _trans.Dispose();
  195.                 _trans = null;
  196.             }
  197.  
  198.             public void Rollback()
  199.             {
  200.                 if (_trans == null)
  201.                     throw new DataException("Attempted to roll back without a pending transaction.");
  202.                 _trans.Rollback();
  203.                 _trans.Dispose();
  204.                 _trans = null;
  205.             }
  206.  
  207.  
  208.             public void Dispose()
  209.             {
  210.                 if (_trans != null)
  211.                 {
  212.                     _trans.Rollback();
  213.                     _trans.Dispose();
  214.                     throw new DataException("Disposed a connection with a pending transaction.  Make sure to explicitly commit or rollback your transactions");
  215.                 }
  216.                 if (_conn != null)
  217.                 {
  218.                     _conn.Dispose();
  219.                 }
  220.  
  221.             }
  222.         }
  223.     }
  224. }