MPSTI.PlenoSoft.Core.DbConfigurations 1.0.0.9

dotnet add package MPSTI.PlenoSoft.Core.DbConfigurations --version 1.0.0.9
NuGet\Install-Package MPSTI.PlenoSoft.Core.DbConfigurations -Version 1.0.0.9
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MPSTI.PlenoSoft.Core.DbConfigurations" Version="1.0.0.9" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MPSTI.PlenoSoft.Core.DbConfigurations --version 1.0.0.9
#r "nuget: MPSTI.PlenoSoft.Core.DbConfigurations, 1.0.0.9"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install MPSTI.PlenoSoft.Core.DbConfigurations as a Cake Addin
#addin nuget:?package=MPSTI.PlenoSoft.Core.DbConfigurations&version=1.0.0.9

// Install MPSTI.PlenoSoft.Core.DbConfigurations as a Cake Tool
#tool nuget:?package=MPSTI.PlenoSoft.Core.DbConfigurations&version=1.0.0.9

MPSTI.PlenoSoft.Core.DbConfigurations

Este pacote permite que você use a estrutura de configuração do .net (IConfiguration), com informações providas por um banco de dados relacional (SQL), de forma que as configurações podem facilmente ser alteradas de forma dinâmica diretamente no seu banco de dados, sem a necessidadade de alterar o arquivo appsettings.json, evitando acesso aos servidores e ao deploy da aplicação.

Getting started

Para usar este pacote, você precisará de 2 arquivos no seu projeto:

  1. appsettings.json / local.settings.json
    • Terá as configurações das strings de conexão com o seu banco de dados;
  2. Program.cs
    • Onde o Configuration builder será criado e configurado;

Prerequisites

  • .net >= 6;
  • VS 2023 community (ou +);
  • String de Conexão com algum Banco de Dados relacional com acesso somente leitura (não há necessidade de escrita);
    • No banco de dados, é necessário uma tabela para armazenar as configurações (ex.: Config, Configuração, Configuration);
    • Na tabela, somente 2 colunas são necessárias: uma que guarda Chave de Identificação e outra que gaurda o Valor (Key, Value);
      • Mas isso não impede que a tabela tenha outros campos, como: Id, Sistema, Tipo, Chave, Valor, Descrição, etc;
    • Flexibilidade: O nome da tabela de configuração, e os nomes das colunas podem ser configurados na dinamicamente.

Usage

Siga os passoa abaixo apara validar a solução:

  1. Instale a última versão do pacote Nuget MPSTI.PlenoSoft.Core.DbConfigurations:
    • Install-Package MPSTI.PlenoSoft.Core.DbConfigurations
    • <PackageReference Include="MPSTI.PlenoSoft.Core.DbConfigurations" Version="1.0.0.9" />
  2. Crie ou edite o arquivo appsettings.json abaixo (ao final deste passo-à-passo):
    • 2.1 Remova as strings de conexão que você não tem ou não deseja usar:
      • Dica: se você não tiver nenhum banco de dados, recomendo o uso do Sqlite para validar a solução;
    • 2.2 Configure as a(s) string(s) de conexão, colocando as informações adequadas;
    • 2.3 Verifique se a(s) string(s) de conexão estão corretas e conectando corretamente ao banco de dados;
  3. Compile o programa e execute-o;

Show me the code!

appsettings.json
{
    "ConnectionStrings": {
        "Sqlite": "Data Source=ConfigDb.sqlite;Cache=Shared"
    }
}
Program.cs
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Configuration;
using MPSTI.PlenoSoft.Core.DbConfigurations.Sql.Extensions;

namespace SmartCase
{
    public static class Program
    {
        public static void Main()
        {
            var configuration = UseConfiguration();
            var messageHello = configuration["DbKeyHello"];
            var messageWorld = configuration["DbKeyWorld"];
            Console.WriteLine($"{messageHello} {messageWorld}!");
        }

