Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
shansfk committed Mar 17, 2015
1 parent 1bfdedd commit bb67722
Show file tree
Hide file tree
Showing 56 changed files with 1,372 additions and 0 deletions.
6 changes: 6 additions & 0 deletions App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
37 changes: 37 additions & 0 deletions DbConnect.DataReaderExt.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

using System;
using System.Data;

namespace DbConnect
{
public static partial class DbConnect
{
public static T Get<T>(this IDataRecord record, string name)
{
var index = record.GetOrdinal(name);
var val = record[index];

return Parse<T>(val);
}

private static T Parse<T>(object val)
{
try
{
return (T)Convert.ChangeType(val, typeof(T));
}
catch
{
if (val == DBNull.Value)
{
if (default(T) != null)
{
throw new ApplicationException("Attempting to cast a DBNull to a non nullable type!");
}
return default(T);
}
throw new ApplicationException("Invalid Cast !");
}
}
}
}
93 changes: 93 additions & 0 deletions DbConnect.DbTypeLookup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Author : sfk
* Licence : Public
*/

using System;
using System.Collections.Generic;
using System.Data;

namespace DbConnect
{
public static partial class DbConnect
{
/// <summary>
/// Contains the DbType for the CLR Type
/// </summary>
static readonly Dictionary<Type, DbType> TypeMap;

static DbConnect()
{
TypeMap = new Dictionary<Type, DbType>();
TypeMap[typeof(byte)] = DbType.Byte;
TypeMap[typeof(sbyte)] = DbType.SByte;
TypeMap[typeof(short)] = DbType.Int16;
TypeMap[typeof(ushort)] = DbType.UInt16;
TypeMap[typeof(int)] = DbType.Int32;
TypeMap[typeof(uint)] = DbType.UInt32;
TypeMap[typeof(long)] = DbType.Int64;
TypeMap[typeof(ulong)] = DbType.UInt64;
TypeMap[typeof(float)] = DbType.Single;
TypeMap[typeof(double)] = DbType.Double;
TypeMap[typeof(decimal)] = DbType.Decimal;
TypeMap[typeof(bool)] = DbType.Boolean;
TypeMap[typeof(string)] = DbType.String;
TypeMap[typeof(char)] = DbType.StringFixedLength;
TypeMap[typeof(Guid)] = DbType.Guid;
TypeMap[typeof(DateTime)] = DbType.DateTime;
TypeMap[typeof(DateTimeOffset)] = DbType.DateTimeOffset;
TypeMap[typeof(TimeSpan)] = DbType.Time;
TypeMap[typeof(byte[])] = DbType.Binary;
TypeMap[typeof(byte?)] = DbType.Byte;
TypeMap[typeof(sbyte?)] = DbType.SByte;
TypeMap[typeof(short?)] = DbType.Int16;
TypeMap[typeof(ushort?)] = DbType.UInt16;
TypeMap[typeof(int?)] = DbType.Int32;
TypeMap[typeof(uint?)] = DbType.UInt32;
TypeMap[typeof(long?)] = DbType.Int64;
TypeMap[typeof(ulong?)] = DbType.UInt64;
TypeMap[typeof(float?)] = DbType.Single;
TypeMap[typeof(double?)] = DbType.Double;
TypeMap[typeof(decimal?)] = DbType.Decimal;
TypeMap[typeof(bool?)] = DbType.Boolean;
TypeMap[typeof(char?)] = DbType.StringFixedLength;
TypeMap[typeof(Guid?)] = DbType.Guid;
TypeMap[typeof(DateTime?)] = DbType.DateTime;
TypeMap[typeof(DateTimeOffset?)] = DbType.DateTimeOffset;
TypeMap[typeof(TimeSpan?)] = DbType.Time;
TypeMap[typeof(object)] = DbType.Object;
TypeMap[typeof (DataTable)] = DbType.Structured;
}

internal const string LinqBinary = "System.Data.Linq.Binary";

/// <summary>
/// Used to find the DbType from the param value type if not specified by the User
/// </summary>
/// <param name="type">CLR Type of param value</param>
/// <param name="name">Param Name</param>
/// <param name="demand">To ensure if it is present else throw error</param>
/// <returns>DbType</returns>
internal static DbType LookDbType(Type type, string name, bool demand)
{
DbType dbType;

if (type.IsEnum && !TypeMap.ContainsKey(type))
{
type = Enum.GetUnderlyingType(type);
}
if (TypeMap.TryGetValue(type, out dbType))
{
return dbType;
}
if (type.FullName == LinqBinary)
{
return DbType.Binary;
}

if (demand)
throw new NotSupportedException(string.Format("The member {0} of type {1} cannot be used as a parameter value", name, type.FullName));
return DbType.Object;
}
}
}
18 changes: 18 additions & 0 deletions DbConnect.Mappers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Author : sfk
* License : Public
*/

