using Microsoft.Data.SqlClient; namespace XmlTool { public sealed class ImporterConfig { public string ConfigPath { get; init; } = string.Empty; public string ConnectionString { get; init; } = string.Empty; public string XmlRootPath { get; init; } = string.Empty; } public static class DatabaseHelper { private const string ConfigFileName = "config.txt"; public static string GetConfigPath() { return Path.Combine(AppContext.BaseDirectory, ConfigFileName); } public static ImporterConfig LoadConfig() { string configPath = GetConfigPath(); if (!File.Exists(configPath)) { throw new FileNotFoundException( $"config.txt file not found in runtime folder.\nExpected path:\n{configPath}", configPath); } string? connectionString = null; string? xmlRootPath = null; foreach (string rawLine in File.ReadAllLines(configPath)) { string line = rawLine.Trim(); if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#") || line.StartsWith("//")) { continue; } int separatorIndex = line.IndexOf('='); if (separatorIndex > 0) { string key = line[..separatorIndex].Trim(); string value = line[(separatorIndex + 1)..].Trim(); if (key.Equals("XML Path", StringComparison.OrdinalIgnoreCase) || key.Equals("XMLPath", StringComparison.OrdinalIgnoreCase)) { xmlRootPath = value; continue; } if (key.Equals("ConnectionString", StringComparison.OrdinalIgnoreCase)) { connectionString = value; continue; } } if (connectionString == null) { connectionString = line; } } if (string.IsNullOrWhiteSpace(connectionString)) { throw new InvalidOperationException( "config.txt does not contain a valid database connection string.\n" + "Add either a raw connection string on the first line or use ConnectionString=..."); } if (string.IsNullOrWhiteSpace(xmlRootPath)) { throw new InvalidOperationException( "config.txt does not contain 'XML Path='.\n" + "Example:\nXML Path=C:\\GDMO\\BDMO\\DProject_vs2022\\Tool\\BinXmlConverter2\\bin\\Debug\\net8.0-windows\\XML"); } if (!Directory.Exists(xmlRootPath)) { throw new DirectoryNotFoundException( $"Configured XML Path does not exist:\n{xmlRootPath}"); } return new ImporterConfig { ConfigPath = configPath, ConnectionString = connectionString, XmlRootPath = xmlRootPath }; } public static bool TestConnection(out string message) { try { ImporterConfig config = LoadConfig(); using SqlConnection conn = new(config.ConnectionString); conn.Open(); message = "Database connection successful!\n\n" + $"Config: {config.ConfigPath}\n" + $"XML Path: {config.XmlRootPath}"; return true; } catch (Exception ex) { message = "Database connection failed:\n\n" + ex.Message; return false; } } } }