17 Commits

Author SHA1 Message Date
2ede7baae6 feat:nuget 2025-09-02 13:57:44 -06:00
c42fb5eb00 Deactivate redis using a flag 2025-08-29 18:46:41 -06:00
dbc21959eb Fix Retrieve updated document in ReplaceOneAsync method 2025-08-07 17:23:44 -06:00
a97e4e2219 Merge pull request 'Strong typed keyvault response' (#5) from bugfix/strongly-typed-keyvault into development
Reviewed-on: #5
2025-07-21 02:45:58 +00:00
35965591f5 Stryong typed keyvault response 2025-07-20 20:42:52 -06:00
38b63455d4 Fix sql server package (revert avoiding chained credential) 2025-06-22 19:19:23 -06:00
fbfa21f89a Merge branch 'development' of https://gitea.white-enciso.pro/AgileWebs/Core.BluePrint.Packages into development 2025-06-22 19:13:00 -06:00
e3cdf1fb32 Fix Redis cache provider 2025-06-22 19:12:58 -06:00
351cc28181 Merge branch 'development' of https://gitea.white-enciso.pro/AgileWebs/Core.BluePrint.Packages into development 2025-06-22 03:46:30 -06:00
4e6bf79656 Add ApplicationVersion constant 2025-06-22 03:46:28 -06:00
73b909f780 Avoid chained credential for local environment in sql package 2025-06-22 01:28:14 -06:00
7b326051bb Upgrade redis package 2025-06-21 22:12:20 -06:00
ff24c06934 Revert memory cache 2025-06-21 22:05:27 -06:00
31b26399a9 Merge pull request #4 from SergioMatias94/feature/adapt-to-connect-to-local-mongo
Adapt to create packages
2025-06-17 15:12:43 -06:00
73f9d8550f Merge pull request #3 from SergioMatias94/feature/adapt-to-connect-to-local-mongo
Adapt the RegisterBlueprint to connect with local mongodb
2025-06-10 23:16:04 -06:00
626105cf0c Implement azurite 2025-06-09 00:39:20 -06:00
eda79010ce Implement azurite 2025-06-08 18:20:34 -06:00
18 changed files with 232 additions and 203 deletions

View File

@@ -7,7 +7,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.Blueprint.KeyVault", "
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Mongo", "Core.Blueprint.Mongo\Core.Blueprint.Mongo.csproj", "{27A8E3E1-D613-4D5B-8105-485699409F1E}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Mongo", "Core.Blueprint.Mongo\Core.Blueprint.Mongo.csproj", "{27A8E3E1-D613-4D5B-8105-485699409F1E}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Caching", "Core.Blueprint.Redis\Core.Blueprint.Caching.csproj", "{11F2AA11-FB98-4A33-AEE4-CD49588D2FE1}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Redis", "Core.Blueprint.Redis\Core.Blueprint.Redis.csproj", "{11F2AA11-FB98-4A33-AEE4-CD49588D2FE1}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Storage", "Core.Blueprint.Storage\Core.Blueprint.Storage.csproj", "{636E4520-79F9-46C8-990D-08F2D24A151C}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Storage", "Core.Blueprint.Storage\Core.Blueprint.Storage.csproj", "{636E4520-79F9-46C8-990D-08F2D24A151C}"
EndProject EndProject

View File

@@ -22,7 +22,7 @@ namespace Core.Blueprint.KeyVault
/// <returns> /// <returns>
/// A <see cref="Tuple"/> containing a status message and a boolean indicating whether the secret was successfully deleted. /// A <see cref="Tuple"/> containing a status message and a boolean indicating whether the secret was successfully deleted.
/// </returns> /// </returns>
ValueTask<Tuple<string, bool>> DeleteSecretAsync(string secretName, CancellationToken cancellationToken); ValueTask<(string Message, bool Deleted)> DeleteSecretAsync(string secretName, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Retrieves a secret from Azure Key Vault. /// Retrieves a secret from Azure Key Vault.
@@ -33,7 +33,7 @@ namespace Core.Blueprint.KeyVault
/// A <see cref="Tuple"/> containing the <see cref="KeyVaultResponse"/> with secret details /// A <see cref="Tuple"/> containing the <see cref="KeyVaultResponse"/> with secret details
/// and an optional error message if the secret was not found. /// and an optional error message if the secret was not found.
/// </returns> /// </returns>
ValueTask<Tuple<KeyVaultResponse, string?>> GetSecretAsync(string secretName, CancellationToken cancellationToken); ValueTask<(KeyVaultResponse Secret, string? Message)> GetSecretAsync(string secretName, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Updates an existing secret in Azure Key Vault. If the secret does not exist, an error is returned. /// Updates an existing secret in Azure Key Vault. If the secret does not exist, an error is returned.
@@ -43,6 +43,6 @@ namespace Core.Blueprint.KeyVault
/// <returns> /// <returns>
/// A <see cref="Tuple"/> containing the updated <see cref="KeyVaultResponse"/> and an optional error message if the secret was not found. /// A <see cref="Tuple"/> containing the updated <see cref="KeyVaultResponse"/> and an optional error message if the secret was not found.
/// </returns> /// </returns>
ValueTask<Tuple<KeyVaultResponse, string>> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken); ValueTask<(KeyVaultResponse Secret, string? Message)> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken);
} }
} }

