//using System; //using System.Collections.Generic; //using Microsoft.Data.SqlClient; //using System.Data; //using System.Linq; //using System.Text; //using System.Threading.Tasks; //using GB5Shared.DTO.Framework.ServerConfig; //using static GB5Shared.DTO.Framework.Enum.FrameworkEnumDTO; //using GB5Shared.DTO.Framework.CommonConfig; //using Microsoft.Extensions.Options; //using System.Text.RegularExpressions; //using System.Security.Cryptography; //using Org.BouncyCastle.Crypto.Modes; //using Org.BouncyCastle.Crypto.Parameters; //using Org.BouncyCastle.Crypto.Engines; //using System.Collections; //using GB5Shared.Query.FrameWork.DbConnection; //using Dapper; //using FrameworkDAL.CustomCode.HybridCache; //using System.Reflection.Metadata; //using GB5Shared.DTO.Framework.HybridCache; //using static GB5Shared.GB5Constant.Constant; ////using System.Linq.Dynamic.Core.Tokenizer; //using Microsoft.Extensions.Caching.Hybrid; //using GB5Shared.DTO.Framework.Login; //using GB5Shared.GB5Exception; //using System.Runtime.Serialization; //using IdentityModel.Client; //using GB5Shared.QueryExecutor; //using System.Diagnostics; //namespace FrameworkDAL.CustomCode.Connection //{ // public class ApplicationConnection : IApplicationConnection // { // private readonly IOptionsSnapshot _DataBaseDTO; // private readonly Microsoft.Extensions.Caching.Hybrid.HybridCache _cache; // // private readonly IQueryExecutor _queryExecutor; // public ApplicationConnection(IOptionsSnapshot DataBaseDTO , Microsoft.Extensions.Caching.Hybrid.HybridCache HybridCache) // { // _DataBaseDTO = DataBaseDTO; // _cache = HybridCache; // //_queryExecutor = queryExecutor; // } // public async Task DBConnectionStringCached(LoginDTO LoginDTO) // { // string DBConnectionstring =""; // try // { // string cacheKey = CacheKeyGenerator.KeyGeneration(-1, GB5Shared.GB5Constant.Constant.Entity.ServerConfig, CacheKeyLevel.DB_SERVER, LoginDTO.DatabaseName , LoginDTO, null); // return await _cache.GetOrCreateAsync(cacheKey, async (cancellationToken) => // { // DBConnectionstring = await FormConnectionString(LoginDTO.DatabaseName); // return DBConnectionstring; // }); // } // catch (Exception ) // { // throw ; // } // finally // { // } // } // public async Task DBConnectionStringCached(string ConnectionName) // { // try // { // return await FormConnectionString(ConnectionName); // } // catch (Exception) // { // throw; // } // } // public async Task DatabaseConnectionObject(string ConnectionName) // { // try // { // string GB5SystemConnectionString = Gb5SystemConnectionString(); // string ssql = ConnectionQueryBuilder.LOAD_DIFFERENT_DATABASE_NAME_FOR_PRODUCTION; // await using (SqlConnection connection = new(GB5SystemConnectionString)) // { // ServerConfigDTO? result = await connection.QueryFirstOrDefaultAsync(ssql, new { CONNECTIONNAME = ConnectionName }); // if (result == null) // { // throw new DataNotFoundException($"No server configuration found for connection name: {ConnectionName}"); // } // return result; // } // } // catch (SqlException sqlEx) // { // throw new DatabaseOperationException("Database query failed.", sqlEx); // } // catch (Exception ex) // { // throw new ApplicationException("An unexpected error occurred while retrieving server configuration.", ex); // } // //TempConnection = new SqlConnection(Connection); // // TempConnection.Open(); // // SqlCommand Ocommand = new SqlCommand(ssql, TempConnection); // // Datareader = Ocommand.ExecuteReader(); // //while (Datareader.Read()) // //{ // // ServerConfigDTO.ServerConfigId = (int)Datareader["SERVERCONFIGID"]; // // ServerConfigDTO.ServerId = (int)Datareader["SERVERID"]; // // ServerConfigDTO.ConnectionName = (string)Datareader["CONNECTIONNAME"]; // // ServerConfigDTO.ServerName = (string)Datareader["SERVERNAME"]; // // ServerConfigDTO.ServerIP = (string)Datareader["SERVERIP"]; // // ServerConfigDTO.DbType = (byte)Datareader["DATABASETYPE"]; // // ServerConfigDTO.DatabaseName = (string)Datareader["DATABASENAME"]; // // ServerConfigDTO.DatabaseUserId = (string)Datareader["DATABASEUSERNAME"]; // // ServerConfigDTO.DatabasePassword = DecryptPasswordHash((string)Datareader["DATABASEPASSWORD"], true); // // ServerConfigDTO.DatabasePort = (string)Datareader["DATABASEPORT"]; // // ServerConfigDTO.DbNaturte = (byte)Datareader["NATURE"]; // // ServerConfigDTO.SystemDataBaseConnectionName = (string)Datareader["SYSTEMDBCONNAME"]; // // ServerConfigDTO.ReferalDataBaseConnectionName = (string)Datareader["REFERALDBCONNAME"]; // // ServerConfigDTO.ArchivedDataBaseConnectionName = (string)Datareader["ARCHIVEDDBCONNAME"]; // // ServerConfigDTO.ClinetId = ((int)Datareader["CLIENTID"]); // // ServerConfigDTO.TypeOfDb = (byte)Datareader["DBSOURCETYPE"]; // // ServerConfigDTO.ClientsiteId = (int)Datareader["CLIENTSITEID"]; // // ServerConfigDTO.ServerMachineName = (string)Datareader["SERVERMACHINENAME"]; // // ServerConfigDTO.UniqueDetails = (string)Datareader["UNIQUEDETAILS"]; // // ServerConfigDTO.Offset = (int)Datareader["OFFSET"]; // // ServerConfigDTO.DbInstanceType = (byte)Datareader["DBINSTANCETYPE"]; // // ServerConfigDTO.ParentServerConfigId = (int)Datareader["PARENTSERVERCONFIGID"]; // // if (Datareader["PARENTSERVERCONFIGCONNECTIONNAME"] == DBNull.Value) // // { // // ServerConfigDTO.ParentServerConfigConnectionName = ""; // // } // // else // // { // // ServerConfigDTO.ParentServerConfigConnectionName = (string)Datareader["PARENTSERVERCONFIGCONNECTIONNAME"]; // // } // // if (Datareader["PARENTSERVERCONFIGDATABASENAME"] == DBNull.Value) // // { // // ServerConfigDTO.ParentServerConfigDatabaseName = ""; // // } // // else // // { // // ServerConfigDTO.ParentServerConfigDatabaseName = (string)Datareader["PARENTSERVERCONFIGDATABASENAME"]; // // } // //} // //if (TempConnection != null || TempConnection.State != ConnectionState.Closed) // //{ // // TempConnection.Close(); // // TempConnection.Dispose(); // //} // //if (Datareader != null) Datareader.Close(); Datareader.Dispose(); // // return ServerConfigDTO; // } // private string Gb5SystemConnectionString() // { // try // { // var databaseConfig = _DataBaseDTO.Value; // string Gb5System = databaseConfig.Gb5System; // Match match = Regex.Match(Gb5System, @"Password=([^;]+)"); // if (!match.Success) // { // throw new FormatException("Invalid connection string format. 'Password=' not found."); // } // string EncryptedPass = match.Groups[1].Value.Trim(); // string DecryptedPass = Decrypt(EncryptedPass, "GB5"); // string ConnectionString = Gb5System.Replace("Password=" + EncryptedPass, "Password=" + DecryptedPass) // + ";Encrypt=False;TrustServerCertificate=True"; // return ConnectionString; // } // catch (Exception) // { // throw; // } // } // //private string TestGb5SystemConnectionString() // //{ // // try // // { // // var databaseConfig = _DataBaseDTO.Value; // // string Gb5System = databaseConfig.Gb5System; // // Match match = Regex.Match(Gb5System, @"Password=([^;]+)"); // // if (!match.Success) // // { // // throw new FormatException("Invalid connection string format. 'Password=' not found."); // // } // // string EncryptedPass = match.Groups[1].Value.Trim(); // // string DecryptedPass = Decrypt(EncryptedPass, "GB5"); // // string ConnectionString = Gb5System.Replace("Password=" + EncryptedPass, "Password=" + DecryptedPass) // // + ";Encrypt=False;TrustServerCertificate=True"; // // return Gb5System; // // } // // catch (Exception) // // { // // throw; // // } // //} // public string DecryptPasswordHash(string CipherString, bool UseHashing) // { // try // { // byte[] keyArray; // byte[] toEncryptArray = Convert.FromBase64String(CipherString); // //System.Configuration.AppSettingsReader settingsReader = new System.Configuration.AppSettingsReader(); // string key = "Password"; // if (UseHashing) // { // SHA256 SHA256 = SHA256.Create(); // keyArray = SHA256.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); // SHA256.Clear(); // } // else // { // keyArray = UTF8Encoding.UTF8.GetBytes(key); // } // //TripleDESCryptoServiceProvider tdes = new(); // //tdes.Key = keyArray; // //tdes.Mode = CipherMode.ECB; // //tdes.Padding = PaddingMode.PKCS7; // Aes Aes = Aes.Create(); // Aes.Key = keyArray; // Aes.Mode = CipherMode.ECB; // Aes.Padding = PaddingMode.PKCS7; // ICryptoTransform cTransform = Aes.CreateDecryptor(); // byte[] resultArray = cTransform.TransformFinalBlock( // toEncryptArray, 0, toEncryptArray.Length); // Aes.Clear(); // return UTF8Encoding.UTF8.GetString(resultArray); // } // catch (Exception Error) // { // throw Error; // } // } // public static string Encrypt(string plaintext, string key) // { // if (string.IsNullOrEmpty(key)) // { // throw new ArgumentException("Key cannot be null or empty."); // } // // Derive a 32-byte key from the string using SHA-256 // using SHA256 sha256 = SHA256.Create(); // byte[] keyBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); // // Generate a 12-byte IV (nonce) for AES-GCM // byte[] iv = new byte[12]; // using (var rng = RandomNumberGenerator.Create()) // { // rng.GetBytes(iv); // } // byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); // byte[] ciphertext = new byte[plaintextBytes.Length + 16]; // Extra 16 bytes for authentication tag // // Encrypt using BouncyCastle AES-GCM // GcmBlockCipher cipher = new(new AesEngine()); // AeadParameters parameters = new(new KeyParameter(keyBytes), 128, iv); // cipher.Init(true, parameters); // int len = cipher.ProcessBytes(plaintextBytes, 0, plaintextBytes.Length, ciphertext, 0); // cipher.DoFinal(ciphertext, len); // DoFinal() already includes the authentication tag // // Concatenate IV + ciphertext (which includes the tag) // byte[] result = new byte[iv.Length + ciphertext.Length]; // Buffer.BlockCopy(iv, 0, result, 0, iv.Length); // Buffer.BlockCopy(ciphertext, 0, result, iv.Length, ciphertext.Length); // return Convert.ToBase64String(result); // } // public static string Decrypt(string encryptedText, string key) // { // if (string.IsNullOrEmpty(key)) // { // throw new ArgumentException("Key cannot be null or empty."); // } // byte[] encryptedBytes = Convert.FromBase64String(encryptedText); // using SHA256 sha256 = SHA256.Create(); // byte[] keyBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); // // Extract IV and ciphertext // byte[] iv = new byte[12]; // byte[] ciphertext = new byte[encryptedBytes.Length - iv.Length]; // Buffer.BlockCopy(encryptedBytes, 0, iv, 0, iv.Length); // Buffer.BlockCopy(encryptedBytes, iv.Length, ciphertext, 0, ciphertext.Length); // // Decrypt using BouncyCastle AES-GCM // GcmBlockCipher cipher = new(new AesEngine()); // AeadParameters parameters = new(new KeyParameter(keyBytes), 128, iv); // cipher.Init(false, parameters); // byte[] decryptedBytes = new byte[ciphertext.Length - 16]; // Remove the 16-byte authentication tag // int len = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, decryptedBytes, 0); // cipher.DoFinal(decryptedBytes, len); // return Encoding.UTF8.GetString(decryptedBytes); // } // private async Task FormConnectionString(string ConnectionName) // { // ServerConfigDTO ServerConfigDTO = new(); // try // { // ServerConfigDTO = await DatabaseConnectionObject(ConnectionName); // string ConnectionString = ""; // if (ServerConfigDTO.DbType == DBType.SQL) // { // ConnectionString = "Data Source=" + ServerConfigDTO.ServerIP + ";" + "Initial Catalog=" + ServerConfigDTO.DatabaseName + ";" + "User Id=" + ServerConfigDTO.DatabaseUserName // + ";" + "Password=" + Decrypt(ServerConfigDTO.DatabasePassword, "GB5") + ";" // + "Pooling = true;Connection Timeout=120;Max Pool Size=250 ;Connection Lifetime=20" // + ";Encrypt=False;TrustServerCertificate=True"; //--MultipleActiveResultSets This is required for // } // else if (ServerConfigDTO.DbType == DBType.Oracle) // { // // ConnectionString = "Data Source = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST =" + ServerIP + ")(PORT = " + Port + "))(CONNECT_DATA = (SERVICE_NAME = " + ServerName + "))); User Id =" + DbUserName + "; Password =" + DbPassword + ""; // } // else if (ServerConfigDTO.DbType == DBType.PostGre) // { // // ConnectionString = "Server=" + ServerIP + ";" + "Database=" + DataBaseName + ";" + "Port=" + Port + ";" + "User Id=" + DbUserName + ";" + "Password=" + DbPassword + ";CommandTimeout=5000;Pooling=false;MaxPoolSize=100;ConnectionLifeTime=0"; // } // else if (ServerConfigDTO.DbType == DBType.MySQL) // { // // ConnectionString = "Server=" + ServerIP + ";" + "Port=" + Port + ";" + "Database=" + DataBaseName + ";" + "User Id=" + DbUserName + ";" + "Password=" + DbPassword + ";" + "CharSet=latin1"; // } // return ConnectionString; // } // catch (Exception ) // { // throw ; // } // } // //public async Task DatabaseOffset(LoginDTO LoginDTO, byte DatabaseType) // //{ // // try // // { // // int DatabaseOffset = 0; // // string Sql = ""; // // if (DatabaseType == DBType.SQL) // // { // // Sql = "SELECT DATEPART(TZ,SYSDATETIMEOFFSET()) as Dboffset"; // // DatabaseOffset = await _queryExecutor.QuerySingleAsync( // // LoginDTO, // // Sql, // // null // // ); // // } // // else if (DatabaseType == DBType.Oracle) // // { // // Sql = "SELECT TZ_OFFSET(sessiontimezone) FROM DUAL"; // // DatabaseOffset = await _queryExecutor.QuerySingleAsync( // // LoginDTO, // // Sql, // // null // // ); // // string TempOffset = Convert.ToString(DatabaseOffset).Trim(); // // int Final = 0; // // negative // // string[] Split1 = TempOffset.Split(':'); // // if (Convert.ToInt32(Split1[0]) * 60 > 0) // // { // // Final = Convert.ToInt32(Split1[0]) * 60 + Convert.ToInt32(Split1[1]); // // } // // else if (Convert.ToInt32(Split1[0]) * 60 < 0) // // { // // Final = Convert.ToInt32(Split1[0]) * 60 - Convert.ToInt32(Split1[1]); // // } // // else // // { // // Final = Convert.ToInt32(Split1[1]); // // } // // DatabaseOffset = Final; // // } // // else if (DatabaseType == DBType.PostGre) // // { // // Sql = "SELECT EXTRACT(TIMEZONE FROM now()) FROM now()"; // // DatabaseOffset = await _queryExecutor.QuerySingleAsync( // // LoginDTO, // // Sql, // // null // // ); // // object TempOffset = tempvalue[0]; // // int Offset = Convert.ToInt32(TempOffset); // // DatabaseOffset = DatabaseOffset / 60; // // } // // else if (DatabaseType == 3)//MySql // // { // // } // // return DatabaseOffset; // // } // // catch (Exception) // // { // // throw; // // } // //} // } //}