MPSTI.PlenoSoft.Core.DbConfigurations 1.0.0.6

There is a newer version of this package available.
See the version list below for details.
dotnet add package MPSTI.PlenoSoft.Core.DbConfigurations --version 1.0.0.6                
NuGet\Install-Package MPSTI.PlenoSoft.Core.DbConfigurations -Version 1.0.0.6                
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.6" />                
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.6                
#r "nuget: MPSTI.PlenoSoft.Core.DbConfigurations, 1.0.0.6"                
#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.6

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

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 3 arquivos no seu projeto, sendo que, dependendo da configuração que você escolher, o último pode não ser necessário:

  1. appsettings.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;
  3. DbSettings.cs
    • Opcional, caso queira usar a configuração in-line.

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.6" />
  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;

appsettings.json

{
	"ConnectionStrings": {
		"Sqlite": "Data Source=ConfigDb.sqlite;Cache=Shared",
		"SqlServer": "Server=your-sqlserver.database.net;Database=Config;Trusted_Connection=True;"
		"MySql": "Server=yourServerAddress;Port=1234;Database=Config;Uid=myUsername;Pwd=myPassword;"
	}
}

Program.cs

using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MPSTI.PlenoSoft.Core.DbConfigurations.Sql.Extensions;
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())

				// Needs to configuration.GetConnectionString, e.g., MySql, SqlServer, Sqlite.
				.AddJsonFile("appsettings.json", optional: false)

				// Use Sqlite With Configuration Setting Class
				.AddDbConfiguration<SqliteConfigurationSettings>()

				// Use SqlServer With Configuration Setting Class
				.AddDbConfiguration<SqlServerConfigurationSettings>()

				// Use MySql With Setup Configuration Settings
				.AddDbConfiguration(settings =>
				{
					settings.CommandSelectQuerySql = "Select * From Configuration;";
					settings.ConfigurationKeyColumn = "Key";
					settings.ConfigurationValueColumn = "Value";
					settings.DbConnectionFactory = configuration => new MySqlConnection(configuration.GetConnectionString("MySql"));
				});

			var configuration = builder.Build();
		}
	}
}

DbSettings.cs

{
	// Sqlite Configuration Settings Class needs to inherit the DbConfigurationSettings that already implement the IDbConfigurationSettings
	public class SqliteConfigurationSettings : DbConfigurationSettings
	{
		public override string CommandSelectQuerySql => "Select Chave, Valor From Configuracao;";
		public override string ConfigurationKeyColumn => "Chave";
		public override string ConfigurationValueColumn => "Valor";
		public override IDbConnection CreateDbConnection(IConfiguration configuration)
		{
			var connectionString = configuration.GetConnectionString("Sqlite");
			return new SqliteConnection(connectionString);
		}
	}

	// SqlServer Configuration Setting Class needs only to implements the IDbConfigurationSettings
	public class SqlServerConfigurationSettings : IDbConfigurationSettings
	{
		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);
		}
	}
}

Additional documentation

View In GitHub Repository
or
Inspect Source Code Directly

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 517 10/7/2023
1.0.0.8 521 10/2/2023
1.0.0.7 511 9/26/2023
1.0.0.6 525 9/26/2023
1.0.0.5 538 9/25/2023
1.0.0.4 531 9/23/2023
1.0.0.3 512 9/23/2023

(Atual)
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;