        private static IConfiguration UseConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false) // Needs to configuration.GetConnectionString
                .AddDbConfiguration(settings => // Use Sqlite With Setup Configuration Settings... but, you can use a separated file for this
                {
                    settings.CheckChangeInterval = TimeSpan.FromMinutes(1);
                    settings.CommandSelectQuerySql = "Select * From Configuration;";
                    settings.ConfigurationKeyColumn = "Key";
                    settings.ConfigurationValueColumn = "Value";
                    settings.DbConnectionFactory = configuration => new SqliteConnection(configuration.GetConnectionString("Sqlite"));
                });

            return builder.Build();
        }
    }
}

Additional documentation

View In GitHub Repository
or
Inspect Source Code Directly

Other implementation

appsettings.json
{
    "ConnectionStrings": {
        "SqlServer": "Server=your-sqlserver.database.net;Database=Config;Trusted_Connection=True;"
    }
}
Program.cs
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using MPSTI.PlenoSoft.Core.DbConfigurations.Sql.Extensions;
using MPSTI.PlenoSoft.Core.DbConfigurations.Sql.Interfaces;
using SmartCase.DbConfigurations;

namespace SmartCase
{
    public static class Program
    {
        public static void Main()
        {
            var configuration = UseConfiguration();
            var messageHello = configuration["DbKeyHello"];
            var messageWorld = configuration["DbKeyWorld"];
            Console.WriteLine($"{messageHello} {messageWorld}!");
        }

        private static IConfiguration UseConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false) // Needs to configuration.GetConnectionString
                .AddDbConfiguration<SqlServerConfigurationSettings>(); // Use SqlServer With Configuration Setting Class

            return builder.Build();
        }
    }
}

DbSettings.cs

using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using MPSTI.PlenoSoft.Core.DbConfigurations.Sql.Interfaces;


namespace SmartCase.DbConfigurations
{
    // SqlServer Configuration Setting Class needs only to implements the IDbConfigurationSettings
    public class SqlServerConfigurationSettings : IDbConfigurationSettings
    {
        public TimeSpan CheckChangeInterval => TimeSpan.FromMinutes(1);
        public string CommandSelectQuerySql => "Select Key, Value From Configuration Where (System Like '%SmartCase%');";
        public string ConfigurationKeyColumn => "Key";
        public string ConfigurationValueColumn => "Value";
        public IDbConnection CreateDbConnection(IConfiguration configuration)
        {
            var connectionString = configuration.GetConnectionString("SqlServer");
            return new SqlConnection(connectionString);
        }
    }
}

Feedback

Conctact me

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0.9 480 10/7/2023
1.0.0.8 498 10/2/2023
1.0.0.7 488 9/26/2023
1.0.0.6 504 9/26/2023
1.0.0.5 516 9/25/2023
1.0.0.4 509 9/23/2023
1.0.0.3 488 9/23/2023

(Atual)
2023-10-06 - 1.0.0.9 - Implementa o ReloadOnChange através do DbConfigurationMonitorLazy com tempo configurável através do CheckChangeInterval, que otimiza a utilização dos recursos;
2023-10-02 - 1.0.0.8 - Implementa o ReloadOnChange através do DbConfigurationMonitor (via pooling) com tempo configurável;
2023-09-25 - 1.0.0.7 - Melhoria da documentação do Readme.md no projeto e no pacote nuget + Correção do teste;
2023-09-25 - 1.0.0.6 - Refatora o DbConfigurationExtensions para usar o ISetDbConfigurationSettings + Adiciona documentação do Readme.md no projeto e no pacote nuget;
2023-09-25 - 1.0.0.5 - Refatora as classes para deixar com um designer mais simples e amigável + documentação dos métodos para uso deste pacote;
2023-09-23 - 1.0.0.4 - Remove tratamento de erro para deixar lançar exception e ser capturada na inicialização + Escrita de testes unitários com o Sqlite;
2023-09-22 - 1.0.0.3 - Rename package from MPSTI.PlenoSoft.Core.Configurations to MPSTI.PlenoSoft.Core.DbConfigurations;
2023-09-22 - 1.0.0.2 - Remove unused Packages References from Project;
2023-09-22 - 1.0.0.1 - Versão Inicial do MPSTI.PlenoSoft.Core.Configurations que permite carregar configurações de uma tabela do banco de dados;