Wolfgang Hottgenroth 9163b1848c fixes
2021-12-13 18:01:06 +01:00

173 lines
8.1 KiB
C#

#pragma warning disable 1591
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json;
// make sure to adjust the prefix with the PACKAGE_NAME from ENV
using com.krohne.genericdatabaseapiservice.Models;
// make sure to adjust the prefix with the PACKAGE_NAME from ENV
namespace com.krohne.genericdatabaseapiservice.Services {
public class DbInfoObject {
public DbInfoObject(string host, string user, string password, string name) {
Host = host;
User = user;
Password = password;
Name = name;
}
public string Host { get; set; }
public string User { get; set; }
public string Password { get; set; }
public string Name { get; set; }
}
public class DbInfoServiceException : Exception {}
public class UnknownDatabaseTagException: DbInfoServiceException {}
public interface IDbInfoService {
DbInfoObject GetInfoByTag(string tag);
string GetInfoStringByTag(string tag);
}
public class DbInfoService : IDbInfoService {
private readonly IConfiguration Configuration;
private readonly ILogger<DbInfoService> Logger;
private Dictionary<string, DbInfoObject> DbInfos;
public DbInfoService(IConfiguration configuration, ILogger<DbInfoService> logger) {
Configuration = configuration;
Logger = logger;
Console.WriteLine("Database Infofile: {0}", Configuration["Database:InfoFile"]);
DbInfos = JsonConvert.DeserializeObject<Dictionary<string, DbInfoObject>>(File.ReadAllText(Configuration["Database:InfoFile"]));
}
public DbInfoObject GetInfoByTag(string tag) {
try {
return DbInfos[tag];
} catch (KeyNotFoundException) {
throw new UnknownDatabaseTagException();
}
}
public string GetInfoStringByTag(string tag) {
return String.Format(
"Server={0};User ID={1};Password={2};Database={3}",
GetInfoByTag(tag).Host,
GetInfoByTag(tag).User,
GetInfoByTag(tag).Password,
GetInfoByTag(tag).Name);
}
}
public interface IDbService {
Task<List<TOUT>> ReadBySelect<TIN, TOUT>(string databaseTag, string selectStatement, bool justOne, TIN input);
}
public class DbServiceException : Exception {}
public class NoDataFoundException : DbServiceException {}
public class TooMuchDataFoundException : DbServiceException {}
public class UnsupportedDataTypeException: DbServiceException {}
public class DbService : IDbService {
private readonly IConfiguration Configuration;
private readonly ILogger<DbService> Logger;
private readonly IDbInfoService DbInfoService;
public DbService(IConfiguration configuration, ILogger<DbService> logger, IDbInfoService dbInfoService) {
Configuration = configuration;
Logger = logger;
DbInfoService = dbInfoService;
}
async public Task<List<TOUT>> ReadBySelect<TIN, TOUT>(string databaseTag, string selectStatement, bool justOne, TIN input) {
var itemList = new List<TOUT>();
var databaseConnInfo = DbInfoService.GetInfoStringByTag(databaseTag);
Logger.LogInformation("ConnInfo: {0}", databaseConnInfo);
Logger.LogInformation("Statement: {0}", selectStatement);
using (var conn = new MySqlConnection(databaseConnInfo)) {
await conn.OpenAsync();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = selectStatement;
if (input != null){
foreach (var propertyInfo in typeof(TIN).GetProperties()) {
Logger.LogInformation("Input Property name: {0} {1} ", propertyInfo.Name, propertyInfo.PropertyType);
var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), true);
var dma = (DataMemberAttribute)attributes[0];
Logger.LogInformation("Input DataMember name: {0} {1} ", dma.Name, dma.TypeId);
var value = propertyInfo.GetValue(input);
Logger.LogInformation("Input Value: {0}", value);
cmd.Parameters.AddWithValue(dma.Name, propertyInfo.GetValue(input));
}
} else {
Logger.LogInformation("no input data");
}
using (var reader = await cmd.ExecuteReaderAsync()) {
while (await reader.ReadAsync()) {
var item = Activator.CreateInstance<TOUT>();
foreach (var propertyInfo in typeof(TOUT).GetProperties()) {
Logger.LogInformation("Output Property name: {0} {1} ", propertyInfo.Name, propertyInfo.PropertyType);
var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), true);
var dma = (DataMemberAttribute)attributes[0];
int ordinal = reader.GetOrdinal(dma.Name);
Logger.LogInformation("Output DataMember name: {0} {1} {2} ", dma.Name, dma.TypeId, ordinal);
if (await reader.IsDBNullAsync(ordinal)) {
propertyInfo.SetValue(item, null);
Logger.LogInformation("Output Value: null");
} else if (propertyInfo.PropertyType == typeof(System.String)) {
var value = reader.GetString(ordinal);
propertyInfo.SetValue(item, value);
Logger.LogInformation("Output Value:{0}", value);
} else if (propertyInfo.PropertyType == typeof(System.Int32) ||
propertyInfo.PropertyType == typeof(System.Nullable<System.Int32>)) {
var value = reader.GetInt32(ordinal);
propertyInfo.SetValue(item, value);
Logger.LogInformation("Output Value:{0}", (System.Int32)value);
} else if (propertyInfo.PropertyType == typeof(System.DateTime)) {
var value = reader.GetDateTime(ordinal);
propertyInfo.SetValue(item, value);
Logger.LogInformation("Output Value:{0}", value);
} else if (propertyInfo.PropertyType == typeof(System.Boolean) ||
propertyInfo.PropertyType == typeof(System.Nullable<System.Boolean>)) {
var value = reader.GetBoolean(ordinal);
propertyInfo.SetValue(item, value);
Logger.LogInformation("Output Value:{0}", value);
} else {
throw new UnsupportedDataTypeException();
}
}
itemList.Add(item);
Logger.LogInformation("Item is {0}", item);
}
}
}
}
if (itemList.Count == 0) {
Logger.LogWarning("no data found");
throw new NoDataFoundException();
}
if (justOne && itemList.Count > 1) {
Logger.LogWarning("too much data found");
throw new TooMuchDataFoundException();
}
return itemList;
}
}
}
#pragma warning restore 1591