Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

MsSqlServerCacheManager.cs

using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Caching.Distributed;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Infrastructure;

namespace Nop.Services.Caching;

/// 
/// Represents a MsSql server distributed cache 
/// 
public partial class MsSqlServerCacheManager : DistributedCacheManager
{
    #region Fields

    protected readonly DistributedCacheConfig _distributedCacheConfig;

    #endregion

    #region Ctor

    public MsSqlServerCacheManager(AppSettings appSettings,
        IDistributedCache distributedCache,
        ICacheKeyManager cacheKeyManager,
        IConcurrentCollection concurrentCollection)
        : base(appSettings, distributedCache, cacheKeyManager, concurrentCollection)
    {
        _distributedCacheConfig = appSettings.Get();
    }

    #endregion

    #region Utilities

    /// 
    /// Performs SQL command
    /// 
    /// SQL command
    /// Parameters for SQL command
    /// A task that represents the asynchronous operation
    protected virtual async Task PerformActionAsync(SqlCommand command, params SqlParameter[] parameters)
    {
        var conn = new SqlConnection(_distributedCacheConfig.ConnectionString);

        try
        {
            await conn.OpenAsync();
            command.Connection = conn;
            if (parameters.Any())
                command.Parameters.AddRange(parameters);

            await command.ExecuteNonQueryAsync();
        }
        finally
        {
            await conn.CloseAsync();
        }
    }

    #endregion

    #region Methods

    /// 
    /// Remove items by cache key prefix
    /// 
    /// Cache key prefix
    /// Parameters to create cache key prefix
    /// A task that represents the asynchronous operation
    public override async Task RemoveByPrefixAsync(string prefix, params object[] prefixParameters)
    {
        prefix = PrepareKeyPrefix(prefix, prefixParameters);

        var command =
            new SqlCommand(
                $"DELETE FROM {_distributedCacheConfig.SchemaName}.{_distributedCacheConfig.TableName} WHERE Id LIKE @Prefix + '%'");

        await PerformActionAsync(command, new SqlParameter("Prefix", SqlDbType.NVarChar) { Value = prefix });

        RemoveByPrefixInstanceData(prefix);
    }

    /// 
    /// Clear all cache data
    /// 
    /// A task that represents the asynchronous operation
    public override async Task ClearAsync()
    {
        var command =
            new SqlCommand(
                $"TRUNCATE TABLE {_distributedCacheConfig.SchemaName}.{_distributedCacheConfig.TableName}");

        await PerformActionAsync(command);

        ClearInstanceData();
    }

    #endregion
}