View File

@@ -1,10 +1,10 @@
using Azure.Security.KeyVault.Secrets; using Azure.Security.KeyVault.Secrets;
using VaultSharp;
using VaultSharp.V1.AuthMethods.Token;
using Core.Blueprint.KeyVault.Configuration; using Core.Blueprint.KeyVault.Configuration;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System.Net.Http.Json; using System.Net.Http.Json;
using VaultSharp;
using VaultSharp.Core; using VaultSharp.Core;
using VaultSharp.V1.AuthMethods.Token;
namespace Core.Blueprint.KeyVault; namespace Core.Blueprint.KeyVault;
@@ -67,7 +67,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
/// <returns> /// <returns>
/// A <see cref="Tuple"/> containing a status message and a boolean indicating whether the secret was successfully deleted. /// A <see cref="Tuple"/> containing a status message and a boolean indicating whether the secret was successfully deleted.
/// </returns> /// </returns>
public async ValueTask<Tuple<string, bool>> DeleteSecretAsync(string secretName, CancellationToken cancellationToken) public async ValueTask<(string Message, bool Deleted)> DeleteSecretAsync(string secretName, CancellationToken cancellationToken)
{ {
if (environment == "Local") if (environment == "Local")
{ {
@@ -88,7 +88,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
/// <summary> /// <summary>
/// Retrieves a secret from Azure Key Vault or HashiCorp Vault. /// Retrieves a secret from Azure Key Vault or HashiCorp Vault.
/// </summary> /// </summary>
public async ValueTask<Tuple<KeyVaultResponse, string?>> GetSecretAsync(string secretName, CancellationToken cancellationToken) public async ValueTask<(KeyVaultResponse Secret, string? Message)> GetSecretAsync(string secretName, CancellationToken cancellationToken)
{ {
if (environment == "Local") if (environment == "Local")
{ {
@@ -108,7 +108,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
} }
catch (VaultSharp.Core.VaultApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound) catch (VaultSharp.Core.VaultApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
{ {
return new(new KeyVaultResponse(), "Key Not Found"); return new(new KeyVaultResponse { }, "Key Not Found");
} }
} }
@@ -126,7 +126,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
/// <summary> /// <summary>
/// Updates an existing secret in Azure Key Vault or HashiCorp Vault. If the secret does not exist, an error is returned. /// Updates an existing secret in Azure Key Vault or HashiCorp Vault. If the secret does not exist, an error is returned.
/// </summary> /// </summary>
public async ValueTask<Tuple<KeyVaultResponse, string>> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken) public async ValueTask<(KeyVaultResponse Secret, string? Message)> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken)
{ {
var existingSecret = await this.GetSecretAsync(newSecret.Name, cancellationToken); var existingSecret = await this.GetSecretAsync(newSecret.Name, cancellationToken);
if (!string.IsNullOrEmpty(existingSecret.Item2)) if (!string.IsNullOrEmpty(existingSecret.Item2))

View File

@@ -13,6 +13,8 @@ namespace Core.Blueprint.Logging
/// </summary> /// </summary>
public static class MimeTypes public static class MimeTypes
{ {
public const string ApplicationVersion = "1.0";
/// <summary> /// <summary>
/// The service application/json mime type. /// The service application/json mime type.
/// </summary> /// </summary>

View File

@@ -104,11 +104,13 @@ namespace Core.Blueprint.Mongo
void ReplaceOne(TDocument document); void ReplaceOne(TDocument document);
/// <summary> /// <summary>
/// Asynchronously replaces an existing document with a new one. /// Asynchronously replaces an existing document in the collection and returns the updated version.
/// </summary> /// </summary>
/// <param name="document">The document to replace the existing one.</param> /// <param name="document">The document with the updated data. Its _Id is used to locate the existing document.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <returns>
Task ReplaceOneAsync(TDocument document); /// The updated document if the replacement was successful; otherwise, <c>null</c> if no matching document was found.
/// </returns>
Task<TDocument?> ReplaceOneAsync(TDocument document);
/// <summary> /// <summary>
/// Deletes a single document by the provided filter expression. /// Deletes a single document by the provided filter expression.

View File

@@ -175,16 +175,27 @@ namespace Core.Blueprint.Mongo
} }
/// <summary> /// <summary>
/// Asynchronously replaces an existing document in the collection. /// Asynchronously replaces an existing document in the collection and returns the updated version.
/// </summary> /// </summary>
/// <param name="document">The document with the updated data.</param> /// <param name="document">The document with the updated data. Its _Id is used to locate the existing document.</param>
/// <returns>A task that represents the asynchronous operation.</returns> /// <returns>
public virtual async Task ReplaceOneAsync(TDocument document) /// The updated document if the replacement was successful; otherwise, <c>null</c> if no matching document was found.
/// </returns>
public virtual async Task<TDocument?> ReplaceOneAsync(TDocument document)
{ {
var filter = Builders<TDocument>.Filter.Eq(doc => doc._Id, document._Id); var filter = Builders<TDocument>.Filter.Eq(doc => doc._Id, document._Id);
await _collection.FindOneAndReplaceAsync(filter, document);
var options = new FindOneAndReplaceOptions<TDocument>
{
ReturnDocument = ReturnDocument.After // return the updated document
};
var result = await _collection.FindOneAndReplaceAsync(filter, document, options);
return result;
} }
/// <summary> /// <summary>
/// Deletes a single document from the collection based on the provided filter expression. /// Deletes a single document from the collection based on the provided filter expression.
/// </summary> /// </summary>

View File

@@ -1,4 +1,4 @@
namespace Core.Blueprint.Caching.Adapters namespace Core.Blueprint.Redis
{ {
public interface ICacheSettings public interface ICacheSettings
{ {

View File

@@ -1,10 +1,8 @@
using Core.Blueprint.Caching.Adapters; using Microsoft.Extensions.Configuration;
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Core.Blueprint.Caching.Configuration namespace Core.Blueprint.Redis.Configuration
{ {
/// <summary> /// <summary>
/// Provides extension methods for registering Redis-related services in the DI container. /// Provides extension methods for registering Redis-related services in the DI container.
@@ -19,30 +17,23 @@ namespace Core.Blueprint.Caching.Configuration
/// <returns>The updated service collection.</returns> /// <returns>The updated service collection.</returns>
public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
{ {
// TODO for the following variable we'll need to add in the appsettings.json the following config: "UseRedisCache": true, // Retrieve the Redis connection string from the configuration.
bool useRedis = configuration.GetValue<bool>("UseRedisCache"); // Get Redis configuration section
if (useRedis)
{
var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value; var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value;
if (string.IsNullOrEmpty(redisConnectionString)) if (string.IsNullOrEmpty(redisConnectionString))
{ {
throw new InvalidOperationException("Redis connection is not configured."); throw new InvalidOperationException("Redis connection is not configured.");
} }
services.AddSingleton<ICacheProvider>(provider => // Register RedisCacheProvider
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>())); services.AddSingleton<IRedisCacheProvider>(provider =>
} new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>(), configuration));
else
{
services.AddMemoryCache();
services.AddSingleton<ICacheProvider, MemoryCacheProvider>();
}
// Get CacheSettings and register with the ICacheSettings interface
var cacheSettings = configuration.GetSection("CacheSettings").Get<CacheSettings>(); var cacheSettings = configuration.GetSection("CacheSettings").Get<CacheSettings>();
if (cacheSettings == null) if (cacheSettings == null)
{ {
throw new InvalidOperationException("CacheSettings section is not configured."); throw new InvalidOperationException("Redis CacheSettings section is not configured.");
} }
services.AddSingleton<ICacheSettings>(cacheSettings); services.AddSingleton<ICacheSettings>(cacheSettings);

View File

@@ -1,9 +1,9 @@
namespace Core.Blueprint.Caching.Contracts namespace Core.Blueprint.Redis
{ {
/// <summary> /// <summary>
/// Interface for managing Redis cache operations. /// Interface for managing Redis cache operations.
/// </summary> /// </summary>
public interface ICacheProvider public interface IRedisCacheProvider
{ {
/// <summary> /// <summary>
/// Retrieves a cache item by its key. /// Retrieves a cache item by its key.

View File

@@ -9,7 +9,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Azure.StackExchangeRedis" Version="3.2.1" /> <PackageReference Include="Microsoft.Azure.StackExchangeRedis" Version="3.2.1" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.5" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.5" /> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.5" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.5" />

View File

@@ -1,7 +1,11 @@
using System.Text; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Core.Blueprint.Caching.Helpers namespace Core.Blueprint.Redis.Helpers
{ {
/// <summary> /// <summary>
/// Helper class for generating consistent and normalized cache keys. /// Helper class for generating consistent and normalized cache keys.

View File

@@ -1,86 +0,0 @@
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Caching.Memory;
using System.Text.Json;
namespace Core.Blueprint.Caching
{
public sealed class MemoryCacheProvider : ICacheProvider
{
private readonly IMemoryCache _cache;
private readonly ILogger<MemoryCacheProvider> _logger;
public MemoryCacheProvider(IMemoryCache cache, ILogger<MemoryCacheProvider> logger)
{
_cache = cache;
_logger = logger;
}
public ValueTask<TEntity> GetAsync<TEntity>(string key)
{
if (_cache.TryGetValue(key, out var value))
{
if (value is TEntity typedValue)
{
return ValueTask.FromResult(typedValue);
}
try
{
var json = value?.ToString();
var deserialized = JsonSerializer.Deserialize<TEntity>(json);
return ValueTask.FromResult(deserialized);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error deserializing cache value for key {Key}", key);
}
}
return ValueTask.FromResult(default(TEntity));
}
public ValueTask SetAsync<TEntity>(string key, TEntity value, TimeSpan? expiry = null)
{
var options = new MemoryCacheEntryOptions();
if (expiry.HasValue)
{
options.SetAbsoluteExpiration(expiry.Value);
}
_cache.Set(key, value, options);
return ValueTask.CompletedTask;
}
public ValueTask RemoveAsync(string key)
{
_cache.Remove(key);
return ValueTask.CompletedTask;
}
public ValueTask<bool> ExistsAsync(string key)
{
return ValueTask.FromResult(_cache.TryGetValue(key, out _));
}
public ValueTask RefreshAsync(string key, TimeSpan? expiry = null)
{
// MemoryCache does not support sliding expiration refresh like Redis,
// so we must re-set the value manually if required.
if (_cache.TryGetValue(key, out var value))
{
_cache.Remove(key);
var options = new MemoryCacheEntryOptions();
if (expiry.HasValue)
{
options.SetAbsoluteExpiration(expiry.Value);
}
_cache.Set(key, value, options);
}
return ValueTask.CompletedTask;
}
}
}

View File

@@ -1,18 +1,19 @@
using Azure.Identity; using Azure.Identity;
using Core.Blueprint.Caching.Contracts; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using StackExchange.Redis; using StackExchange.Redis;
using System.Text.Json; using System.Text.Json;
namespace Core.Blueprint.Caching namespace Core.Blueprint.Redis
{ {
/// <summary> /// <summary>
/// Redis cache provider for managing cache operations. /// Redis cache provider for managing cache operations.
/// </summary> /// </summary>
public sealed class RedisCacheProvider : ICacheProvider public sealed class RedisCacheProvider : IRedisCacheProvider
{ {
private IDatabase _cacheDatabase = null!; private IDatabase _cacheDatabase = null!;
private readonly ILogger<RedisCacheProvider> _logger; private readonly ILogger<RedisCacheProvider> _logger;
private readonly bool _useRedis;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="RedisCacheProvider"/> class. /// Initializes a new instance of the <see cref="RedisCacheProvider"/> class.
@@ -20,50 +21,53 @@ namespace Core.Blueprint.Caching
/// <param name="connectionString">The Redis connection string.</param> /// <param name="connectionString">The Redis connection string.</param>
/// <param name="logger">The logger instance for logging operations.</param> /// <param name="logger">The logger instance for logging operations.</param>
/// <exception cref="ArgumentNullException">Thrown when connection string is null or empty.</exception> /// <exception cref="ArgumentNullException">Thrown when connection string is null or empty.</exception>
public RedisCacheProvider(string connectionString, ILogger<RedisCacheProvider> logger) public RedisCacheProvider(string connectionString, ILogger<RedisCacheProvider> logger, IConfiguration configuration)
{ {
if (string.IsNullOrWhiteSpace(connectionString)) if (string.IsNullOrWhiteSpace(connectionString))
throw new ArgumentNullException(nameof(connectionString), "Redis connection string cannot be null or empty."); throw new ArgumentNullException(nameof(connectionString), "Redis connection string cannot be null or empty.");
_logger = logger; _logger = logger;
_useRedis = configuration.GetValue<bool>("UseRedisCache", false);
_cacheDatabase = InitializeRedisAsync(connectionString).GetAwaiter().GetResult(); _cacheDatabase = InitializeRedisAsync(connectionString).GetAwaiter().GetResult();
} }
/// <summary> /// <summary>
/// Initializes and establishes a connection to Redis using the provided connection string. /// Initializes and establishes a connection to Redis based on the environment.
/// Uses a local connection in development, and Azure with token credentials in other environments.
/// </summary> /// </summary>
/// <param name="connectionString">The Redis connection string.</param> /// <param name="connectionString">The Redis connection string.</param>
/// <returns>An <see cref="IDatabase"/> instance representing the Redis cache database.</returns> /// <returns>An <see cref="IDatabase"/> instance representing the Redis cache database.</returns>
/// <exception cref="Exception">Thrown when the connection to Redis fails.</exce /// <exception cref="Exception">Thrown when the connection to Redis fails.</exception>
public async Task<IDatabase> InitializeRedisAsync(string connectionString) async Task<IDatabase?> InitializeRedisAsync(string connectionString)
{ {
try try
{
if (_useRedis)
{ {
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty; var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
ConnectionMultiplexer connectionMultiplexer;
ConfigurationOptions configurationOptions;
if (environment.Equals("Local", StringComparison.OrdinalIgnoreCase)) if (environment.Equals("Local", StringComparison.OrdinalIgnoreCase))
{ {
// Use simple local Redis config connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(connectionString);
configurationOptions = ConfigurationOptions.Parse(connectionString);
} }
else else
{ {
// Use Azure Redis config var configurationOptions = await ConfigurationOptions.Parse(connectionString)
configurationOptions = await ConfigurationOptions
.Parse(connectionString)
.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential()); .ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
}
configurationOptions.AbortOnConnectFail = false; configurationOptions.AbortOnConnectFail = false;
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions); connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
}
_logger.LogInformation("Successfully connected to Redis."); _logger.LogInformation("Successfully connected to Redis.");
return connectionMultiplexer.GetDatabase(); return connectionMultiplexer.GetDatabase();
} }
return null;
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error establishing Redis connection."); _logger.LogError(ex, "Error establishing Redis connection.");
@@ -80,8 +84,11 @@ namespace Core.Blueprint.Caching
public async ValueTask<TEntity> GetAsync<TEntity>(string key) public async ValueTask<TEntity> GetAsync<TEntity>(string key)
{ {
try try
{
if (_useRedis is not false)
{ {
var value = await _cacheDatabase.StringGetAsync(key); var value = await _cacheDatabase.StringGetAsync(key);
if (value.IsNullOrEmpty) if (value.IsNullOrEmpty)
{ {
_logger.LogInformation($"Cache miss for key: {key}"); _logger.LogInformation($"Cache miss for key: {key}");
@@ -91,6 +98,9 @@ namespace Core.Blueprint.Caching
_logger.LogInformation($"Cache hit for key: {key}"); _logger.LogInformation($"Cache hit for key: {key}");
return JsonSerializer.Deserialize<TEntity>(value); return JsonSerializer.Deserialize<TEntity>(value);
} }
return default;
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"Error getting cache item with key {key}"); _logger.LogError(ex, $"Error getting cache item with key {key}");
@@ -107,11 +117,14 @@ namespace Core.Blueprint.Caching
public async ValueTask SetAsync<TEntity>(string key, TEntity value, TimeSpan? expiry = null) public async ValueTask SetAsync<TEntity>(string key, TEntity value, TimeSpan? expiry = null)
{ {
try try
{
if (_useRedis is not false)
{ {
var json = JsonSerializer.Serialize(value); var json = JsonSerializer.Serialize(value);
await _cacheDatabase.StringSetAsync(key, json, expiry); await _cacheDatabase.StringSetAsync(key, json, expiry);
_logger.LogInformation($"Cache item set with key: {key}"); _logger.LogInformation($"Cache item set with key: {key}");
} }
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"Error setting cache item with key {key}"); _logger.LogError(ex, $"Error setting cache item with key {key}");
@@ -126,10 +139,13 @@ namespace Core.Blueprint.Caching
public async ValueTask RemoveAsync(string key) public async ValueTask RemoveAsync(string key)
{ {
try try
{
if (_useRedis is not false)
{ {
await _cacheDatabase.KeyDeleteAsync(key); await _cacheDatabase.KeyDeleteAsync(key);
_logger.LogInformation($"Cache item removed with key: {key}"); _logger.LogInformation($"Cache item removed with key: {key}");
} }
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"Error removing cache item with key {key}"); _logger.LogError(ex, $"Error removing cache item with key {key}");
@@ -145,10 +161,14 @@ namespace Core.Blueprint.Caching
public async ValueTask<bool> ExistsAsync(string key) public async ValueTask<bool> ExistsAsync(string key)
{ {
try try
{
if (_useRedis is not false)
{ {
var exists = await _cacheDatabase.KeyExistsAsync(key); var exists = await _cacheDatabase.KeyExistsAsync(key);
_logger.LogInformation($"Cache item exists check for key: {key} - {exists}"); _logger.LogInformation($"Cache item exists check for key: {key} - {exists}");
return exists; }
return false;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -165,6 +185,8 @@ namespace Core.Blueprint.Caching
public async ValueTask RefreshAsync(string key, TimeSpan? expiry = null) public async ValueTask RefreshAsync(string key, TimeSpan? expiry = null)
{ {
try try
{
if (_useRedis is not false)
{ {
var value = await _cacheDatabase.StringGetAsync(key); var value = await _cacheDatabase.StringGetAsync(key);
if (!value.IsNullOrEmpty) if (!value.IsNullOrEmpty)
@@ -177,6 +199,7 @@ namespace Core.Blueprint.Caching
_logger.LogWarning($"Cache item with key: {key} does not exist, cannot refresh"); _logger.LogWarning($"Cache item with key: {key} does not exist, cannot refresh");
} }
} }
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"Error refreshing cache item with key {key}"); _logger.LogError(ex, $"Error refreshing cache item with key {key}");

View File

@@ -18,6 +18,8 @@ namespace Core.Blueprint.SQLServer.Configuration
/// <returns>An updated <see cref="IServiceCollection"/> with SQL Server services registered.</returns> /// <returns>An updated <see cref="IServiceCollection"/> with SQL Server services registered.</returns>
public static IServiceCollection AddSQLServer(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddSQLServer(this IServiceCollection services, IConfiguration configuration)
{ {
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
var chainedCredentials = new ChainedTokenCredential( var chainedCredentials = new ChainedTokenCredential(
new ManagedIdentityCredential(), new ManagedIdentityCredential(),
new SharedTokenCacheCredential(), new SharedTokenCacheCredential(),

View File

@@ -11,23 +11,37 @@ namespace Core.Blueprint.Storage.Configuration
{ {
public static IServiceCollection AddBlobStorage(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddBlobStorage(this IServiceCollection services, IConfiguration configuration)
{ {
var blobConnection = configuration.GetConnectionString("BlobStorage"); var blobConnection = configuration.GetConnectionString("BlobStorage");
if (blobConnection == null || string.IsNullOrWhiteSpace(blobConnection)) if (string.IsNullOrWhiteSpace(blobConnection))
{
throw new ArgumentException("The BlobStorage configuration section is missing or empty."); throw new ArgumentException("The BlobStorage configuration section is missing or empty.");
}
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
services.AddAzureClients(cfg =>
{
if (environment == "Local")
{
var accountKey = configuration.GetSection("BlobStorage:AccountKey").Value;
var accountName = configuration.GetSection("BlobStorage:AccountName").Value;
if(string.IsNullOrEmpty(accountKey) && string.IsNullOrEmpty(accountName))
throw new ArgumentException("The BlobStorage configuration section is missing or empty.");
cfg.AddBlobServiceClient(configuration.GetConnectionString("BlobStorage"));
}
else
{
var chainedCredentials = new ChainedTokenCredential( var chainedCredentials = new ChainedTokenCredential(
new ManagedIdentityCredential(), new ManagedIdentityCredential(),
new SharedTokenCacheCredential(), new SharedTokenCacheCredential(),
new VisualStudioCredential(), new VisualStudioCredential(),
new VisualStudioCodeCredential() new VisualStudioCodeCredential()
); );
services.AddAzureClients(cfg =>
{ cfg.AddBlobServiceClient(new Uri(blobConnection))
cfg.AddBlobServiceClient(new Uri(blobConnection)).WithCredential(chainedCredentials); .WithCredential(chainedCredentials);
}
}); });
services.AddScoped<IBlobStorageProvider, BlobStorageProvider>(); services.AddScoped<IBlobStorageProvider, BlobStorageProvider>();

View File

@@ -162,7 +162,7 @@ namespace Core.Blueprint.Storage.Contracts
/// </remarks> /// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception>
/// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception> /// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception>
BlobDownloadUriAdapter GenerateBlobDownloadUri(string blobName); ValueTask<BlobDownloadUriAdapter?> GenerateBlobDownloadUri(string blobName);
/// <summary> /// <summary>
/// Retrieves the hierarchical folder structure. /// Retrieves the hierarchical folder structure.

View File

@@ -1,4 +1,5 @@
using Azure; using Azure;
using Azure.Storage;
using Azure.Storage.Blobs; using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models; using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized; using Azure.Storage.Blobs.Specialized;
@@ -6,6 +7,7 @@ using Azure.Storage.Sas;
using Core.Blueprint.Storage.Adapters; using Core.Blueprint.Storage.Adapters;
using Core.Blueprint.Storage.Contracts; using Core.Blueprint.Storage.Contracts;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
namespace Core.Blueprint.Storage.Provider namespace Core.Blueprint.Storage.Provider
{ {
@@ -15,10 +17,12 @@ namespace Core.Blueprint.Storage.Provider
private readonly BlobContainerClient _blobContainerClient; private readonly BlobContainerClient _blobContainerClient;
private readonly string _containerName; private readonly string _containerName;
private readonly Trie _trie = new Trie(); private readonly Trie _trie = new Trie();
private readonly IConfiguration _configuration;
public BlobStorageProvider(BlobServiceClient blobServiceClient, IConfiguration configuration) public BlobStorageProvider(BlobServiceClient blobServiceClient, IConfiguration configuration)
{ {
_blobServiceClient = blobServiceClient; _blobServiceClient = blobServiceClient;
_configuration = configuration;
_containerName = configuration.GetSection("BlobStorage:ContainerName").Value ?? ""; _containerName = configuration.GetSection("BlobStorage:ContainerName").Value ?? "";
if (string.IsNullOrEmpty(_containerName)) if (string.IsNullOrEmpty(_containerName))
@@ -278,7 +282,8 @@ namespace Core.Blueprint.Storage.Provider
/// </summary> /// </summary>
/// <param name="blobName">The name of the blob for which the download URI is being generated.</param> /// <param name="blobName">The name of the blob for which the download URI is being generated.</param>
/// <returns> /// <returns>
/// An instance of <see cref="BlobDownloadUriAdapter"/> containing the generated URI, blob name, and status. /// An instance of <see cref="BlobDownloadUriAdapter"/> containing the generated URI, blob name, and status,
/// or <c>null</c> if the blob does not exist.
/// </returns> /// </returns>
/// <remarks> /// <remarks>
/// The generated URI includes a Shared Access Signature (SAS) token, which allows secure, time-limited access to the blob. /// The generated URI includes a Shared Access Signature (SAS) token, which allows secure, time-limited access to the blob.
@@ -286,22 +291,36 @@ namespace Core.Blueprint.Storage.Provider
/// </remarks> /// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception>
/// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception> /// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception>
public BlobDownloadUriAdapter GenerateBlobDownloadUri(string blobName) public async ValueTask<BlobDownloadUriAdapter?> GenerateBlobDownloadUri(string blobName)
{ {
var delegationKey = _blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow, if (string.IsNullOrWhiteSpace(blobName))
DateTimeOffset.UtcNow.AddHours(2)); throw new ArgumentNullException(nameof(blobName), "Blob name cannot be null or empty.");
var blob = _blobContainerClient.GetBlobClient(blobName); var blob = _blobContainerClient.GetBlobClient(blobName);
var sasBuilder = new BlobSasBuilder() if (!await blob.ExistsAsync())
return null;
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
if (environment == "Local")
{
return GenerateDownloadUri(blob);
}
var delegationKey = await _blobServiceClient.GetUserDelegationKeyAsync(
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow.AddHours(2));
var sasBuilder = new BlobSasBuilder
{ {
BlobContainerName = blob.BlobContainerName, BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name, BlobName = blob.Name,
Resource = "b", Resource = "b",
StartsOn = DateTimeOffset.UtcNow, StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5), ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5)
}; };
sasBuilder.SetPermissions(BlobAccountSasPermissions.Read); sasBuilder.SetPermissions(BlobSasPermissions.Read);
sasBuilder.Protocol = SasProtocol.Https; sasBuilder.Protocol = SasProtocol.Https;
var blobUriBuilder = new BlobUriBuilder(blob.Uri) var blobUriBuilder = new BlobUriBuilder(blob.Uri)
@@ -317,6 +336,45 @@ namespace Core.Blueprint.Storage.Provider
}; };
} }
/// <summary>
/// Generates a download URI for a blob using a Shared Access Signature in local (Azurite) environment.
/// </summary>
/// <param name="blob">The blob client for which the URI is being generated.</param>
/// <returns>An instance of <see cref="BlobDownloadUriAdapter"/> containing the SAS URI and metadata.</returns>
private BlobDownloadUriAdapter GenerateDownloadUri(BlobClient blob)
{
var sasBuilder = new BlobSasBuilder
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name,
Resource = "b",
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5)
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
sasBuilder.Protocol = SasProtocol.HttpsAndHttp;
var accountName = _configuration["BlobStorage:AccountName"];
var accountKey = _configuration["BlobStorage:AccountKey"];
var storageCredentials = new StorageSharedKeyCredential(accountName, accountKey);
var sasToken = sasBuilder.ToSasQueryParameters(storageCredentials);
var blobUriBuilder = new BlobUriBuilder(blob.Uri)
{
Sas = sasToken
};
return new BlobDownloadUriAdapter
{
Uri = blobUriBuilder.ToUri(),
Name = blob.Name,
Status = "Available"
};
}
/// <summary> /// <summary>
/// Retrieves the hierarchical folder structure. /// Retrieves the hierarchical folder structure.
/// </summary> /// </summary>

9
nuget.config Normal file
View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<!-- Tu BaGet primero -->
<add key="BaGet" value="https://nuget.dream-views.com/v3/index.json" protocolVersion="3" />
<!-- NuGet oficial como fallback (si quieres) -->
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources>
</configuration>