using System.Collections.Generic;
using System.Data;

namespace DbConnect
{
public static partial class DbConnect
{
public static IEnumerable<T> Query<T>(this IDbConnection con)
{
return null;
}
}
}
225 changes: 225 additions & 0 deletions DbConnect.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
/*
* Author : sfk
* Licence : Public
*/

using System;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;


namespace DbConnect
{
/// <summary>
/// Class that extends IDbConnection and provides facility to make operation with the datatabases supported by ADO.Net
/// </summary>
public static partial class DbConnect
{
/// <summary>
/// Executes Parametrized/Non-Parametrized sql statements, Stored procedure which dont have return result sets
/// Suited for Insert/Update/Delete/ Stored Procedures without results with In/Out params
/// </summary>
/// <param name="con">Connection object</param>
/// <param name="sql">sql staement</param>
/// <param name="parameters">parameters</param>
/// <param name="commandType">Command Type</param>
/// <returns></returns>
public static int Execute(this IDbConnection con, string sql, DynamicParameters parameters = null, CommandType? commandType = null)
{
int rowsAffected;
IDbCommand cmd = null;

var wasClosed = con.State == ConnectionState.Closed;

try
{

if (wasClosed) con.Open();

cmd = CommandDefnition(con, sql, parameters, commandType);
rowsAffected = cmd.ExecuteNonQuery();

if (parameters != null)
((IDynamicParameters)parameters).CallBack(cmd);
}
finally
{
if (wasClosed) con.Close();
if (cmd != null) cmd.Dispose();
}

return rowsAffected;
}

/// <summary>
/// Reads the data and returns in IDataReader object
/// </summary>
/// <param name="con">Connection object</param>
/// <param name="sql">sql staement</param>
/// <param name="readDataFunc">Action delegate to perform read operation for the reader</param>
/// <param name="parameters">parameters</param>
/// <param name="commandType">Command Type</param>
public static void ExecuteReader(this IDbConnection con, string sql, Action<DbDataReader> readDataFunc, DynamicParameters parameters = null, CommandType? commandType = null)
{
IDbCommand cmd = null;
var wasClosed = con.State == ConnectionState.Closed;

try
{
if (wasClosed) con.Open();

cmd = CommandDefnition(con, sql, parameters, commandType);
readDataFunc((DbDataReader)cmd.ExecuteReader());

if (parameters != null)
((IDynamicParameters)parameters).CallBack(cmd);
}
finally
{
if (wasClosed) con.Close();
if (cmd != null) cmd.Dispose();
}
}

/// <summary>
/// Fills Result in DataTable and returns it
/// Suited for only query with single resultset
/// </summary>
/// <param name="con">Connection object</param>
/// <param name="sql">sql staement</param>
/// <param name="parameters">parameters</param>
/// <param name="commandType">Command Type</param>
/// <returns>DataTable</returns>
public static DataTable FillDataTable(this IDbConnection con, string sql, DynamicParameters parameters = null, CommandType? commandType = null)
{
IDbCommand cmd = null;
var table = new DataTable();
var wasClosed = con.State == ConnectionState.Closed;

try
{
if (wasClosed) con.Open();

cmd = CommandDefnition(con, sql, parameters, commandType);
table.Load(cmd.ExecuteReader());

if (parameters != null)
((IDynamicParameters)parameters).CallBack(cmd);

return table;
}
finally
{
if (wasClosed) con.Close();
if (cmd != null) cmd.Dispose();
}
}

/// <summary>
/// Fills DataSet for the given Query
/// </summary>
/// <param name="con">Connection object</param>
/// <param name="sql">sql staement</param>
/// <param name="parameters">parameters</param>
/// <param name="commandType">Command Type</param>
/// <returns></returns>
public static DataSet FillDataSet(this IDbConnection con, string sql, DynamicParameters parameters = null, CommandType? commandType = null)
{
IDbCommand cmd = null;
var dataSet = new DataSet();
var wasClosed = con.State == ConnectionState.Closed;

try
{
if (wasClosed) con.Open();

var adapter = GetAdapter(con);
cmd = con.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
adapter.SelectCommand = cmd;
adapter.Fill(dataSet);

if (parameters != null)
((IDynamicParameters)parameters).CallBack(cmd);
}
finally
{
if (wasClosed) con.Close();
if (cmd != null) cmd.Dispose();
}
return dataSet;
}

/// <summary>
/// Executes Query and returns scalar value results
/// </summary>
/// <typeparam name="T">Type to cast</typeparam>
/// <param name="con">Connectoion object</param>
/// <param name="sql">Sql query</param>
/// <param name="parameters">Parameters</param>
/// <param name="commandType">CommandType</param>
/// <returns>Scalar Result Of type T</returns>
public static T ExecuteScalar<T>(this IDbConnection con, string sql, DynamicParameters parameters = null, CommandType? commandType = null)
{
IDbCommand cmd = null;
object result;
var wasClosed = con.State == ConnectionState.Closed;
try
{
if (wasClosed) con.Open();

cmd = CommandDefnition(con, sql, parameters, commandType);
result = cmd.ExecuteScalar();

if (parameters != null)
((IDynamicParameters)parameters).CallBack(cmd);
}
finally
{
if (wasClosed) con.Close();
if (cmd != null) cmd.Dispose();
}
return (T)(result);
}

/// <summary>
/// Creates a IDbCommand object for the connetcion with all necessary parameters to execute the query
/// </summary>
private static IDbCommand CommandDefnition(IDbConnection con, string sql, DynamicParameters parameters = null, CommandType? commandType = null)
{
var cmd = con.CreateCommand();
var cmdType = commandType ?? CommandType.Text;
cmd.CommandType = cmdType;
cmd.CommandText = sql;
if (parameters != null)
{
((IDynamicParameters)parameters).AddParameters(cmd);
}
return cmd;
}

/// Reference :- http://stackoverflow.com/questions/10723558/instantiate-idataadapter-from-instance-of-idbconnection
/// <summary>
/// Gets the instance of IDbDataAdapter from the connection
/// </summary>
private static IDbDataAdapter GetAdapter(IDbConnection con)
{
var assembly = con.GetType().Assembly;
var @namespace = con.GetType().Namespace;

// Assumes the factory is in the same namespace
var factoryType = assembly.GetTypes().Where(x => x.Namespace == @namespace).Single(x => x.IsSubclassOf(typeof(DbProviderFactory)));

// SqlClientFactory and OleDbFactory both have an Instance field.
var instanceFieldInfo = factoryType.GetField("Instance", BindingFlags.Static | BindingFlags.Public);

if (instanceFieldInfo == null) throw new Exception("Couldn't find the data provider.. Specify the correct one in the connection string");

var factory = (DbProviderFactory)instanceFieldInfo.GetValue(null);
return factory.CreateDataAdapter();
}
}
}
Loading

0 comments on commit bb67722

Please sign in to comment.