common/Logic/ServiceCore/SqlDataAccess.cs
2026-04-23 17:50:07 +02:00

304 lines
10 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;
namespace Xylem.Common.Logic.ServiceCore
{
public class SqlDataAccess : IDisposable
{
private readonly String _connectionString;
public SqlDataAccess(String connectionString)
{
_connectionString = connectionString;
}
public String GenerateParam<T>(String name, String typeName,T value)
{
var sb = new StringBuilder();
sb.AppendLine($"Declare @{name} as {typeName}" );
if (value is String)
{
sb.AppendLine($"set @{name} = '%{value.ToString()}%' ");
return sb.ToString();
}
sb.AppendLine($"set @{name} = ");
if (value == null)
{
sb.Append(" null ");
return sb.ToString();
}
if (value is Int32)
{
var tmp = Convert.ToInt32(value);
sb.Append(tmp.ToString());
}
if (value is Boolean)
{
var tmp = Convert.ToBoolean(value);
sb.Append(tmp ? "1" : "0");
}
return sb.ToString();
}
private SqlConnection _con;
/// <summary>
/// Creating a database connection if there is none.
/// </summary>
/// <remarks>Working with a global connection variable to make sure the connection would be closed at the end of working with it.</remarks>
// ReSharper disable once UnusedMember.Local
private void CreateConnection()
{
if (_con == null)
{
_con = new SqlConnection(_connectionString);
}
if (_con != null && _con.State == ConnectionState.Closed)
{
_con.Open();
}
}
public DataTable ExecuteQuery(String sqlStatement, List<SqlParameter> parameter = null)
{
DataTable ret;
SqlConnection connection = null;
SqlDataReader reader = null;
try
{
connection = new SqlConnection(_connectionString);
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
var cmd = connection.CreateCommand();
cmd.CommandTimeout = 120;
cmd.CommandText = sqlStatement;
if (parameter != null)
{
foreach (var item in parameter)
{
cmd.Parameters.Add(item);
}
}
reader = cmd.ExecuteReader();
var entries = new Object[reader.FieldCount];
ret = new DataTable();
var jcount = 0;
try
{
while (reader.Read())
{
if (jcount == 0)
{
for (var i = 0; i < reader.FieldCount; i++)
{
var headline = reader.GetName(i);
if (!ret.Columns.Contains(headline))
{
ret.Columns.Add(headline, Type.GetType("System.Object") ?? typeof(String));
}
else
{
ret.Columns.Add(headline + Guid.NewGuid(), Type.GetType("System.Object") ?? typeof(String));
}
}
}
for (var i = 0; i < reader.FieldCount; i++)
{
entries[i] = reader[i];
}
jcount++;
ret.Rows.Add(entries);
}
}
catch (Exception ex)
{
throw (new Exception(ex.Message, ex));
}
}
catch (Exception ex)
{
throw (new Exception(ex.Message, ex));
}
finally
{
try
{
if (reader != null)
{
try
{
reader.Dispose();
}
catch
{
// ignored
}
}
if (connection != null && connection.State == ConnectionState.Open)
{
connection.Close();
}
}
catch (Exception ex) { throw (new Exception("Unhandled exception within finally: " + ex.Message)); }
}
return ret;
}
/// <summary>
/// Closing and disposing the connection.
/// </summary>
private void CloseConnection()
{
if (_con != null)
{
if (_con.State != ConnectionState.Closed)
{
_con.Close();
}
_con.Dispose();
}
}
/// <summary>
/// Generating a list of comma seperated parameters by a given string array.
/// </summary>
/// <param name="parameter">array to work on</param>
/// <returns>comma seperated string with parameters.</returns>
// ReSharper disable once UnusedMember.Local
private String GenerateParameter(String[] parameter)
{
var list = new StringBuilder();
var ret = "";
var first = true;
foreach (var param in parameter)
{
if (list.ToString().Length > 0)
{
list.Append(",");
}
var result = param;
var content = param;
const String mitpat = @"(?:^@\w[\w_\s]*=[\s]*(?:'(.*)'$|(.*)$)|^(?:'(.*)'$|(.*)$))";
const String numbpat = @"^[+-]?(?:\d+\.?|,?\d*|\d*(\.?|,?)\d+)[\r\n]*$";
if (!first || !result.Contains(","))
{
first = false;
var mtch = Regex.Match(content, mitpat);
if (mtch.Groups[1].Success)
{
var orig = mtch.Groups[1].Value;
var mch = Regex.Replace(orig, "[']+", "'");
mch = Regex.Replace(mch, "[']+", "''");
result = !string.IsNullOrEmpty(mch) ? content.Replace(orig, mch) : content;
}
else if (mtch.Groups[2].Success)
{
var orig = mtch.Groups[2].Value;
var mch = Regex.Replace(orig, "[']+", "'");
mch = Regex.Replace(mch, "[']+", "''");
if (!string.IsNullOrEmpty(mch))
{
if (Regex.IsMatch(mch, numbpat) || mch.ToLower() == "null")
{
result = content;
}
else
{
result = content.Replace(orig, "'" + mch + "'");
}
}
else
{
result = content;
}
}
else if (mtch.Groups[3].Success)
{
var orig = mtch.Groups[3].Value;
var mch = Regex.Replace(orig, "[']+", "'");
mch = Regex.Replace(mch, "[']+", "''");
result = !string.IsNullOrEmpty(mch) ? content.Replace(orig, mch) : content;
}
else if (mtch.Groups[4].Success)
{
var orig = mtch.Groups[4].Value;
var mch = Regex.Replace(orig, "[']+", "'");
mch = Regex.Replace(mch, "[']+", "''");
if (!string.IsNullOrEmpty(mch))
{
if (Regex.IsMatch(mch, numbpat) || mch.ToLower() == "null")
{
result = content;
}
else
{
result = content.Replace(orig, "'" + mch + "'");
}
}
else
{
result = content;
}
}
}
list.Append(result);
}
if (list.ToString().Length > 0)
{
ret = " " + list;
}
return ret;
}
public String GetConnectionString()
{
//if (_conifg.SupportConnectionString)
//{
return _connectionString;
//}
//else
//{
//StringBuilder ret = new StringBuilder();
//ret.Append("Data Source=").Append(_conifg.ReadFromConfig("Data Source", "Connection"));
//ret.Append(";Initial Catalog=").Append(_conifg.ReadFromConfig("Initial Catalog", "Connection"));
//ret.Append(";User id=").Append(_conifg.ReadFromConfig("User id", "Connection"));
//ret.Append(";Password=").Append(_conifg.ReadFromConfig("Password", "Connection"));
//return ret.ToString();
//}
}
public void Dispose()
{
CloseConnection();
GC.SuppressFinalize(this);
}
}
}