using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PRSDesktop; public abstract class MicrosoftSQLClient : IDisposable { private SqlConnection? connection; protected abstract string GetConnectionString(); public bool Connect() { connection = new SqlConnection(GetConnectionString()); try { connection.Open(); } catch (Exception e) { connection = null; } return IsConnected; } public bool IsConnected => connection != null; public void Disconnect() { if (connection != null) { connection.Dispose(); connection = null; } } public DataTable Query(string sql, string tablename, SqlParameter[]? parameters = null) { var result = new DataTable(tablename); if (connection != null) { using (var _command = new SqlCommand(sql.Replace("\r\n"," ").Replace("\n"," ").Replace("\r"," "), connection)) { if (parameters is not null) { foreach (var _parameter in parameters) _command.Parameters.Add(_parameter); } using var _adapter = new SqlDataAdapter(_command); _adapter.Fill(result); } connection.Close(); } return result; } public int ExecuteSQL(string sql, SqlParameter[]? parameters = null) { int result = 0; if(connection != null) { using(var command = new SqlCommand(sql.Replace("\r\n"," ").Replace("\n", " ").Replace("\r"," "), connection)) { if (parameters is not null) { foreach (var _parameter in parameters) command.Parameters.Add(_parameter); } result = command.ExecuteNonQuery(); } connection.Close(); } return result; } public static int GetInteger(DataRow row, string field, int defaultvalue = 0) { return row[field] == DBNull.Value ? 0 : Convert.ToInt32(row[field]); } public static double GetDouble(DataRow row, string field, double defaultvalue = 0.0) { return row[field] == DBNull.Value ? 0.0 : Convert.ToDouble(row[field]); } public static string GetString(DataRow row, string field, string defaultvalue = "") { return row[field] == DBNull.Value ? "" : row[field] as string ?? defaultvalue; } public static byte[] GetBinary(DataRow row, string field) { return row[field] == DBNull.Value ? [] : (byte[])row[field]; } public void Dispose() { Disconnect(); } }