namespace Kit.Helpers.MsSql
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
public class OutPutValue
{
public object Value;
}
public static class SqlServerHelper
{
///
/// Проверка на наличие столбца в запросе
///
///
///
///
public static bool HasColumn(this IDataReader reader, string name)
{
string nameLow = name.ToLower();
for (int n = 0; n < reader.FieldCount; n++)
{
if (reader.GetName(n).ToLower() == nameLow) return true;
}
return false;
}
public static SqlCommand CreateCommand(this string connectionString, string sql, IEnumerable> parameters = null)
{
if (string.IsNullOrWhiteSpace(connectionString)) throw new ArgumentNullException("connectionString");
if (string.IsNullOrWhiteSpace(sql)) throw new ArgumentNullException("sql");
SqlCommand command = new SqlConnection(connectionString).CreateCommand();
command.CommandTimeout = 60 * 60 * 60;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = sql;
if (parameters != null && parameters.Any())
{
parameters.ToList().ForEach(
x => { command.Parameters.AddWithValue(x.Key, x.Value ?? DBNull.Value); }
);
}
return command;
}
public static SqlCommand CreateCommandWithOutput(this string connectionString, string sql, IEnumerable> parameters = null)
{
if (string.IsNullOrWhiteSpace(connectionString)) throw new ArgumentNullException("connectionString");
if (string.IsNullOrWhiteSpace(sql)) throw new ArgumentNullException("sql");
SqlCommand command = new SqlConnection(connectionString).CreateCommand();
command.CommandTimeout = 60 * 60 * 60;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = sql;
if (parameters != null && parameters.Any())
{
parameters.ToList().ForEach(
x =>
{
object value = x.Value;
bool isOutPut = false;
if (x.Value is OutPutValue)
{
value = ((OutPutValue)x.Value).Value;
isOutPut = true;
}
var parameter = command.Parameters.AddWithValue(x.Key, value ?? DBNull.Value);
if (isOutPut)
{
parameter.Direction = ParameterDirection.Output;
}
}
);
}
return command;
}
public static SqlCommand CreateCommand(this string connectionString, string sql, bool isStoredProcedure = false, IEnumerable> parameters = null)
{
// if (connectionString.IsNullOrEmpty()) throw new ArgumentNullException("connectionString");
// if (sql.IsNullOrEmpty()) throw new ArgumentNullException("sql");
var sqlConnection = new SqlConnection(connectionString);
SqlCommand command = sqlConnection.CreateCommand();
command.CommandTimeout = sqlConnection.ConnectionTimeout;
if (isStoredProcedure)
{
command.CommandType = System.Data.CommandType.StoredProcedure;
}
else
{
command.CommandType = System.Data.CommandType.Text;
}
command.CommandText = sql;
if (parameters != null && parameters.Any())
{
foreach (var keyValuePair in parameters)
{
SqlParameter addedParameter = command.Parameters.AddWithValue(keyValuePair.Key, keyValuePair.Value ?? DBNull.Value);
if (keyValuePair.Value is DataTable) addedParameter.SqlDbType = SqlDbType.Structured;
}
}
return command;
}
public static void ExecuteNonQuery(this string connectionString, string sql, IEnumerable> parameters = null)
{
SqlCommand command = connectionString.CreateCommand(sql, parameters);
using (command.Connection)
{
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
}
public static void ExecuteNonQuery(this string connectionString, string sql, bool isStoredProcedure = false, IEnumerable> parameters = null)
{
SqlCommand command = connectionString.CreateCommand(sql, isStoredProcedure, parameters);
using (command.Connection)
{
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
}
public static object ExecuteScalar(this string connectionString, string sql, IEnumerable> parameters = null)
{
object returnScalar;
SqlCommand command = connectionString.CreateCommand(sql, parameters);
using (command.Connection)
{
command.Connection.Open();
returnScalar = command.ExecuteScalar();
command.Connection.Close();
}
return returnScalar;
}
public static IEnumerable> ExecuteOutputParameters(this string connectionString, string sql, IEnumerable> parameters = null)
{
List> result = new List>();
SqlCommand command = connectionString.CreateCommandWithOutput(sql, parameters);
using (command.Connection)
{
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
foreach(SqlParameter parameter in command.Parameters)
{
if(parameter.Direction == ParameterDirection.Output)
{
result.Add(new KeyValuePair(parameter.ParameterName, parameter.Value));
}
}
}
return result;
}
public static TResult ExecuteScalar(this string connectionString, string sql, bool isStoredProcedure = false, IEnumerable> parameters = null)
{
object returnScalar;
SqlCommand command = connectionString.CreateCommand(sql, isStoredProcedure, parameters);
using (command.Connection)
{
command.Connection.Open();
returnScalar = command.ExecuteScalar();
command.Connection.Close();
}
return (TResult)returnScalar;
}
public static IEnumerable ExecuteSelect(this string connectionString, string sql, Func converter, IEnumerable> parameters = null)
{
if (converter == null) throw new ArgumentNullException("converter");
SqlCommand command = connectionString.CreateCommand(sql, parameters);
using (command.Connection)
{
command.Connection.Open();
using (IDataReader reader = command.ExecuteReader())
{
IList selectResult = new List();
while (reader.Read())
{
selectResult.Add(converter(reader));
}
return selectResult;
}
}
}
public static IEnumerable ExecuteSelect(this string connectionString, Func converter, string sql, bool isStoredProcedure = false, IEnumerable> parameters = null)
{
if (converter == null) throw new ArgumentNullException("converter");
SqlCommand command = connectionString.CreateCommand(sql, isStoredProcedure, parameters);
command.CommandTimeout = command.Connection.ConnectionTimeout;
using (command.Connection)
{
command.Connection.Open();
using (IDataReader reader = command.ExecuteReader())
{
IList selectResult = new List();
while (reader.Read())
{
selectResult.Add(converter(reader));
}
return selectResult;
}
}
}
public static DataTable ExecuteDataTable(this string connectionString, string sql, IEnumerable> parameters = null)
{
SqlCommand command = connectionString.CreateCommand(sql, parameters);
using (command.Connection)
{
command.Connection.Open();
using (var adapter = new SqlDataAdapter(command))
{
var table = new DataTable();
adapter.Fill(table);
return table;
}
}
}
public static DataTable ExecuteDataTable(this string connectionString, string sql, bool isStoredProcedure = false, IEnumerable> parameters = null)
{
SqlCommand command = connectionString.CreateCommand(sql, isStoredProcedure, parameters);
using (command.Connection)
{
command.Connection.Open();
using (var adapter = new SqlDataAdapter(command))
{
var table = new DataTable();
adapter.Fill(table);
return table;
}
}
}
public static TValue Get(this IDataRecord record, string fieldName)
{
try
{
//if ((record[fieldName] == DBNull.Value) && (typeof(TValue) == typeof(object)) ) return (TValue)null;
return (TValue)record[fieldName];
}
catch (InvalidCastException ex)
{
throw new InvalidCastException(string.Format("{2} {0} нельзя привести к {1}", record[fieldName].GetType().FullName, typeof(TValue).FullName, fieldName), ex);
}
}
public static Decimal GetDecimalX(this IDataRecord record, string fieldName)
{
Decimal rret = 0;
if (record[fieldName] != DBNull.Value)
{
if (record[fieldName].GetType().Name == "Int32")
{
rret = Convert.ToDecimal(record[fieldName]);
}
else
{
rret = record.Get (fieldName);
}
}
return rret;
}
public static string CreateParameterListString(this IEnumerable> parameters)
{
return string.Join(", ", parameters.Select(x => x.Key).ToArray());
}
public static TValue GetN(this IDataRecord record, string fieldName)
{
return record[fieldName] != DBNull.Value ? record.Get(fieldName) : default(TValue);
}
public static IEnumerable ExecuteSelectMany(this string connectionString, string sql,
bool isStoredProcedure = false, IEnumerable> parameters = null,
params Action>[] converters)
{
if (converters == null) throw new ArgumentNullException("converters");
SqlCommand command = connectionString.CreateCommand(sql, isStoredProcedure, parameters);
command.CommandTimeout = command.Connection.ConnectionTimeout;
using (command.Connection)
{
command.Connection.Open();
using (IDataReader reader = command.ExecuteReader())
{
IList selectResult = new List();
foreach (var converter in converters)
{
while (reader.Read())
{
converter(reader, selectResult);
}
reader.NextResult();
}
return selectResult;
}
}
}
public static IEnumerableWithPage ExecuteSelectManyWithPage(
this string connectionString,
string sql,
bool isStoredProcedure = false,
IEnumerable> parameters = null,
params Action>[] converters
)
{
if (converters == null) throw new ArgumentNullException("converters");
SqlCommand command = connectionString.CreateCommand(sql, isStoredProcedure, parameters);
command.CommandTimeout = command.Connection.ConnectionTimeout;
using (command.Connection)
{
command.Connection.Open();
using (IDataReader reader = command.ExecuteReader())
{
var result = new ListWithPage();
foreach (var converter in converters)
{
while (reader.Read())
{
converter(reader, result);
}
reader.NextResult();
}
// считывание данных постраничного вывода
while (reader.Read())
{
if (reader.HasColumn("TotalRows")) result.TotalRows = reader.Get("TotalRows");
if (reader.HasColumn("PageNo")) result.PageNo = reader.Get("PageNo");
if (reader.HasColumn("PageSize")) result.PageSize = reader.Get("PageSize");
if (reader.HasColumn("Sort")) result.Sort = reader.Get("Sort");
}
return result;
}
}
}
public static IEnumerableWithOffer ExecuteSelectManyWithOffer(
this string connectionString,
string sql,
bool isStoredProcedure = false,
IEnumerable> parameters = null,
params Action>[] converters
)
{
if (converters == null) throw new ArgumentNullException("converters");
SqlCommand command = connectionString.CreateCommand(sql, isStoredProcedure, parameters);
command.CommandTimeout = command.Connection.ConnectionTimeout;
using (command.Connection)
{
command.Connection.Open();
using (IDataReader reader = command.ExecuteReader())
{
var result = new ListWithOffer();
foreach (var converter in converters)
{
while (reader.Read())
{
converter(reader, result);
}
reader.NextResult();
}
// считывание данных постраничного вывода
while (reader.Read())
{
if (reader.HasColumn("TotalRows")) result.TotalRows = reader.Get("TotalRows");
if (reader.HasColumn("PageNo")) result.Start = reader.Get("Start");
if (reader.HasColumn("PageSize")) result.Lenght = reader.Get("Length");
if (reader.HasColumn("Sort")) result.Sort = reader.Get("Sort");
}
return result;
}
}
}
#region Add -----------------------------------------------------------
#endregion
}
}