From 8d08acf647e49963dd10bd5603baec0774405fb8 Mon Sep 17 00:00:00 2001 From: MichaC Date: Wed, 25 Sep 2019 15:10:18 +0200 Subject: [PATCH 01/13] Hardening tests for ASP.NET Core 2.2 and 3.0 dependencies Setting up integration tests/samples for the different ASP.NET Core targets todo: fix obsolete logging setups and extensions --- CacheManager.sln | 44 +++-- appveyor.yml | 4 +- .../Controllers/ValuesController.cs | 0 .../Program.cs | 0 .../Properties/launchSettings.json | 13 ++ .../Startup.cs | 2 +- .../Web.csproj} | 8 +- .../appsettings.json | 0 .../cache.json | 0 .../web.config | 0 .../Controllers/ValuesController.cs | 70 ++++++++ samples/AspNetCore.2.2/Program.cs | 23 +++ .../Properties/launchSettings.json | 13 ++ samples/AspNetCore.2.2/Startup.cs | 106 ++++++++++++ samples/AspNetCore.2.2/Web.csproj | 23 +++ samples/AspNetCore.2.2/appsettings.json | 11 ++ samples/AspNetCore.2.2/cache.json | 13 ++ samples/AspNetCore.2.2/web.config | 14 ++ .../Controllers/ValuesController.cs | 70 ++++++++ samples/AspNetCore.3.0/Program.cs | 23 +++ .../Properties/launchSettings.json | 13 ++ samples/AspNetCore.3.0/Startup.cs | 106 ++++++++++++ samples/AspNetCore.3.0/Web.csproj | 22 +++ samples/AspNetCore.3.0/appsettings.json | 11 ++ samples/AspNetCore.3.0/cache.json | 13 ++ samples/AspNetCore.3.0/web.config | 14 ++ .../Properties/launchSettings.json | 29 ---- test/CacheManager.Tests/CacheFactoryTests.cs | 34 ++-- .../CacheManager.Tests/CacheItemValidation.cs | 62 ++++--- .../CacheManager.Tests.csproj | 46 +++-- .../CacheManagerEventsTest.cs | 6 +- .../CacheManagerSimpleTests.cs | 160 +++++++++--------- .../InvalidConfigurationValidationTests.cs | 16 +- .../MicrosoftConfigurationTests.cs | 24 +-- .../MicrosoftLoggingTests.cs | 59 +++++-- test/CacheManager.Tests/RedisTests.cs | 9 +- ...etstandard2.config => testhost.dll.config} | 0 37 files changed, 838 insertions(+), 223 deletions(-) rename samples/{AspnetCore.WebApp => AspNetCore.2.1}/Controllers/ValuesController.cs (100%) rename samples/{AspnetCore.WebApp => AspNetCore.2.1}/Program.cs (100%) create mode 100644 samples/AspNetCore.2.1/Properties/launchSettings.json rename samples/{AspnetCore.WebApp => AspNetCore.2.1}/Startup.cs (98%) rename samples/{AspnetCore.WebApp/AspnetCore.WebApp.csproj => AspNetCore.2.1/Web.csproj} (82%) rename samples/{AspnetCore.WebApp => AspNetCore.2.1}/appsettings.json (100%) rename samples/{AspnetCore.WebApp => AspNetCore.2.1}/cache.json (100%) rename samples/{AspnetCore.WebApp => AspNetCore.2.1}/web.config (100%) create mode 100644 samples/AspNetCore.2.2/Controllers/ValuesController.cs create mode 100644 samples/AspNetCore.2.2/Program.cs create mode 100644 samples/AspNetCore.2.2/Properties/launchSettings.json create mode 100644 samples/AspNetCore.2.2/Startup.cs create mode 100644 samples/AspNetCore.2.2/Web.csproj create mode 100644 samples/AspNetCore.2.2/appsettings.json create mode 100644 samples/AspNetCore.2.2/cache.json create mode 100644 samples/AspNetCore.2.2/web.config create mode 100644 samples/AspNetCore.3.0/Controllers/ValuesController.cs create mode 100644 samples/AspNetCore.3.0/Program.cs create mode 100644 samples/AspNetCore.3.0/Properties/launchSettings.json create mode 100644 samples/AspNetCore.3.0/Startup.cs create mode 100644 samples/AspNetCore.3.0/Web.csproj create mode 100644 samples/AspNetCore.3.0/appsettings.json create mode 100644 samples/AspNetCore.3.0/cache.json create mode 100644 samples/AspNetCore.3.0/web.config delete mode 100644 samples/AspnetCore.WebApp/Properties/launchSettings.json rename test/CacheManager.Tests/{App.netstandard2.config => testhost.dll.config} (100%) diff --git a/CacheManager.sln b/CacheManager.sln index 7ad8c22c..73eeeb7f 100644 --- a/CacheManager.sln +++ b/CacheManager.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27004.2009 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29318.209 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{58CC885F-40A7-4C82-990D-3F36AAA088A7}" EndProject @@ -64,8 +64,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheManager.Microsoft.Exte EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheManager.Serialization.ProtoBuf", "src\CacheManager.Serialization.ProtoBuf\CacheManager.Serialization.ProtoBuf.csproj", "{85CD8BC7-3E72-422E-AF91-6FDF2133E155}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspnetCore.WebApp", "samples\AspnetCore.WebApp\AspnetCore.WebApp.csproj", "{CB9C05BF-E567-412F-B3C8-C85289E60DBC}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheManager.Serialization.Bond", "src\CacheManager.Serialization.Bond\CacheManager.Serialization.Bond.csproj", "{2FB30F61-B2E7-43AC-80AF-C45218F1D4BA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheManager.Benchmarks", "test\CacheManager.Benchmarks\CacheManager.Benchmarks.csproj", "{987C4CD7-D162-4635-8C50-214A25494676}" @@ -91,6 +89,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheManager.Examples.Confi EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheManager.Serialization.DataContract", "src\CacheManager.Serialization.DataContract\CacheManager.Serialization.DataContract.csproj", "{38709D89-E43C-44E3-A865-39BBEBF28D98}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AspNetCore.2.1", "AspNetCore.2.1", "{B49ECA3E-A2D8-4D7E-A46E-79434987B795}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AspNetCore.2.2", "AspNetCore.2.2", "{80DA481C-D9B3-4061-BA77-0C97C7551AC0}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AspNetCore.3.0", "AspNetCore.3.0", "{CF22CA37-DEF7-4C89-AF28-030FC2417549}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web", "samples\AspNetCore.2.1\Web.csproj", "{8B12A86A-2A90-44AB-A2CA-404F47153A37}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web", "samples\AspNetCore.2.2\Web.csproj", "{531D2F7D-1772-48F4-9151-C2DA90AA6507}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web", "samples\AspNetCore.3.0\Web.csproj", "{EA732407-C45C-4E06-8949-CB7CE6226697}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -157,10 +167,6 @@ Global {85CD8BC7-3E72-422E-AF91-6FDF2133E155}.Debug|Any CPU.Build.0 = Debug|Any CPU {85CD8BC7-3E72-422E-AF91-6FDF2133E155}.Release|Any CPU.ActiveCfg = Release|Any CPU {85CD8BC7-3E72-422E-AF91-6FDF2133E155}.Release|Any CPU.Build.0 = Release|Any CPU - {CB9C05BF-E567-412F-B3C8-C85289E60DBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CB9C05BF-E567-412F-B3C8-C85289E60DBC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CB9C05BF-E567-412F-B3C8-C85289E60DBC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CB9C05BF-E567-412F-B3C8-C85289E60DBC}.Release|Any CPU.Build.0 = Release|Any CPU {2FB30F61-B2E7-43AC-80AF-C45218F1D4BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2FB30F61-B2E7-43AC-80AF-C45218F1D4BA}.Debug|Any CPU.Build.0 = Debug|Any CPU {2FB30F61-B2E7-43AC-80AF-C45218F1D4BA}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -181,6 +187,18 @@ Global {38709D89-E43C-44E3-A865-39BBEBF28D98}.Debug|Any CPU.Build.0 = Debug|Any CPU {38709D89-E43C-44E3-A865-39BBEBF28D98}.Release|Any CPU.ActiveCfg = Release|Any CPU {38709D89-E43C-44E3-A865-39BBEBF28D98}.Release|Any CPU.Build.0 = Release|Any CPU + {8B12A86A-2A90-44AB-A2CA-404F47153A37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8B12A86A-2A90-44AB-A2CA-404F47153A37}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8B12A86A-2A90-44AB-A2CA-404F47153A37}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8B12A86A-2A90-44AB-A2CA-404F47153A37}.Release|Any CPU.Build.0 = Release|Any CPU + {531D2F7D-1772-48F4-9151-C2DA90AA6507}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {531D2F7D-1772-48F4-9151-C2DA90AA6507}.Debug|Any CPU.Build.0 = Debug|Any CPU + {531D2F7D-1772-48F4-9151-C2DA90AA6507}.Release|Any CPU.ActiveCfg = Release|Any CPU + {531D2F7D-1772-48F4-9151-C2DA90AA6507}.Release|Any CPU.Build.0 = Release|Any CPU + {EA732407-C45C-4E06-8949-CB7CE6226697}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EA732407-C45C-4E06-8949-CB7CE6226697}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EA732407-C45C-4E06-8949-CB7CE6226697}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EA732407-C45C-4E06-8949-CB7CE6226697}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -202,7 +220,6 @@ Global {360D0B25-F9EB-4553-92DC-FB0FD24EF344} = {C013E552-43F5-4496-BE29-DB401C3334BB} {48DD6E04-0CFD-4FB4-A178-749B0FBFBA36} = {58CC885F-40A7-4C82-990D-3F36AAA088A7} {85CD8BC7-3E72-422E-AF91-6FDF2133E155} = {58CC885F-40A7-4C82-990D-3F36AAA088A7} - {CB9C05BF-E567-412F-B3C8-C85289E60DBC} = {C23C189C-3AFC-45D6-8E32-9B5E190BBA20} {2FB30F61-B2E7-43AC-80AF-C45218F1D4BA} = {58CC885F-40A7-4C82-990D-3F36AAA088A7} {987C4CD7-D162-4635-8C50-214A25494676} = {C013E552-43F5-4496-BE29-DB401C3334BB} {CB286D98-C974-4266-B8F2-1F9DE8B2B0EC} = {D83D3737-3BD4-4AEE-8C42-CDED9410DB79} @@ -210,9 +227,12 @@ Global {AA4A2053-1ECD-4331-B805-BF8062B04CFC} = {C013E552-43F5-4496-BE29-DB401C3334BB} {29E6BC78-BD1E-4E83-AAC6-D3D21DA883AB} = {C23C189C-3AFC-45D6-8E32-9B5E190BBA20} {38709D89-E43C-44E3-A865-39BBEBF28D98} = {58CC885F-40A7-4C82-990D-3F36AAA088A7} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {AE6516EA-95EF-4F46-9DF9-752B5CD432E1} + {B49ECA3E-A2D8-4D7E-A46E-79434987B795} = {C23C189C-3AFC-45D6-8E32-9B5E190BBA20} + {80DA481C-D9B3-4061-BA77-0C97C7551AC0} = {C23C189C-3AFC-45D6-8E32-9B5E190BBA20} + {CF22CA37-DEF7-4C89-AF28-030FC2417549} = {C23C189C-3AFC-45D6-8E32-9B5E190BBA20} + {8B12A86A-2A90-44AB-A2CA-404F47153A37} = {B49ECA3E-A2D8-4D7E-A46E-79434987B795} + {531D2F7D-1772-48F4-9151-C2DA90AA6507} = {80DA481C-D9B3-4061-BA77-0C97C7551AC0} + {EA732407-C45C-4E06-8949-CB7CE6226697} = {CF22CA37-DEF7-4C89-AF28-030FC2417549} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {55AD6484-7AB9-4CE1-B604-3410DA3876C0} diff --git a/appveyor.yml b/appveyor.yml index 0ace97c1..f6c296b5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,6 +1,6 @@ -version: 1.2.0-beta-{build} +version: 2.0.0-beta-{build} skip_tags: true -image: Visual Studio 2017 +image: Visual Studio 2019 configuration: Release clone_folder: C:\projects\CacheManager\ init: diff --git a/samples/AspnetCore.WebApp/Controllers/ValuesController.cs b/samples/AspNetCore.2.1/Controllers/ValuesController.cs similarity index 100% rename from samples/AspnetCore.WebApp/Controllers/ValuesController.cs rename to samples/AspNetCore.2.1/Controllers/ValuesController.cs diff --git a/samples/AspnetCore.WebApp/Program.cs b/samples/AspNetCore.2.1/Program.cs similarity index 100% rename from samples/AspnetCore.WebApp/Program.cs rename to samples/AspNetCore.2.1/Program.cs diff --git a/samples/AspNetCore.2.1/Properties/launchSettings.json b/samples/AspNetCore.2.1/Properties/launchSettings.json new file mode 100644 index 00000000..730e96ba --- /dev/null +++ b/samples/AspNetCore.2.1/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "profiles": { + "AspnetCore.WebApp": { + "commandName": "Project", + "launchBrowser": false, + "launchUrl": "http://localhost:5000/swagger/ui", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:5000" + } + } +} diff --git a/samples/AspnetCore.WebApp/Startup.cs b/samples/AspNetCore.2.1/Startup.cs similarity index 98% rename from samples/AspnetCore.WebApp/Startup.cs rename to samples/AspNetCore.2.1/Startup.cs index 1d5c6f8f..56136c32 100644 --- a/samples/AspnetCore.WebApp/Startup.cs +++ b/samples/AspNetCore.2.1/Startup.cs @@ -85,7 +85,7 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF { if (ctx.Request.Path.StartsWithSegments("/")) { - ctx.Response.Redirect("/swagger/ui"); + ctx.Response.Redirect("/swagger/"); } else { diff --git a/samples/AspnetCore.WebApp/AspnetCore.WebApp.csproj b/samples/AspNetCore.2.1/Web.csproj similarity index 82% rename from samples/AspnetCore.WebApp/AspnetCore.WebApp.csproj rename to samples/AspNetCore.2.1/Web.csproj index d418524c..bf42c7a8 100644 --- a/samples/AspnetCore.WebApp/AspnetCore.WebApp.csproj +++ b/samples/AspNetCore.2.1/Web.csproj @@ -8,12 +8,6 @@ AspnetCore.WebApp - - - PreserveNewest - - - @@ -23,7 +17,7 @@ - + \ No newline at end of file diff --git a/samples/AspnetCore.WebApp/appsettings.json b/samples/AspNetCore.2.1/appsettings.json similarity index 100% rename from samples/AspnetCore.WebApp/appsettings.json rename to samples/AspNetCore.2.1/appsettings.json diff --git a/samples/AspnetCore.WebApp/cache.json b/samples/AspNetCore.2.1/cache.json similarity index 100% rename from samples/AspnetCore.WebApp/cache.json rename to samples/AspNetCore.2.1/cache.json diff --git a/samples/AspnetCore.WebApp/web.config b/samples/AspNetCore.2.1/web.config similarity index 100% rename from samples/AspnetCore.WebApp/web.config rename to samples/AspNetCore.2.1/web.config diff --git a/samples/AspNetCore.2.2/Controllers/ValuesController.cs b/samples/AspNetCore.2.2/Controllers/ValuesController.cs new file mode 100644 index 00000000..8c16b9b0 --- /dev/null +++ b/samples/AspNetCore.2.2/Controllers/ValuesController.cs @@ -0,0 +1,70 @@ +using System; +using System.Linq; +using CacheManager.Core; +using Microsoft.AspNetCore.Mvc; + +namespace AspnetCore.WebApp.Controllers +{ + [Route("api/[controller]")] + public class ValuesController : Controller + { + private readonly ICacheManager _cache; + + public ValuesController(ICacheManager valuesCache, ICacheManager intCache, ICacheManager dates) + { + _cache = valuesCache; + + dates.Add("now", DateTime.UtcNow); + intCache.Add("count", 1); + } + + // DELETE api/values/key + [HttpDelete("{key}")] + public IActionResult Delete(string key) + { + if (_cache.Remove(key)) + { + return Ok(); + } + + return NotFound(); + } + + // GET api/values/key + [HttpGet("{key}")] + public IActionResult Get(string key) + { + var value = _cache.GetCacheItem(key); + if (value == null) + { + return NotFound(); + } + + return Json(value.Value); + } + + // POST api/values/key + [HttpPost("{key}")] + public IActionResult Post(string key, [FromBody]string value) + { + if (_cache.Add(key, value)) + { + return Ok(); + } + + return BadRequest("Item already exists."); + } + + // PUT api/values/key + [HttpPut("{key}")] + public IActionResult Put(string key, [FromBody]string value) + { + if (_cache.AddOrUpdate(key, value, (v) => value) != null) + { + return Ok(); + } + + return NotFound(); + } + } +} \ No newline at end of file diff --git a/samples/AspNetCore.2.2/Program.cs b/samples/AspNetCore.2.2/Program.cs new file mode 100644 index 00000000..1b58aeb7 --- /dev/null +++ b/samples/AspNetCore.2.2/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.IO; +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; + +namespace AspnetCore.WebApp +{ + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } + } +} \ No newline at end of file diff --git a/samples/AspNetCore.2.2/Properties/launchSettings.json b/samples/AspNetCore.2.2/Properties/launchSettings.json new file mode 100644 index 00000000..730e96ba --- /dev/null +++ b/samples/AspNetCore.2.2/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "profiles": { + "AspnetCore.WebApp": { + "commandName": "Project", + "launchBrowser": false, + "launchUrl": "http://localhost:5000/swagger/ui", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:5000" + } + } +} diff --git a/samples/AspNetCore.2.2/Startup.cs b/samples/AspNetCore.2.2/Startup.cs new file mode 100644 index 00000000..56136c32 --- /dev/null +++ b/samples/AspNetCore.2.2/Startup.cs @@ -0,0 +1,106 @@ +using System; +using System.Linq; +using CacheManager.Core; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace AspnetCore.WebApp +{ + using Microsoft.Extensions.Configuration; + using Swashbuckle.AspNetCore.Swagger; + + public class Startup + { + public Startup(IHostingEnvironment env) + { + var builder = new ConfigurationBuilder() + .SetBasePath(env.ContentRootPath) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) + // adding cache.json which contains cachemanager configuration(s) + .AddJsonFile("cache.json", optional: false) + .AddEnvironmentVariables(); + + Configuration = builder.Build(); + } + + public IConfigurationRoot Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + services.AddMvc(); + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", + new Info + { + Title = "My API - V1", + Version = "v1" + } + ); + }); + + services.AddLogging(c => c.AddConsole().AddDebug().AddConfiguration(Configuration)); + + // using the new overload which adds a singleton of the configuration to services and the configure method to add logging + // TODO: still not 100% happy with the logging part + services.AddCacheManagerConfiguration(Configuration, cfg => cfg.WithMicrosoftLogging(services)); + + // uses a refined configurastion (this will not log, as we added the MS Logger only to the configuration above + services.AddCacheManager(Configuration, configure: builder => builder.WithJsonSerializer()); + + // creates a completely new configuration for this instance (also not logging) + services.AddCacheManager(inline => inline.WithDictionaryHandle()); + + // any other type will be this. Configurastion used will be the one defined by AddCacheManagerConfiguration earlier. + services.AddCacheManager(); + } + + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + { + // add console logging with the configured log levels from appsettings.json + loggerFactory.AddConsole(Configuration.GetSection("Logging")); + + // give some error details in debug mode + if (env.IsDevelopment()) + { + app.Use(async (ctx, next) => + { + try + { + await next.Invoke(); + } + catch (Exception ex) + { + await ctx.Response.WriteAsync($"{{\"error\": \"{ex}\"}}"); + } + }); + } + + // lets redirect to the swagger ui, there is nothing else to display otherwise ;) + app.Use(async (ctx, next) => + { + if (ctx.Request.Path.StartsWithSegments("/")) + { + ctx.Response.Redirect("/swagger/"); + } + else + { + await next.Invoke(); + } + }); + + //app.UseStaticFiles(); + app.UseMvc(); + + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); + }); + } + } +} diff --git a/samples/AspNetCore.2.2/Web.csproj b/samples/AspNetCore.2.2/Web.csproj new file mode 100644 index 00000000..4d23e7b7 --- /dev/null +++ b/samples/AspNetCore.2.2/Web.csproj @@ -0,0 +1,23 @@ + + + + netcoreapp2.2 + true + AspnetCore.WebApp + Exe + AspnetCore.WebApp + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/AspNetCore.2.2/appsettings.json b/samples/AspNetCore.2.2/appsettings.json new file mode 100644 index 00000000..bd260c7a --- /dev/null +++ b/samples/AspNetCore.2.2/appsettings.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "IncludeScopes": false, + "LogLevel": { + "Default": "Debug", + "CacheManager": "Debug", + "System": "Error", + "Microsoft": "Error" + } + } +} diff --git a/samples/AspNetCore.2.2/cache.json b/samples/AspNetCore.2.2/cache.json new file mode 100644 index 00000000..b79fc464 --- /dev/null +++ b/samples/AspNetCore.2.2/cache.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://cachemanager.michaco.net/schemas/cachemanager.json#", + "cacheManagers": [ + { + "name": "simpleMemoryCache", + "handles": [ + { + "knownType": "Dictionary" + } + ] + } + ] +} diff --git a/samples/AspNetCore.2.2/web.config b/samples/AspNetCore.2.2/web.config new file mode 100644 index 00000000..dc0514fc --- /dev/null +++ b/samples/AspNetCore.2.2/web.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + diff --git a/samples/AspNetCore.3.0/Controllers/ValuesController.cs b/samples/AspNetCore.3.0/Controllers/ValuesController.cs new file mode 100644 index 00000000..8c16b9b0 --- /dev/null +++ b/samples/AspNetCore.3.0/Controllers/ValuesController.cs @@ -0,0 +1,70 @@ +using System; +using System.Linq; +using CacheManager.Core; +using Microsoft.AspNetCore.Mvc; + +namespace AspnetCore.WebApp.Controllers +{ + [Route("api/[controller]")] + public class ValuesController : Controller + { + private readonly ICacheManager _cache; + + public ValuesController(ICacheManager valuesCache, ICacheManager intCache, ICacheManager dates) + { + _cache = valuesCache; + + dates.Add("now", DateTime.UtcNow); + intCache.Add("count", 1); + } + + // DELETE api/values/key + [HttpDelete("{key}")] + public IActionResult Delete(string key) + { + if (_cache.Remove(key)) + { + return Ok(); + } + + return NotFound(); + } + + // GET api/values/key + [HttpGet("{key}")] + public IActionResult Get(string key) + { + var value = _cache.GetCacheItem(key); + if (value == null) + { + return NotFound(); + } + + return Json(value.Value); + } + + // POST api/values/key + [HttpPost("{key}")] + public IActionResult Post(string key, [FromBody]string value) + { + if (_cache.Add(key, value)) + { + return Ok(); + } + + return BadRequest("Item already exists."); + } + + // PUT api/values/key + [HttpPut("{key}")] + public IActionResult Put(string key, [FromBody]string value) + { + if (_cache.AddOrUpdate(key, value, (v) => value) != null) + { + return Ok(); + } + + return NotFound(); + } + } +} \ No newline at end of file diff --git a/samples/AspNetCore.3.0/Program.cs b/samples/AspNetCore.3.0/Program.cs new file mode 100644 index 00000000..1b58aeb7 --- /dev/null +++ b/samples/AspNetCore.3.0/Program.cs @@ -0,0 +1,23 @@ +using System; +using System.IO; +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; + +namespace AspnetCore.WebApp +{ + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup() + .Build(); + + host.Run(); + } + } +} \ No newline at end of file diff --git a/samples/AspNetCore.3.0/Properties/launchSettings.json b/samples/AspNetCore.3.0/Properties/launchSettings.json new file mode 100644 index 00000000..730e96ba --- /dev/null +++ b/samples/AspNetCore.3.0/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "profiles": { + "AspnetCore.WebApp": { + "commandName": "Project", + "launchBrowser": false, + "launchUrl": "http://localhost:5000/swagger/ui", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:5000" + } + } +} diff --git a/samples/AspNetCore.3.0/Startup.cs b/samples/AspNetCore.3.0/Startup.cs new file mode 100644 index 00000000..56136c32 --- /dev/null +++ b/samples/AspNetCore.3.0/Startup.cs @@ -0,0 +1,106 @@ +using System; +using System.Linq; +using CacheManager.Core; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace AspnetCore.WebApp +{ + using Microsoft.Extensions.Configuration; + using Swashbuckle.AspNetCore.Swagger; + + public class Startup + { + public Startup(IHostingEnvironment env) + { + var builder = new ConfigurationBuilder() + .SetBasePath(env.ContentRootPath) + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) + // adding cache.json which contains cachemanager configuration(s) + .AddJsonFile("cache.json", optional: false) + .AddEnvironmentVariables(); + + Configuration = builder.Build(); + } + + public IConfigurationRoot Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + services.AddMvc(); + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", + new Info + { + Title = "My API - V1", + Version = "v1" + } + ); + }); + + services.AddLogging(c => c.AddConsole().AddDebug().AddConfiguration(Configuration)); + + // using the new overload which adds a singleton of the configuration to services and the configure method to add logging + // TODO: still not 100% happy with the logging part + services.AddCacheManagerConfiguration(Configuration, cfg => cfg.WithMicrosoftLogging(services)); + + // uses a refined configurastion (this will not log, as we added the MS Logger only to the configuration above + services.AddCacheManager(Configuration, configure: builder => builder.WithJsonSerializer()); + + // creates a completely new configuration for this instance (also not logging) + services.AddCacheManager(inline => inline.WithDictionaryHandle()); + + // any other type will be this. Configurastion used will be the one defined by AddCacheManagerConfiguration earlier. + services.AddCacheManager(); + } + + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + { + // add console logging with the configured log levels from appsettings.json + loggerFactory.AddConsole(Configuration.GetSection("Logging")); + + // give some error details in debug mode + if (env.IsDevelopment()) + { + app.Use(async (ctx, next) => + { + try + { + await next.Invoke(); + } + catch (Exception ex) + { + await ctx.Response.WriteAsync($"{{\"error\": \"{ex}\"}}"); + } + }); + } + + // lets redirect to the swagger ui, there is nothing else to display otherwise ;) + app.Use(async (ctx, next) => + { + if (ctx.Request.Path.StartsWithSegments("/")) + { + ctx.Response.Redirect("/swagger/"); + } + else + { + await next.Invoke(); + } + }); + + //app.UseStaticFiles(); + app.UseMvc(); + + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); + }); + } + } +} diff --git a/samples/AspNetCore.3.0/Web.csproj b/samples/AspNetCore.3.0/Web.csproj new file mode 100644 index 00000000..a53206b7 --- /dev/null +++ b/samples/AspNetCore.3.0/Web.csproj @@ -0,0 +1,22 @@ + + + + netcoreapp3.0 + true + AspnetCore.WebApp + Exe + AspnetCore.WebApp + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/AspNetCore.3.0/appsettings.json b/samples/AspNetCore.3.0/appsettings.json new file mode 100644 index 00000000..bd260c7a --- /dev/null +++ b/samples/AspNetCore.3.0/appsettings.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "IncludeScopes": false, + "LogLevel": { + "Default": "Debug", + "CacheManager": "Debug", + "System": "Error", + "Microsoft": "Error" + } + } +} diff --git a/samples/AspNetCore.3.0/cache.json b/samples/AspNetCore.3.0/cache.json new file mode 100644 index 00000000..b79fc464 --- /dev/null +++ b/samples/AspNetCore.3.0/cache.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://cachemanager.michaco.net/schemas/cachemanager.json#", + "cacheManagers": [ + { + "name": "simpleMemoryCache", + "handles": [ + { + "knownType": "Dictionary" + } + ] + } + ] +} diff --git a/samples/AspNetCore.3.0/web.config b/samples/AspNetCore.3.0/web.config new file mode 100644 index 00000000..dc0514fc --- /dev/null +++ b/samples/AspNetCore.3.0/web.config @@ -0,0 +1,14 @@ + + + + + + + + + + + + diff --git a/samples/AspnetCore.WebApp/Properties/launchSettings.json b/samples/AspnetCore.WebApp/Properties/launchSettings.json deleted file mode 100644 index 2d46cd93..00000000 --- a/samples/AspnetCore.WebApp/Properties/launchSettings.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:58186", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": false, - "launchUrl": "/swagger/ui", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "AspnetCore.WebApp": { - "commandName": "Project", - "launchBrowser": false, - "launchUrl": "http://localhost:5000/swagger/ui", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:5000" - } - } -} \ No newline at end of file diff --git a/test/CacheManager.Tests/CacheFactoryTests.cs b/test/CacheManager.Tests/CacheFactoryTests.cs index cf0d97c8..08902a46 100644 --- a/test/CacheManager.Tests/CacheFactoryTests.cs +++ b/test/CacheManager.Tests/CacheFactoryTests.cs @@ -29,7 +29,8 @@ public void ConfigurationBuilder_NamedCtorNull() { Action act = () => new ConfigurationBuilder((string)null); - act.Should().Throw().WithMessage("*name*"); + act.Should().Throw() + .And.ParamName.Equals("name"); } [Fact] @@ -37,7 +38,8 @@ public void ConfigurationBuilder_ForConfigCtorNull() { Action act = () => new ConfigurationBuilder((ICacheManagerConfiguration)null); - act.Should().Throw().WithMessage("*forConfiguration*"); + act.Should().Throw() + .And.ParamName.Equals("forConfiguration"); } [Fact] @@ -45,7 +47,8 @@ public void ConfigurationBuilder_NamedForConfigCtorNull() { Action act = () => new ConfigurationBuilder(null, null); - act.Should().Throw().WithMessage("*name*"); + act.Should().Throw() + .And.ParamName.Equals("name"); } [Fact] @@ -53,7 +56,8 @@ public void ConfigurationBuilder_NamedForConfigCtorNullB() { Action act = () => new ConfigurationBuilder("name", null); - act.Should().Throw().WithMessage("*forConfiguration*"); + act.Should().Throw() + .And.ParamName.Equals("forConfiguration"); } [Fact] @@ -97,7 +101,7 @@ public void CacheFactory_FromConfig_NullCheck_A() // assert act.Should().Throw() - .WithMessage("*Parameter name: configuration*"); + .And.ParamName.Equals("configuration"); } [Fact] @@ -111,7 +115,7 @@ public void CacheFactory_FromConfig_NullCheck_B() // assert act.Should().Throw() - .WithMessage("*Parameter name: configName*"); + .And.ParamName.Equals("configName"); } [Fact] @@ -170,7 +174,7 @@ public void CacheFactory_FromConfig_NonGeneric_NullCheck_A() // assert act.Should().Throw() - .WithMessage("*cacheValueType*"); + .And.ParamName.Equals("cacheValueType"); } [Fact] @@ -184,7 +188,7 @@ public void CacheFactory_FromConfig_NonGeneric_NullCheck_B() // assert act.Should().Throw() - .WithMessage("*cacheValueType*"); + .And.ParamName.Equals("cacheValueType"); } [Fact] @@ -199,7 +203,7 @@ public void CacheFactory_FromConfig_NonGeneric_NullCheck_C() // assert act.Should().Throw() - .WithMessage("*cacheValueType*"); + .And.ParamName.Equals("cacheValueType"); } #endif @@ -218,7 +222,7 @@ public void CacheFactory_Build_WithHandle_WithoutName() // assert act.Should().Throw() - .WithMessage("*Parameter name: handleName*"); + .And.ParamName.Equals("handleName"); } [Fact] @@ -232,7 +236,7 @@ public void CacheFactory_Build_ParamB() // assert act.Should().Throw() - .WithMessage("*Parameter name: settings*"); + .And.ParamName.Equals("settings"); } [Fact] @@ -418,7 +422,7 @@ public void CacheFactory_Build_WithRedisBackplaneNoName() // assert act.Should().Throw() - .WithMessage("*Parameter name: configurationKey*"); + .And.ParamName.Equals("configurationKey"); } [Fact] @@ -433,7 +437,7 @@ public void CacheFactory_Build_WithRedisConfigurationNoKeyA() // assert act.Should().Throw() - .WithMessage("*Parameter name: configurationKey*"); + .And.ParamName.Equals("configurationKey"); } [Fact] @@ -448,7 +452,7 @@ public void CacheFactory_Build_WithRedisConfigurationNoKeyB() // assert act.Should().Throw() - .WithMessage("*Parameter name: configurationKey*"); + .And.ParamName.Equals("configurationKey"); } [Fact] @@ -463,7 +467,7 @@ public void CacheFactory_Build_WithRedisConfigurationInvalidEndpoint() // assert act.Should().Throw() - .WithMessage("*Parameter name: host*"); + .And.ParamName.Equals("configurationKey"); } [Fact] diff --git a/test/CacheManager.Tests/CacheItemValidation.cs b/test/CacheManager.Tests/CacheItemValidation.cs index 16232fcf..4597f7e7 100644 --- a/test/CacheManager.Tests/CacheItemValidation.cs +++ b/test/CacheManager.Tests/CacheItemValidation.cs @@ -230,7 +230,8 @@ public void CacheItemValidation_Ctor1_EmptyKey() Action act = () => new CacheItem(key, value); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -245,7 +246,8 @@ public void CacheItemValidation_Ctor1_NullKey() Action act = () => new CacheItem(key, value); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -260,7 +262,8 @@ public void CacheItemValidation_Ctor1_WhitespaceKey() Action act = () => new CacheItem(key, value); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -275,7 +278,8 @@ public void CacheItemValidation_Ctor1_NullValue() Action act = () => new CacheItem(key, value); // assert - act.Should().Throw().WithMessage("*cannot be null.\r\nParameter name: value"); + act.Should().Throw() + .And.ParamName.Equals("value"); } [Fact] @@ -315,7 +319,8 @@ public void CacheItemValidation_Ctor2_EmptyKey() Action act = () => new CacheItem(key, region, value); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -331,7 +336,8 @@ public void CacheItemValidation_Ctor2_NullKey() Action act = () => new CacheItem(key, region, value); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -347,7 +353,8 @@ public void CacheItemValidation_Ctor2_WhitespaceKey() Action act = () => new CacheItem(key, region, value); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -363,7 +370,8 @@ public void CacheItemValidation_Ctor2_NullValue() Action act = () => new CacheItem(key, region, value); // assert - act.Should().Throw().WithMessage("*cannot be null.\r\nParameter name: value"); + act.Should().Throw() + .And.ParamName.Equals("value"); } [Fact] @@ -380,7 +388,7 @@ public void CacheItemValidation_Ctor2_EmptyRegion() // assert act.Should().Throw() - .WithMessage("*Parameter name: region"); + .And.ParamName.Equals("region"); } [Fact] @@ -397,7 +405,7 @@ public void CacheItemValidation_Ctor2_NullRegion() // assert act.Should().Throw() - .WithMessage("*Parameter name: region"); + .And.ParamName.Equals("region"); } [Fact] @@ -414,7 +422,7 @@ public void CacheItemValidation_Ctor2_WhitespaceRegion() // assert act.Should().Throw() - .WithMessage("*Parameter name: region"); + .And.ParamName.Equals("region"); } [Fact] @@ -456,7 +464,8 @@ public void CacheItemValidation_Ctor3_EmptyKey() Action act = () => new CacheItem(key, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -473,7 +482,8 @@ public void CacheItemValidation_Ctor3_NullKey() Action act = () => new CacheItem(key, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*cannot be null.\r\nParameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -490,7 +500,8 @@ public void CacheItemValidation_Ctor3_WhitespaceKey() Action act = () => new CacheItem(key, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -507,7 +518,8 @@ public void CacheItemValidation_Ctor3_NullValue() Action act = () => new CacheItem(key, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*cannot be null.\r\nParameter name: value"); + act.Should().Throw() + .And.ParamName.Equals("value"); } [Fact] @@ -551,7 +563,8 @@ public void CacheItemValidation_Ctor4_EmptyKey() Action act = () => new CacheItem(key, region, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -569,7 +582,8 @@ public void CacheItemValidation_Ctor4_NullKey() Action act = () => new CacheItem(key, region, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -587,7 +601,8 @@ public void CacheItemValidation_Ctor4_WhitespaceKey() Action act = () => new CacheItem(key, region, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*Parameter name: key"); + act.Should().Throw() + .And.ParamName.Equals("key"); } [Fact] @@ -605,7 +620,8 @@ public void CacheItemValidation_Ctor4_NullValue() Action act = () => new CacheItem(key, region, value, mode, timeout); // assert - act.Should().Throw().WithMessage("*Parameter name: value"); + act.Should().Throw() + .And.ParamName.Equals("value"); } [Fact] @@ -624,7 +640,7 @@ public void CacheItemValidation_Ctor4_EmptyRegion() // assert act.Should().Throw() - .WithMessage("*Parameter name: region"); + .And.ParamName.Equals("region"); } [Fact] @@ -643,7 +659,7 @@ public void CacheItemValidation_Ctor4_NullRegion() // assert act.Should().Throw() - .WithMessage("*Parameter name: region"); + .And.ParamName.Equals("region"); } [Fact] @@ -662,7 +678,7 @@ public void CacheItemValidation_Ctor4_WhitespaceRegion() // assert act.Should().Throw() - .WithMessage("*Parameter name: region"); + .And.ParamName.Equals("region"); } [Fact] @@ -709,4 +725,4 @@ public void CacheItemValidation_Ctor_ExpirationTimeoutDefaults() .And.Match>(p => p.Value == value); } } -} \ No newline at end of file +} diff --git a/test/CacheManager.Tests/CacheManager.Tests.csproj b/test/CacheManager.Tests/CacheManager.Tests.csproj index 5580ac87..d3aa1dc9 100644 --- a/test/CacheManager.Tests/CacheManager.Tests.csproj +++ b/test/CacheManager.Tests/CacheManager.Tests.csproj @@ -2,7 +2,7 @@ - net461;netcoreapp2.1; + net461;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0; 1.0.0 CacheManager.Tests @@ -21,14 +21,20 @@ - - PreserveNewest + + Always App.config - + @@ -41,13 +47,18 @@ - - - - - - - + + + + + + + + + + + + @@ -62,6 +73,13 @@ + + + + + + + @@ -74,6 +92,12 @@ $(DefineConstants);REDISENABLED;NETCOREAPP2; + + $(DefineConstants);REDISENABLED;NETCOREAPP2; + + + $(DefineConstants);REDISENABLED;NETCOREAPP2; + - - - - - - - - diff --git a/samples/AspNetCore.3.0/Controllers/ValuesController.cs b/samples/AspNetCore.3.0/Controllers/ValuesController.cs index 69a01310..923d7d4c 100644 --- a/samples/AspNetCore.3.0/Controllers/ValuesController.cs +++ b/samples/AspNetCore.3.0/Controllers/ValuesController.cs @@ -13,7 +13,7 @@ public class ValuesController : Controller public ValuesController(ICacheManager valuesCache, ICacheManager nullableInts) { _cache = valuesCache; - nullableInts.Add("key", null); + nullableInts.Add("key", 1); } // DELETE api/values/key diff --git a/samples/AspNetCore.3.0/Startup.cs b/samples/AspNetCore.3.0/Startup.cs index d027d21c..9d5cb5b6 100644 --- a/samples/AspNetCore.3.0/Startup.cs +++ b/samples/AspNetCore.3.0/Startup.cs @@ -15,16 +15,19 @@ namespace AspnetCore.WebApp public class Startup { - public Startup(IWebHostEnvironment env, IConfiguration configuration) + public Startup(IWebHostEnvironment env, IConfiguration configuration, ILoggerFactory loggerFactory) { HostingEnvironment = env ?? throw new ArgumentNullException(nameof(env)); Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); } public IWebHostEnvironment HostingEnvironment { get; } public IConfiguration Configuration { get; } + public ILoggerFactory LoggerFactory { get; } + public void ConfigureServices(IServiceCollection services) { services.AddMvc(); @@ -42,15 +45,15 @@ public void ConfigureServices(IServiceCollection services) // using the new overload which adds a singleton of the configuration to services and the configure method to add logging // TODO: still not 100% happy with the logging part - services.AddCacheManagerConfiguration(Configuration, cfg => cfg.WithMicrosoftLogging(services)); + services.AddCacheManagerConfiguration(Configuration, cfg => cfg.WithMicrosoftLogging(LoggerFactory)); - // uses a refined configurastion (this will not log, as we added the MS Logger only to the configuration above + // uses a refined configuration (this will not log, as we added the MS Logger only to the configuration above services.AddCacheManager(Configuration, configure: builder => builder.WithJsonSerializer()); // creates a completely new configuration for this instance (also not logging) services.AddCacheManager(inline => inline.WithDictionaryHandle()); - // any other type will be this. Configurastion used will be the one defined by AddCacheManagerConfiguration earlier. + // any other type will be this. Configuration used will be the one defined by AddCacheManagerConfiguration earlier. services.AddCacheManager(); } @@ -72,7 +75,7 @@ public void Configure(IApplicationBuilder app) }); } - // lets redirect to the swagger ui, there is nothing else to display otherwise ;) + // lets redirect to the swagger UI, there is nothing else to display otherwise ;) app.Use(async (ctx, next) => { if (ctx.Request.Path.StartsWithSegments("/")) diff --git a/samples/AspNetCore.3.0/Web.csproj b/samples/AspNetCore.3.0/Web.csproj index 8c3e5b69..e20f2d5c 100644 --- a/samples/AspNetCore.3.0/Web.csproj +++ b/samples/AspNetCore.3.0/Web.csproj @@ -1,7 +1,7 @@  - netcoreapp3.0 + netcoreapp3.1 true AspnetCore.WebApp Exe @@ -17,6 +17,6 @@ - + \ No newline at end of file diff --git a/samples/AspNetCore.3.0/appsettings.json b/samples/AspNetCore.3.0/appsettings.json index 1f34c718..7efae0d9 100644 --- a/samples/AspNetCore.3.0/appsettings.json +++ b/samples/AspNetCore.3.0/appsettings.json @@ -1,6 +1,5 @@ { "Logging": { - "IncludeScopes": false, "LogLevel": { "Default": "Debug", "CacheManager": "Trace", diff --git a/samples/CacheManager.Examples/Program.cs b/samples/CacheManager.Examples/Program.cs index 72b24f00..bf37c17a 100644 --- a/samples/CacheManager.Examples/Program.cs +++ b/samples/CacheManager.Examples/Program.cs @@ -52,8 +52,11 @@ private static void MostSimpleCacheManagerC() private static void MostSimpleCacheManagerWithLogging() { + var loggerFactory = new LoggerFactory() + .AddConsole(); + var config = new ConfigurationBuilder() - .WithMicrosoftLogging(l => l.AddConsole(LogLevel.Information)) + .WithMicrosoftLogging(loggerFactory) .WithSystemRuntimeCacheHandle() .Build(); @@ -64,13 +67,16 @@ private static void MostSimpleCacheManagerWithLogging() private static void EditExistingConfiguration() { + var loggerFactory = new LoggerFactory() + .AddConsole(); + var config = new ConfigurationBuilder() .WithSystemRuntimeCacheHandle() .EnableStatistics() .Build(); config = new ConfigurationBuilder(config) - .WithMicrosoftLogging(f => f.AddConsole()) + .WithMicrosoftLogging(loggerFactory) .Build(); } @@ -78,12 +84,12 @@ private static void EditExistingConfiguration() private static void LoggingSample() { + var loggerFactory = new LoggerFactory() + .AddConsole(); + var cache = CacheFactory.Build( c => - c.WithMicrosoftLogging(log => - { - log.AddConsole(LogLevel.Trace); - }) + c.WithMicrosoftLogging(loggerFactory) .WithDictionaryHandle() .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10))); diff --git a/src/CacheManager.Core/CacheItem.cs b/src/CacheManager.Core/CacheItem.cs index 788bc9fd..10750617 100644 --- a/src/CacheManager.Core/CacheItem.cs +++ b/src/CacheManager.Core/CacheItem.cs @@ -1,7 +1,7 @@ using System; using CacheManager.Core.Internal; -#if !NETSTANDARD2 +#if !NETSTANDARD2_0 using System.Runtime.Serialization; @@ -16,7 +16,7 @@ namespace CacheManager.Core /// information needed by the cache handles and manager. /// /// The type of the cache value. -#if !NETSTANDARD2 +#if !NETSTANDARD2_0 [Serializable] public class CacheItem : ISerializable, ICacheItemProperties @@ -83,7 +83,7 @@ protected CacheItem() { } -#if !NETSTANDARD2 +#if !NETSTANDARD2_0 /// /// Initializes a new instance of the class. @@ -226,7 +226,7 @@ public bool IsExpired /// public bool UsesExpirationDefaults { get; } = true; -#if !NETSTANDARD2 +#if !NETSTANDARD2_0 /// /// Populates a with the data diff --git a/src/CacheManager.Core/CacheManager.Core.csproj b/src/CacheManager.Core/CacheManager.Core.csproj index ed848cbd..15da3865 100644 --- a/src/CacheManager.Core/CacheManager.Core.csproj +++ b/src/CacheManager.Core/CacheManager.Core.csproj @@ -2,18 +2,14 @@ CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. The Core library contains all base interfaces and tools. You should install at least one other CacheManager package to get cache handle implementations. - net45;netstandard2.0 + net45;netstandard2.0;netstandard2.1;net50 False Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Memcached - - - + + - - $(DefineConstants);NETSTANDARD2 - \ No newline at end of file diff --git a/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs b/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs index 4eaf7e16..c4892136 100644 --- a/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs +++ b/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs @@ -741,33 +741,6 @@ public ConfigurationBuilderCachePart WithSerializer(Type serializerType, params return this; } -#if !NETSTANDARD2 - - /// - /// Configures a to be used for serialization and deserialization. - /// - /// The builder part. - public ConfigurationBuilderCachePart WithBinarySerializer() - { - Configuration.SerializerType = typeof(BinaryCacheSerializer); - return this; - } - - /// - /// Configures a to be used for serialization and deserialization. - /// - /// The for serialization. - /// The for deserialization. - /// The builder part. - public ConfigurationBuilderCachePart WithBinarySerializer(BinaryFormatter serializationFormatter, BinaryFormatter deserializationFormatter) - { - Configuration.SerializerType = typeof(BinaryCacheSerializer); - Configuration.SerializerTypeArguments = new object[] { serializationFormatter, deserializationFormatter }; - return this; - } - -#endif - /// /// Enables logging by setting the for the cache manager instance. /// diff --git a/src/CacheManager.Core/Internal/BackplaneMessage.cs b/src/CacheManager.Core/Internal/BackplaneMessage.cs index 2fc13a9a..e8dfd604 100644 --- a/src/CacheManager.Core/Internal/BackplaneMessage.cs +++ b/src/CacheManager.Core/Internal/BackplaneMessage.cs @@ -116,9 +116,7 @@ private BackplaneMessage(byte[] owner, BackplaneAction action, string key, strin /// Gets or sets the key. /// /// The key. - public string? Key { get; } - -#pragma warning disable CA1819 // Properties should not return arrays + public string Key { get; } /// /// Gets or sets the owner identity. @@ -126,13 +124,11 @@ private BackplaneMessage(byte[] owner, BackplaneAction action, string key, strin /// The owner identity. public byte[] OwnerIdentity { get; } -#pragma warning restore CA1819 // Properties should not return arrays - /// /// Gets or sets the region. /// /// The region. - public string? Region { get; private set; } + public string Region { get; private set; } /// /// Gets or sets the cache action. @@ -303,7 +299,7 @@ private static void SerializeMessage(MessageWriter writer, BackplaneMessage mess { case Changed: writer.WriteByte((byte)message.ChangeAction); - if (!IsNullOrEmpty(message.Region)) + if (!string.IsNullOrEmpty(message.Region)) { writer.WriteByte(2); writer.WriteString(message.Region); @@ -312,14 +308,12 @@ private static void SerializeMessage(MessageWriter writer, BackplaneMessage mess { writer.WriteByte(1); } - - EnsureNotNull(message.Key, "Key was expected but was null."); writer.WriteString(message.Key); break; case Removed: - if (!IsNullOrEmpty(message.Region)) + if (!string.IsNullOrEmpty(message.Region)) { writer.WriteByte(2); writer.WriteString(message.Region); @@ -328,14 +322,11 @@ private static void SerializeMessage(MessageWriter writer, BackplaneMessage mess { writer.WriteByte(1); } - - EnsureNotNull(message.Key, "Key was expected but was null."); writer.WriteString(message.Key); break; case ClearRegion: - EnsureNotNull(message.Region, "Region was expected but was null."); writer.WriteString(message.Region); break; @@ -354,7 +345,7 @@ private static void SerializeMessage(MessageWriter writer, BackplaneMessage mess /// /// If is null. /// If the message is not valid. - public static IEnumerable Deserialize(byte[] message, byte[]? skipOwner = null) + public static IEnumerable Deserialize(byte[] message, byte[] skipOwner = null) { NotNull(message, nameof(message)); if (message.Length < 5) @@ -381,7 +372,7 @@ public static IEnumerable Deserialize(byte[] message, byte[]? } } - private static BackplaneMessage DeserializeMessage(MessageReader reader, byte[]? existingOwner) + private static BackplaneMessage DeserializeMessage(MessageReader reader, byte[] existingOwner) { var owner = existingOwner ?? reader.ReadBytes(reader.ReadInt()); var action = (BackplaneAction)reader.ReadByte(); diff --git a/src/CacheManager.Core/Internal/BaseCacheHandle.cs b/src/CacheManager.Core/Internal/BaseCacheHandle.cs index 523e9f0b..32480323 100644 --- a/src/CacheManager.Core/Internal/BaseCacheHandle.cs +++ b/src/CacheManager.Core/Internal/BaseCacheHandle.cs @@ -244,7 +244,6 @@ protected override void Dispose(bool disposeManaged) { if (disposeManaged) { - Stats.Dispose(); } base.Dispose(disposeManaged); diff --git a/src/CacheManager.Core/Internal/BinaryCacheSerializer.cs b/src/CacheManager.Core/Internal/BinaryCacheSerializer.cs index 366b3565..31d756cf 100644 --- a/src/CacheManager.Core/Internal/BinaryCacheSerializer.cs +++ b/src/CacheManager.Core/Internal/BinaryCacheSerializer.cs @@ -1,105 +1,105 @@ -#if !NETSTANDARD2 -using System; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Runtime.Serialization.Formatters; -using System.Runtime.Serialization.Formatters.Binary; -using CacheManager.Core.Utility; +////#if NET45 +////using System; +////using System.Diagnostics.CodeAnalysis; +////using System.IO; +////using System.Runtime.Serialization.Formatters; +////using System.Runtime.Serialization.Formatters.Binary; +////using CacheManager.Core.Utility; -namespace CacheManager.Core.Internal -{ - /// - /// Basic binary serialization implementation of the . - /// This implementation will be used in case no other serializer is configured for the cache manager - /// and serialization is needed (only distributed caches will have to serialize the cache value). - /// Binary serialization will not be available in some environments. - /// - public class BinaryCacheSerializer : ICacheSerializer - { - /// - /// Initializes a new instance of the class. - /// - /// The formatter to use to do the serialization. - /// The formatter to use to do the deserialization. - public BinaryCacheSerializer(BinaryFormatter serializationFormatter, BinaryFormatter deserializationFormatter) - { - Guard.NotNull(serializationFormatter, nameof(serializationFormatter)); - Guard.NotNull(deserializationFormatter, nameof(deserializationFormatter)); +////namespace CacheManager.Core.Internal +////{ +//// /// +//// /// Basic binary serialization implementation of the . +//// /// This implementation will be used in case no other serializer is configured for the cache manager +//// /// and serialization is needed (only distributed caches will have to serialize the cache value). +//// /// Binary serialization will not be available in some environments. +//// /// +//// public class BinaryCacheSerializer : ICacheSerializer +//// { +//// /// +//// /// Initializes a new instance of the class. +//// /// +//// /// The formatter to use to do the serialization. +//// /// The formatter to use to do the deserialization. +//// public BinaryCacheSerializer(BinaryFormatter serializationFormatter, BinaryFormatter deserializationFormatter) +//// { +//// Guard.NotNull(serializationFormatter, nameof(serializationFormatter)); +//// Guard.NotNull(deserializationFormatter, nameof(deserializationFormatter)); - SerializationFormatter = serializationFormatter; - DeserializationFormatter = deserializationFormatter; - } +//// SerializationFormatter = serializationFormatter; +//// DeserializationFormatter = deserializationFormatter; +//// } - /// - /// Initializes a new instance of the class. - /// - public BinaryCacheSerializer() - { - DeserializationFormatter = SerializationFormatter = new BinaryFormatter() - { - AssemblyFormat = FormatterAssemblyStyle.Simple - }; - } +//// /// +//// /// Initializes a new instance of the class. +//// /// +//// public BinaryCacheSerializer() +//// { +//// DeserializationFormatter = SerializationFormatter = new BinaryFormatter() +//// { +//// AssemblyFormat = FormatterAssemblyStyle.Simple +//// }; +//// } - /// - /// Gets the formatter which should be used during deserialization. - /// If nothing is specified the default will be used. - /// - /// The deserialization formatter. - public BinaryFormatter DeserializationFormatter { get; } +//// /// +//// /// Gets the formatter which should be used during deserialization. +//// /// If nothing is specified the default will be used. +//// /// +//// /// The deserialization formatter. +//// public BinaryFormatter DeserializationFormatter { get; } - /// - /// Gets the formatter which should be used during serialization. - /// If nothing is specified the default will be used. - /// - /// The serialization formatter. - public BinaryFormatter SerializationFormatter { get; } +//// /// +//// /// Gets the formatter which should be used during serialization. +//// /// If nothing is specified the default will be used. +//// /// +//// /// The serialization formatter. +//// public BinaryFormatter SerializationFormatter { get; } - /// - public object Deserialize(byte[] data, Type target) - { - if (data == null) - { - return null; - } +//// /// +//// public object Deserialize(byte[] data, Type target) +//// { +//// if (data == null) +//// { +//// return null; +//// } - using (var memoryStream = new MemoryStream(data)) - { - return DeserializationFormatter.Deserialize(memoryStream); - } - } +//// using (var memoryStream = new MemoryStream(data)) +//// { +//// return DeserializationFormatter.Deserialize(memoryStream); +//// } +//// } - /// - public CacheItem DeserializeCacheItem(byte[] value, Type valueType) - { - var result = Deserialize(value, valueType); - if (result == null) - { - return null; - } +//// /// +//// public CacheItem DeserializeCacheItem(byte[] value, Type valueType) +//// { +//// var result = Deserialize(value, valueType); +//// if (result == null) +//// { +//// return null; +//// } - return (CacheItem)result; - } +//// return (CacheItem)result; +//// } - /// - public byte[] Serialize(T value) - { - if (value == null) - { - return null; - } +//// /// +//// public byte[] Serialize(T value) +//// { +//// if (value == null) +//// { +//// return null; +//// } - using (var memoryStream = new MemoryStream()) - { - SerializationFormatter.Serialize(memoryStream, value); - var objectDataAsStream = memoryStream.ToArray(); - return objectDataAsStream; - } - } +//// using (var memoryStream = new MemoryStream()) +//// { +//// SerializationFormatter.Serialize(memoryStream, value); +//// var objectDataAsStream = memoryStream.ToArray(); +//// return objectDataAsStream; +//// } +//// } - /// - public byte[] SerializeCacheItem(CacheItem? value) - => Serialize(value); - } -} -#endif +//// /// +//// public byte[] SerializeCacheItem(CacheItem value) +//// => Serialize(value); +//// } +////} +////#endif diff --git a/src/CacheManager.Core/Internal/CachePerformanceCounters.cs b/src/CacheManager.Core/Internal/CachePerformanceCounters.cs index 096f8f72..584d35fa 100644 --- a/src/CacheManager.Core/Internal/CachePerformanceCounters.cs +++ b/src/CacheManager.Core/Internal/CachePerformanceCounters.cs @@ -1,272 +1,271 @@ -namespace CacheManager.Core.Internal -{ - using System; - using System.Diagnostics; - using System.Threading; - using static CacheManager.Core.Utility.Guard; - - internal class CachePerformanceCounters : IDisposable - { - private const string Category = ".NET CacheManager"; - private const string Entries = "Total cache items"; - private const string HitRatio = "Hit ratio"; - private const string HitRatioBase = "Cache hit ratio Base"; - private const string Hits = "Total hits"; - private const string HitsPerSecond = "Avg hits per second"; - private const string Misses = "Total misses"; - private const string ReadsPerSecond = "Avg gets per second"; - private const string Writes = "Total cache writes"; - private const string WritesPerSecond = "Avg writes per second"; - private static readonly int _numStatsCounters = Enum.GetValues(typeof(CacheStatsCounterType)).Length; - - private readonly Timer _counterTimer; - private readonly string _instanceName = string.Empty; - private readonly CacheStats _stats; - private readonly long[] _statsCounts; - private PerformanceCounter[] _counters; - private bool _enabled = true; - private object _updateLock = new object(); - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Mobility", "CA1601:DoNotUseTimersThatPreventPowerStateChanges", Justification = "If perfCounters are enabled, we can live with the power consumption...")] - public CachePerformanceCounters(string cacheName, string handleName, CacheStats stats) - { - NotNullOrWhiteSpace(cacheName, nameof(cacheName)); - - NotNullOrWhiteSpace(handleName, nameof(handleName)); - - var processName = Process.GetCurrentProcess().ProcessName; - - _instanceName = string.Concat(processName + ":" + cacheName + ":" + handleName); - - var invalidInstanceChars = new string[] { "(", ")", "#", "\\", "/" }; - - foreach (var ichar in invalidInstanceChars) - { - _instanceName = _instanceName.Replace(ichar, string.Empty); - } - - if (_instanceName.Length > 128) - { - _instanceName = _instanceName.Substring(0, 128); - } - - InitializeCounters(); - _stats = stats; - _statsCounts = new long[_numStatsCounters]; - - if (_enabled) - { - _counterTimer = new Timer(new TimerCallback(PerformanceCounterWorker), null, 450L, 450L); - } - } - - ~CachePerformanceCounters() - { - Dispose(false); - } - - public void Decrement(CachePerformanceCounterType type) - { - GetCounter(type).Decrement(); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - public void Increment(CachePerformanceCounterType type) - { - GetCounter(type).Increment(); - } - - public void IncrementBy(CachePerformanceCounterType type, long value) - { - GetCounter(type).IncrementBy(value); - } - - public void SetValue(CachePerformanceCounterType type, long value) - { - GetCounter(type).RawValue = value < 0 ? 0 : value; - } - - private static void InitializeCategory() - { - if (PerformanceCounterCategory.Exists(Category)) - { - return; - } - - PerformanceCounterCategory.Create( - Category, - "CacheManager counters per handle", - PerformanceCounterCategoryType.MultiInstance, - new CounterCreationDataCollection - { - new CounterCreationData - { - CounterName = Entries, - CounterHelp = "Current number of cache items stored within the cache handle", - CounterType = PerformanceCounterType.NumberOfItems64 - }, - new CounterCreationData - { - CounterName = HitRatio, - CounterHelp = "Cache hit ratio of the cache handle", - CounterType = PerformanceCounterType.AverageCount64 - }, - new CounterCreationData - { - CounterName = HitRatioBase, - CounterHelp = HitRatioBase, - CounterType = PerformanceCounterType.AverageBase - }, - new CounterCreationData - { - CounterName = Hits, - CounterHelp = "Total number of cache hits of the cache handle", - CounterType = PerformanceCounterType.NumberOfItems64 - }, - new CounterCreationData - { - CounterName = Misses, - CounterHelp = "Total number of cache misses of the cache handle", - CounterType = PerformanceCounterType.NumberOfItems64 - }, - new CounterCreationData - { - CounterName = Writes, - CounterHelp = "Total number of cache writes (add,put,remove) of the cache handle", - CounterType = PerformanceCounterType.NumberOfItems64 - }, - new CounterCreationData - { - CounterName = WritesPerSecond, - CounterHelp = WritesPerSecond, - CounterType = PerformanceCounterType.RateOfCountsPerSecond64 - }, - new CounterCreationData - { - CounterName = ReadsPerSecond, - CounterHelp = ReadsPerSecond, - CounterType = PerformanceCounterType.RateOfCountsPerSecond64 - }, - new CounterCreationData - { - CounterName = HitsPerSecond, - CounterHelp = HitsPerSecond, - CounterType = PerformanceCounterType.RateOfCountsPerSecond64 - }, - }); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "On Dispose the catch is just for safety...")] - private void Dispose(bool disposeManaged) - { - if (disposeManaged) - { - try - { - ResetCounters(); - - if (_counterTimer != null) - { - _counterTimer.Dispose(); - } - - if (_counters != null) - { - foreach (var counter in _counters) - { - counter.Dispose(); - } - } - } - catch - { - } - } - } - - private PerformanceCounter GetCounter(CachePerformanceCounterType type) => _counters?[(int)type] ?? throw new InvalidOperationException("Counters not initialized"); - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "At this point its fine")] - private void InitializeCounters() - { - try - { - InitializeCategory(); - - _counters = new PerformanceCounter[9]; - _counters[0] = new PerformanceCounter(Category, Entries, _instanceName, false); - _counters[1] = new PerformanceCounter(Category, HitRatio, _instanceName, false); - _counters[2] = new PerformanceCounter(Category, HitRatioBase, _instanceName, false); - _counters[3] = new PerformanceCounter(Category, Hits, _instanceName, false); - _counters[4] = new PerformanceCounter(Category, Misses, _instanceName, false); - _counters[5] = new PerformanceCounter(Category, Writes, _instanceName, false); - _counters[6] = new PerformanceCounter(Category, ReadsPerSecond, _instanceName, false); - _counters[7] = new PerformanceCounter(Category, WritesPerSecond, _instanceName, false); - _counters[8] = new PerformanceCounter(Category, HitsPerSecond, _instanceName, false); - - // resetting them cleans up previous runs on the same category, which will otherwise - // stay in perfmon forever - ResetCounters(); - } - catch - { - _enabled = false; - } - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Is just fine at that point.")] - private void PerformanceCounterWorker(object state) - { - if (_enabled && Monitor.TryEnter(_updateLock)) - { - try - { - var previousCounts = new long[_numStatsCounters]; - Array.Copy(_statsCounts, previousCounts, _numStatsCounters); - - for (var i = 0; i < _numStatsCounters; i++) - { - _statsCounts[i] = _stats.GetStatistic((CacheStatsCounterType)i); - } - - var writes = _statsCounts[4] + _statsCounts[5] + _statsCounts[7] + _statsCounts[8]; - var previousWrites = previousCounts[4] + previousCounts[5] + previousCounts[7] + previousCounts[8]; - var hits = _statsCounts[0] - previousCounts[0]; - - SetValue(CachePerformanceCounterType.Items, _statsCounts[2]); - - IncrementBy(CachePerformanceCounterType.HitRatioBase, _statsCounts[6] - previousCounts[6]); - IncrementBy(CachePerformanceCounterType.HitRatio, hits); - IncrementBy(CachePerformanceCounterType.TotalHits, hits); - IncrementBy(CachePerformanceCounterType.TotalMisses, _statsCounts[1] - previousCounts[1]); - IncrementBy(CachePerformanceCounterType.TotalWrites, writes - previousWrites); - IncrementBy(CachePerformanceCounterType.ReadsPerSecond, _statsCounts[6] - previousCounts[6]); - IncrementBy(CachePerformanceCounterType.WritesPerSecond, writes - previousWrites); - IncrementBy(CachePerformanceCounterType.HitsPerSecond, hits); - } - catch (Exception e) - { - _enabled = false; - Trace.TraceError(e.Message + "\n" + e.StackTrace); - } - finally - { - Monitor.Exit(_updateLock); - } - } - } - - private void ResetCounters() - { - for (var i = 0; i < Enum.GetValues(typeof(CachePerformanceCounterType)).Length; i++) - { - SetValue((CachePerformanceCounterType)i, 0L); - } - } - } -} +////namespace CacheManager.Core.Internal +////{ +//// using System; +//// using System.Diagnostics; +//// using System.Threading; +//// using static CacheManager.Core.Utility.Guard; + +//// internal class CachePerformanceCounters : IDisposable +//// { +//// private const string Category = ".NET CacheManager"; +//// private const string Entries = "Total cache items"; +//// private const string HitRatio = "Hit ratio"; +//// private const string HitRatioBase = "Cache hit ratio Base"; +//// private const string Hits = "Total hits"; +//// private const string HitsPerSecond = "Avg hits per second"; +//// private const string Misses = "Total misses"; +//// private const string ReadsPerSecond = "Avg gets per second"; +//// private const string Writes = "Total cache writes"; +//// private const string WritesPerSecond = "Avg writes per second"; +//// private static readonly int _numStatsCounters = Enum.GetValues(typeof(CacheStatsCounterType)).Length; + +//// private readonly Timer _counterTimer; +//// private readonly string _instanceName = string.Empty; +//// private readonly CacheStats _stats; +//// private readonly long[] _statsCounts; +//// private PerformanceCounter[] _counters; +//// private bool _enabled = true; +//// private object _updateLock = new object(); + +//// public CachePerformanceCounters(string cacheName, string handleName, CacheStats stats) +//// { +//// NotNullOrWhiteSpace(cacheName, nameof(cacheName)); + +//// NotNullOrWhiteSpace(handleName, nameof(handleName)); + +//// var processName = Process.GetCurrentProcess().ProcessName; + +//// _instanceName = string.Concat(processName + ":" + cacheName + ":" + handleName); + +//// var invalidInstanceChars = new string[] { "(", ")", "#", "\\", "/" }; + +//// foreach (var ichar in invalidInstanceChars) +//// { +//// _instanceName = _instanceName.Replace(ichar, string.Empty); +//// } + +//// if (_instanceName.Length > 128) +//// { +//// _instanceName = _instanceName.Substring(0, 128); +//// } + +//// InitializeCounters(); +//// _stats = stats; +//// _statsCounts = new long[_numStatsCounters]; + +//// if (_enabled) +//// { +//// _counterTimer = new Timer(new TimerCallback(PerformanceCounterWorker), null, 450L, 450L); +//// } +//// } + +//// ~CachePerformanceCounters() +//// { +//// Dispose(false); +//// } + +//// public void Decrement(CachePerformanceCounterType type) +//// { +//// GetCounter(type).Decrement(); +//// } + +//// public void Dispose() +//// { +//// Dispose(true); +//// GC.SuppressFinalize(this); +//// } + +//// public void Increment(CachePerformanceCounterType type) +//// { +//// GetCounter(type).Increment(); +//// } + +//// public void IncrementBy(CachePerformanceCounterType type, long value) +//// { +//// GetCounter(type).IncrementBy(value); +//// } + +//// public void SetValue(CachePerformanceCounterType type, long value) +//// { +//// GetCounter(type).RawValue = value < 0 ? 0 : value; +//// } + +//// private static void InitializeCategory() +//// { +//// if (PerformanceCounterCategory.Exists(Category)) +//// { +//// return; +//// } + +//// PerformanceCounterCategory.Create( +//// Category, +//// "CacheManager counters per handle", +//// PerformanceCounterCategoryType.MultiInstance, +//// new CounterCreationDataCollection +//// { +//// new CounterCreationData +//// { +//// CounterName = Entries, +//// CounterHelp = "Current number of cache items stored within the cache handle", +//// CounterType = PerformanceCounterType.NumberOfItems64 +//// }, +//// new CounterCreationData +//// { +//// CounterName = HitRatio, +//// CounterHelp = "Cache hit ratio of the cache handle", +//// CounterType = PerformanceCounterType.AverageCount64 +//// }, +//// new CounterCreationData +//// { +//// CounterName = HitRatioBase, +//// CounterHelp = HitRatioBase, +//// CounterType = PerformanceCounterType.AverageBase +//// }, +//// new CounterCreationData +//// { +//// CounterName = Hits, +//// CounterHelp = "Total number of cache hits of the cache handle", +//// CounterType = PerformanceCounterType.NumberOfItems64 +//// }, +//// new CounterCreationData +//// { +//// CounterName = Misses, +//// CounterHelp = "Total number of cache misses of the cache handle", +//// CounterType = PerformanceCounterType.NumberOfItems64 +//// }, +//// new CounterCreationData +//// { +//// CounterName = Writes, +//// CounterHelp = "Total number of cache writes (add,put,remove) of the cache handle", +//// CounterType = PerformanceCounterType.NumberOfItems64 +//// }, +//// new CounterCreationData +//// { +//// CounterName = WritesPerSecond, +//// CounterHelp = WritesPerSecond, +//// CounterType = PerformanceCounterType.RateOfCountsPerSecond64 +//// }, +//// new CounterCreationData +//// { +//// CounterName = ReadsPerSecond, +//// CounterHelp = ReadsPerSecond, +//// CounterType = PerformanceCounterType.RateOfCountsPerSecond64 +//// }, +//// new CounterCreationData +//// { +//// CounterName = HitsPerSecond, +//// CounterHelp = HitsPerSecond, +//// CounterType = PerformanceCounterType.RateOfCountsPerSecond64 +//// }, +//// }); +//// } + +//// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "On Dispose the catch is just for safety...")] +//// private void Dispose(bool disposeManaged) +//// { +//// if (disposeManaged) +//// { +//// try +//// { +//// ResetCounters(); + +//// if (_counterTimer != null) +//// { +//// _counterTimer.Dispose(); +//// } + +//// if (_counters != null) +//// { +//// foreach (var counter in _counters) +//// { +//// counter.Dispose(); +//// } +//// } +//// } +//// catch +//// { +//// } +//// } +//// } + +//// private PerformanceCounter GetCounter(CachePerformanceCounterType type) => _counters?[(int)type] ?? throw new InvalidOperationException("Counters not initialized"); + +//// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "At this point its fine")] +//// private void InitializeCounters() +//// { +//// try +//// { +//// InitializeCategory(); + +//// _counters = new PerformanceCounter[9]; +//// _counters[0] = new PerformanceCounter(Category, Entries, _instanceName, false); +//// _counters[1] = new PerformanceCounter(Category, HitRatio, _instanceName, false); +//// _counters[2] = new PerformanceCounter(Category, HitRatioBase, _instanceName, false); +//// _counters[3] = new PerformanceCounter(Category, Hits, _instanceName, false); +//// _counters[4] = new PerformanceCounter(Category, Misses, _instanceName, false); +//// _counters[5] = new PerformanceCounter(Category, Writes, _instanceName, false); +//// _counters[6] = new PerformanceCounter(Category, ReadsPerSecond, _instanceName, false); +//// _counters[7] = new PerformanceCounter(Category, WritesPerSecond, _instanceName, false); +//// _counters[8] = new PerformanceCounter(Category, HitsPerSecond, _instanceName, false); + +//// // resetting them cleans up previous runs on the same category, which will otherwise +//// // stay in perfmon forever +//// ResetCounters(); +//// } +//// catch +//// { +//// _enabled = false; +//// } +//// } + +//// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Is just fine at that point.")] +//// private void PerformanceCounterWorker(object state) +//// { +//// if (_enabled && Monitor.TryEnter(_updateLock)) +//// { +//// try +//// { +//// var previousCounts = new long[_numStatsCounters]; +//// Array.Copy(_statsCounts, previousCounts, _numStatsCounters); + +//// for (var i = 0; i < _numStatsCounters; i++) +//// { +//// _statsCounts[i] = _stats.GetStatistic((CacheStatsCounterType)i); +//// } + +//// var writes = _statsCounts[4] + _statsCounts[5] + _statsCounts[7] + _statsCounts[8]; +//// var previousWrites = previousCounts[4] + previousCounts[5] + previousCounts[7] + previousCounts[8]; +//// var hits = _statsCounts[0] - previousCounts[0]; + +//// SetValue(CachePerformanceCounterType.Items, _statsCounts[2]); + +//// IncrementBy(CachePerformanceCounterType.HitRatioBase, _statsCounts[6] - previousCounts[6]); +//// IncrementBy(CachePerformanceCounterType.HitRatio, hits); +//// IncrementBy(CachePerformanceCounterType.TotalHits, hits); +//// IncrementBy(CachePerformanceCounterType.TotalMisses, _statsCounts[1] - previousCounts[1]); +//// IncrementBy(CachePerformanceCounterType.TotalWrites, writes - previousWrites); +//// IncrementBy(CachePerformanceCounterType.ReadsPerSecond, _statsCounts[6] - previousCounts[6]); +//// IncrementBy(CachePerformanceCounterType.WritesPerSecond, writes - previousWrites); +//// IncrementBy(CachePerformanceCounterType.HitsPerSecond, hits); +//// } +//// catch (Exception e) +//// { +//// _enabled = false; +//// Trace.TraceError(e.Message + "\n" + e.StackTrace); +//// } +//// finally +//// { +//// Monitor.Exit(_updateLock); +//// } +//// } +//// } + +//// private void ResetCounters() +//// { +//// for (var i = 0; i < Enum.GetValues(typeof(CachePerformanceCounterType)).Length; i++) +//// { +//// SetValue((CachePerformanceCounterType)i, 0L); +//// } +//// } +//// } +////} diff --git a/src/CacheManager.Core/Internal/CacheReflectionHelper.cs b/src/CacheManager.Core/Internal/CacheReflectionHelper.cs index 1256b67d..826e60e2 100644 --- a/src/CacheManager.Core/Internal/CacheReflectionHelper.cs +++ b/src/CacheManager.Core/Internal/CacheReflectionHelper.cs @@ -35,13 +35,6 @@ internal static ICacheSerializer CreateSerializer(ICacheManagerConfiguration con NotNull(configuration, nameof(configuration)); NotNull(loggerFactory, nameof(loggerFactory)); -#if !NETSTANDARD2 - if (configuration.SerializerType == null) - { - return new BinaryCacheSerializer(); - } -#endif - if (configuration.SerializerType != null) { CheckImplements(configuration.SerializerType); diff --git a/src/CacheManager.Core/Internal/CacheStats.cs b/src/CacheManager.Core/Internal/CacheStats.cs index 7671bf81..a8ca4a76 100644 --- a/src/CacheManager.Core/Internal/CacheStats.cs +++ b/src/CacheManager.Core/Internal/CacheStats.cs @@ -20,14 +20,13 @@ namespace CacheManager.Core.Internal /// class is sealed. /// /// Inherited object type of the owning cache handle. - public sealed class CacheStats : IDisposable + public sealed class CacheStats { private static readonly string _nullRegionKey = Guid.NewGuid().ToString(); private readonly ConcurrentDictionary _counters; - private readonly bool _isPerformanceCounterEnabled; private readonly bool _isStatsEnabled; - private readonly CachePerformanceCounters _performanceCounters; + // TODO: remove parameter. /// /// Initializes a new instance of the class. /// @@ -38,7 +37,7 @@ public sealed class CacheStats : IDisposable /// counters will be disabled. /// /// - /// If set to true performance counters and statistics will be enabled. + /// This feature has been removed in CacheManager 2.0. Parameter is still here to not break compatibility /// /// /// If cacheName or handleName are null. @@ -50,31 +49,7 @@ public CacheStats(string cacheName, string handleName, bool enabled = true, bool // if performance counters are enabled, stats must be enabled, too. _isStatsEnabled = enablePerformanceCounters ? true : enabled; - _isPerformanceCounterEnabled = enablePerformanceCounters; _counters = new ConcurrentDictionary(); - - if (_isPerformanceCounterEnabled) - { - _performanceCounters = new CachePerformanceCounters(cacheName, handleName, this); - } - } - - /// - /// Finalizes an instance of the class. - /// - ~CacheStats() - { - Dispose(false); - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting - /// unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); } /// @@ -364,17 +339,6 @@ public void OnUpdate(string key, string region, UpdateItemResult re } } - private void Dispose(bool disposeManaged) - { - if (disposeManaged) - { - if (_isPerformanceCounterEnabled) - { - _performanceCounters?.Dispose(); - } - } - } - private CacheStatsCounter GetCounter(string key) { NotNullOrWhiteSpace(key, nameof(key)); @@ -397,7 +361,7 @@ private IEnumerable GetWorkingCounters(string region) { yield return GetCounter(_nullRegionKey); - if (!IsNullOrEmpty(region)) + if (!string.IsNullOrEmpty(region)) { var counter = GetCounter(region); if (counter != null) diff --git a/src/CacheManager.Memcached/CacheManager.Memcached.csproj b/src/CacheManager.Memcached/CacheManager.Memcached.csproj index 5fbff950..1d09888f 100644 --- a/src/CacheManager.Memcached/CacheManager.Memcached.csproj +++ b/src/CacheManager.Memcached/CacheManager.Memcached.csproj @@ -2,7 +2,7 @@ CacheManager extension package to work with Memcached as a distributed cache. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. This package contains the specific Memcached handles. - net45 + net45; true true Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached @@ -11,9 +11,10 @@ - + + \ No newline at end of file diff --git a/src/CacheManager.Memcached/MemcachedCacheHandle.cs b/src/CacheManager.Memcached/MemcachedCacheHandle.cs index fbaaa901..8136cca0 100644 --- a/src/CacheManager.Memcached/MemcachedCacheHandle.cs +++ b/src/CacheManager.Memcached/MemcachedCacheHandle.cs @@ -767,4 +767,4 @@ protected override ArraySegment SerializeObject(object value) } } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj b/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj index 2e2ba406..d32ecf66 100644 --- a/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj +++ b/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj @@ -2,7 +2,7 @@ CacheManager extension package to use Microsoft.Extensions.Configuration to configure the CacheManager instance. CacheManager is an open source caching abstraction layer for .NET written in C#. This is the ASP.NET Core configuration integration package. - netstandard2.0;net461; + netstandard2.0;net461;net50 true true Caching;Cache;CacheManager;Distributed Cache;Configuration @@ -12,9 +12,15 @@ - + + + + + + + \ No newline at end of file diff --git a/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs b/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs index 16b9e564..b018fcd3 100644 --- a/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs +++ b/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs @@ -38,7 +38,6 @@ public static class MicrosoftConfigurationExtensions private const string TypeMsExtensionMemoryCacheHandle = "CacheManager.MicrosoftCachingMemory.MemoryCacheHandle`1, CacheManager.Microsoft.Extensions.Caching.Memory"; private const string TypeRedisConfiguration = "CacheManager.Redis.RedisConfiguration, CacheManager.StackExchange.Redis"; private const string TypeRedisConfigurations = "CacheManager.Redis.RedisConfigurations, CacheManager.StackExchange.Redis"; - private const string KnonwSerializerBinary = "binary"; private const string KnonwSerializerJson = "json"; private const string KnonwSerializerGzJson = "gzjson"; private const string KnonwSerializerProto = "protobuf"; @@ -461,15 +460,6 @@ private static Type GetKnownSerializerType(string knownTypeName, string path) { switch (knownTypeName.ToLowerInvariant()) { -#if !NET461 - case KnonwSerializerBinary: - throw new PlatformNotSupportedException("BinaryCacheSerializer is not available on this platform"); -#else - case KnonwSerializerBinary: - return typeof(BinaryCacheSerializer); - -#endif - case KnonwSerializerJson: return Type.GetType(TypeJsonCacheSerializer, true); diff --git a/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggingBuilderExtensions.cs b/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggingBuilderExtensions.cs index 46c76061..02e92254 100644 --- a/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggingBuilderExtensions.cs +++ b/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggingBuilderExtensions.cs @@ -13,31 +13,7 @@ namespace CacheManager.Core public static class MicrosoftLoggingBuilderExtensions { /// - /// Enables logging for the cache manager instance. - /// Using this extension will create a NEW instance of Microsoft.Extensions.Logging.ILoggerFactory. - /// - /// If you use the standard Micorosft AspNetCore DI, you might want to use the other extensions which make CacheManager use - /// the already injected/shared instance of . - /// - /// - /// Use the to configure the logger factory and add s as needed. - /// - /// - /// The builder part. - /// The logger factory used for configuring logging. - /// The builder. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "not owning it")] - public static ConfigurationBuilderCachePart WithMicrosoftLogging(this ConfigurationBuilderCachePart part, Action factory) - { - NotNull(part, nameof(part)); - NotNull(factory, nameof(factory)); - var externalFactory = new LoggerFactory(); - factory(externalFactory); - return part.WithLogging(typeof(MicrosoftLoggerFactoryAdapter), new Func(() => externalFactory)); - } - - /// - /// Enables logging for the cache manager instance using an existion Microsoft.Extensions.Logging.ILoggerFactory as target. + /// Enables logging for the cache manager instance using an existing Microsoft.Extensions.Logging.ILoggerFactory as target. /// /// The builder part. /// The logger factory which should be used. @@ -48,27 +24,5 @@ public static ConfigurationBuilderCachePart WithMicrosoftLogging(this Configurat NotNull(loggerFactory, nameof(loggerFactory)); return part.WithLogging(typeof(MicrosoftLoggerFactoryAdapter), new Func(() => loggerFactory)); } - - /// - /// Configures cache manager logging to use a Microsoft.Extensions.Logging.ILoggerFactory - /// which gets resolved from the . - /// - /// The builder part. - /// The services collection. - /// The builder. - public static ConfigurationBuilderCachePart WithMicrosoftLogging(this ConfigurationBuilderCachePart part, IServiceCollection serviceCollection) - { - NotNull(part, nameof(part)); - NotNull(serviceCollection, nameof(serviceCollection)); - - return part.WithLogging(typeof(MicrosoftLoggerFactoryAdapter), new Func(() => GetLoggerFactory(serviceCollection))); - } - - private static ILoggerFactory GetLoggerFactory(IServiceCollection serviceCollection) - { - var factory = serviceCollection.BuildServiceProvider().GetRequiredService(); - EnsureNotNull(factory, "No instance of ILoggerFactory found in {0}.", nameof(serviceCollection)); - return factory; - } } } diff --git a/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj b/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj index 9c2a08e5..c127bd7b 100644 --- a/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj +++ b/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj @@ -2,13 +2,13 @@ CacheManager extension package which adds support for Redis as a distributed cache layer. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - net461;netstandard2.0 + net461;netstandard2.0;net50 true true Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached - + @@ -17,6 +17,6 @@ - $(DefineConstants);NETSTANDARD2 + $(DefineConstants);NETSTANDARD2_0 \ No newline at end of file diff --git a/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs b/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs index 2950615d..d468a922 100644 --- a/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs +++ b/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs @@ -167,7 +167,7 @@ public override int Count } var count = 0; - foreach (var server in Servers.Where(p => !p.IsSlave && p.IsConnected)) + foreach (var server in Servers.Where(p => !p.IsReplica && p.IsConnected)) { count += (int)server.DatabaseSize(_redisConfiguration.Database); } @@ -210,7 +210,7 @@ public override void Clear() { try { - foreach (var server in Servers.Where(p => !p.IsSlave)) + foreach (var server in Servers.Where(p => !p.IsReplica)) { Retry(() => { @@ -1054,4 +1054,4 @@ private void LoadScripts() } } } -} \ No newline at end of file +} diff --git a/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs b/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs index 751c9c00..983d583b 100644 --- a/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs +++ b/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs @@ -168,9 +168,10 @@ public IConnectionMultiplexer Connect() if (!_configuration.TwemproxyEnabled) { + // TODO: re-test what IsReplica can do for us, readonly? var endpoints = connection.GetEndPoints(); if (!endpoints.Select(p => connection.GetServer(p)) - .Any(p => !p.IsSlave || p.AllowSlaveWrites)) + .Any(p => !p.IsReplica)) { throw new InvalidOperationException("No writeable endpoint found."); } diff --git a/src/CacheManager.StackExchange.Redis/RedisValueConverter.cs b/src/CacheManager.StackExchange.Redis/RedisValueConverter.cs index dd383b18..b089bfad 100644 --- a/src/CacheManager.StackExchange.Redis/RedisValueConverter.cs +++ b/src/CacheManager.StackExchange.Redis/RedisValueConverter.cs @@ -63,9 +63,9 @@ public RedisValueConverter(ICacheSerializer serializer) byte[] IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => value; - RedisValue IRedisValueConverter.ToRedisValue(byte value) => value; + RedisValue IRedisValueConverter.ToRedisValue(byte value) => (int)value; - byte IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => (byte)value; + byte IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => (byte)(int)value; RedisValue IRedisValueConverter.ToRedisValue(string value) => value; @@ -83,9 +83,9 @@ public RedisValueConverter(ICacheSerializer serializer) short IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => (short)value; - RedisValue IRedisValueConverter.ToRedisValue(ushort value) => value; + RedisValue IRedisValueConverter.ToRedisValue(ushort value) => (int)value; - ushort IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => (ushort)value; + ushort IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => (ushort)(int)value; RedisValue IRedisValueConverter.ToRedisValue(float value) => (double)value; @@ -109,9 +109,9 @@ public RedisValueConverter(ICacheSerializer serializer) ulong IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => ulong.Parse(value); - RedisValue IRedisValueConverter.ToRedisValue(char value) => value; + RedisValue IRedisValueConverter.ToRedisValue(char value) => (uint)value; - char IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => (char)value; + char IRedisValueConverter.FromRedisValue(RedisValue value, string valueType) => (char)(uint)value; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "CacheManager.Redis.RedisValueConverter.#CacheManager.Redis.IRedisValueConverter`1.ToRedisValue(System.Object)", Justification = "For performance reasons we don't do checks at this point. Also, its internally used only.")] RedisValue IRedisValueConverter.ToRedisValue(object value) @@ -271,4 +271,4 @@ private object Deserialize(RedisValue value, string valueType) return _serializer.Deserialize(value, type); } } -} \ No newline at end of file +} diff --git a/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj b/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj index 18f81ef3..e65faaa9 100644 --- a/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj +++ b/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj @@ -2,7 +2,7 @@ CacheManager extension package which adds System.Runtime.Caching.MemoryCache as an option for a local in-memory cache layer. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - net45;netstandard2.0 + net45;netstandard2.0;net50 true true Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached @@ -13,7 +13,7 @@ - - + + \ No newline at end of file diff --git a/src/CacheManager.Web/SystemWebCacheHandle`1.cs b/src/CacheManager.Web/SystemWebCacheHandle`1.cs index 2ae002fb..c982a220 100644 --- a/src/CacheManager.Web/SystemWebCacheHandle`1.cs +++ b/src/CacheManager.Web/SystemWebCacheHandle`1.cs @@ -6,6 +6,7 @@ using CacheManager.Core.Logging; using static CacheManager.Core.Utility.Guard; +// TODO: Make this thing obsolete, not tested, outdated. namespace CacheManager.Web { /// @@ -27,7 +28,6 @@ public class SystemWebCacheHandle : BaseCacheHandle /// The manager configuration. /// The cache handle configuration. /// The logger factory. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "For unit testing only, will never cause issues.")] public SystemWebCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory) : base(managerConfiguration, configuration) { @@ -396,4 +396,4 @@ private class CacheSettings public TimeSpan SlidingExpire { get; set; } = Cache.NoSlidingExpiration; } } -} \ No newline at end of file +} diff --git a/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj b/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj index 77792172..c7d50f35 100644 --- a/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj +++ b/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj @@ -3,7 +3,7 @@ CacheManager.MSConfiguration.TypeLoad.Tests Class Library Micha - netcoreapp2.0 + netcoreapp5.0;netcoreapp3.1;netcoreapp2.1 CacheManager.MSConfiguration.TypeLoad.Tests CacheManager.MSConfiguration.TypeLoad.Tests true @@ -20,13 +20,26 @@ - + + + + all + runtime; build; native; contentfiles; analyzers + - - - + + + + + + + + + + + \ No newline at end of file diff --git a/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs b/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs index 55806674..cd9250a6 100644 --- a/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs +++ b/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using FluentAssertions; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Xunit; namespace CacheManager.MSConfiguration.TypeLoad.Tests @@ -186,25 +187,9 @@ public void Configuration_Serializer_BondSimpleJson_NotReferenced() action.Should().Throw().WithMessage("*serializer type 'BondSimpleJson' could not be loaded*"); } -#if NETCOREAPP - [Fact] - public void Configuration_Serializer_BinaryInvalidOnCore() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Dictionary"}, - {"cacheManagers:0:serializer:knownType", "Binary"}, - }; - - Action act = () => GetConfiguration(data).GetCacheConfiguration("name"); - act.Should().Throw().WithMessage("*BinaryCacheSerializer is not available*"); - } -#endif - private static IConfigurationRoot GetConfiguration(IDictionary data) { - var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); + var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddInMemoryCollection(data); return configurationBuilder.Build(); } diff --git a/test/CacheManager.Tests/CacheFactoryTests.cs b/test/CacheManager.Tests/CacheFactoryTests.cs index 08902a46..eb97a43b 100644 --- a/test/CacheManager.Tests/CacheFactoryTests.cs +++ b/test/CacheManager.Tests/CacheFactoryTests.cs @@ -2,7 +2,6 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using CacheManager.Core; -using CacheManager.Core.Internal; using CacheManager.Redis; using CacheManager.Serialization.Json; using FluentAssertions; @@ -717,22 +716,5 @@ public void CacheFactory_Build_WithJsonSerializerCustomSettings() .WithJsonSerializer(serializationSettings, deserializationSettings) .WithSystemRuntimeCacheHandle()); } - -#if !NETCOREAPP2 - - [Fact] - [ReplaceCulture] - public void CacheFactory_Build_WithSerializer_SimpleBinary() - { - var cache = CacheFactory.Build( - p => - p.WithSerializer(typeof(BinaryCacheSerializer)) - .WithSystemRuntimeCacheHandle()); - - cache.Configuration.SerializerType.Should().NotBeNull(); - cache.Configuration.SerializerType.Should().Be(typeof(BinaryCacheSerializer)); - } - -#endif } } diff --git a/test/CacheManager.Tests/CacheManager.Tests.csproj b/test/CacheManager.Tests/CacheManager.Tests.csproj index d3aa1dc9..2d3e21d1 100644 --- a/test/CacheManager.Tests/CacheManager.Tests.csproj +++ b/test/CacheManager.Tests/CacheManager.Tests.csproj @@ -2,7 +2,7 @@ - net461;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0; + net461;netcoreapp2.1;netcoreapp3.1;net50 1.0.0 CacheManager.Tests @@ -13,6 +13,10 @@ true + + + + PreserveNewest @@ -21,20 +25,15 @@ + + Always + App.config + Always App.config - @@ -53,18 +52,25 @@ - - - - - + + + + + + + - + + + + all + runtime; build; native; contentfiles; analyzers + - + @@ -90,18 +96,14 @@ $(DefineConstants);REDISENABLED;MOCK_HTTPCONTEXT_ENABLED; - $(DefineConstants);REDISENABLED;NETCOREAPP2; - - - $(DefineConstants);REDISENABLED;NETCOREAPP2; + $(DefineConstants);REDISENABLED; - - $(DefineConstants);REDISENABLED;NETCOREAPP2; + + $(DefineConstants);REDISENABLED; - + + \ No newline at end of file diff --git a/test/CacheManager.Tests/MemoryCacheTests.cs b/test/CacheManager.Tests/MemoryCacheTests.cs index 1fb3fa3e..09ea4178 100644 --- a/test/CacheManager.Tests/MemoryCacheTests.cs +++ b/test/CacheManager.Tests/MemoryCacheTests.cs @@ -223,8 +223,7 @@ public void SysRuntime_Extensions_DefaultWithCodeCfg() } // disabling for netstandard 2 as it doesn't seem to read the "default" configuration from app.config. Might be an xunit/runner issue as the configuration stuff has been ported -#if !NETCOREAPP2 - + // TODO: re-test [Fact] [Trait("category", "NotOnMono")] public void SysRuntime_CreateDefaultCache() @@ -279,7 +278,6 @@ public void SysRuntime_CreateNamedCacheOverrideWithCodeCfg() settings["PollingInterval"].Should().Be(expectedCacheOptions.PollingInterval.ToString("c")); } } -#endif #endregion System Runtime Caching diff --git a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs index 4847751c..f1a0c6b7 100644 --- a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs +++ b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs @@ -374,8 +374,6 @@ public void Configuration_CacheHandle_KnownType_RedisB() config.CacheHandleConfigurations[0].Key.Should().Be("name"); // now key gets set to name } -#if !NETCOREAPP2 - [Fact] public void Configuration_CacheHandle_KnownType_CouchbaseNoKey() { @@ -431,22 +429,7 @@ public void Configuration_CacheHandle_KnownType_CouchbaseB() var cache = new BaseCacheManager(config); } - [Fact] - public void Configuration_CacheHandle_KnownType_MemcachedNoKey() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Memcached"}, - }; - - var config = GetConfiguration(data); - Action action = () => config.GetCacheConfiguration("name"); - action.Should().Throw().WithMessage("*'key' or 'name'*"); - } - #if MEMCACHEDENABLED - [Fact] [Trait("category", "memcached")] public void Configuration_CacheHandle_KnownType_Memcached() @@ -471,6 +454,21 @@ public void Configuration_CacheHandle_KnownType_Memcached() } #endif +#if NET461 + + [Fact] + public void Configuration_CacheHandle_KnownType_MemcachedNoKey() + { + var data = new Dictionary + { + {"cacheManagers:0:name", "name"}, + {"cacheManagers:0:handles:0:knownType", "Memcached"}, + }; + + var config = GetConfiguration(data); + Action action = () => config.GetCacheConfiguration("name"); + action.Should().Throw().WithMessage("*'key' or 'name'*"); + } [Fact] public void Configuration_CacheHandle_KnownType_MemcachedB() @@ -946,31 +944,6 @@ public void Configuration_Serializer_SomeType_Valid() act.Should().Throw().WithMessage("*ICacheSerializer*"); } -#if !NETCOREAPP2 - - [Fact] - public void Configuration_Serializer_KnownType_Binary() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Dictionary"}, - {"cacheManagers:0:serializer:knownType", "Binary"} - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - Action act = () => - { - var cache = new BaseCacheManager(config); - cache.Add("key", "value"); - }; - - config.SerializerType.Should().Be(typeof(Core.Internal.BinaryCacheSerializer)); - act.Should().NotThrow(); - } - -#endif - [Fact] public void Configuration_Serializer_KnownType_Json() { diff --git a/test/CacheManager.Tests/MicrosoftLoggingTests.cs b/test/CacheManager.Tests/MicrosoftLoggingTests.cs index 6d6a6180..f64f6953 100644 --- a/test/CacheManager.Tests/MicrosoftLoggingTests.cs +++ b/test/CacheManager.Tests/MicrosoftLoggingTests.cs @@ -137,40 +137,16 @@ public void AspNetCoreLogging_MinLogLevel_Critical() logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); } - [Fact] - public void AspNetCoreLogging_Builder_InvalidFactory() - { - Action act = () => ConfigurationBuilder.BuildConfiguration( - s => s.WithMicrosoftLogging((Action)null)); - - act.Should().Throw() - .And.ParamName.Equals("factory"); - } - [Fact] public void AspNetCoreLogging_Builder_InvalidLoggerFactory() { Action act = () => ConfigurationBuilder.BuildConfiguration( - s => s.WithMicrosoftLogging((ILoggerFactory)null)); + s => s.WithMicrosoftLogging(null)); act.Should().Throw() .And.ParamName.Equals("loggerFactory"); } - [Fact] - public void AspNetCoreLogging_Builder_ValidFactory() - { - var services = new ServiceCollection(); - var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Critical)).BuildServiceProvider(); - var external = provider.GetRequiredService(); - - var cfg = ConfigurationBuilder.BuildConfiguration( - s => s.WithMicrosoftLogging(services)); - - cfg.LoggerFactoryType.Should().NotBeNull(); - cfg.LoggerFactoryType.Should().Be(typeof(MicrosoftLoggerFactoryAdapter)); - } - [Fact] public void AspNetCoreLogging_TypedLogger() { diff --git a/test/CacheManager.Tests/RedisTests.cs b/test/CacheManager.Tests/RedisTests.cs index aa121c83..7d466d4c 100644 --- a/test/CacheManager.Tests/RedisTests.cs +++ b/test/CacheManager.Tests/RedisTests.cs @@ -29,7 +29,6 @@ private enum CacheEvent OnClearRegion } -#if NETCOREAPP2 [Fact] public void Redis_WithoutSerializer_ShouldThrow() { @@ -42,7 +41,6 @@ public void Redis_WithoutSerializer_ShouldThrow() Action act = () => new BaseCacheManager(cfg); act.Should().Throw().WithMessage("*requires serialization*"); } -#endif [Fact] [Trait("category", "Redis")] @@ -195,6 +193,8 @@ public void Redis_UseExistingConnection() } [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_AddWithRegion() { var key = Guid.NewGuid().ToString(); @@ -227,6 +227,8 @@ await TestBackplaneEventDistributed( /// /// [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_InMemory_AddWithRegion() { var key = Guid.NewGuid().ToString(); @@ -260,6 +262,8 @@ await TestBackplaneEventInMemory( } [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_Put() { var key = Guid.NewGuid().ToString(); @@ -292,6 +296,8 @@ await TestBackplaneEventDistributed( /// /// [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_InMemory_Put() { var key = Guid.NewGuid().ToString(); @@ -322,6 +328,8 @@ await TestBackplaneEventInMemory( } [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_PutWithRegion() { var key = Guid.NewGuid().ToString(); @@ -351,6 +359,8 @@ await TestBackplaneEventDistributed( } [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_Remove() { var key = Guid.NewGuid().ToString(); @@ -379,6 +389,8 @@ await TestBackplaneEventDistributed( } [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_Remove_WithRegion() { var key = Guid.NewGuid().ToString(); @@ -417,6 +429,8 @@ await TestBackplaneEventDistributed( /// /// [Fact] + [Trait("category", "Redis")] + [Trait("category", "Unreliable")] public async Task Redis_BackplaneEvents_InMemory_Remove_WithRegion() { var key = Guid.NewGuid().ToString(); diff --git a/test/CacheManager.Tests/SerializerTests.cs b/test/CacheManager.Tests/SerializerTests.cs index 6b091b20..9beca732 100644 --- a/test/CacheManager.Tests/SerializerTests.cs +++ b/test/CacheManager.Tests/SerializerTests.cs @@ -23,147 +23,6 @@ namespace CacheManager.Tests [ExcludeFromCodeCoverage] public class SerializerTests { - #region binary serializer - -#if !NETCOREAPP2 - - [Fact] - public void BinarySerializer_RespectBinarySerializerSettings() - { - var serializationSettings = new BinaryFormatter() - { - AssemblyFormat = FormatterAssemblyStyle.Simple, - FilterLevel = TypeFilterLevel.Low, - TypeFormat = FormatterTypeStyle.TypesWhenNeeded - }; - - var deserializationSettings = new BinaryFormatter() - { - AssemblyFormat = FormatterAssemblyStyle.Full, - FilterLevel = TypeFilterLevel.Full, - TypeFormat = FormatterTypeStyle.TypesAlways - }; - - var cache = CacheFactory.Build( - p => p - .WithBinarySerializer(serializationSettings, deserializationSettings) - .WithHandle(typeof(SerializerTestCacheHandle))); - - var handle = cache.CacheHandles.ElementAt(0) as SerializerTestCacheHandle; - var serializer = handle.Serializer as BinaryCacheSerializer; - - serializer.SerializationFormatter.AssemblyFormat.Should().Be(FormatterAssemblyStyle.Simple); - serializer.SerializationFormatter.FilterLevel.Should().Be(TypeFilterLevel.Low); - serializer.SerializationFormatter.TypeFormat.Should().Be(FormatterTypeStyle.TypesWhenNeeded); - serializer.DeserializationFormatter.AssemblyFormat.Should().Be(FormatterAssemblyStyle.Full); - serializer.DeserializationFormatter.FilterLevel.Should().Be(TypeFilterLevel.Full); - serializer.DeserializationFormatter.TypeFormat.Should().Be(FormatterTypeStyle.TypesAlways); - - cache.Configuration.SerializerTypeArguments.Length.Should().Be(2); - } - - [Theory] - [InlineData(true)] - [InlineData(float.MaxValue)] - [InlineData(int.MaxValue)] - [InlineData(long.MaxValue)] - [InlineData("some string")] - [ReplaceCulture] - public void BinarySerializer_Primitives(T value) - { - // arrange - var serializer = new BinaryCacheSerializer(); - - // act - var data = serializer.Serialize(value); - var result = serializer.Deserialize(data, typeof(T)); - - result.Should().Be(value); - } - - [Fact] - public void BinarySerializer_Pocco() - { - // arrange - var serializer = new BinaryCacheSerializer(); - var item = SerializerPoccoSerializable.Create(); - - // act - var data = serializer.Serialize(item); - var result = serializer.Deserialize(data, item.GetType()); - - result.Should().BeEquivalentTo(item); - } - - [Fact] - public void BinarySerializer_CacheItemWithPocco() - { - // arrange - var serializer = new BinaryCacheSerializer(); - var pocco = SerializerPoccoSerializable.Create(); - var item = new CacheItem("key", "region", pocco, ExpirationMode.Absolute, TimeSpan.FromDays(1)); - - // act - var data = serializer.SerializeCacheItem(item); - var result = serializer.DeserializeCacheItem(data, pocco.GetType()); - - result.Should().BeEquivalentTo(item); - } - - [Fact] - public void BinarySerializer_ObjectCacheItemWithPocco() - { - // arrange - var serializer = new BinaryCacheSerializer(); - var pocco = SerializerPoccoSerializable.Create(); - var item = new CacheItem("key", "region", pocco, ExpirationMode.Absolute, TimeSpan.FromDays(1)); - - // act - var data = serializer.SerializeCacheItem(item); - var result = serializer.DeserializeCacheItem(data, pocco.GetType()); - - result.Should().BeEquivalentTo(item); - } - - [Fact] - public void BinarySerializer_CacheItemWithDerivedPocco() - { - // arrange - var serializer = new BinaryCacheSerializer(); - var pocco = DerivedPocco.CreateDerived(); - var item = new CacheItem("key", "region", pocco, ExpirationMode.Absolute, TimeSpan.FromDays(1)); - - // act - var data = serializer.SerializeCacheItem(item); - var result = serializer.DeserializeCacheItem(data, pocco.GetType()); - - result.Should().BeEquivalentTo(item); - pocco.Should().BeEquivalentTo(item.Value); - } - - [Fact] - public void BinarySerializer_List() - { - // arrange - var serializer = new BinaryCacheSerializer(); - var items = new List() - { - SerializerPoccoSerializable.Create(), - SerializerPoccoSerializable.Create(), - SerializerPoccoSerializable.Create() - }; - - // act - var data = serializer.Serialize(items); - var result = serializer.Deserialize(data, items.GetType()); - - result.Should().BeEquivalentTo(items); - } - -#endif - - #endregion binary serializer - #region newtonsoft json serializer [Fact] diff --git a/test/CacheManager.Tests/TestCacheManagers.cs b/test/CacheManager.Tests/TestCacheManagers.cs index 027f0aaf..33989a0c 100644 --- a/test/CacheManager.Tests/TestCacheManagers.cs +++ b/test/CacheManager.Tests/TestCacheManagers.cs @@ -31,9 +31,7 @@ public IEnumerator GetEnumerator() yield return new object[] { TestManagers.WithManyDictionaryHandles }; yield return new object[] { TestManagers.WithOneDicCacheHandle }; #if REDISENABLED -#if !NETCOREAPP2 - yield return new object[] { TestManagers.WithRedisCacheBinary }; -#endif + yield return new object[] { TestManagers.WithRedisCacheDataContract }; yield return new object[] { TestManagers.WithRedisCacheDataContractBinary }; yield return new object[] { TestManagers.WithRedisCacheDataContractGzJson }; @@ -49,7 +47,7 @@ public IEnumerator GetEnumerator() yield return new object[] { TestManagers.WithDicAndRedisCacheNoLua }; #endif #if MEMCACHEDENABLED -#if !NETCOREAPP2 +#if NET461 yield return new object[] { TestManagers.WithMemcachedBinary }; #endif yield return new object[] { TestManagers.WithMemcachedJson }; @@ -121,20 +119,6 @@ public static ICacheManager WithManyDictionaryHandles .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1000)) .Build()); - public static ICacheManager WithRedisCacheBinary - { - get - { - Interlocked.Increment(ref _databaseCount); - if (_databaseCount >= NumDatabases) - { - _databaseCount = StartDbCount; - } - - return CreateRedisCache(_databaseCount, false, Serializer.Binary); - } - } - public static ICacheManager WithRedisCacheBondBinary { get @@ -597,7 +581,6 @@ public static ICacheManager CreateMemcachedCache(Serializer serializer = S public enum Serializer { - Binary, Json, GzJson, Proto, @@ -615,9 +598,6 @@ public static ConfigurationBuilderCachePart TestSerializer(this ConfigurationBui { switch (serializer) { - case Serializer.Binary: - break; - case Serializer.GzJson: part.WithGzJsonSerializer(); break; diff --git a/test/CacheManager.Tests/testhost.x86.dll.config b/test/CacheManager.Tests/testhost.x86.dll.config new file mode 100644 index 00000000..ed981526 --- /dev/null +++ b/test/CacheManager.Tests/testhost.x86.dll.config @@ -0,0 +1,109 @@ + + + + + +
+ +
+
+ + +
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/cacheManager.json b/tools/cacheManager.json index ca8c02f4..004d5ebb 100644 --- a/tools/cacheManager.json +++ b/tools/cacheManager.json @@ -95,8 +95,8 @@ "properties": { "knownType": { "type": "string", - "enum": [ "Binary", "Json", "Protobuf", "GzJson", "BondCompactBinary", "BondFastBinary", "BondSimpleJson" ], - "description": "Define a known serializer type instead of setting 'serializerType'. The respective library has to be installed. The default 'binary' might not be available on all platforms." + "enum": [ "Json", "Protobuf", "GzJson", "BondCompactBinary", "BondFastBinary", "BondSimpleJson" ], + "description": "Define a known serializer type instead of setting 'serializerType'. The respective library has to be installed." } }, "additionalProperties": false diff --git a/tools/common.props b/tools/common.props index bee0e01e..3c1d16ff 100644 --- a/tools/common.props +++ b/tools/common.props @@ -2,32 +2,29 @@ - Copyright (c) 2017 MichaConrad + Copyright (c) 2021 Michael Conrad MichaConrad true - - http://cachemanager.michaco.net/favicon-128.png + + CacheManager.NET + Apache-2.0 + + icon.png + http://cachemanager.michaco.net - https://github.com/MichaCo/CacheManager/blob/master/LICENSE + http://cachemanager.michaco.net + git https://github.com/MichaCo/CacheManager - CacheManager.NET - $(MSBuildThisFileDirectory)key.snk true true + $(VersionSuffix)-$(BuildNumber) - - - - \ No newline at end of file + + + diff --git a/tools/icon.png b/tools/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9e92eaa45bf80a66a16b3cfbb36884660e51f3 GIT binary patch literal 7260 zcma)BWmMEr)Bo>MOP6%Fv`9#I!?JWpi6SB0x$J@pNJtn%?Di_H9|aEJOBU)HPn^$|Lw^CFa-PG+AC}G9RTRr zG?Wz#{Xg$#1$aL)Iv;d1GC9-=)Q}7s(t+4OAsRoy?^NWKyRj7dJOI+yQ{Oyj&bBYT z=r;z3V)7x6n*p9MX7iscEF_8$TMoLs`a_M9i>fbG*LR@`sa5ilSwyeqx9P`m;pM2d zlAA>%x0VZ8fbzfT8MtL#j-Ci6>pW?w(GwYf2|Y`J@pS-H3g12kIHsLzhVZ!5uVq!E z1OO4|{=`FZT#t#)axA0Syx-z*WX!t3jWmOhgfX( z5cHKj_P|_QuKR_+2M?e>%NV6a!jI1rq#C5iG6gT8IBKvR+ zVAt-HkgykwAy#?WdG|u+=!SsT+oKHOoF4ld>FPH*tP)KzEwiJh3X0S&Q+k@r}ew=OapU@xV-zyyG72%&;;Qsdpv zvWcn(_ak^l{xD;}0>+aBUB-s3ei>8mSd60;Uf!kFcBekrt zjO>oYw@C$I0@m~lFeV@H!X~hnI!7G<2pp&tpA*c+(wS9qO?NpD38?pv8D|Lxd#VE# zEY@WAX|IC_^xrehh+@Xd_;!n<=*o&d(QX?E@dZf@HCSp*dJx`#;vljc!>9= z5d$x_qHUv8CY(jAyAtM%t+Lj&nP!DZU%|Ju5fPCw8A!Ir3wOjIkPK(Cyz(igO&<~$ z z>go=kJKAQKS4E<(VT^6FW_Mnf7J8S7_MJz8dkyue_fyD(k3Y3YUlbfZgx(W@e`}CiogW!vOHJn#V6qcrhZ4|DSI2#CaC#15v!wRxAZBWdo$ai-f*`6Qv$eNIFy9wX2%ePBnf3Cbxe6f*evAx-*I|E%ijPRweDB^#*0^;c; zP^5?;5kjufzx4{ZplBg^M(2EW zg)^p7WWN~weVk&YRIqtDE*G*zML|EfMn^8rw`BX@a_IY7_InaDmM=Taklq=du<;dC$c$8?kG3UEeVE`C`zPEh_e=VKAY z&aW2#P>x>x0Mp*T#xCA-h~jjLcC}TUiq#fRZ2TqMC#WhUwq`bUS*tZFoiOScB2}KJ zLn7Z@($V>8SVv7chN4WG(H(n@`kpOf^vMYNfwgapu>Wb*Oq;UO*2MMD?k2-{FfO5~ zi;u$ojgy+?!$De?@7d;J=$jV3G?VkO715${)P8(niOZ($2E!gt^4Qj-q*nD3YvzQ- z&+sX+Hc>l1={$D#m(%$xf11eWW^t=0eM{gX4zQe?kzc)vo5&jWsacKk){Hm$MX$Ft zSFZe%8!MicbHURWeF!bZA#}qa9mu6>DOa$KXDt+wt=Q$|= znY#3wT%{aE*Dc|B$@JsUPoP=?;giF*f4ab|fmoZ4*Jd+~MohXNf>?+qEZcezTZMDt zgZCEMBV%_)sESGtJH$#Y23OKImSb&SqRGkH^^&>PFH$%GsQAu8+4kDGAg$6 z_qMZs3#dC#6kC7Q%}4V6ZcyCkHAzZIjQM~F z$xN2^BA94}GyO=LS`1(9U>WaF+0;D6AkFgA?x<`Qv>Gp$NBAPQu%IDoSb*-ZeZ=<5 zJZ@sC5=o_brZSf1S7+^Qykz7}KLf3KPD>g5a>2h$c%Oh9uoQ9+w0ptx1(HRX{ zIy$EF)=t|3`Xr{$MZ)C5jL@!9_Zud8BUl25r&~ZG=;}pB2({RC?=M`N} zW0$(ZBxHzOZFJ9(i7X|8Nz!(RAV^GLa?%@(rjprTcfG}V&*4Kd>Z_oZsX9NYzlIL^ zXE46J`J%;0dG*+Tl457IkLRo`3qdAib~TBiym>hjH-(r#pi!roGOy`yrFLT3ts_*n(Xc-Jc2n z8yw&X4@f?t18y}qF1@I8QOw^W zP1|@8(#hc&7=v;3?=bH}G$h|6Aq=vZ9^>8dB0ZU4D%FZXa9GBo#HQDEuK00<%eIocTLk{&;4q^b5P*}8Zno}z5%3Xq`u1zl=fqKx zQ_u_Xv?~`FIcFgF*%Rh)u1DT`9zRT)r6s;{pPiOa_dKCielqGd(tN{drw*4>O#OvUFw2L(-q`rSL zg~6yS%wkOqwo{MCvS6@du3Ib)iV-}iP1-Gt!)0JjVyrLvWfffdl7%xqFJarLHvJ_0cIitG>8qL+Ng#3P5al$QPC zy?onPCCmHZF4!7KTxmquuUHUQTTG(C#vIS|!wL7vcs>kkGI(E=v#FRTb9g+SLDJxN z5ky|%F)aP5FZawWEXTux%dx+WK3Re;BVT=eb4j4yqnYjHHeO-AK$6N$hO8jDeQWYx z{G>5?)>SFT)0a7y-)3TX+}i5FvYJYZzg9k6w=j)4rb~VDWCj7F;M!@#!eyG}j)C8f z7s#-<*d>*feSJLL7G0_mBFtG;OdWFPpfQ|o3_WzdS&1(WI}x$*Qli3uVP0~R8*9Ql zT8C&4%&#o~Y0g@*rl1#jBN2PT^jht#xZ%m6^2&*)mf zs-`H-4%1<>uTKSoQu>@_WPO1!s>2Oq{CtS?G_4A4b4|i6kF*`?Sl?^#ftpka2|R8I zyN>ysa~11jxf1%ZwAA)+u%u&uG(=_P%j6$FV|vog8i!1mh0`Y1oSe3m1Ybrx(5w}Y zI>lG96u%3&zwtQ?-ty0m7i{WUcNalFp6t7Wmp)HL+DV@bApMLPw=bSBk*#~E+%e{y z1YR!qc@2YvlBAmYDA*zRAvy+THjz*Uf6)3<0V_{q%H{ z-;P`u(xtmQxs>q1oKp6omiYZLIhZF|YnBw>4lZ&zLp*{B8?|y;!#(sb%%$GaZDC5I z{IDC9!DinH$xJ-?LbE12DUeZ_%WP!cZ}G0DUw1Rpk3XJ(fL`+&>nEY!Vc)<1Yief( z74=!<{`KPAk~LJNsAMcfG(feoQ)B+8F_wFMYK`Qq95yNLW?kf}_zLo#JOHD>z?&UB zp1mh40)8UWWWquV6?><=n$438q1rkca$cz?2?Qko z<2<~U+TN-iIs6B)%6dj{M1k(0rZQx6p7Y_VtteA4M_7;1^;rLQ^5CD zgdFRasSWQ2(^&@HT!ke=lfoPCna}xMaB0<`0());BHY{q&13GumSNWeDLuV}WmDtz z8Uy~K6tmQ%61k={sP?mGPF3)_xx9?#CIde{czK7tNR&ChsJ(!sXnr$C*Xius`~zt@ z>gZR&?RPV|VfTX6#r}*?8O+Co`bt3z&)8hbLzcOcsw%E?LVc*J&^`mNCiBdYd9_9c zH*43&E4?^6smkxzeLJfJA4`}8l`+q~L7SNx_c!Jk<5;)(T8J=v(wp!lV*u16t`^Rt z+>&;VZ)Q#lT>#|Cm{cm(HWfV?aU^{N?$uKO@UncR;be7OmilySc{p1)GX+s2#{0l* z(w$VQh=KhbTQzR;#$N?;qZYGu)O?|=VBXNmY3>8fK2|+T$q1VkX7GV-ihcGDtozVA zBd=r-l)`ehWUMaJG?z{U0sv@I27W+S&wJ?so>wwq`5MrHIrzslQ;+^^c~f^KCB6Qu z@cb&J5sQAMXV@=1`2V+-SqFs+DAd$UX$ZHl-f#uiG-F4Iy?u8F#tABB7d(UD)3{bt zjFh7gwpm4awdOXE4`#k%c6F%Fzbu3J#`>C4m>M{+XU%f5+@~TP0u?M5W2{Yo%D)ylf@d(u!kzph5x3*cI zoaf(1>Qj;utrczc56#_J)x8FZ^i|r9!`|8)%IqG zapa{awTRKLFoh|Dl$Qyx@^YcRVMFp@GvQ~KLWBadU{&~UoaMX-ePqyF0G4N+z@D>Iu^S#=k+ zPF|kG);AMdT&{@y-S194y0z*wov)Rg7Sm()$5408b>^r|H*Y5b=J+V}Tp8PtE#4~} z4VS^ORcI7zgG#^SNpAO_)h25h9$frb157OCGD^7{qoJOFJpc&iink^^y{Ds^tXXA` z_t2QYk-eF19T&UHhI?i)3%PcBz8Q(i^_&0P|4xynXEW*=aeBaErHBq5vHiibHF3xO zVz@`@H_)*C)DLN~wJ!Q*!vX;2-qi}~@>kMYdN`_Xi}nCrj~}}DP}TG#>C7i*L}~ni z*IEyQ#T|G6vY#+OQ5-R@IK(79^{Rd2QckkPKqI+=3nIU4{Hv>O7-}5~J zHfal$xrHNrb{UkPZtyUGe-yhG^abp^ zVx^Zl(KN;;VkAMb$|S&;RRjFG-LGU#49}kyVJc`*p?>B~bn)h1XyxczJ>O3HqGMDi z1h)|7P{ywqh`rFrVPgDv3c=O7W~1K2tXDv zDuOOnGR`oceUH|yfo1Ik>D(2NSX$IjsdK<$fB{T)u1u{}cYe+37H8GxJVW2=HQH{X z)eHuz@T^+A)1a)z1=t2!i-b^xp|FxI3?On_u2v6Eo-~>8aac`ma3=(ikMYRce7-}I zITr$DFSkNXH(sm;O<#FERO&FoVZVac=fY+e+z=LV0J2DFzUP+EC&v}H+w)G9GN%{B z!|E;4vmW&?F@gX{M~5Ostx}1Goeo^7=`P|m;h>I7)Sa(^n*9&Xe|Htx+eMej)ekHG z`rTv^-&8^z`f>I+X}|M4O}{OZ@;^m^aBJ~z)9xHI^V(S#O^pngyP!anM**c?FZP(I z>(xO^>x?5R!u7WKJfw{BlP)v9>HRjt79P~Mm&#g>?s@~=k@bHf9-n#7{#UR1a}P6EphXZS^sjQKG>;%G02d*mX%jyX&}UsyOCLO6)~2G&0g znALZkj>LKdx1TH>dnrUsOB=KaeEIj{r97vZ1Gy8}RLroOvg@T9O zRw=({0FqtYA#wsu2?~SpuX^9J zz-TVW&KLPf0A#!ST3g(8P@GIbY=03=V@7K*37)OE!pF#QU6k+YpXZh#Q;y6UymEZv z*~K81lPIEex{Q&rqIqF;s1FfUZ!;wkPaP@yitok-cBU07%6}-B?>z_C@xa!ebeW;b zOZw2OH}?wpMU~UfO+6F0_ZZ3;#r(;>_4oPjoOyd0K^e!^AnF;ar&NN6pr{^FUe{cW zLeFw9>6;?M1G8Q%BXUj=u5q*`$MSH72xd^G>0+3?kfrYhxge=;5- zh8fDgEqH(ptOk|$?ri-y`GMxesi4SkwsG&W`KrG{Jj}b`HcfXLu4NLUH%OQ{LU_uw z)Qm3Ca>{iH}b87K)aFDl&-$=5&q`+-hu4lFY98L|IK&miS{f=0*VubV9J)p}M{S{FknN_P2z{6ncSy8SB;){Qp!j=d?K!+vNKUXV5aPX9=81sa$C{ zrf1h;nPaMn>>7#2OZgL>G^0_Tx^dm}T+@d7zT?l$;O}>|&X4{Q^e2*0`QD>`q% zdkCkXQ<2wqf0u(pCJ)mqQ_mhU41HQI-}O#kW018T+$n! zZkt!O>#x`YYCtK8@g9XNtGQG@-fg=6`%V$}!@BtEdYNS0FUz46NQ_mxze*j0lMFxA z{{KNyxFa*+Crye9yz~9KEr#z1oPWaYqRwDPV zQ}B%+TnqTI)YEI4ix@q0Q$%{}SpJKd?Qy0$(WWC~jz;rW$gQ_(^95&BQr;hm+~oJ@ zqBDu_J1GzmBA0kAIr9}eZqekga@ZfAZ$GGoMYFzWcfTsxf=9@H_4U~0#{Vz+&Xn Date: Mon, 31 May 2021 01:23:00 +0200 Subject: [PATCH 07/13] Removing any timeout delay via Tasks to prevent any chance for a deadlock. #300 --- .../ICacheManagerConfiguration.cs | 6 ++- .../MemcachedCacheHandle.cs | 12 ++--- .../RedisCacheBackplane.cs | 2 +- .../RetryHelper.cs | 48 +++++++++++-------- 4 files changed, 39 insertions(+), 29 deletions(-) diff --git a/src/CacheManager.Core/ICacheManagerConfiguration.cs b/src/CacheManager.Core/ICacheManagerConfiguration.cs index 97573ce7..279f9986 100644 --- a/src/CacheManager.Core/ICacheManagerConfiguration.cs +++ b/src/CacheManager.Core/ICacheManagerConfiguration.cs @@ -92,6 +92,10 @@ public interface IReadOnlyCacheManagerConfiguration /// Gets the number of milliseconds the cache should wait before it will retry an action. /// Default is 100. /// + /// + /// This does not have any effect in synchronous context. + /// Will be brought back if CacheManager has async overloads. + /// /// The retry timeout. int RetryTimeout { get; } @@ -119,4 +123,4 @@ public interface IReadOnlyCacheManagerConfiguration /// CacheUpdateMode UpdateMode { get; } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Memcached/MemcachedCacheHandle.cs b/src/CacheManager.Memcached/MemcachedCacheHandle.cs index 8136cca0..0c3c5b10 100644 --- a/src/CacheManager.Memcached/MemcachedCacheHandle.cs +++ b/src/CacheManager.Memcached/MemcachedCacheHandle.cs @@ -336,12 +336,12 @@ private void WaitRetry(int currentTry) { adjusted = 10000; } - -#if !NET40 - Task.Delay(adjusted).ConfigureAwait(false).GetAwaiter().GetResult(); -#else - Thread.Sleep(adjusted); -#endif +// Disabling any async in sync +////#if !NET40 +//// Task.Delay(adjusted).ConfigureAwait(false).GetAwaiter().GetResult(); +////#else +//// Thread.Sleep(adjusted); +////#endif } /// diff --git a/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs b/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs index 5897010d..a6334a76 100644 --- a/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs +++ b/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs @@ -207,7 +207,7 @@ private void SendMessages(object state) _logger.LogInfo($"Backplane is sending {_messages.Count} messages triggered by timer."); } #if !NET40 - await Task.Delay(10).ConfigureAwait(false); + await Task.Delay(50).ConfigureAwait(false); #endif byte[] msgs = null; lock (_messageLock) diff --git a/src/CacheManager.StackExchange.Redis/RetryHelper.cs b/src/CacheManager.StackExchange.Redis/RetryHelper.cs index 92d9cb48..278301d1 100644 --- a/src/CacheManager.StackExchange.Redis/RetryHelper.cs +++ b/src/CacheManager.StackExchange.Redis/RetryHelper.cs @@ -37,11 +37,13 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg } logger.LogWarn(ex, WarningMessage, tries, retries); -#if NET40 - TaskEx.Delay(timeOut).Wait(); -#else - Task.Delay(timeOut).Wait(); -#endif + + // Removed all async delay to prevent potential deadlocks +////#if NET40 +//// TaskEx.Delay(timeOut).Wait(); +////#else +//// Task.Delay(timeOut).Wait(); +////#endif } catch (RedisConnectionException ex) { @@ -52,11 +54,13 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg } logger.LogWarn(ex, WarningMessage, tries, retries); -#if NET40 - TaskEx.Delay(timeOut).Wait(); -#else - Task.Delay(timeOut).Wait(); -#endif + + // Removed all async delay to prevent potential deadlocks +////#if NET40 +//// TaskEx.Delay(timeOut).Wait(); +////#else +//// Task.Delay(timeOut).Wait(); +////#endif } catch (TimeoutException ex) { @@ -67,11 +71,12 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg } logger.LogWarn(ex, WarningMessage, tries, retries); -#if NET40 - TaskEx.Delay(timeOut).Wait(); -#else - Task.Delay(timeOut).Wait(); -#endif + // Removed all async delay to prevent potential deadlocks +////#if NET40 +//// TaskEx.Delay(timeOut).Wait(); +////#else +//// Task.Delay(timeOut).Wait(); +////#endif } catch (AggregateException aggregateException) { @@ -91,11 +96,12 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg if (e is RedisConnectionException || e is System.TimeoutException || e is RedisServerException) { logger.LogWarn(e, WarningMessage, tries, retries); -#if NET40 - TaskEx.Delay(timeOut).Wait(); -#else - Task.Delay(timeOut).Wait(); -#endif + // Removed all async delay to prevent potential deadlocks +////#if NET40 +//// TaskEx.Delay(timeOut).Wait(); +////#else +//// Task.Delay(timeOut).Wait(); +////#endif return true; } @@ -123,4 +129,4 @@ public static void Retry(Action retryme, int timeOut, int retries, ILogger logge logger); } } -} \ No newline at end of file +} From 8e8b0616da666cf328c8c64094630bcd5bf1524b Mon Sep 17 00:00:00 2001 From: MichaC Date: Mon, 31 May 2021 01:31:29 +0200 Subject: [PATCH 08/13] blub --- _releasenotes - deleteme.txt | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 _releasenotes - deleteme.txt diff --git a/_releasenotes - deleteme.txt b/_releasenotes - deleteme.txt deleted file mode 100644 index d06caa85..00000000 --- a/_releasenotes - deleteme.txt +++ /dev/null @@ -1,22 +0,0 @@ -Release Notes CacheManager 2.0.0 - -Merged PR -* #275 -* #266 -* #200 New Feature / package: CacheManager.Serialization.DataContract -* #177 Additional configuration options for System.Runtime.Caching - - - -{crafted}Allocates Flaying - -REMOVED Binary Serialization -For the same reason it'll be obsolete in NET50 https://docs.microsoft.com/de-de/dotnet/fundamentals/syslib-diagnostics/syslib0011 -Was never a good option anyways. - -REMOVED Performance Counters - was never working with distributed cache reliably, and never will be. Use Redis metrics if you need that. -REMOVED 2 overloads of WithMicrosoftLogging which either don't work with latest frameworks or would cause more confusion. - Just use the DI as intended and create a logger factory with providers and use the one option available. - -TODO: use Enym.Memcached2 beta package for netstandard2.1 and net50 targeting. - There are breaking changes which requires slight rewrites and I have no way to test it anyways -> up-for-graps? From fac491670ab9a8331ab2f381b3bb99c13a5e0f3a Mon Sep 17 00:00:00 2001 From: MichaC Date: Mon, 31 May 2021 02:21:03 +0200 Subject: [PATCH 09/13] Removing perf counters configuration --- samples/CacheManager.Examples/App.config | 2 +- samples/CacheManager.Examples/Program.cs | 2 - src/CacheManager.Core/CacheFactory.cs | 7 ---- .../CacheHandleConfiguration.cs | 12 +----- .../Configuration/CacheManagerSection.cs | 18 -------- .../Configuration/ConfigurationBuilder.cs | 24 ----------- .../Internal/BaseCacheHandle.cs | 3 +- src/CacheManager.Core/Internal/CacheStats.cs | 7 +--- test/CacheManager.Tests/CacheFactoryTests.cs | 42 +------------------ .../configuration.ExpireTest.config | 4 +- ...n.invalid.InvalidEnablePerfCounters.config | 4 +- .../configuration.valid.allFeatures.config | 2 +- .../InvalidConfigurationValidationTests.cs | 17 -------- .../MicrosoftConfigurationTests.cs | 19 --------- test/CacheManager.Tests/TestCacheManagers.cs | 1 - .../ValidConfigurationValidationTests.cs | 30 +------------ tools/CacheManagerCfg.xsd | 1 - tools/cacheManager.json | 4 -- 18 files changed, 13 insertions(+), 186 deletions(-) diff --git a/samples/CacheManager.Examples/App.config b/samples/CacheManager.Examples/App.config index 2a2a36c0..c901d07c 100644 --- a/samples/CacheManager.Examples/App.config +++ b/samples/CacheManager.Examples/App.config @@ -10,7 +10,7 @@ - + diff --git a/samples/CacheManager.Examples/Program.cs b/samples/CacheManager.Examples/Program.cs index bf37c17a..13cf7dbf 100644 --- a/samples/CacheManager.Examples/Program.cs +++ b/samples/CacheManager.Examples/Program.cs @@ -159,7 +159,6 @@ private static void SimpleCustomBuildConfigurationUsingConfigBuilder() { settings.WithUpdateMode(CacheUpdateMode.Up) .WithDictionaryHandle() - .EnablePerformanceCounters() .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); }); @@ -179,7 +178,6 @@ private static void SimpleCustomBuildConfigurationUsingFactory() settings .WithUpdateMode(CacheUpdateMode.Up) .WithDictionaryHandle() - .EnablePerformanceCounters() .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); }); diff --git a/src/CacheManager.Core/CacheFactory.cs b/src/CacheManager.Core/CacheFactory.cs index 718ef039..ad37ccd9 100644 --- a/src/CacheManager.Core/CacheFactory.cs +++ b/src/CacheManager.Core/CacheFactory.cs @@ -24,7 +24,6 @@ public static class CacheFactory /// settings /// .WithUpdateMode(CacheUpdateMode.Up) /// .WithDictionaryHandle() - /// .EnablePerformanceCounters() /// .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); /// }); /// @@ -62,7 +61,6 @@ public static ICacheManager Build(string cacheName, Action Build(Action /// settings /// .WithUpdateMode(CacheUpdateMode.Up) /// .WithDictionaryHandle() - /// .EnablePerformanceCounters() /// .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); /// }); /// @@ -143,7 +140,6 @@ public static ICacheManager Build(string cacheName, Ac /// settings /// .WithUpdateMode(CacheUpdateMode.Up) /// .WithDictionaryHandle() - /// .EnablePerformanceCounters() /// .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); /// }); /// @@ -181,7 +177,6 @@ public static ICacheManager Build(Action FromConfiguration(string c /// { /// settings.WithUpdateMode(CacheUpdateMode.Up) /// .WithDictionaryCacheHandle>() - /// .EnablePerformanceCounters() /// .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); /// }); /// diff --git a/src/CacheManager.Core/CacheHandleConfiguration.cs b/src/CacheManager.Core/CacheHandleConfiguration.cs index 018cdd6e..873204c9 100644 --- a/src/CacheManager.Core/CacheHandleConfiguration.cs +++ b/src/CacheManager.Core/CacheHandleConfiguration.cs @@ -45,16 +45,6 @@ public CacheHandleConfiguration(string handleName, string configurationKey) Key = configurationKey; } - /// - /// Gets or sets a value indicating whether performance counters should be enabled or not. - /// - /// If enabled, and the initialization of performance counters doesn't work, for example - /// because of security reasons. The counters will get disabled silently. - /// - /// - /// true if performance counters should be enable; otherwise, false. - public bool EnablePerformanceCounters { get; set; } - /// /// Gets or sets a value indicating whether statistics should be enabled. /// @@ -111,4 +101,4 @@ public override string ToString() return $"{HandleType}"; } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Core/Configuration/CacheManagerSection.cs b/src/CacheManager.Core/Configuration/CacheManagerSection.cs index 67b71aa7..bcef8c12 100644 --- a/src/CacheManager.Core/Configuration/CacheManagerSection.cs +++ b/src/CacheManager.Core/Configuration/CacheManagerSection.cs @@ -318,7 +318,6 @@ public sealed class CacheManagerHandleCollection : ConfigurationElementCollectio private const string BackplaneNameKey = "backplaneName"; private const string BackplaneTypeKey = "backplaneType"; private const string SerializerTypeKey = "serializerType"; - private const string EnablePerformanceCountersKey = "enablePerformanceCounters"; private const string EnableStatisticsKey = "enableStatistics"; private const string MaxRetriesKey = "maxRetries"; private const string NameKey = "name"; @@ -384,23 +383,6 @@ public string SerializerType } } - /// - /// Gets or sets a value indicating whether performance counters should be enabled. - /// - /// true if performance counters should be enabled; otherwise, false. - [ConfigurationProperty(EnablePerformanceCountersKey, IsRequired = false, DefaultValue = false)] - public bool EnablePerformanceCounters - { - get - { - return (bool)this[EnablePerformanceCountersKey]; - } - set - { - this[EnablePerformanceCountersKey] = value; - } - } - /// /// Gets or sets a value indicating whether statistics should be enabled. /// diff --git a/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs b/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs index c4892136..a8ed49f9 100644 --- a/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs +++ b/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs @@ -311,7 +311,6 @@ internal static CacheManagerConfiguration LoadFromSection(CacheManagerSection se ExpirationMode = handleDef.ExpirationMode, ExpirationTimeout = handleDef.ExpirationTimeout, EnableStatistics = managerCfg.EnableStatistics, - EnablePerformanceCounters = managerCfg.EnablePerformanceCounters, IsBackplaneSource = handleItem.IsBackplaneSource }; @@ -424,16 +423,6 @@ public ICacheManagerConfiguration Build() return _parent.Build(); } - /// - /// Disables performance counters for this cache handle. - /// - /// The builder part. - public ConfigurationBuilderCacheHandlePart DisablePerformanceCounters() - { - Configuration.EnablePerformanceCounters = false; - return this; - } - /// /// Disables statistic gathering for this cache handle. /// This also disables performance counters as statistics are required for the counters. @@ -442,19 +431,6 @@ public ConfigurationBuilderCacheHandlePart DisablePerformanceCounters() public ConfigurationBuilderCacheHandlePart DisableStatistics() { Configuration.EnableStatistics = false; - Configuration.EnablePerformanceCounters = false; - return this; - } - - /// - /// Enables performance counters for this cache handle. - /// This also enables statistics, as this is required for performance counters. - /// - /// The builder part. - public ConfigurationBuilderCacheHandlePart EnablePerformanceCounters() - { - Configuration.EnablePerformanceCounters = true; - Configuration.EnableStatistics = true; return this; } diff --git a/src/CacheManager.Core/Internal/BaseCacheHandle.cs b/src/CacheManager.Core/Internal/BaseCacheHandle.cs index 32480323..9e8de78c 100644 --- a/src/CacheManager.Core/Internal/BaseCacheHandle.cs +++ b/src/CacheManager.Core/Internal/BaseCacheHandle.cs @@ -35,8 +35,7 @@ protected BaseCacheHandle(ICacheManagerConfiguration managerConfiguration, Cache Stats = new CacheStats( managerConfiguration.Name, Configuration.Name, - Configuration.EnableStatistics, - Configuration.EnablePerformanceCounters); + Configuration.EnableStatistics); } /// diff --git a/src/CacheManager.Core/Internal/CacheStats.cs b/src/CacheManager.Core/Internal/CacheStats.cs index a8ca4a76..45aa9ac4 100644 --- a/src/CacheManager.Core/Internal/CacheStats.cs +++ b/src/CacheManager.Core/Internal/CacheStats.cs @@ -36,19 +36,16 @@ public sealed class CacheStats /// If set to true the stats are enabled. Otherwise any statistics and performance /// counters will be disabled. /// - /// - /// This feature has been removed in CacheManager 2.0. Parameter is still here to not break compatibility - /// /// /// If cacheName or handleName are null. /// - public CacheStats(string cacheName, string handleName, bool enabled = true, bool enablePerformanceCounters = false) + public CacheStats(string cacheName, string handleName, bool enabled = true) { NotNullOrWhiteSpace(cacheName, nameof(cacheName)); NotNullOrWhiteSpace(handleName, nameof(handleName)); // if performance counters are enabled, stats must be enabled, too. - _isStatsEnabled = enablePerformanceCounters ? true : enabled; + _isStatsEnabled = enabled; _counters = new ConcurrentDictionary(); } diff --git a/test/CacheManager.Tests/CacheFactoryTests.cs b/test/CacheManager.Tests/CacheFactoryTests.cs index eb97a43b..4374abca 100644 --- a/test/CacheManager.Tests/CacheFactoryTests.cs +++ b/test/CacheManager.Tests/CacheFactoryTests.cs @@ -238,41 +238,6 @@ public void CacheFactory_Build_ParamB() .And.ParamName.Equals("settings"); } - [Fact] - [ReplaceCulture] - public void CacheFactory_Build_DisablePerfCounters() - { - // act - Func> act = () => CacheFactory.Build(settings => - { - settings.WithUpdateMode(CacheUpdateMode.Up) - .WithDictionaryHandle("h1") - .DisablePerformanceCounters(); - }); - - // assert - act().CacheHandles.ElementAt(0).Configuration.EnablePerformanceCounters.Should().BeFalse(); - act().CacheHandles.ElementAt(0).Configuration.EnableStatistics.Should().BeFalse("this is the default value"); - } - - [Fact] - [ReplaceCulture] - public void CacheFactory_Build_EnablePerfCounters() - { - // act - Func> act = () => CacheFactory.Build(settings => - { - settings - .WithDictionaryHandle("h1") - .DisableStatistics() // disable it first - .EnablePerformanceCounters(); // should enable stats - }); - - // assert - act().CacheHandles.ElementAt(0).Configuration.EnablePerformanceCounters.Should().BeTrue(); - act().CacheHandles.ElementAt(0).Configuration.EnableStatistics.Should().BeTrue("is required for perf counters"); - } - [Fact] [ReplaceCulture] public void CacheFactory_Build_EnableStats() @@ -286,7 +251,6 @@ public void CacheFactory_Build_EnableStats() }); // assert - act().CacheHandles.ElementAt(0).Configuration.EnablePerformanceCounters.Should().BeFalse("is default"); act().CacheHandles.ElementAt(0).Configuration.EnableStatistics.Should().BeTrue(); } @@ -302,7 +266,6 @@ public void CacheFactory_Build_DefaultStatsAndPerf() }); // assert - act().CacheHandles.ElementAt(0).Configuration.EnablePerformanceCounters.Should().BeFalse("is default"); act().CacheHandles.ElementAt(0).Configuration.EnableStatistics.Should().BeFalse("is default"); } @@ -579,7 +542,7 @@ public void CacheFactory_Build_ValidateSettings() .WithUpdateMode(CacheUpdateMode.None) .WithDictionaryHandle("h1") .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(12)) - .EnablePerformanceCounters() + .EnableStatistics() .And.WithDictionaryHandle("h2") .WithExpiration(ExpirationMode.None, TimeSpan.Zero) .DisableStatistics() @@ -594,19 +557,16 @@ public void CacheFactory_Build_ValidateSettings() act.Configuration.MaxRetries.Should().Be(22); act.Configuration.RetryTimeout.Should().Be(2223); act.CacheHandles.ElementAt(0).Configuration.Name.Should().Be("h1"); - act.CacheHandles.ElementAt(0).Configuration.EnablePerformanceCounters.Should().BeTrue(); act.CacheHandles.ElementAt(0).Configuration.EnableStatistics.Should().BeTrue(); act.CacheHandles.ElementAt(0).Configuration.ExpirationMode.Should().Be(ExpirationMode.Absolute); act.CacheHandles.ElementAt(0).Configuration.ExpirationTimeout.Should().Be(new TimeSpan(12, 0, 0)); act.CacheHandles.ElementAt(1).Configuration.Name.Should().Be("h2"); - act.CacheHandles.ElementAt(1).Configuration.EnablePerformanceCounters.Should().BeFalse(); act.CacheHandles.ElementAt(1).Configuration.EnableStatistics.Should().BeFalse(); act.CacheHandles.ElementAt(1).Configuration.ExpirationMode.Should().Be(ExpirationMode.None); act.CacheHandles.ElementAt(1).Configuration.ExpirationTimeout.Should().Be(new TimeSpan(0, 0, 0)); act.CacheHandles.ElementAt(2).Configuration.Name.Should().Be("h3"); - act.CacheHandles.ElementAt(2).Configuration.EnablePerformanceCounters.Should().BeFalse(); act.CacheHandles.ElementAt(2).Configuration.EnableStatistics.Should().BeTrue(); act.CacheHandles.ElementAt(2).Configuration.ExpirationMode.Should().Be(ExpirationMode.Sliding); act.CacheHandles.ElementAt(2).Configuration.ExpirationTimeout.Should().Be(new TimeSpan(0, 0, 231)); diff --git a/test/CacheManager.Tests/Configuration/configuration.ExpireTest.config b/test/CacheManager.Tests/Configuration/configuration.ExpireTest.config index 996a3dab..ad1f4fb9 100644 --- a/test/CacheManager.Tests/Configuration/configuration.ExpireTest.config +++ b/test/CacheManager.Tests/Configuration/configuration.ExpireTest.config @@ -6,7 +6,7 @@ - + @@ -14,4 +14,4 @@ - \ No newline at end of file + diff --git a/test/CacheManager.Tests/Configuration/configuration.invalid.InvalidEnablePerfCounters.config b/test/CacheManager.Tests/Configuration/configuration.invalid.InvalidEnablePerfCounters.config index 327598c1..3036fd4b 100644 --- a/test/CacheManager.Tests/Configuration/configuration.invalid.InvalidEnablePerfCounters.config +++ b/test/CacheManager.Tests/Configuration/configuration.invalid.InvalidEnablePerfCounters.config @@ -6,7 +6,7 @@ - + @@ -18,4 +18,4 @@ defaultExpirationMode="Sliding" defaultTimeout="20m" /> - \ No newline at end of file + diff --git a/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config b/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config index 6ff469e8..63bf0d16 100644 --- a/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config +++ b/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config @@ -26,7 +26,7 @@ - + - - - - - - - - diff --git a/samples/AspNetCore.2.1/Controllers/InfoController.cs b/samples/AspNetCore/Controllers/InfoController.cs similarity index 100% rename from samples/AspNetCore.2.1/Controllers/InfoController.cs rename to samples/AspNetCore/Controllers/InfoController.cs diff --git a/samples/AspNetCore.3.0/Controllers/ValuesController.cs b/samples/AspNetCore/Controllers/ValuesController.cs similarity index 100% rename from samples/AspNetCore.3.0/Controllers/ValuesController.cs rename to samples/AspNetCore/Controllers/ValuesController.cs diff --git a/samples/AspNetCore.3.0/Program.cs b/samples/AspNetCore/Program.cs similarity index 100% rename from samples/AspNetCore.3.0/Program.cs rename to samples/AspNetCore/Program.cs diff --git a/samples/AspNetCore.2.1/Properties/launchSettings.json b/samples/AspNetCore/Properties/launchSettings.json similarity index 100% rename from samples/AspNetCore.2.1/Properties/launchSettings.json rename to samples/AspNetCore/Properties/launchSettings.json diff --git a/samples/AspNetCore.3.0/Startup.cs b/samples/AspNetCore/Startup.cs similarity index 81% rename from samples/AspNetCore.3.0/Startup.cs rename to samples/AspNetCore/Startup.cs index 9d5cb5b6..f311a67e 100644 --- a/samples/AspNetCore.3.0/Startup.cs +++ b/samples/AspNetCore/Startup.cs @@ -1,17 +1,14 @@ -using System; -using System.Linq; -using CacheManager.Core; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace AspnetCore.WebApp +namespace AspnetCore.WebApp { + using System; + using CacheManager.Core; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; - using Swashbuckle.AspNetCore.Swagger; public class Startup { @@ -43,12 +40,11 @@ public void ConfigureServices(IServiceCollection services) ); }); - // using the new overload which adds a singleton of the configuration to services and the configure method to add logging - // TODO: still not 100% happy with the logging part - services.AddCacheManagerConfiguration(Configuration, cfg => cfg.WithMicrosoftLogging(LoggerFactory)); - // uses a refined configuration (this will not log, as we added the MS Logger only to the configuration above - services.AddCacheManager(Configuration, configure: builder => builder.WithJsonSerializer()); + services.AddCacheManagerConfiguration(Configuration, configure: builder => builder + .WithJsonSerializer() + .WithRedisConfiguration("redis", c => c.WithEndpoint("localhost", 6379)) + .WithRedisCacheHandle("redis")); // creates a completely new configuration for this instance (also not logging) services.AddCacheManager(inline => inline.WithDictionaryHandle()); diff --git a/samples/AspNetCore.3.0/Web.csproj b/samples/AspNetCore/Web.csproj similarity index 81% rename from samples/AspNetCore.3.0/Web.csproj rename to samples/AspNetCore/Web.csproj index e20f2d5c..ec0ca829 100644 --- a/samples/AspNetCore.3.0/Web.csproj +++ b/samples/AspNetCore/Web.csproj @@ -1,7 +1,7 @@  - netcoreapp3.1 + net8.0 true AspnetCore.WebApp Exe @@ -11,12 +11,11 @@ - - + \ No newline at end of file diff --git a/samples/AspNetCore.2.1/appsettings.json b/samples/AspNetCore/appsettings.json similarity index 100% rename from samples/AspNetCore.2.1/appsettings.json rename to samples/AspNetCore/appsettings.json diff --git a/samples/AspNetCore.2.1/cache.json b/samples/AspNetCore/cache.json similarity index 100% rename from samples/AspNetCore.2.1/cache.json rename to samples/AspNetCore/cache.json diff --git a/samples/AspNetCore.2.1/web.config b/samples/AspNetCore/web.config similarity index 100% rename from samples/AspNetCore.2.1/web.config rename to samples/AspNetCore/web.config diff --git a/samples/CacheManager.Examples.Configuration/CacheManager.Examples.Configuration.csproj b/samples/CacheManager.Examples.Configuration/CacheManager.Examples.Configuration.csproj deleted file mode 100644 index 56226f1a..00000000 --- a/samples/CacheManager.Examples.Configuration/CacheManager.Examples.Configuration.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - Exe - net462 - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - - - - - - \ No newline at end of file diff --git a/samples/CacheManager.Examples.Configuration/Couchbase.cs b/samples/CacheManager.Examples.Configuration/Couchbase.cs deleted file mode 100644 index 75eb40b4..00000000 --- a/samples/CacheManager.Examples.Configuration/Couchbase.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System; -using System.Collections.Generic; -using CacheManager.Core; -using Couchbase; -using Couchbase.Authentication; -using Couchbase.Configuration.Client; - -namespace Configuration -{ - public class Couchbase - { - public void UsingClusterHelper() - { - var cfg = new ClientConfiguration() - { - Servers = new List() - { - new Uri("http://127.0.0.1:8091") - } - }; - - ClusterHelper.Initialize(cfg); - ClusterHelper.Get().Authenticate(new PasswordAuthenticator("admin", "password")); - - // using cluster helper is enough for CacheManager since 1.0.2 as it falls back to ClusterHelper internally - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseCacheHandle("cb") - .Build(); - - var cache = new BaseCacheManager(cacheConfig); - cache.AddOrUpdate("test", 1, (v) => v + 1); - } - - public void UsingAppConfig() - { - // see couchbaseClients/couchbase section in app.config of this project - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseCacheHandle("couchbaseClients/couchbase") - .Build(); - - var cache = new BaseCacheManager(cacheConfig); - cache.AddOrUpdate("test", 1, (v) => v + 1); - } - - public void UsingAppConfigWithAuthentication() - { - // see couchbaseClients/couchbase section in app.config of this project - // Note: even though we pass in "cb", CacheManager will fall back to the - // default couchbase section at couchbaseClients/couchbase! - // We could also pass in the section name explicitly instead of "cb". - - ClusterHelper.Initialize("couchbaseClients/couchbase"); - ClusterHelper.Get().Authenticate(new PasswordAuthenticator("admin", "password")); - - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseCacheHandle("keydoesnotmatter") - .Build(); - - var cache = new BaseCacheManager(cacheConfig); - cache.AddOrUpdate("test", 1, (v) => v + 1); - } - - public void UsingClientConfiguration() - { - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseConfiguration("myConfig", new ClientConfiguration()) // add the configuration you need here... - .WithCouchbaseCacheHandle("myConfig") - .Build(); - } - - public void UsingAlreadyDefinedCluster() - { - var cluster = new Cluster(new ClientConfiguration()); - cluster.Authenticate(new PasswordAuthenticator("admin", "password")); - - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseCluster("myCluster", cluster) - .WithCouchbaseCacheHandle("myCluster") - .Build(); - } - - public void UsingExplicitBucketName() - { - ClusterHelper.Initialize(); - ClusterHelper.Get().Authenticate(new PasswordAuthenticator("admin", "password")); - - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseCacheHandle("keydoesnotmatter", "beer-sample") // passing in a bucket name which should be used - .Build(); - - var cache = new BaseCacheManager(cacheConfig); - cache.AddOrUpdate("test", 1, (v) => v + 1); - } - - public void UsingExplicitBucketNameWithPassword() - { - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseConfiguration("cb", new ClientConfiguration()) - .WithCouchbaseCacheHandle("cb", "secret-bucket", "secret") // passing in a bucket-name and bucket-password - .Build(); - - var cache = new BaseCacheManager(cacheConfig); - cache.AddOrUpdate("test", 1, (v) => v + 1); - } - } -} \ No newline at end of file diff --git a/samples/CacheManager.Examples.Configuration/Program.cs b/samples/CacheManager.Examples.Configuration/Program.cs deleted file mode 100644 index 4677b0c4..00000000 --- a/samples/CacheManager.Examples.Configuration/Program.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; - -namespace Configuration -{ - class Program - { - static void Main(string[] args) - { - //var cb = new Couchbase(); - //cb.UsingClusterHelper(); - //cb.UsingAppConfig(); - //cb.UsingAppConfigWithAuthentication(); - //cb.UsingExplicitBucketName(); - //cb.UsingExplicitBucketNameWithPassword(); - } - } -} \ No newline at end of file diff --git a/samples/CacheManager.Examples.Configuration/app.config b/samples/CacheManager.Examples.Configuration/app.config deleted file mode 100644 index 1a94b5f2..00000000 --- a/samples/CacheManager.Examples.Configuration/app.config +++ /dev/null @@ -1,20 +0,0 @@ - - - - -
- - - - - - - - - - - - - - - \ No newline at end of file diff --git a/samples/CacheManager.Examples/CacheManager.Examples.csproj b/samples/CacheManager.Examples/CacheManager.Examples.csproj index 11ebd285..fa264379 100644 --- a/samples/CacheManager.Examples/CacheManager.Examples.csproj +++ b/samples/CacheManager.Examples/CacheManager.Examples.csproj @@ -3,7 +3,7 @@ CacheManager.Examples Console Application MICHA - net461 + net8.0 CacheManager.Examples Exe CacheManager.Examples @@ -22,18 +22,9 @@ - - - - - - - - - - + \ No newline at end of file diff --git a/samples/CacheManager.Examples/Program.cs b/samples/CacheManager.Examples/Program.cs index 13cf7dbf..1f0b1c14 100644 --- a/samples/CacheManager.Examples/Program.cs +++ b/samples/CacheManager.Examples/Program.cs @@ -2,9 +2,7 @@ using System.Threading; using CacheManager.Core; using Microsoft.Extensions.Logging; -using Unity; -using Unity.Injection; -using Unity.Lifetime; +using Microsoft.Extensions.DependencyInjection; namespace CacheManager.Examples { @@ -13,8 +11,7 @@ public class Program private static void Main() { EventsExample(); - UnityInjectionExample(); - UnityInjectionExample_Advanced(); + MostSimpleCacheManagerWithLogging(); SimpleCustomBuildConfigurationUsingConfigBuilder(); SimpleCustomBuildConfigurationUsingFactory(); UpdateTest(); @@ -22,11 +19,9 @@ private static void Main() LoggingSample(); } -#if !NETCOREAPP - private static void MostSimpleCacheManager() { - var config = new ConfigurationBuilder() + var config = new CacheConfigurationBuilder() .WithSystemRuntimeCacheHandle() .Build(); @@ -52,46 +47,48 @@ private static void MostSimpleCacheManagerC() private static void MostSimpleCacheManagerWithLogging() { - var loggerFactory = new LoggerFactory() - .AddConsole(); + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Trace)); + var loggerFactory = services.BuildServiceProvider().GetService(); - var config = new ConfigurationBuilder() - .WithMicrosoftLogging(loggerFactory) + var config = new CacheConfigurationBuilder() .WithSystemRuntimeCacheHandle() .Build(); - var cache = new BaseCacheManager(config); + ICacheManager cache = new BaseCacheManager(config, loggerFactory); + cache.Add("test", "test"); + cache.Exists("test no"); + cache.Remove("test"); + // or - var cache2 = CacheFactory.FromConfiguration(config); + cache = CacheFactory.FromConfiguration(config, loggerFactory); + + cache.Add("test", "test"); + cache.Exists("test no"); + cache.Remove("test"); } private static void EditExistingConfiguration() { - var loggerFactory = new LoggerFactory() - .AddConsole(); - - var config = new ConfigurationBuilder() + var config = new CacheConfigurationBuilder() .WithSystemRuntimeCacheHandle() .EnableStatistics() .Build(); - config = new ConfigurationBuilder(config) - .WithMicrosoftLogging(loggerFactory) + config = new CacheConfigurationBuilder(config) .Build(); } -#endif - private static void LoggingSample() { - var loggerFactory = new LoggerFactory() - .AddConsole(); + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Trace)); + var loggerFactory = services.BuildServiceProvider().GetService(); var cache = CacheFactory.Build( - c => - c.WithMicrosoftLogging(loggerFactory) - .WithDictionaryHandle() - .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10))); + c => c.WithDictionaryHandle() + .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)), + loggerFactory); cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value"); cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value"); @@ -99,19 +96,23 @@ private static void LoggingSample() var val = cache.Get("myKey", "someregion"); } -#if !NETCOREAPP - private static void AppConfigLoadInstalledCacheCfg() { - var cache = CacheFactory.FromConfiguration("myCache"); + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole()); + var loggerFactory = services.BuildServiceProvider().GetService(); + + var cache = CacheFactory.FromConfiguration("myCache", loggerFactory); cache.Add("key", "value"); } -#endif - private static void EventsExample() { - var cache = CacheFactory.Build(s => s.WithDictionaryHandle()); + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole()); + var loggerFactory = services.BuildServiceProvider().GetService(); + + var cache = CacheFactory.Build(s => s.WithDictionaryHandle(), loggerFactory); cache.OnAdd += (sender, args) => Console.WriteLine("Added " + args.Key); cache.OnGet += (sender, args) => Console.WriteLine("Got " + args.Key); cache.OnRemove += (sender, args) => Console.WriteLine("Removed " + args.Key); @@ -121,10 +122,12 @@ private static void EventsExample() cache.Remove("key"); } -#if !NETCOREAPP - private static void RedisSample() { + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole()); + var loggerFactory = services.BuildServiceProvider().GetService(); + var cache = CacheFactory.Build(settings => { settings @@ -140,7 +143,8 @@ private static void RedisSample() .WithRetryTimeout(100) .WithRedisBackplane("redis") .WithRedisCacheHandle("redis", true); - }); + }, + loggerFactory); cache.Add("test", 123456); @@ -149,13 +153,11 @@ private static void RedisSample() var result = cache.Get("test"); } -#endif - private static void SimpleCustomBuildConfigurationUsingConfigBuilder() { // this is using the CacheManager.Core.Configuration.ConfigurationBuilder to build a // custom config you can do the same with the CacheFactory - var cfg = ConfigurationBuilder.BuildConfiguration(settings => + var cfg = CacheConfigurationBuilder.BuildConfiguration(settings => { settings.WithUpdateMode(CacheUpdateMode.Up) .WithDictionaryHandle() @@ -184,55 +186,6 @@ private static void SimpleCustomBuildConfigurationUsingFactory() cache.Add("key", "value"); } - private static void UnityInjectionExample() - { - var container = new UnityContainer(); - container.RegisterType>( - new ContainerControlledLifetimeManager(), - new InjectionFactory((c) => CacheFactory.Build(s => s.WithDictionaryHandle()))); - - container.RegisterType(); - - // resolving the test target object should also resolve the cache instance - var target = container.Resolve(); - target.PutSomethingIntoTheCache(); - - // our cache manager instance should still be there so should the object we added in the - // previous step. - var checkTarget = container.Resolve(); - checkTarget.GetSomething(); - } - - private static void UnityInjectionExample_Advanced() - { - var container = new UnityContainer(); - container.RegisterType( - typeof(ICacheManager<>), - new ContainerControlledLifetimeManager(), - new InjectionFactory( - (c, t, n) => CacheFactory.FromConfiguration( - t.GetGenericArguments()[0], - ConfigurationBuilder.BuildConfiguration(cfg => cfg.WithDictionaryHandle())))); - - var stringCache = container.Resolve>(); - - // testing if we create a singleton instance per type, every Resolve of the same type should return the same instance! - var stringCacheB = container.Resolve>(); - stringCache.Put("key", "something"); - - var intCache = container.Resolve>(); - var intCacheB = container.Resolve>(); - intCache.Put("key", 22); - - var boolCache = container.Resolve>(); - var boolCacheB = container.Resolve>(); - boolCache.Put("key", false); - - Console.WriteLine("Value type is: " + stringCache.GetType().GetGenericArguments()[0].Name + " test value: " + stringCacheB["key"]); - Console.WriteLine("Value type is: " + intCache.GetType().GetGenericArguments()[0].Name + " test value: " + intCacheB["key"]); - Console.WriteLine("Value type is: " + boolCache.GetType().GetGenericArguments()[0].Name + " test value: " + boolCacheB["key"]); - } - private static void UpdateTest() { var cache = CacheFactory.Build(s => s.WithDictionaryHandle()); @@ -287,7 +240,7 @@ private static void UpdateCounterTest() private static void MultiCacheEvictionWithoutRedisCacheHandle() { - var config = new ConfigurationBuilder("Redis with Redis Backplane") + var config = new CacheConfigurationBuilder("Redis with Redis Backplane") .WithDictionaryHandle(true) .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(5)) .And @@ -338,29 +291,4 @@ private static void MultiCacheEvictionWithoutRedisCacheHandle() cacheA.Remove(key); } } - - public class UnityInjectionExampleTarget - { - private ICacheManager _cache; - - public UnityInjectionExampleTarget(ICacheManager cache) - { - _cache = cache ?? throw new ArgumentNullException(nameof(cache)); - } - - public void GetSomething() - { - var value = _cache.Get("myKey"); - var x = value; - if (value == null) - { - throw new InvalidOperationException(); - } - } - - public void PutSomethingIntoTheCache() - { - _cache.Put("myKey", "something"); - } - } } diff --git a/src/CacheManager.Core/BaseCacheManager.Expire.cs b/src/CacheManager.Core/BaseCacheManager.Expire.cs index ab1b7050..15af3f9d 100644 --- a/src/CacheManager.Core/BaseCacheManager.Expire.cs +++ b/src/CacheManager.Core/BaseCacheManager.Expire.cs @@ -1,6 +1,7 @@ using System; using System.Linq; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; + namespace CacheManager.Core { diff --git a/src/CacheManager.Core/BaseCacheManager.Update.cs b/src/CacheManager.Core/BaseCacheManager.Update.cs index 06c03e45..930db93b 100644 --- a/src/CacheManager.Core/BaseCacheManager.Update.cs +++ b/src/CacheManager.Core/BaseCacheManager.Update.cs @@ -1,8 +1,7 @@ using System; using System.Globalization; -using System.Linq; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core @@ -241,7 +240,7 @@ private bool UpdateInternal( } else if (result.UpdateState == UpdateItemResultState.FactoryReturnedNull) { - Logger.LogWarn($"Update failed on '{region}:{key}' because value factory returned null."); + Logger.LogWarning($"Update failed on '{region}:{key}' because value factory returned null."); if (throwOnFailure) { @@ -253,7 +252,7 @@ private bool UpdateInternal( // if we had too many retries, this basically indicates an // invalid state of the cache: The item is there, but we couldn't update it and // it most likely has a different version - Logger.LogWarn($"Update failed on '{region}:{key}' because of too many retries."); + Logger.LogWarning($"Update failed on '{region}:{key}' because of too many retries."); EvictFromOtherHandles(key, region, handleIndex); @@ -267,7 +266,7 @@ private bool UpdateInternal( // If update fails because item doesn't exist AND the current handle is backplane source or the lowest cache handle level, // remove the item from other handles (if exists). // Otherwise, if we do not exit here, calling update on the next handle might succeed and would return a misleading result. - Logger.LogInfo($"Update failed on '{region}:{key}' because the region/key did not exist."); + Logger.LogInformation($"Update failed on '{region}:{key}' because the region/key did not exist."); EvictFromOtherHandles(key, region, handleIndex); diff --git a/src/CacheManager.Core/BaseCacheManager.cs b/src/CacheManager.Core/BaseCacheManager.cs index 353f11bc..39fb48f0 100644 --- a/src/CacheManager.Core/BaseCacheManager.cs +++ b/src/CacheManager.Core/BaseCacheManager.cs @@ -4,7 +4,7 @@ using System.Globalization; using System.Linq; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core @@ -18,6 +18,34 @@ namespace CacheManager.Core /// The type of the cache value. public partial class BaseCacheManager : BaseCache, ICacheManager, IDisposable { + private class NullLoggerFactory : ILoggerFactory + { + public void AddProvider(ILoggerProvider provider) + { + } + + public ILogger CreateLogger(string categoryName) + { + return new NullLogger(); + } + + public void Dispose() + { + } + } + + private class NullLogger : ILogger> + { + public IDisposable BeginScope(TState state) => null; + + public bool IsEnabled(LogLevel logLevel) => false; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + { + // do nothing; + } + } + private readonly bool _logTrace = false; private readonly BaseCacheHandle[] _cacheHandles; private readonly CacheBackplane _cacheBackplane; @@ -31,49 +59,35 @@ public partial class BaseCacheManager : BaseCache, ICa /// /// The configuration which defines the structure and complexity of the cache manager. /// + /// Optional logger factory. /// /// When is null. /// /// - /// + /// /// - public BaseCacheManager(ICacheManagerConfiguration configuration) - : this(configuration?.Name ?? Guid.NewGuid().ToString(), configuration) + public BaseCacheManager(ICacheManagerConfiguration configuration, ILoggerFactory loggerFactory = null) + : this(configuration?.Name ?? Guid.NewGuid().ToString(), configuration, loggerFactory ?? new NullLoggerFactory()) { } - /// - /// Initializes a new instance of the class - /// using the specified and . - /// - /// The cache name. - /// - /// The configuration which defines the structure and complexity of the cache manager. - /// - /// - /// When or is null. - /// - /// - /// - /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2200:RethrowToPreserveStackDetails", Justification = "fine for now")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "nope")] - private BaseCacheManager(string name, ICacheManagerConfiguration configuration) + private BaseCacheManager(string name, ICacheManagerConfiguration configuration, ILoggerFactory loggerFactory) { NotNullOrWhiteSpace(name, nameof(name)); NotNull(configuration, nameof(configuration)); + NotNull(loggerFactory, nameof(loggerFactory)); Name = name; Configuration = configuration; - - var loggerFactory = CacheReflectionHelper.CreateLoggerFactory(configuration); var serializer = CacheReflectionHelper.CreateSerializer(configuration, loggerFactory); - Logger = loggerFactory.CreateLogger(this); + Logger = loggerFactory.CreateLogger(this.GetType()); _logTrace = Logger.IsEnabled(LogLevel.Trace); - Logger.LogInfo("Cache manager: adding cache handles..."); + Logger.LogInformation("Cache manager: adding cache handles..."); try { diff --git a/src/CacheManager.Core/CacheFactory.cs b/src/CacheManager.Core/CacheFactory.cs index ad37ccd9..45784664 100644 --- a/src/CacheManager.Core/CacheFactory.cs +++ b/src/CacheManager.Core/CacheFactory.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Reflection; +using Microsoft.Extensions.Logging; using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core @@ -36,6 +37,7 @@ public static class CacheFactory /// The configuration. Use the settings element to configure the cache manager instance, add /// cache handles and also to configure the cache handles in a fluent way. /// + /// Optional logger factory. /// The cache manager instance with cache item type being System.Object. /// /// @@ -44,8 +46,8 @@ public static class CacheFactory /// /// Thrown on certain configuration errors related to the cache handles. /// - public static ICacheManager Build(string cacheName, Action settings) => - Build(cacheName, settings); + public static ICacheManager Build(string cacheName, Action settings, ILoggerFactory loggerFactory = null) => + Build(cacheName, settings, loggerFactory); /// /// Instantiates a cache manager using the inline configuration defined by . @@ -72,6 +74,7 @@ public static ICacheManager Build(string cacheName, Action + /// Optional logger factory. /// The cache manager instance. /// /// @@ -80,8 +83,8 @@ public static ICacheManager Build(string cacheName, Action /// Thrown on certain configuration errors related to the cache handles. /// - public static ICacheManager Build(Action settings) => - Build(Guid.NewGuid().ToString("N"), settings); + public static ICacheManager Build(Action settings, ILoggerFactory loggerFactory = null) => + Build(Guid.NewGuid().ToString("N"), settings, loggerFactory); /// /// Instantiates a cache manager using the inline configuration defined by . @@ -108,6 +111,7 @@ public static ICacheManager Build(Action /// The configuration. Use the settings element to configure the cache manager instance, add /// cache handles and also to configure the cache handles in a fluent way. /// + /// Optional logger factory. /// The type of the cache item value. /// The cache manager instance with cache item type being TCacheValue. /// @@ -117,14 +121,17 @@ public static ICacheManager Build(Action /// /// Thrown on certain configuration errors related to the cache handles. /// - public static ICacheManager Build(string cacheName, Action settings) + public static ICacheManager Build( + string cacheName, + Action settings, + ILoggerFactory loggerFactory = null) { NotNull(settings, nameof(settings)); var part = new ConfigurationBuilderCachePart(); settings(part); part.Configuration.Name = cacheName; - return new BaseCacheManager(part.Configuration); + return new BaseCacheManager(part.Configuration, loggerFactory); } /// @@ -151,6 +158,7 @@ public static ICacheManager Build(string cacheName, Ac /// The configuration. Use the settings element to configure the cache manager instance, add /// cache handles and also to configure the cache handles in a fluent way. /// + /// Optional logger factory. /// The type of the cache item value. /// The cache manager instance with cache item type being TCacheValue. /// @@ -160,8 +168,8 @@ public static ICacheManager Build(string cacheName, Ac /// /// Thrown on certain configuration errors related to the cache handles. /// - public static ICacheManager Build(Action settings) - => Build(Guid.NewGuid().ToString("N"), settings); + public static ICacheManager Build(Action settings, ILoggerFactory loggerFactory = null) + => Build(Guid.NewGuid().ToString("N"), settings, loggerFactory); /// /// Instantiates a cache manager using the given type and the inline configuration defined by . @@ -189,6 +197,7 @@ public static ICacheManager Build(Action + /// Optional logger factory. /// The cache manager instance. /// /// Thrown if the or is null. @@ -196,14 +205,14 @@ public static ICacheManager Build(Action /// Thrown on certain configuration errors related to the cache handles. /// - public static object Build(Type cacheValueType, string cacheName, Action settings) + public static object Build(Type cacheValueType, string cacheName, Action settings, ILoggerFactory loggerFactory = null) { NotNull(cacheValueType, nameof(cacheValueType)); var factoryType = typeof(CacheFactory).GetTypeInfo(); var buildMethod = factoryType.GetDeclaredMethods("Build").First(p => p.IsGenericMethod); var genericMethod = buildMethod.MakeGenericMethod(cacheValueType); - return genericMethod.Invoke(null, new object[] { cacheName, settings }); + return genericMethod.Invoke(null, new object[] { cacheName, settings, loggerFactory }); } /// @@ -231,6 +240,7 @@ public static object Build(Type cacheValueType, string cacheName, Action + /// Optional logger factory. /// The cache manager instance. /// /// Thrown if is null. @@ -238,8 +248,8 @@ public static object Build(Type cacheValueType, string cacheName, Action /// Thrown on certain configuration errors related to the cache handles. /// - public static object Build(Type cacheValueType, Action settings) - => Build(cacheValueType, Guid.NewGuid().ToString("N"), settings); + public static object Build(Type cacheValueType, Action settings, ILoggerFactory loggerFactory = null) + => Build(cacheValueType, Guid.NewGuid().ToString("N"), settings, loggerFactory); /// /// Instantiates a cache manager from app.config or web.config. @@ -261,6 +271,7 @@ public static object Build(Type cacheValueType, Action /// The name of the cache, must also match with the configured cache name. /// + /// Optional logger factory. /// The type of the cache item value. /// The cache manager instance. /// @@ -272,11 +283,11 @@ public static object Build(Type cacheValueType, Action - public static ICacheManager FromConfiguration(string cacheName) + public static ICacheManager FromConfiguration(string cacheName, ILoggerFactory loggerFactory = null) { - var cfg = ConfigurationBuilder.LoadConfiguration(cacheName); + var cfg = CacheConfigurationBuilder.LoadConfiguration(cacheName); - return CacheFactory.FromConfiguration(cacheName, cfg); + return CacheFactory.FromConfiguration(cacheName, cfg, loggerFactory); } /// @@ -292,6 +303,7 @@ public static ICacheManager FromConfiguration(string c /// /// The name of the cache, must also match with the configured cache name. /// + /// Optional logger factory. /// The cache manager instance. /// /// Thrown if the or is null or an empty. @@ -301,11 +313,11 @@ public static ICacheManager FromConfiguration(string c /// Thrown if no cacheManager section is defined or on certain configuration errors related /// to the cache handles. /// - public static object FromConfiguration(Type cacheValueType, string cacheName) + public static object FromConfiguration(Type cacheValueType, string cacheName, ILoggerFactory loggerFactory = null) { - var cfg = ConfigurationBuilder.LoadConfiguration(cacheName); + var cfg = CacheConfigurationBuilder.LoadConfiguration(cacheName); - return CacheFactory.FromConfiguration(cacheValueType, cacheName, cfg); + return CacheFactory.FromConfiguration(cacheValueType, cacheName, cfg, loggerFactory); } /// @@ -329,6 +341,7 @@ public static object FromConfiguration(Type cacheValueType, string cacheName) /// /// The cache manager section name. /// + /// Optional logger factory. /// The type of the cache item value. /// The cache manager instance. /// @@ -340,11 +353,11 @@ public static object FromConfiguration(Type cacheValueType, string cacheName) /// Thrown if no cacheManager section is defined or on certain configuration errors related /// to the cache handles. /// - public static ICacheManager FromConfiguration(string cacheName, string sectionName) + public static ICacheManager FromConfiguration(string cacheName, string sectionName, ILoggerFactory loggerFactory = null) { - var cfg = ConfigurationBuilder.LoadConfiguration(sectionName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfiguration(sectionName, cacheName); - return CacheFactory.FromConfiguration(cacheName, cfg); + return CacheFactory.FromConfiguration(cacheName, cfg, loggerFactory); } /// @@ -361,6 +374,7 @@ public static ICacheManager FromConfiguration(string c /// /// The cache manager section name. /// + /// Optional logger factory. /// The cache manager instance. /// /// Thrown if the , or @@ -371,11 +385,11 @@ public static ICacheManager FromConfiguration(string c /// Thrown if no cacheManager section is defined or on certain configuration errors related /// to the cache handles. /// - public static object FromConfiguration(Type cacheValueType, string cacheName, string sectionName) + public static object FromConfiguration(Type cacheValueType, string cacheName, string sectionName, ILoggerFactory loggerFactory = null) { - var cfg = ConfigurationBuilder.LoadConfiguration(sectionName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfiguration(sectionName, cacheName); - return CacheFactory.FromConfiguration(cacheValueType, cacheName, cfg); + return CacheFactory.FromConfiguration(cacheValueType, cacheName, cfg, loggerFactory); } /// @@ -385,21 +399,25 @@ public static object FromConfiguration(Type cacheValueType, string cacheName, st /// /// The configured which will be used to configure the cache manager instance. /// + /// Optional logger factory. /// The type of the cache item value. /// The cache manager instance. - /// + /// /// /// Thrown if the is null. /// /// /// Thrown on certain configuration errors related to the cache handles. /// - public static ICacheManager FromConfiguration(string cacheName, ICacheManagerConfiguration configuration) + public static ICacheManager FromConfiguration( + string cacheName, + ICacheManagerConfiguration configuration, + ILoggerFactory loggerFactory = null) { NotNull(configuration, nameof(configuration)); var cfg = (CacheManagerConfiguration)configuration; cfg.Name = cacheName; - return new BaseCacheManager(cfg); + return new BaseCacheManager(cfg, loggerFactory); } /// @@ -425,17 +443,20 @@ public static ICacheManager FromConfiguration(string c /// /// The configured which will be used to configure the cache manager instance. /// + /// Optional logger factory. /// The type of the cache item value. /// The cache manager instance. - /// + /// /// /// Thrown if the is null. /// /// /// Thrown on certain configuration errors related to the cache handles. /// - public static ICacheManager FromConfiguration(ICacheManagerConfiguration configuration) - => FromConfiguration(Guid.NewGuid().ToString("N"), configuration); + public static ICacheManager FromConfiguration( + ICacheManagerConfiguration configuration, + ILoggerFactory loggerFactory = null) + => FromConfiguration(Guid.NewGuid().ToString("N"), configuration, loggerFactory); /// /// Instantiates a cache manager using the given and . @@ -447,15 +468,20 @@ public static ICacheManager FromConfiguration(ICacheMa /// /// The configured which will be used to configure the cache manager instance. /// + /// Optional logger factory. /// The cache manager instance. - /// + /// /// /// Thrown if the cacheValueType, cacheName or configuration is null. /// /// /// Thrown on certain configuration errors related to the cache handles. /// - public static object FromConfiguration(Type cacheValueType, string cacheName, ICacheManagerConfiguration configuration) + public static object FromConfiguration( + Type cacheValueType, + string cacheName, + ICacheManagerConfiguration configuration, + ILoggerFactory loggerFactory = null) { NotNull(cacheValueType, nameof(cacheValueType)); NotNull(configuration, nameof(configuration)); @@ -464,7 +490,7 @@ public static object FromConfiguration(Type cacheValueType, string cacheName, IC cfg.Name = cacheName; var type = typeof(BaseCacheManager<>).MakeGenericType(new[] { cacheValueType }); - return Activator.CreateInstance(type, new object[] { cfg }); + return Activator.CreateInstance(type, new object[] { cfg, loggerFactory }); } /// @@ -476,15 +502,19 @@ public static object FromConfiguration(Type cacheValueType, string cacheName, IC /// /// The configured which will be used to configure the cache manager instance. /// + /// Optional logger factory. /// The cache manager instance. - /// + /// /// /// Thrown if the or are null. /// /// /// Thrown on certain configuration errors related to the cache handles. /// - public static object FromConfiguration(Type cacheValueType, ICacheManagerConfiguration configuration) - => FromConfiguration(cacheValueType, Guid.NewGuid().ToString("N"), configuration); + public static object FromConfiguration( + Type cacheValueType, + ICacheManagerConfiguration configuration, + ILoggerFactory loggerFactory = null) + => FromConfiguration(cacheValueType, Guid.NewGuid().ToString("N"), configuration, loggerFactory); } } diff --git a/src/CacheManager.Core/CacheManager.Core.csproj b/src/CacheManager.Core/CacheManager.Core.csproj index 15da3865..f9db80b3 100644 --- a/src/CacheManager.Core/CacheManager.Core.csproj +++ b/src/CacheManager.Core/CacheManager.Core.csproj @@ -2,14 +2,24 @@ CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. The Core library contains all base interfaces and tools. You should install at least one other CacheManager package to get cache handle implementations. - net45;netstandard2.0;netstandard2.1;net50 + net472;netstandard2.0;netstandard2.1;net80 False - Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Memcached + Caching;Cache;CacheManager;Distributed Cache;Redis; - + + + + + + + + + + + - - + + - \ No newline at end of file + diff --git a/src/CacheManager.Core/CacheManagerConfiguration.cs b/src/CacheManager.Core/CacheManagerConfiguration.cs index 6755fb38..6af770f1 100644 --- a/src/CacheManager.Core/CacheManagerConfiguration.cs +++ b/src/CacheManager.Core/CacheManagerConfiguration.cs @@ -17,11 +17,11 @@ public CacheManagerConfiguration() } /// - /// Gets a for the current instance + /// Gets a for the current instance /// to manipulate the configuration fluently. /// - /// The . - public ConfigurationBuilder Builder => new ConfigurationBuilder(this); + /// The . + public CacheConfigurationBuilder Builder => new CacheConfigurationBuilder(this); /// /// Gets or sets the name of the cache. diff --git a/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs b/src/CacheManager.Core/Configuration/CacheConfigurationBuilder.cs similarity index 95% rename from src/CacheManager.Core/Configuration/ConfigurationBuilder.cs rename to src/CacheManager.Core/Configuration/CacheConfigurationBuilder.cs index a8ed49f9..f6e3a4ee 100644 --- a/src/CacheManager.Core/Configuration/ConfigurationBuilder.cs +++ b/src/CacheManager.Core/Configuration/CacheConfigurationBuilder.cs @@ -4,7 +4,6 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Runtime.Serialization.Formatters.Binary; using System.Text.RegularExpressions; using CacheManager.Core.Configuration; using CacheManager.Core.Internal; @@ -21,26 +20,26 @@ namespace CacheManager.Core /// /// /// - public class ConfigurationBuilder : ConfigurationBuilderCachePart + public class CacheConfigurationBuilder : ConfigurationBuilderCachePart { private const string Hours = "h"; private const string Minutes = "m"; /// - /// Initializes a new instance of the class + /// Initializes a new instance of the class /// which provides fluent configuration methods. /// - public ConfigurationBuilder() + public CacheConfigurationBuilder() : base() { } /// - /// Initializes a new instance of the class + /// Initializes a new instance of the class /// which provides fluent configuration methods. /// /// The name of the cache manager. - public ConfigurationBuilder(string name) + public CacheConfigurationBuilder(string name) : base() { NotNullOrWhiteSpace(name, nameof(name)); @@ -48,24 +47,24 @@ public ConfigurationBuilder(string name) } /// - /// Initializes a new instance of the class + /// Initializes a new instance of the class /// which provides fluent configuration methods. /// Creates a builder which allows to modify the existing . /// /// The configuration the builder should be instantiated for. - public ConfigurationBuilder(ICacheManagerConfiguration forConfiguration) + public CacheConfigurationBuilder(ICacheManagerConfiguration forConfiguration) : base((CacheManagerConfiguration)forConfiguration) { } /// - /// Initializes a new instance of the class + /// Initializes a new instance of the class /// which provides fluent configuration methods. /// Creates a builder which allows to modify the existing . /// /// The name of the cache manager. /// The configuration the builder should be instantiated for. - public ConfigurationBuilder(string name, ICacheManagerConfiguration forConfiguration) + public CacheConfigurationBuilder(string name, ICacheManagerConfiguration forConfiguration) : base(NotNull((CacheManagerConfiguration)forConfiguration, nameof(forConfiguration))) { NotNullOrWhiteSpace(name, nameof(name)); @@ -88,7 +87,7 @@ public static ICacheManagerConfiguration BuildConfiguration(Action - /// Enables logging by setting the for the cache manager instance. - /// - /// The type of the logger factory. - /// Additional arguments the type might need to get initialized. - /// The builder part. - public ConfigurationBuilderCachePart WithLogging(Type loggerFactoryType, params object[] args) - { - NotNull(loggerFactoryType, nameof(loggerFactoryType)); - - Configuration.LoggerFactoryType = loggerFactoryType; - Configuration.LoggerFactoryTypeArguments = args; - return this; - } + /////// + /////// Enables logging by setting the for the cache manager instance. + /////// + /////// The type of the logger factory. + /////// Additional arguments the type might need to get initialized. + /////// The builder part. + ////public ConfigurationBuilderCachePart WithLogging(Type loggerFactoryType, params object[] args) + ////{ + //// NotNull(loggerFactoryType, nameof(loggerFactoryType)); + + //// Configuration.LoggerFactoryType = loggerFactoryType; + //// Configuration.LoggerFactoryTypeArguments = args; + //// return this; + ////} /// /// Hands back the new instance. diff --git a/src/CacheManager.Core/ICacheManagerConfiguration.cs b/src/CacheManager.Core/ICacheManagerConfiguration.cs index 279f9986..e717a05b 100644 --- a/src/CacheManager.Core/ICacheManagerConfiguration.cs +++ b/src/CacheManager.Core/ICacheManagerConfiguration.cs @@ -15,11 +15,11 @@ public interface ICacheManagerConfiguration : IReadOnlyCacheManagerConfiguration IList CacheHandleConfigurations { get; } /// - /// Gets a for the current instance + /// Gets a for the current instance /// to manipulate the configuration fluently. /// - /// The . - ConfigurationBuilder Builder { get; } + /// The . + CacheConfigurationBuilder Builder { get; } } /// diff --git a/src/CacheManager.Core/Internal/BaseCache.cs b/src/CacheManager.Core/Internal/BaseCache.cs index a8018724..0de563ba 100644 --- a/src/CacheManager.Core/Internal/BaseCache.cs +++ b/src/CacheManager.Core/Internal/BaseCache.cs @@ -1,6 +1,6 @@ using System; using System.Globalization; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core.Internal diff --git a/src/CacheManager.Core/Internal/BaseCacheHandle.cs b/src/CacheManager.Core/Internal/BaseCacheHandle.cs index 9e8de78c..ed0f3c50 100644 --- a/src/CacheManager.Core/Internal/BaseCacheHandle.cs +++ b/src/CacheManager.Core/Internal/BaseCacheHandle.cs @@ -1,5 +1,5 @@ using System; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core.Internal diff --git a/src/CacheManager.Core/Internal/BinaryCacheSerializer.cs b/src/CacheManager.Core/Internal/BinaryCacheSerializer.cs deleted file mode 100644 index 31d756cf..00000000 --- a/src/CacheManager.Core/Internal/BinaryCacheSerializer.cs +++ /dev/null @@ -1,105 +0,0 @@ -////#if NET45 -////using System; -////using System.Diagnostics.CodeAnalysis; -////using System.IO; -////using System.Runtime.Serialization.Formatters; -////using System.Runtime.Serialization.Formatters.Binary; -////using CacheManager.Core.Utility; - -////namespace CacheManager.Core.Internal -////{ -//// /// -//// /// Basic binary serialization implementation of the . -//// /// This implementation will be used in case no other serializer is configured for the cache manager -//// /// and serialization is needed (only distributed caches will have to serialize the cache value). -//// /// Binary serialization will not be available in some environments. -//// /// -//// public class BinaryCacheSerializer : ICacheSerializer -//// { -//// /// -//// /// Initializes a new instance of the class. -//// /// -//// /// The formatter to use to do the serialization. -//// /// The formatter to use to do the deserialization. -//// public BinaryCacheSerializer(BinaryFormatter serializationFormatter, BinaryFormatter deserializationFormatter) -//// { -//// Guard.NotNull(serializationFormatter, nameof(serializationFormatter)); -//// Guard.NotNull(deserializationFormatter, nameof(deserializationFormatter)); - -//// SerializationFormatter = serializationFormatter; -//// DeserializationFormatter = deserializationFormatter; -//// } - -//// /// -//// /// Initializes a new instance of the class. -//// /// -//// public BinaryCacheSerializer() -//// { -//// DeserializationFormatter = SerializationFormatter = new BinaryFormatter() -//// { -//// AssemblyFormat = FormatterAssemblyStyle.Simple -//// }; -//// } - -//// /// -//// /// Gets the formatter which should be used during deserialization. -//// /// If nothing is specified the default will be used. -//// /// -//// /// The deserialization formatter. -//// public BinaryFormatter DeserializationFormatter { get; } - -//// /// -//// /// Gets the formatter which should be used during serialization. -//// /// If nothing is specified the default will be used. -//// /// -//// /// The serialization formatter. -//// public BinaryFormatter SerializationFormatter { get; } - -//// /// -//// public object Deserialize(byte[] data, Type target) -//// { -//// if (data == null) -//// { -//// return null; -//// } - -//// using (var memoryStream = new MemoryStream(data)) -//// { -//// return DeserializationFormatter.Deserialize(memoryStream); -//// } -//// } - -//// /// -//// public CacheItem DeserializeCacheItem(byte[] value, Type valueType) -//// { -//// var result = Deserialize(value, valueType); -//// if (result == null) -//// { -//// return null; -//// } - -//// return (CacheItem)result; -//// } - -//// /// -//// public byte[] Serialize(T value) -//// { -//// if (value == null) -//// { -//// return null; -//// } - -//// using (var memoryStream = new MemoryStream()) -//// { -//// SerializationFormatter.Serialize(memoryStream, value); -//// var objectDataAsStream = memoryStream.ToArray(); -//// return objectDataAsStream; -//// } -//// } - -//// /// -//// public byte[] SerializeCacheItem(CacheItem value) -//// => Serialize(value); -//// } -////} -////#endif diff --git a/src/CacheManager.Core/Internal/CacheReflectionHelper.cs b/src/CacheManager.Core/Internal/CacheReflectionHelper.cs index 826e60e2..d432e140 100644 --- a/src/CacheManager.Core/Internal/CacheReflectionHelper.cs +++ b/src/CacheManager.Core/Internal/CacheReflectionHelper.cs @@ -3,32 +3,32 @@ using System.Globalization; using System.Linq; using System.Reflection; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core.Internal { internal static class CacheReflectionHelper { - internal static ILoggerFactory CreateLoggerFactory(ICacheManagerConfiguration configuration) - { - NotNull(configuration, nameof(configuration)); + ////internal static ILoggerFactory CreateLoggerFactory(ICacheManagerConfiguration configuration) + ////{ + //// NotNull(configuration, nameof(configuration)); - if (configuration.LoggerFactoryType == null) - { - return new NullLoggerFactory(); - } + //// if (configuration.LoggerFactoryType == null) + //// { + //// return new NullLoggerFactory(); + //// } - CheckImplements(configuration.LoggerFactoryType); + //// CheckImplements(configuration.LoggerFactoryType); - var args = new object[] { configuration }; - if (configuration.LoggerFactoryTypeArguments != null) - { - args = configuration.LoggerFactoryTypeArguments.Concat(args).ToArray(); - } + //// var args = new object[] { configuration }; + //// if (configuration.LoggerFactoryTypeArguments != null) + //// { + //// args = configuration.LoggerFactoryTypeArguments.Concat(args).ToArray(); + //// } - return (ILoggerFactory)CreateInstance(configuration.LoggerFactoryType, args); - } + //// return (ILoggerFactory)CreateInstance(configuration.LoggerFactoryType, args); + ////} internal static ICacheSerializer CreateSerializer(ICacheManagerConfiguration configuration, ILoggerFactory loggerFactory) { @@ -92,7 +92,7 @@ internal static ICollection> CreateCacheHandles>(); options = options ?? new DictionaryCacheOptions(); @@ -278,7 +278,7 @@ private int ScanForExpiredItems() if (removed > 0 && Logger.IsEnabled(LogLevel.Information)) { - Logger.LogInfo("'{0}' removed '{1}' expired items during eviction run.", Configuration.Name, removed); + Logger.LogInformation("'{0}' removed '{1}' expired items during eviction run.", Configuration.Name, removed); } return removed; diff --git a/src/CacheManager.Core/Internal/ICacheSerializer.cs b/src/CacheManager.Core/Internal/ICacheSerializer.cs index ed881712..fb81b7de 100644 --- a/src/CacheManager.Core/Internal/ICacheSerializer.cs +++ b/src/CacheManager.Core/Internal/ICacheSerializer.cs @@ -46,4 +46,4 @@ public interface ICacheSerializer /// The deserialized cache item. CacheItem DeserializeCacheItem(byte[] value, Type valueType); } -} \ No newline at end of file +} diff --git a/src/CacheManager.Core/Logging/ILogger.cs b/src/CacheManager.Core/Logging/ILogger.cs index 89f96a58..302ecde9 100644 --- a/src/CacheManager.Core/Logging/ILogger.cs +++ b/src/CacheManager.Core/Logging/ILogger.cs @@ -1,44 +1,44 @@ -using System; +////using System; -namespace CacheManager.Core.Logging -{ - /// - /// Represents a type used to perform logging. - /// - public interface ILogger - { - /// - /// Logs a message for the given . - /// - /// The log level. - /// The optional even id. - /// The log message. - /// The optional exception. - void Log(LogLevel logLevel, int eventId, object message, Exception exception); +////namespace CacheManager.Core.Logging +////{ +//// /// +//// /// Represents a type used to perform logging. +//// /// +//// public interface ILogger +//// { +//// /// +//// /// Logs a message for the given . +//// /// +//// /// The log level. +//// /// The optional even id. +//// /// The log message. +//// /// The optional exception. +//// void Log(LogLevel logLevel, int eventId, object message, Exception exception); - /// - /// Checks if the given LogLevel is enabled. - /// - /// The log level. - /// True if the is enabled, False otherwise. - bool IsEnabled(LogLevel logLevel); +//// /// +//// /// Checks if the given LogLevel is enabled. +//// /// +//// /// The log level. +//// /// True if the is enabled, False otherwise. +//// bool IsEnabled(LogLevel logLevel); - /// - /// Begins a logical operation scope. - /// - /// The identifier for the scope. - /// An IDisposable that ends the logical operation scope on dispose. - IDisposable BeginScope(object state); - } +//// /// +//// /// Begins a logical operation scope. +//// /// +//// /// The identifier for the scope. +//// /// An IDisposable that ends the logical operation scope on dispose. +//// IDisposable BeginScope(object state); +//// } - internal class NullLogger : ILogger - { - public IDisposable BeginScope(object state) => null; +//// internal class NullLogger : ILogger +//// { +//// public IDisposable BeginScope(object state) => null; - public bool IsEnabled(LogLevel logLevel) => false; +//// public bool IsEnabled(LogLevel logLevel) => false; - public void Log(LogLevel logLevel, int eventId, object message, Exception exception) - { - } - } -} \ No newline at end of file +//// public void Log(LogLevel logLevel, int eventId, object message, Exception exception) +//// { +//// } +//// } +////} diff --git a/src/CacheManager.Core/Logging/ILoggerFactory.cs b/src/CacheManager.Core/Logging/ILoggerFactory.cs index 611aa1ca..7f775922 100644 --- a/src/CacheManager.Core/Logging/ILoggerFactory.cs +++ b/src/CacheManager.Core/Logging/ILoggerFactory.cs @@ -1,20 +1,20 @@ -namespace CacheManager.Core.Logging -{ -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member -#pragma warning disable SA1600 - public interface ILoggerFactory - { - ILogger CreateLogger(string categoryName); +////namespace CacheManager.Core.Logging +////{ +////#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +////#pragma warning disable SA1600 +//// public interface ILoggerFactory +//// { +//// ILogger CreateLogger(string categoryName); - ILogger CreateLogger(T instance); - } +//// ILogger CreateLogger(T instance); +//// } - public class NullLoggerFactory : ILoggerFactory - { - public ILogger CreateLogger(string categoryName) => new NullLogger(); +//// public class NullLoggerFactory : ILoggerFactory +//// { +//// public ILogger CreateLogger(string categoryName) => new NullLogger(); - public ILogger CreateLogger(T instance) => new NullLogger(); - } -#pragma warning restore SA1600 -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -} \ No newline at end of file +//// public ILogger CreateLogger(T instance) => new NullLogger(); +//// } +////#pragma warning restore SA1600 +////#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +////} diff --git a/src/CacheManager.Core/Logging/LogLevel.cs b/src/CacheManager.Core/Logging/LogLevel.cs index 651c9b84..8f7ceb59 100644 --- a/src/CacheManager.Core/Logging/LogLevel.cs +++ b/src/CacheManager.Core/Logging/LogLevel.cs @@ -1,20 +1,20 @@ -namespace CacheManager.Core.Logging -{ -#pragma warning disable SA1600 -#pragma warning disable SA1602 // Enumeration items must be documented -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +////namespace CacheManager.Core.Logging +////{ +////#pragma warning disable SA1600 +////#pragma warning disable SA1602 // Enumeration items must be documented +////#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - public enum LogLevel - { - Trace, - Debug, - Information, - Warning, - Error, - Critical - } +//// public enum LogLevel +//// { +//// Trace, +//// Debug, +//// Information, +//// Warning, +//// Error, +//// Critical +//// } -#pragma warning restore CS1591 -#pragma warning restore SA1602 -#pragma warning restore SA1600 -} \ No newline at end of file +////#pragma warning restore CS1591 +////#pragma warning restore SA1602 +////#pragma warning restore SA1600 +////} diff --git a/src/CacheManager.Core/Logging/LoggerExtensions.cs b/src/CacheManager.Core/Logging/LoggerExtensions.cs index cb352d35..79ac0750 100644 --- a/src/CacheManager.Core/Logging/LoggerExtensions.cs +++ b/src/CacheManager.Core/Logging/LoggerExtensions.cs @@ -1,294 +1,294 @@ -using System; -using System.Globalization; - -namespace CacheManager.Core.Logging -{ -#pragma warning disable SA1600 -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - - public static class LoggerExtensions - { - //// Critical - - public static void LogCritical(this ILogger logger, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Critical, 0, new FormatMessage(message, args), null); - } - - public static void LogCritical(this ILogger logger, int eventId, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Critical, eventId, new FormatMessage(message, args), null); - } - - public static void LogCritical(this ILogger logger, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Critical, 0, new FormatMessage(message, args), exception); - } - - public static void LogCritical(this ILogger logger, int eventId, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Critical, eventId, new FormatMessage(message, args), exception); - } - - //// DEBUG - - public static void LogDebug(this ILogger logger, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Debug, 0, new FormatMessage(message, args), null); - } - - public static void LogDebug(this ILogger logger, int eventId, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Debug, eventId, new FormatMessage(message, args), null); - } - - public static void LogDebug(this ILogger logger, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Debug, 0, new FormatMessage(message, args), exception); - } - - public static void LogDebug(this ILogger logger, int eventId, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Debug, eventId, new FormatMessage(message, args), exception); - } - - //// Error - - public static void LogError(this ILogger logger, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Error, 0, new FormatMessage(message, args), null); - } - - public static void LogError(this ILogger logger, int eventId, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Error, eventId, new FormatMessage(message, args), null); - } - - public static void LogError(this ILogger logger, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Error, 0, new FormatMessage(message, args), exception); - } - - public static void LogError(this ILogger logger, int eventId, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Error, eventId, new FormatMessage(message, args), exception); - } - - //// Information - - public static void LogInfo(this ILogger logger, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Information, 0, new FormatMessage(message, args), null); - } - - public static void LogInfo(this ILogger logger, int eventId, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Information, eventId, new FormatMessage(message, args), null); - } - - public static void LogInfo(this ILogger logger, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Information, 0, new FormatMessage(message, args), exception); - } - - public static void LogInfo(this ILogger logger, int eventId, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Information, eventId, new FormatMessage(message, args), exception); - } - - //// Trace - - public static void LogTrace(this ILogger logger, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Trace, 0, new FormatMessage(message, args), null); - } - - public static void LogTrace(this ILogger logger, int eventId, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Trace, eventId, new FormatMessage(message, args), null); - } - - public static void LogTrace(this ILogger logger, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Trace, 0, new FormatMessage(message, args), exception); - } - - public static void LogTrace(this ILogger logger, int eventId, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Trace, eventId, new FormatMessage(message, args), exception); - } - - //// Warning - - public static void LogWarn(this ILogger logger, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Warning, 0, new FormatMessage(message, args), null); - } - - public static void LogWarn(this ILogger logger, int eventId, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Warning, eventId, new FormatMessage(message, args), null); - } - - public static void LogWarn(this ILogger logger, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Warning, 0, new FormatMessage(message, args), exception); - } - - public static void LogWarn(this ILogger logger, int eventId, Exception exception, string message, params object[] args) - { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - logger.Log(LogLevel.Warning, eventId, new FormatMessage(message, args), exception); - } - - private class FormatMessage - { - private readonly string _format; - private readonly object[] _args; - - public FormatMessage(string format, params object[] args) - { - _format = format; - _args = args; - } - - public override string ToString() - { - if (_args == null || _args.Length == 0) - { - return _format; - } - - try - { - return string.Format(CultureInfo.CurrentCulture, _format, _args); - } - catch - { - return "Failed to format string"; - } - } - } - } -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -#pragma warning restore SA1600 -} \ No newline at end of file +////using System; +////using System.Globalization; + +////namespace CacheManager.Core.Logging +////{ +////#pragma warning disable SA1600 +////#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + +//// public static class LoggerExtensions +//// { +//// //// Critical + +//// public static void LogCritical(this ILogger logger, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Critical, 0, new FormatMessage(message, args), null); +//// } + +//// public static void LogCritical(this ILogger logger, int eventId, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Critical, eventId, new FormatMessage(message, args), null); +//// } + +//// public static void LogCritical(this ILogger logger, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Critical, 0, new FormatMessage(message, args), exception); +//// } + +//// public static void LogCritical(this ILogger logger, int eventId, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Critical, eventId, new FormatMessage(message, args), exception); +//// } + +//// //// DEBUG + +//// public static void LogDebug(this ILogger logger, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Debug, 0, new FormatMessage(message, args), null); +//// } + +//// public static void LogDebug(this ILogger logger, int eventId, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Debug, eventId, new FormatMessage(message, args), null); +//// } + +//// public static void LogDebug(this ILogger logger, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Debug, 0, new FormatMessage(message, args), exception); +//// } + +//// public static void LogDebug(this ILogger logger, int eventId, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Debug, eventId, new FormatMessage(message, args), exception); +//// } + +//// //// Error + +//// public static void LogError(this ILogger logger, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Error, 0, new FormatMessage(message, args), null); +//// } + +//// public static void LogError(this ILogger logger, int eventId, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Error, eventId, new FormatMessage(message, args), null); +//// } + +//// public static void LogError(this ILogger logger, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Error, 0, new FormatMessage(message, args), exception); +//// } + +//// public static void LogError(this ILogger logger, int eventId, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Error, eventId, new FormatMessage(message, args), exception); +//// } + +//// //// Information + +//// public static void LogInfo(this ILogger logger, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Information, 0, new FormatMessage(message, args), null); +//// } + +//// public static void LogInfo(this ILogger logger, int eventId, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Information, eventId, new FormatMessage(message, args), null); +//// } + +//// public static void LogInfo(this ILogger logger, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Information, 0, new FormatMessage(message, args), exception); +//// } + +//// public static void LogInfo(this ILogger logger, int eventId, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Information, eventId, new FormatMessage(message, args), exception); +//// } + +//// //// Trace + +//// public static void LogTrace(this ILogger logger, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Trace, 0, new FormatMessage(message, args), null); +//// } + +//// public static void LogTrace(this ILogger logger, int eventId, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Trace, eventId, new FormatMessage(message, args), null); +//// } + +//// public static void LogTrace(this ILogger logger, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Trace, 0, new FormatMessage(message, args), exception); +//// } + +//// public static void LogTrace(this ILogger logger, int eventId, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Trace, eventId, new FormatMessage(message, args), exception); +//// } + +//// //// Warning + +//// public static void LogWarn(this ILogger logger, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Warning, 0, new FormatMessage(message, args), null); +//// } + +//// public static void LogWarn(this ILogger logger, int eventId, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Warning, eventId, new FormatMessage(message, args), null); +//// } + +//// public static void LogWarn(this ILogger logger, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Warning, 0, new FormatMessage(message, args), exception); +//// } + +//// public static void LogWarn(this ILogger logger, int eventId, Exception exception, string message, params object[] args) +//// { +//// if (logger == null) +//// { +//// throw new ArgumentNullException(nameof(logger)); +//// } + +//// logger.Log(LogLevel.Warning, eventId, new FormatMessage(message, args), exception); +//// } + +//// private class FormatMessage +//// { +//// private readonly string _format; +//// private readonly object[] _args; + +//// public FormatMessage(string format, params object[] args) +//// { +//// _format = format; +//// _args = args; +//// } + +//// public override string ToString() +//// { +//// if (_args == null || _args.Length == 0) +//// { +//// return _format; +//// } + +//// try +//// { +//// return string.Format(CultureInfo.CurrentCulture, _format, _args); +//// } +//// catch +//// { +//// return "Failed to format string"; +//// } +//// } +//// } +//// } +////#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member +////#pragma warning restore SA1600 +////} diff --git a/src/CacheManager.Core/Properties/AssemblyInfo.cs b/src/CacheManager.Core/Properties/AssemblyInfo.cs index 9f3d2ab6..253d258d 100644 --- a/src/CacheManager.Core/Properties/AssemblyInfo.cs +++ b/src/CacheManager.Core/Properties/AssemblyInfo.cs @@ -1,5 +1,2 @@ using System; -using System.Runtime.CompilerServices; - [assembly: CLSCompliant(true)] -[assembly: InternalsVisibleTo("CacheManager.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010051a13aa6dd4e78f62051f0d2608ba1e1e50f7038dad1e72f6a2233ec77ec58d49eec5ba13b0f7508d11fbbcd79ee39b0322b58873962771396ec08096f5d4bd2d1622ed9cad79016c154397390336a4a5a619aeec126f8d54b9ea884c510267d1d413ab5afc3c1aea86c199e57ecb23bd39458528328d2de90050e11d4649ec3")] \ No newline at end of file diff --git a/src/CacheManager.Core/Utility/Clock.cs b/src/CacheManager.Core/Utility/Clock.cs index 1124b476..337a2f16 100644 --- a/src/CacheManager.Core/Utility/Clock.cs +++ b/src/CacheManager.Core/Utility/Clock.cs @@ -1,73 +1,72 @@ -using System; -using System.Linq; -using System.Runtime.CompilerServices; +////using System; +////using System.Runtime.CompilerServices; -namespace CacheManager.Core.Utility -{ - /// - /// Time related helper. - /// - public static class Clock - { - /// - /// Number of ticks per millisecond. - /// - public const long TicksPerMillisecond = 10000; +////namespace CacheManager.Core.Utility +////{ +//// /// +//// /// Time related helper. +//// /// +//// internal static class Clock +//// { +//// /// +//// /// Number of ticks per millisecond. +//// /// +//// public const long TicksPerMillisecond = 10000; - /// - /// Ticks since 1970. - /// - public const long UnixEpochTicks = TimeSpan.TicksPerDay * DaysTo1970; +//// /// +//// /// Ticks since 1970. +//// /// +//// public const long UnixEpochTicks = TimeSpan.TicksPerDay * DaysTo1970; - /// - /// Seconds since 1970. - /// - public const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; +//// /// +//// /// Seconds since 1970. +//// /// +//// public const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; - // Number of days in a non-leap year - private const int DaysPerYear = 365; +//// // Number of days in a non-leap year +//// private const int DaysPerYear = 365; - // Number of days in 4 years - private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461 +//// // Number of days in 4 years +//// private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461 - // Number of days in 100 years - private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524 +//// // Number of days in 100 years +//// private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524 - // Number of days in 400 years - private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097 +//// // Number of days in 400 years +//// private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097 - // Number of days from 1/1/0001 to 12/31/1969 - private const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; // 719,162 +//// // Number of days from 1/1/0001 to 12/31/1969 +//// private const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; // 719,162 - /// - /// Computes a timestamp representing milliseconds since 1970. - /// - /// The milliseconds. - [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static long GetUnixTimestampMillis() - { - return (DateTime.UtcNow.Ticks - UnixEpochTicks) / TicksPerMillisecond; - } +//// /// +//// /// Computes a timestamp representing milliseconds since 1970. +//// /// +//// /// The milliseconds. +//// [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] +//// public static long GetUnixTimestampMillis() +//// { +//// return (DateTime.UtcNow.Ticks - UnixEpochTicks) / TicksPerMillisecond; +//// } - /// - /// Computes a timestamp representing ticks since 1970. - /// - /// The ticks. - [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static long GetUnixTimestampTicks() - { - return DateTime.UtcNow.Ticks - UnixEpochTicks; - } +//// /// +//// /// Computes a timestamp representing ticks since 1970. +//// /// +//// /// The ticks. +//// [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] +//// public static long GetUnixTimestampTicks() +//// { +//// return DateTime.UtcNow.Ticks - UnixEpochTicks; +//// } - /// - /// Computes the milliseconds since 1970 up to the given . - /// - /// The base. - /// The milliseconds since 1970. - [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static long ToUnixTimestampMillis(DateTime date) - { - return (date.Ticks - UnixEpochTicks) / TicksPerMillisecond; - } - } -} +//// /// +//// /// Computes the milliseconds since 1970 up to the given . +//// /// +//// /// The base. +//// /// The milliseconds since 1970. +//// [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] +//// public static long ToUnixTimestampMillis(DateTime date) +//// { +//// return (date.Ticks - UnixEpochTicks) / TicksPerMillisecond; +//// } +//// } +////} diff --git a/src/CacheManager.Core/Utility/Guard.cs b/src/CacheManager.Core/Utility/Guard.cs index b1ee20ae..8f48a087 100644 --- a/src/CacheManager.Core/Utility/Guard.cs +++ b/src/CacheManager.Core/Utility/Guard.cs @@ -8,7 +8,7 @@ namespace CacheManager.Core.Utility /// /// Utility class to do null and other checks. /// - public static class Guard + internal static class Guard { /// /// Validates that is not null and otherwise throws an exception. diff --git a/src/CacheManager.Core/Utility/ObjectPool.cs b/src/CacheManager.Core/Utility/ObjectPool.cs index f5c005be..d3ebacf7 100644 --- a/src/CacheManager.Core/Utility/ObjectPool.cs +++ b/src/CacheManager.Core/Utility/ObjectPool.cs @@ -1,96 +1,96 @@ -using System; -using System.Linq; -using System.Threading; +////using System; +////using System.Linq; +////using System.Threading; -namespace CacheManager.Core.Utility -{ - /// - /// Contract used by to define how to create and return instances to a pool. - /// - /// The type of objects of the pool. - public interface IObjectPoolPolicy - { - /// - /// Creates a new instance of . - /// - /// The new instance. - T CreateNew(); +////namespace CacheManager.Core.Utility +////{ +//// /// +//// /// Contract used by to define how to create and return instances to a pool. +//// /// +//// /// The type of objects of the pool. +//// public interface IObjectPoolPolicy +//// { +//// /// +//// /// Creates a new instance of . +//// /// +//// /// The new instance. +//// T CreateNew(); - /// - /// Checks if the instance can be returned and may reset the instance to a state which can be reused. - /// - /// The instance which should be returned. - /// True if the instance can be returned, False otherwise. - bool Return(T value); - } +//// /// +//// /// Checks if the instance can be returned and may reset the instance to a state which can be reused. +//// /// +//// /// The instance which should be returned. +//// /// True if the instance can be returned, False otherwise. +//// bool Return(T value); +//// } - /// - /// Simple policy based pool for objects. - /// - /// The object type to pool. - public class ObjectPool where T : class - { - private readonly T[] _items; - private readonly IObjectPoolPolicy _policy; +//// /// +//// /// Simple policy based pool for objects. +//// /// +//// /// The object type to pool. +//// public class ObjectPool where T : class +//// { +//// private readonly T[] _items; +//// private readonly IObjectPoolPolicy _policy; - /// - /// Initializes a new instance of the class. - /// - /// The object pool policy. - /// Number of items to keep, defaults to number of processors * 2. - public ObjectPool(IObjectPoolPolicy policy, int? maxItems = null) - { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } +//// /// +//// /// Initializes a new instance of the class. +//// /// +//// /// The object pool policy. +//// /// Number of items to keep, defaults to number of processors * 2. +//// public ObjectPool(IObjectPoolPolicy policy, int? maxItems = null) +//// { +//// if (policy == null) +//// { +//// throw new ArgumentNullException(nameof(policy)); +//// } - if (maxItems == null || maxItems <= 0) - { - maxItems = Environment.ProcessorCount * 2; - } +//// if (maxItems == null || maxItems <= 0) +//// { +//// maxItems = Environment.ProcessorCount * 2; +//// } - _policy = policy; - _items = new T[maxItems.Value]; - } +//// _policy = policy; +//// _items = new T[maxItems.Value]; +//// } - /// - /// Returns either a pooled or new instance of . - /// - /// The pooled or new instance. - public T Lease() - { - for (var i = 0; i < _items.Length; i++) - { - var item = _items[i]; - if (item != null && Interlocked.CompareExchange(ref _items[i], null, item) == item) - { - return item; - } - } +//// /// +//// /// Returns either a pooled or new instance of . +//// /// +//// /// The pooled or new instance. +//// public T Lease() +//// { +//// for (var i = 0; i < _items.Length; i++) +//// { +//// var item = _items[i]; +//// if (item != null && Interlocked.CompareExchange(ref _items[i], null, item) == item) +//// { +//// return item; +//// } +//// } - return _policy.CreateNew(); - } +//// return _policy.CreateNew(); +//// } - /// - /// Returns the instance to the pool (if possible). - /// - /// The instance to return to the pool. - public void Return(T value) - { - if (!_policy.Return(value)) - { - return; - } +//// /// +//// /// Returns the instance to the pool (if possible). +//// /// +//// /// The instance to return to the pool. +//// public void Return(T value) +//// { +//// if (!_policy.Return(value)) +//// { +//// return; +//// } - for (var i = 0; i < _items.Length; i++) - { - if (_items[i] == null) - { - _items[i] = value; - return; - } - } - } - } -} \ No newline at end of file +//// for (var i = 0; i < _items.Length; i++) +//// { +//// if (_items[i] == null) +//// { +//// _items[i] = value; +//// return; +//// } +//// } +//// } +//// } +////} diff --git a/src/CacheManager.Couchbase/BucketCacheHandle.cs b/src/CacheManager.Couchbase/BucketCacheHandle.cs deleted file mode 100644 index db10593a..00000000 --- a/src/CacheManager.Couchbase/BucketCacheHandle.cs +++ /dev/null @@ -1,301 +0,0 @@ -using System; -using System.Security.Cryptography; -using System.Text; -using CacheManager.Core; -using CacheManager.Core.Internal; -using CacheManager.Core.Logging; -using Newtonsoft.Json.Linq; -using static CacheManager.Core.Utility.Guard; - -namespace CacheManager.Couchbase -{ - /// - /// Definition for what bucket should be used and optionally a bucket password. - /// - /// - public class BucketCacheHandleAdditionalConfiguration - { - /// - /// Gets or sets the name of the bucket. - /// - /// - /// The name of the bucket. - /// - public string BucketName { get; set; } = CouchbaseConfigurationManager.DefaultBucketName; - - /// - /// Gets or sets the bucket password. - /// - /// - /// The bucket password. - /// - public string BucketPassword { get; set; } - } - - /// - /// Cache handle implementation based on the couchbase .net client. - /// - /// The type of the cache value. - public class BucketCacheHandle : BaseCacheHandle - { - private readonly CouchbaseConfigurationManager _bucketManager; - - /// - /// Initializes a new instance of the class. - /// - /// The manager configuration. - /// The cache handle configuration. - /// The logger factory. - /// If configuration.HandleName is not valid. - public BucketCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory) - : this(managerConfiguration, configuration, loggerFactory, new BucketCacheHandleAdditionalConfiguration()) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The manager configuration. - /// The cache handle configuration. - /// The logger factory. - /// The additional settings. - /// If configuration.HandleName is not valid. - public BucketCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory, BucketCacheHandleAdditionalConfiguration additionalSettings) - : base(managerConfiguration, configuration) - { - NotNull(configuration, nameof(configuration)); - NotNull(loggerFactory, nameof(loggerFactory)); - - Logger = loggerFactory.CreateLogger(this); - - if (additionalSettings == null) - { - additionalSettings = new BucketCacheHandleAdditionalConfiguration(); - } - - // we can configure the bucket name by having ":" as handle's - // this should only be used in 100% by app/web.config based configuration - var nameParts = configuration.Key.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries); - - var configurationName = nameParts.Length > 0 ? nameParts[0] : Guid.NewGuid().ToString(); - - if (nameParts.Length == 2) - { - additionalSettings.BucketName = nameParts[1]; - } - - _bucketManager = new CouchbaseConfigurationManager(configurationName, additionalSettings.BucketName, additionalSettings.BucketPassword); - } - - /// - public override bool IsDistributedCache => true; - - /// - /// Gets the number of items the cache handle currently maintains. - /// - /// The count. - public override int Count => (int)Stats.GetStatistic(CacheStatsCounterType.Items); - - /// - protected override ILogger Logger { get; } - - /// - /// Clears this cache, removing all items in the base cache and all regions. - /// - public override void Clear() - { - // warning: takes ~20seconds to flush the bucket... - var manager = _bucketManager.GetManager(); - if (manager != null) - { - using (manager) - { - manager.Flush(); - } - } - } - - /// - /// Clears the cache region, removing all items from the specified only. - /// - /// The cache region. - /// Not supported in this version. - public override void ClearRegion(string region) - { - // TODO: not supported? - throw new NotImplementedException(); - } - - /// - public override bool Exists(string key) - { - var fullKey = GetKey(key); - return _bucketManager.Bucket.Exists(fullKey); - } - - /// - public override bool Exists(string key, string region) - { - NotNullOrWhiteSpace(region, nameof(region)); - - var fullKey = GetKey(key, region); - return _bucketManager.Bucket.Exists(fullKey); - } - - /// - /// Adds a value to the cache. - /// - /// The CacheItem to be added to the cache. - /// - /// true if the key was not already added to the cache, false otherwise. - /// - protected override bool AddInternalPrepared(CacheItem item) - { - NotNull(item, nameof(item)); - - var fullKey = GetKey(item.Key, item.Region); - if (item.ExpirationMode != ExpirationMode.None) - { - return _bucketManager.Bucket.Insert(fullKey, item, item.ExpirationTimeout).Success; - } - - return _bucketManager.Bucket.Insert(fullKey, item).Success; - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting - /// unmanaged resources. - /// - /// Indicator if managed resources should be released. - protected override void Dispose(bool disposeManaged) - { - if (disposeManaged) - { - } - - base.Dispose(disposeManaged); - } - - /// - /// Gets a CacheItem for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The CacheItem. - protected override CacheItem GetCacheItemInternal(string key) => - GetCacheItemInternal(key, null); - - /// - /// Gets a CacheItem for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The cache region. - /// The CacheItem. - protected override CacheItem GetCacheItemInternal(string key, string region) - { - var fullkey = GetKey(key, region); - var result = _bucketManager.Bucket.Get>(fullkey); - - if (!result.Success) - { - return null; - } - - var cacheItem = result.Value; - if (cacheItem.Value is JToken) - { - var value = cacheItem.Value as JToken; - cacheItem = cacheItem.WithValue((TCacheValue)value.ToObject(cacheItem.ValueType)); - } - - if (cacheItem.IsExpired) - { - return null; - } - - // extend sliding expiration - if (cacheItem.ExpirationMode == ExpirationMode.Sliding) - { - cacheItem.LastAccessedUtc = DateTime.UtcNow; - PutInternalPrepared(cacheItem); - } - - return cacheItem; - } - - /// - /// Puts the into the cache. If the item exists it will get updated - /// with the new value. If the item doesn't exist, the item will be added to the cache. - /// - /// The CacheItem to be added to the cache. - protected override void PutInternalPrepared(CacheItem item) - { - NotNull(item, nameof(item)); - - var fullKey = GetKey(item.Key, item.Region); - if (item.ExpirationMode == ExpirationMode.Absolute || item.ExpirationMode == ExpirationMode.Sliding) - { - _bucketManager.Bucket.Upsert(fullKey, item, item.ExpirationTimeout); - } - else - { - _bucketManager.Bucket.Upsert(fullKey, item); - } - } - - /// - /// Removes a value from the cache for the specified key. - /// - /// The key being used to identify the item within the cache. - /// - /// true if the key was found and removed from the cache, false otherwise. - /// - protected override bool RemoveInternal(string key) => RemoveInternal(key, null); - - /// - /// Removes a value from the cache for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The cache region. - /// - /// true if the key was found and removed from the cache, false otherwise. - /// - protected override bool RemoveInternal(string key, string region) - { - var fullKey = GetKey(key, region); - var result = _bucketManager.Bucket.Remove(fullKey); - return result.Success; - } - - private static string GetSHA256Key(string key) - { - using (var sha = SHA256.Create()) - { - var hashBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(key)); - return Convert.ToBase64String(hashBytes); - } - } - - private static string GetKey(string key, string region = null) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key)); - } - - var fullKey = key; - - if (!string.IsNullOrWhiteSpace(region)) - { - fullKey = string.Concat(region, ":", key); - } - - // Memcached still has a 250 character limit - if (fullKey.Length >= 250) - { - return GetSHA256Key(fullKey); - } - - return fullKey; - } - } -} \ No newline at end of file diff --git a/src/CacheManager.Couchbase/CacheManager.Couchbase.csproj b/src/CacheManager.Couchbase/CacheManager.Couchbase.csproj deleted file mode 100644 index 03a90e2b..00000000 --- a/src/CacheManager.Couchbase/CacheManager.Couchbase.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - CacheManager extension package to work with Couchbase as a distributed cache. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - net452;netstandard2.0 - true - true - Caching;Cache;CacheManager;Distributed Cache;Couchebase - - - - - - - - - - - \ No newline at end of file diff --git a/src/CacheManager.Couchbase/CouchbaseConfigurationBuilderExtensions.cs b/src/CacheManager.Couchbase/CouchbaseConfigurationBuilderExtensions.cs deleted file mode 100644 index 9a642023..00000000 --- a/src/CacheManager.Couchbase/CouchbaseConfigurationBuilderExtensions.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; -using CacheManager.Couchbase; -using Couchbase; -using Couchbase.Configuration.Client; -using Couchbase.Core; -using static CacheManager.Core.Utility.Guard; - -namespace CacheManager.Core -{ - /// - /// Extensions for the configuration builder specific to the Couchbase cache handle. - /// - public static class CouchbaseConfigurationBuilderExtensions - { - /// - /// Adds a for the given key. - /// The key will be matched with the Couchbase cache handle name. - /// - /// The part. - /// The key which has to match with the cache handle name. - /// The Couchbase configuration object. - /// - /// The configuration builder. - /// - /// If or is null. - public static ConfigurationBuilderCachePart WithCouchbaseConfiguration(this ConfigurationBuilderCachePart part, string configurationKey, ClientConfiguration config) - { - NotNullOrWhiteSpace(configurationKey, nameof(configurationKey)); - NotNull(config, nameof(config)); - - CouchbaseConfigurationManager.AddConfiguration(configurationKey, config); - return part; - } - - /// - /// Adds a for the given key. - /// The key will be matched with the Couchbase cache handle name. - /// - /// The part. - /// The key which has to match with the cache handle name. - /// The Couchbase configuration object. - /// - /// The configuration builder. - /// - /// If or is null. - public static ConfigurationBuilderCachePart WithCouchbaseConfiguration(this ConfigurationBuilderCachePart part, string configurationKey, ICouchbaseClientDefinition definition) - { - return WithCouchbaseConfiguration(part, configurationKey, new ClientConfiguration(definition)); - } - - /// - /// Adds an already configured for the given key. Use this in case you want to use the outside of CacheManager, too - /// and you want to share this instance. - /// - /// Use in (or similar overloads) - /// to have the cache handle use this configuration. - /// - /// If your cluster requires authentication, you might have to configure cluster.Authenticate(...). - /// - /// - /// The part. - /// The configuration key. - /// The . - /// - /// The configuration builder. - /// If or is null. - /// - public static ConfigurationBuilderCachePart WithCouchbaseCluster(this ConfigurationBuilderCachePart part, string configurationKey, ICluster cluster) - { - NotNullOrWhiteSpace(configurationKey, nameof(configurationKey)); - NotNull(cluster, nameof(cluster)); - - CouchbaseConfigurationManager.AddCluster(configurationKey, cluster); - return part; - } - - /// - /// Adds a using the configuration referenced via . - /// - /// The cache handle needs configuration specific to Couchbase, see remarks for details. - /// - /// - /// The builder part. - /// The configuration identifier. - /// The name of the Couchbase bucket which should be used by the cache handle. - /// Set this to true if this cache handle should be the source of the backplane. This setting will be ignored if no backplane is configured. - /// - /// The part. - /// - /// Thrown if or is null. - /// - /// The Couchbase cache handle requires configuration which can be defined via: - /// - /// - /// A configuration with a matching being added via . - /// - /// - /// A cluster with a matching being added via . - /// - /// - /// A CouchbaseClientSection configured in App/Web.config (only available on full .NET Framework). - /// - /// - /// Or, the cluster has been configured via and CacheManager will use the cluster returned by . - /// Anyways, this will be the last fallback which, if nothing has been configured at all, will fall back to the default server endpoint on 127.0.0.1:8091. - /// - /// - /// - /// If your cluster requires authentication, use either the or add a with valid authentication via cluster.Authenticate(...). - /// - /// - public static ConfigurationBuilderCacheHandlePart WithCouchbaseCacheHandle( - this ConfigurationBuilderCachePart part, - string couchbaseConfigurationKey, - string bucketName = CouchbaseConfigurationManager.DefaultBucketName, - bool isBackplaneSource = true) - { - NotNull(part, nameof(part)); - NotNullOrWhiteSpace(bucketName, nameof(bucketName)); - - return part.WithHandle(typeof(BucketCacheHandle<>), couchbaseConfigurationKey, isBackplaneSource, new BucketCacheHandleAdditionalConfiguration() - { - BucketName = bucketName - }); - } - - /// - /// Adds a using the configuration referenced via . - /// - /// The cache handle needs configuration specific to Couchbase, see remarks for details. - /// - /// - /// The builder part. - /// The configuration identifier. - /// The name of the Couchbase bucket which should be used by the cache handle. - /// The bucket password. - /// Set this to true if this cache handle should be the source of the backplane. This setting will be ignored if no backplane is configured. - /// - /// The part. - /// - /// Thrown if or is null. - /// - /// The Couchbase cache handle requires configuration which can be defined via: - /// - /// - /// A configuration with a matching being added via . - /// - /// - /// A cluster with a matching being added via . - /// - /// - /// A CouchbaseClientSection configured in App/Web.config (only available on full .NET Framework). - /// - /// - /// Or, the cluster has been configured via and CacheManager will use the cluster returned by . - /// Anyways, this will be the last fallback which, if nothing has been configured at all, will fall back to the default server endpoint on 127.0.0.1:8091. - /// - /// - /// - /// If your cluster requires authentication, use either the or add a with valid authentication via cluster.Authenticate(...). - /// - /// - public static ConfigurationBuilderCacheHandlePart WithCouchbaseCacheHandle( - this ConfigurationBuilderCachePart part, - string couchbaseConfigurationKey, - string bucketName, - string bucketPassword, - bool isBackplaneSource = true) - { - NotNull(part, nameof(part)); - NotNullOrWhiteSpace(bucketName, nameof(bucketName)); - - return part.WithHandle(typeof(BucketCacheHandle<>), couchbaseConfigurationKey, isBackplaneSource, new BucketCacheHandleAdditionalConfiguration() - { - BucketName = bucketName, - BucketPassword = bucketPassword - }); - } - } -} \ No newline at end of file diff --git a/src/CacheManager.Couchbase/CouchbaseConfigurationManager.cs b/src/CacheManager.Couchbase/CouchbaseConfigurationManager.cs deleted file mode 100644 index 71e227ee..00000000 --- a/src/CacheManager.Couchbase/CouchbaseConfigurationManager.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System; -using System.Linq; -using Couchbase; -using Couchbase.Configuration.Client; -using Couchbase.Core; -using static CacheManager.Core.Utility.Guard; -using Couchbase.Management; -using System.Collections.Concurrent; -using CacheManager.Core; - -#if NET45 -using System.Configuration; -using Couchbase.Configuration.Client.Providers; -#endif - -namespace CacheManager.Couchbase -{ - /// - /// Manages configurations for the couchbase cache handle. - /// - /// As of version 1.0.2, changed the management of s as those instances are already - /// managed by the of the couchbase client libraray. No need to have additional collections of stuff in here. - /// - /// - /// We keep track of added configurations via - /// and eventually added predefined . - /// Referencing still works via configuration key, although, if nothing in particular is defined, the fallback should always at least go to the couchbase default cluster settings. - /// - /// - /// Also new, fallback to which can be used to initialize settings of a cluster statically. - /// - /// - public class CouchbaseConfigurationManager - { - /// - /// The default bucket name - /// - public const string DefaultBucketName = "default"; - -#if NET45 - - /// - /// The section name usually used for couchbase in app/web.config. - /// - public const string DefaultCouchbaseConfigurationSection = "couchbaseClients/couchbase"; - -#endif - - private static object _configLock = new object(); - private static ConcurrentDictionary _configurations = new ConcurrentDictionary(); - private static ConcurrentDictionary _clusters = new ConcurrentDictionary(); - private readonly string _configurationName; - private readonly string _bucketName; - private readonly string _bucketPassword; - - /// - /// Initializes a new instance of the class. - /// - /// The configuration name. - /// The bucket name. - /// The bucket password. - public CouchbaseConfigurationManager(string configurationKey, string bucketName = DefaultBucketName, string bucketPassword = null) - { - NotNullOrWhiteSpace(configurationKey, nameof(configurationKey)); - NotNullOrWhiteSpace(bucketName, nameof(bucketName)); - _configurationName = configurationKey; - _bucketName = bucketName; - _bucketPassword = bucketPassword; - } - - /// - /// Gets a bucket for configuration name and bucket name. - /// - /// - /// The bucket. - /// - public IBucket Bucket => GetBucket(_configurationName, _bucketName, _bucketPassword); - - /// - /// Gets a instance. - /// If username and password have been defined in the bucket's configuration, those will be used to create the manager. - /// - /// The manager instance or null. - public IBucketManager GetManager() - { - var bucket = Bucket; - return string.IsNullOrWhiteSpace(bucket.Configuration.Username) ? - bucket.CreateManager() : - bucket.CreateManager(bucket.Configuration.Username, bucket.Configuration.Password); - } - - /// - /// Adds a already configured to the named collection of buckets. - /// This can be referenced by the via configuration key and . - /// - /// The configuration key. - /// The bucket. - public static void AddCluster(string configurationKey, ICluster cluster) - { - NotNullOrWhiteSpace(configurationKey, nameof(configurationKey)); - NotNull(cluster, nameof(cluster)); - - // not sure if we even need this, but eventually we have to create a new instance of that bucket - _configurations.TryAdd(configurationKey, cluster.Configuration); - _clusters.TryAdd(configurationKey, cluster); - } - - /// - /// Adds a for a . - /// - /// The name. - /// The configuration. - /// If name or configuration are null. - public static void AddConfiguration(string configurationKey, ClientConfiguration configuration) - { - NotNullOrWhiteSpace(configurationKey, nameof(configurationKey)); - NotNull(configuration, nameof(configuration)); - _configurations.TryAdd(configurationKey, configuration); - } - - /// - /// Gets a for the given . - /// - /// If the configuration is not already present and the target framework supports ConfigurationManager, the method tries to resolve the configuration from the - /// section with the given name. - /// - /// - /// The name. - /// The configuration. - /// If name is null. - /// - /// If no configuration or section can be found for configuration. - /// - public static ClientConfiguration GetConfiguration(string configurationKeyOrSectionName) - { - NotNullOrWhiteSpace(configurationKeyOrSectionName, nameof(configurationKeyOrSectionName)); - - if (_configurations.TryGetValue(configurationKeyOrSectionName, out ClientConfiguration configuration)) - { - return configuration; - } - -#if NET45 - var section = ConfigurationManager.GetSection(configurationKeyOrSectionName) as CouchbaseClientSection; - - if (section == null) - { - return null; - } - - var config = new ClientConfiguration(section); - AddConfiguration(configurationKeyOrSectionName, config); - return config; -#else - - return null; -#endif - } - - private static ICluster GetCluster(string configurationKey) - { - NotNullOrWhiteSpace(configurationKey, nameof(configurationKey)); - - if (!_clusters.TryGetValue(configurationKey, out ICluster cluster)) - { - var config = GetConfiguration(configurationKey); - if (config != null) - { - cluster = new Cluster(config); - } - else - { - // fallback to ClusterHelper as that's also a way ppl can configure this stuff... - try - { - cluster = ClusterHelper.Get(); - } - catch (InitializationException) - { - // last fallback has also not been initialized yet - // this will use the development settings on localhost without any auth (might not work and blow up later). - cluster = new Cluster(); - } - - // update our configuration cache just in case - AddConfiguration(configurationKey, cluster.Configuration); - } - - _clusters.TryAdd(configurationKey, cluster); - } - - return cluster; - } - - private static IBucket GetBucket(string configurationKey, string bucketName, string bucketPassword) - { - NotNullOrWhiteSpace(bucketName, nameof(bucketName)); - var cluster = GetCluster(configurationKey); - if (cluster == null) - { - // should probably never occur. - throw new InvalidOperationException("Cluster is not configured although we should fall back to ClusterHelper at least."); - } - - return string.IsNullOrEmpty(bucketPassword) ? cluster.OpenBucket(bucketName) : cluster.OpenBucket(bucketName, bucketPassword); - } - } -} \ No newline at end of file diff --git a/src/CacheManager.Memcached/CacheManager.Memcached.csproj b/src/CacheManager.Memcached/CacheManager.Memcached.csproj deleted file mode 100644 index 1d09888f..00000000 --- a/src/CacheManager.Memcached/CacheManager.Memcached.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - CacheManager extension package to work with Memcached as a distributed cache. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. This package contains the specific Memcached handles. - net45; - true - true - Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached - - - - - - - - - - - - \ No newline at end of file diff --git a/src/CacheManager.Memcached/MemcachedCacheHandle.cs b/src/CacheManager.Memcached/MemcachedCacheHandle.cs deleted file mode 100644 index 0c3c5b10..00000000 --- a/src/CacheManager.Memcached/MemcachedCacheHandle.cs +++ /dev/null @@ -1,770 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using CacheManager.Core; -using CacheManager.Core.Internal; -using CacheManager.Core.Logging; -using CacheManager.Core.Utility; -using Enyim.Caching; -using Enyim.Caching.Configuration; -using Enyim.Caching.Memcached; -using Enyim.Caching.Memcached.Results; -using static CacheManager.Core.Utility.Guard; - -namespace CacheManager.Memcached -{ - /// - /// Cache handle implementation based on the Enyim memcached client. - /// - /// The type of the cache value. - [RequiresSerializer] - public class MemcachedCacheHandle : BaseCacheHandle - { - private static readonly string _defaultEnyimSectionName = "enyim.com/memcached"; - private static readonly string _defaultSectionName = "default"; - private static readonly TimeSpan _maximumTimeout = TimeSpan.FromDays(30); - private readonly ICacheManagerConfiguration _managerConfiguration; - - /// - /// Initializes a new instance of the class. - /// - /// The manager configuration. - /// The cache handle configuration. - /// The logger factory. - /// The serializer. - /// - /// If or is null. - /// - /// - /// The cache value type is not serializable or if the enyim configuration section could not - /// be initialized. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Cache gets disposed correctly when the owner gets disposed.")] - public MemcachedCacheHandle( - ICacheManagerConfiguration managerConfiguration, - CacheHandleConfiguration configuration, - ILoggerFactory loggerFactory, - ICacheSerializer serializer) - : this(configuration, managerConfiguration, loggerFactory) - { - try - { - NotNull(configuration, nameof(configuration)); - var sectionName = GetEnyimSectionName(configuration.Key); - var section = GetSection(sectionName); - - Cache = new MemcachedClient(section); - } - catch (ConfigurationErrorsException ex) - { - throw new InvalidOperationException("Failed to initialize " + GetType().Name + ". " + ex.BareMessage, ex); - } - } - - /// - /// Initializes a new instance of the class. - /// - /// The manager configuration. - /// The cache handle configuration. - /// The logger factory. - /// The serializer. - /// The to use. - public MemcachedCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory, ICacheSerializer serializer, MemcachedClient client) - : this(configuration, managerConfiguration, loggerFactory) - { - // serializer gets ignored, just added to the ctor to satisfy the ctor finder in our custom DI to actually hit this ctor if the client is specified. - NotNull(client, nameof(client)); - Cache = client; - } - - /// - /// Initializes a new instance of the class. - /// - /// The manager configuration. - /// The cache handle configuration. - /// The logger factory. - /// The serializer. - /// The to use to create the . - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Cache gets disposed correctly when the owner gets disposed.")] - public MemcachedCacheHandle( - ICacheManagerConfiguration managerConfiguration, - CacheHandleConfiguration configuration, - ILoggerFactory loggerFactory, - ICacheSerializer serializer, - MemcachedClientConfiguration clientConfiguration) - : this(configuration, managerConfiguration, loggerFactory) - { - NotNull(clientConfiguration, nameof(clientConfiguration)); - if (clientConfiguration.Transcoder.GetType() == typeof(DefaultTranscoder)) - { - clientConfiguration.Transcoder = new CacheManagerTanscoder(serializer); - - // default is 10, that might be too long as it can take up to 10sec to recover during retries - clientConfiguration.SocketPool.DeadTimeout = TimeSpan.FromSeconds(2); - } - - Cache = new MemcachedClient(clientConfiguration); - } - - private MemcachedCacheHandle( - CacheHandleConfiguration configuration, - ICacheManagerConfiguration managerConfiguration, - ILoggerFactory loggerFactory) - : base(managerConfiguration, configuration) - { - NotNull(configuration, nameof(configuration)); - NotNull(loggerFactory, nameof(loggerFactory)); - NotNull(managerConfiguration, nameof(managerConfiguration)); - - _managerConfiguration = managerConfiguration; - Logger = loggerFactory.CreateLogger(this); - } - - /// - public override bool IsDistributedCache - { - get - { - return true; - } - } - - /// - /// Gets the number of items the cache handle currently maintains. - /// - /// The count. - public override int Count => int.Parse(Cache.Stats().GetRaw("curr_items").First().Value); - - /// - /// Gets the get memcached client configuration. - /// - /// The get memcached client configuration. - public IMemcachedClientConfiguration GetMemcachedClientConfiguration => GetSection(); - - /// - /// Gets the total number of items per server. - /// - /// The total number of items per server. - public IEnumerable ServerItemCount - { - get - { - foreach (var count in Cache.Stats().GetRaw("total_items")) - { - yield return long.Parse(count.Value, CultureInfo.InvariantCulture); - } - } - } - - /// - /// Gets the servers. - /// - /// The servers. - public IList Servers => GetServers(); - - /// - /// Gets the cache. - /// - /// The cache. - public MemcachedClient Cache { get; } - - /// - protected override ILogger Logger { get; } - - /// - /// Clears this cache, removing all items in the base cache and all regions. - /// - public override void Clear() => Cache.FlushAll(); - - /// - /// Clears the cache region, removing all items from the specified only. - /// - /// Not supported for memcached. - /// The cache region. - public override void ClearRegion(string region) - { - var regionPrefix = StoreNewRegionPrefix(region); - - if (Logger.IsEnabled(LogLevel.Debug)) - { - Logger.LogDebug("Cleared region {0}, new region key is {1}.", region, regionPrefix); - } - } - - /// - public override bool Exists(string key) - { - var result = Cache.ExecuteAppend(GetKey(key, null, false), default(ArraySegment)); - return result.StatusCode.HasValue && result.StatusCode.Value != (int)StatusCode.KeyNotFound; - } - - /// - public override bool Exists(string key, string region) - { - NotNullOrWhiteSpace(region, nameof(region)); - - var result = Cache.ExecuteAppend(GetKey(key, region, false), default(ArraySegment)); - return result.StatusCode.HasValue && result.StatusCode.Value != (int)StatusCode.KeyNotFound; - } - - /// - public override UpdateItemResult Update(string key, Func updateValue, int maxRetries) => - Update(key, null, updateValue, maxRetries); - - /// - public override UpdateItemResult Update(string key, string region, Func updateValue, int maxRetries) => - Set(key, region, updateValue, maxRetries); - - /// - /// Adds a value to the cache. - /// - /// The CacheItem to be added to the cache. - /// - /// true if the key was not already added to the cache, false otherwise. - /// - protected override bool AddInternalPrepared(CacheItem item) - { - IOperationResult result; - var shouldRetry = false; - var tries = 0; - do - { - tries++; - result = Store(StoreMode.Add, item, out shouldRetry); - if (!shouldRetry) - { - return result.Success; - } - - WaitRetry(tries); - } - while (shouldRetry && tries < _managerConfiguration.MaxRetries); - - throw new InvalidOperationException($"Add failed after {tries} tries for [{item.ToString()}]. {result.InnerResult?.Message ?? result.Message}"); - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting - /// unmanaged resources. - /// - /// Indicator if managed resources should be released. - protected override void Dispose(bool disposeManaged) - { - if (disposeManaged) - { - Cache.Dispose(); - } - - base.Dispose(disposeManaged); - } - - /// - /// Gets a CacheItem for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The CacheItem. - protected override CacheItem GetCacheItemInternal(string key) => - GetCacheItemInternal(key, null); - - /// - /// Gets a CacheItem for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The cache region. - /// The CacheItem. - protected override CacheItem GetCacheItemInternal(string key, string region) - { - var item = Cache.Get(GetKey(key, region)) as CacheItem; - if (item != null) - { - if (item.IsExpired) - { - return null; - } - else if (item.ExpirationMode == ExpirationMode.Sliding) - { - // the only way I see to update sliding expiration for keys - // is to store them again with updated TTL... What a b...t - item.LastAccessedUtc = DateTime.UtcNow; - bool shouldRetry; - Store(StoreMode.Set, item, out shouldRetry); - } - } - - return item; - } - - /// - /// Puts the into the cache. If the item exists it will get updated - /// with the new value. If the item doesn't exist, the item will be added to the cache. - /// - /// The CacheItem to be added to the cache. - protected override void PutInternalPrepared(CacheItem item) - { - IOperationResult result; - var shouldRetry = false; - var tries = 0; - do - { - tries++; - result = Store(StoreMode.Set, item, out shouldRetry); - if (!shouldRetry) - { - return; - } - - WaitRetry(tries); - } - while (shouldRetry && tries < _managerConfiguration.MaxRetries); - - throw new InvalidOperationException($"Put failed after {tries} tries for [{item.ToString()}]. {result.InnerResult?.Message ?? result.Message}"); - } - - private void WaitRetry(int currentTry) - { - var delay = _managerConfiguration.RetryTimeout == 0 ? 10 : _managerConfiguration.RetryTimeout; - - var adjusted = delay * currentTry; - if (adjusted > 10000) - { - adjusted = 10000; - } -// Disabling any async in sync -////#if !NET40 -//// Task.Delay(adjusted).ConfigureAwait(false).GetAwaiter().GetResult(); -////#else -//// Thread.Sleep(adjusted); -////#endif - } - - /// - /// Removes a value from the cache for the specified key. - /// - /// The key being used to identify the item within the cache. - /// - /// true if the key was found and removed from the cache, false otherwise. - /// - protected override bool RemoveInternal(string key) => RemoveInternal(key, null); - - /// - /// Removes a value from the cache for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The cache region. - /// - /// true if the key was found and removed from the cache, false otherwise. - /// - protected override bool RemoveInternal(string key, string region) - { - var result = Cache.ExecuteRemove(GetKey(key, region, false)); - var statusCode = result.StatusCode ?? result.InnerResult?.StatusCode ?? -1; - if (result.Success && statusCode != (int)StatusCode.KeyNotFound) - { - LogOperationResult(LogLevel.Debug, result, "Removed {0} {1}", region, key); - } - else - { - if (statusCode == (int)StatusCode.KeyNotFound) - { - LogOperationResult(LogLevel.Information, result, "Remove Failed, key not found: {0} {1}", region, key); - } - else - { - LogOperationResult(LogLevel.Error, result, "Remove Failed for {0} {1}", region, key); - //// throw new InvalidOperationException($"Remove failed for {region} {key}; statusCode:{statusCode}, message:{result.InnerResult?.Message ?? result.Message}"); - } - } - - return result.Success; - } - - /// - /// Stores the item with the specified mode. - /// - /// - /// Memcached only supports expiration of seconds, meaning anything less than one second will mean zero, which means it expires right after adding it. - /// - /// The mode. - /// The item. - /// Flag indicating if the operation should be retried. Returnd succssess code will be false anyways. - /// The result. - protected virtual IStoreOperationResult Store(StoreMode mode, CacheItem item, out bool shouldRetry) - { - NotNull(item, nameof(item)); - shouldRetry = false; - - var key = GetKey(item.Key, item.Region); - IStoreOperationResult result; - - if (item.ExpirationMode == ExpirationMode.Absolute || item.ExpirationMode == ExpirationMode.Sliding) - { - if (item.ExpirationTimeout > _maximumTimeout) - { - throw new InvalidOperationException($"Timeout must not exceed {_maximumTimeout.TotalDays} days."); - } - - result = Cache.ExecuteStore(mode, key, item, item.ExpirationTimeout); - } - else - { - result = Cache.ExecuteStore(mode, key, item); - } - - if (mode == StoreMode.Add && result.StatusCode == (int?)StatusCode.KeyExists) - { - LogOperationResult(LogLevel.Information, result, "Failed to add item [{0}] because it exists.", item); - } - else if (result.Success) - { - LogOperationResult(LogLevel.Debug, result, "Stored [{0}]", item); - } - else - { - shouldRetry = true; - LogOperationResult(LogLevel.Error, result, "Store failed for [{0}]", item); - } - - return result; - } - - private void LogOperationResult(LogLevel level, IOperationResult result, string message, params object[] args) - { - if (Logger.IsEnabled(level)) - { - var msg = $"{string.Format(message, args)}; Result Success:'{result.Success}' Code:'{result.InnerResult?.StatusCode ?? result.StatusCode}' Message:'{result.InnerResult?.Message ?? result.Message}'."; - Logger.Log(level, 0, msg, result.Exception); - } - } - - private string StoreNewRegionPrefix(string region) - { - var regionKey = ComputeRegionLookupKey(region); - var oldRegionPredix = GetRegionPrefix(region); - var tries = 0; - var created = false; - while (!created && tries <= _managerConfiguration.MaxRetries) - { - var timestamp = Clock.GetUnixTimestampMillis(); - if (timestamp.ToString() == oldRegionPredix) - { - // we are too fast in creating new keys it seems, try again... - continue; - } - - tries++; - - if (Logger.IsEnabled(LogLevel.Debug)) - { - Logger.LogDebug("Trying to store new region prefix '{0}', for region key '{1}'.", timestamp, regionKey); - } - - created = Cache.Store(StoreMode.Set, regionKey, timestamp); - - if (created) - { - if (Logger.IsEnabled(LogLevel.Debug)) - { - Logger.LogDebug("Successfully stored new region prefix '{0}', for region key '{1}'.", timestamp, regionKey); - } - - return timestamp.ToString(); - } - } - - Logger.LogError("Failed to store prefix for region key '{0}'", regionKey); - - throw new InvalidOperationException($"Could not store new cache region prefix."); - } - - private string GetRegionPrefix(string region) - { - var regionKey = ComputeRegionLookupKey(region); - - object val; - if (Cache.ExecuteTryGet(regionKey, out val).Success) - { - return val?.ToString(); - } - - return null; - } - - private static string ComputeRegionLookupKey(string region) - { - return GetPerhapsHashedKey("__" + region + "_rk__"); - } - - /// - /// Gets the name of the enyim section. - /// - /// Name of the handle. - /// The section name. - private static string GetEnyimSectionName(string handleName) - { - if (handleName.Equals(_defaultSectionName, StringComparison.OrdinalIgnoreCase)) - { - return _defaultEnyimSectionName; - } - else - { - return handleName; - } - } - - private string GetKey(string key, string region = null, bool eventuallyCreateNewRegion = true) - { - if (string.IsNullOrWhiteSpace(key)) - { - throw new ArgumentNullException(nameof(key)); - } - - var fullKey = key; - - if (!string.IsNullOrWhiteSpace(region)) - { - var regionKey = GetRegionPrefix(region); - if (regionKey == null) - { - if (eventuallyCreateNewRegion) - { - if (Logger.IsEnabled(LogLevel.Debug)) - { - Logger.LogDebug("Region key for region '{0}' not present, creating a new one...", region); - } - - regionKey = StoreNewRegionPrefix(region); - } - else - { - // create a fake one (e.g. on Remove key, we don't have to create a region if it doesn't exist at all) - regionKey = (Clock.GetUnixTimestampMillis() * -1).ToString(); - } - } - - fullKey = string.Concat(regionKey, ":", key); - } - - return GetPerhapsHashedKey(fullKey); - } - - private static string GetPerhapsHashedKey(string key) - { - // Memcached still has a 250 character limit - if (key.Length >= 250) - { - return GetSHA256Key(key); - } - - return key; - } - - // TODO: test the config section ctor now with this - private static IMemcachedClientConfiguration GetSection(string sectionName) - { - var section = (MemcachedClientSection)ConfigurationManager.GetSection(sectionName); - if (section == null) - { - throw new ConfigurationErrorsException("Section " + sectionName + " is not found."); - } - - return section; - } - - private static string GetSHA256Key(string key) - { - using (var sha = SHA256Managed.Create()) - { - var hashBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(key)); - return Convert.ToBase64String(hashBytes); - } - } - - private static bool ShouldRetry(StatusCode statusCode) - { - switch (statusCode) - { - case StatusCode.NodeShutdown: - case StatusCode.OperationTimeout: - case StatusCode.OutOfMemory: - case StatusCode.Busy: - case StatusCode.SocketPoolTimeout: - case StatusCode.UnableToLocateNode: - case StatusCode.VBucketBelongsToAnotherServer: - return true; - } - - return false; - } - - /// - /// Gets the section. - /// - /// The client configuration. - /// - /// If memcached client section was not found or there are no servers defined for memcached. - /// - private IMemcachedClientConfiguration GetSection() - { - var sectionName = GetEnyimSectionName(Configuration.Name); - var section = (MemcachedClientSection)ConfigurationManager.GetSection(sectionName); - - if (section == null) - { - throw new ConfigurationErrorsException("Client section " + sectionName + " is not found."); - } - - // validate - if (section.Servers.Count <= 0) - { - throw new ConfigurationErrorsException("There are no servers defined."); - } - - return section; - } - - private IList GetServers() - { - var section = GetSection(); - return section.Servers; - } - - private UpdateItemResult Set(string key, string region, Func updateValue, int maxRetries) - { - var fullyKey = GetKey(key, region); - var tries = 0; - IStoreOperationResult result; - - do - { - tries++; - var getTries = 0; - StatusCode getStatus; - IGetOperationResult> getResult; - CacheItem item; - do - { - getTries++; - getResult = Cache.ExecuteGet>(fullyKey); - - item = getResult.Value; - getStatus = (StatusCode)(getResult.StatusCode ?? getResult.InnerResult?.StatusCode ?? -1); - } - while (ShouldRetry(getStatus) && getTries <= maxRetries); - - // break operation if we cannot retrieve the object (maybe it has expired already). - if (!getResult.Success || item == null) - { - LogOperationResult(LogLevel.Warning, getResult, "Get item during update failed for '{0}'.", fullyKey); - return UpdateItemResult.ForItemDidNotExist(); - } - - if (item.IsExpired) - { - return UpdateItemResult.ForItemDidNotExist(); - } - - var newValue = updateValue(item.Value); - - // added null check, throw explicit to me more consistent. Otherwise it would throw later eventually - if (newValue == null) - { - return UpdateItemResult.ForFactoryReturnedNull(); - } - - item = item.WithValue(newValue); - item.LastAccessedUtc = DateTime.UtcNow; - - if (item.ExpirationMode == ExpirationMode.Absolute || item.ExpirationMode == ExpirationMode.Sliding) - { - if (item.ExpirationTimeout > _maximumTimeout) - { - throw new InvalidOperationException($"Timeout must not exceed {_maximumTimeout.TotalDays} days."); - } - - result = Cache.ExecuteCas(StoreMode.Set, fullyKey, item, item.ExpirationTimeout, getResult.Cas); - } - else - { - result = Cache.ExecuteCas(StoreMode.Set, fullyKey, item, getResult.Cas); - } - - if (result.Success) - { - return UpdateItemResult.ForSuccess(item, tries > 1, tries); - } - else - { - LogOperationResult(LogLevel.Warning, result, "Update failed for '{0}'.", fullyKey); - } - - WaitRetry(tries); - } - while (tries < maxRetries); - - return UpdateItemResult.ForTooManyRetries(tries); - } - - private class CacheManagerTanscoder : DefaultTranscoder - { - private readonly ICacheSerializer _serializer; - - public CacheManagerTanscoder(ICacheSerializer serializer) - { - NotNull(serializer, nameof(serializer)); - _serializer = serializer; - } - - protected override object DeserializeObject(ArraySegment value) - { - var position = value.Offset; - var typeNameLen = BitConverter.ToUInt16(value.Array, position); - position += 2; - - var typeName = Encoding.UTF8.GetString(value.Array, position, typeNameLen); - position += typeNameLen; - if (value.Array[position++] != 0) - { - throw new InvalidOperationException("Invalid data, stop bit not found in type name encoding."); - } - - var data = new byte[value.Count - position + value.Offset]; - Buffer.BlockCopy(value.Array, position, data, 0, data.Length); - return _serializer.DeserializeCacheItem(data, TypeCache.GetType(typeName)); - } - - protected override ArraySegment SerializeObject(object value) - { - var cacheItem = value as CacheItem; - if (cacheItem == null) - { - throw new ArgumentException($"Value is not {nameof(CacheItem)}.", nameof(value)); - } - - var typeName = cacheItem.Value.GetType().AssemblyQualifiedName; - var typeNameBytes = Encoding.UTF8.GetBytes(typeName); - var typeBytesLength = BitConverter.GetBytes((ushort)typeNameBytes.Length); - var data = _serializer.SerializeCacheItem(cacheItem); - - var result = new byte[typeNameBytes.Length + typeBytesLength.Length + data.Length + 1]; - - /* Encoding the actual item value Type into the cached item - * - * | 0 - 1 | 2 - len | len + 1 | ... - * | len |TypeName |0 - stop | data - */ - Buffer.BlockCopy(typeBytesLength, 0, result, 0, typeBytesLength.Length); - Buffer.BlockCopy(typeNameBytes, 0, result, typeBytesLength.Length, typeNameBytes.Length); - Buffer.BlockCopy(data, 0, result, typeBytesLength.Length + typeNameBytes.Length + 1, data.Length); - - return new ArraySegment(result); - } - } - } -} diff --git a/src/CacheManager.Memcached/MemcachedConfigurationBuilderExtensions.cs b/src/CacheManager.Memcached/MemcachedConfigurationBuilderExtensions.cs deleted file mode 100644 index ab779b7a..00000000 --- a/src/CacheManager.Memcached/MemcachedConfigurationBuilderExtensions.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using CacheManager.Memcached; -using Enyim.Caching; -using Enyim.Caching.Configuration; -using static CacheManager.Core.Utility.Guard; - -namespace CacheManager.Core -{ - /// - /// Extensions for the configuration builder specific to the Memcached cache handle. - /// - public static class MemcachedConfigurationBuilderExtensions - { - /// - /// Adds a . The must match with cache configured via enyim configuration section. - /// - /// The builder part. - /// The configuration name. - /// - /// Set this to true if this cache handle should be the source of the backplane. - /// This setting will be ignored if no backplane is configured. - /// - /// The part. - /// - /// Thrown if handleName or handleType are null. - /// - public static ConfigurationBuilderCacheHandlePart WithMemcachedCacheHandle(this ConfigurationBuilderCachePart part, string configurationName, bool isBackplaneSource = true) - { - NotNull(part, nameof(part)); - - return part.WithHandle(typeof(MemcachedCacheHandle<>), configurationName, isBackplaneSource); - } - - /// - /// Adds a with a preconfigured instance. - /// - /// The builder part. - /// The to use for this cache handle. - /// - /// Set this to true if this cache handle should be the source of the backplane. - /// This setting will be ignored if no backplane is configured. - /// - /// The part. - /// - /// Thrown if is null. - /// - public static ConfigurationBuilderCacheHandlePart WithMemcachedCacheHandle(this ConfigurationBuilderCachePart part, MemcachedClient client, bool isBackplaneSource = true) - { - NotNull(part, nameof(part)); - NotNull(client, nameof(client)); - - return part.WithHandle(typeof(MemcachedCacheHandle<>), Guid.NewGuid().ToString(), isBackplaneSource, client); - } - - /// - /// Adds a . The must match with cache configured via enyim configuration section. - /// - /// The builder part. - /// The configuration name. - /// The to use for this cache handle. - /// - /// Set this to true if this cache handle should be the source of the backplane. - /// This setting will be ignored if no backplane is configured. - /// - /// The part. - /// - /// Thrown if is null. - /// - public static ConfigurationBuilderCacheHandlePart WithMemcachedCacheHandle(this ConfigurationBuilderCachePart part, string configurationName, MemcachedClient client, bool isBackplaneSource = true) - { - NotNull(part, nameof(part)); - - return part.WithHandle(typeof(MemcachedCacheHandle<>), configurationName, isBackplaneSource, client); - } - - /// - /// Adds a using the to setup a instance. - /// - /// The builder part. - /// The to use to create the for this cache handle. - /// - /// Set this to true if this cache handle should be the source of the backplane. - /// This setting will be ignored if no backplane is configured. - /// - /// The part. - /// - /// Thrown if is null. - /// - public static ConfigurationBuilderCacheHandlePart WithMemcachedCacheHandle(this ConfigurationBuilderCachePart part, MemcachedClientConfiguration clientConfiguration, bool isBackplaneSource = true) - { - NotNull(part, nameof(part)); - NotNull(clientConfiguration, nameof(clientConfiguration)); - - return part.WithHandle(typeof(MemcachedCacheHandle<>), Guid.NewGuid().ToString(), isBackplaneSource, clientConfiguration); - } - - /// - /// Adds a using the to setup a instance. - /// - /// The builder part. - /// The configuration name. - /// The to use to create the for this cache handle. - /// - /// Set this to true if this cache handle should be the source of the backplane. - /// This setting will be ignored if no backplane is configured. - /// - /// The part. - /// - /// Thrown if is null. - /// - public static ConfigurationBuilderCacheHandlePart WithMemcachedCacheHandle(this ConfigurationBuilderCachePart part, string configurationName, MemcachedClientConfiguration clientConfiguration, bool isBackplaneSource = true) - { - NotNull(part, nameof(part)); - - return part.WithHandle(typeof(MemcachedCacheHandle<>), configurationName, isBackplaneSource, clientConfiguration); - } - } -} \ No newline at end of file diff --git a/src/CacheManager.Memcached/StatusCode.cs b/src/CacheManager.Memcached/StatusCode.cs deleted file mode 100644 index 2ed73cbf..00000000 --- a/src/CacheManager.Memcached/StatusCode.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace CacheManager.Memcached -{ - internal enum StatusCode - { - Success = 0x0000, - KeyNotFound = 0x0001, - KeyExists = 0x0002, - ValueTooLarge = 0x0003, - InvalidArguments = 0x0004, - ItemNotStored = 0x0005, - IncrDecrOnNonNumericValue = 0x0006, - VBucketBelongsToAnotherServer = 0x0007, - AuthenticationError = 0x0020, - AuthenticationContinue = 0x0021, - InvalidRange = 0x0022, - UnknownCommand = 0x0081, - OutOfMemory = 0x0082, - NotSupported = 0x0083, - InternalError = 0x0084, - Busy = 0x0085, - TemporaryFailure = 0x0086, - - SocketPoolTimeout = 0x091, - UnableToLocateNode = 0x092, - NodeShutdown = 0x093, - OperationTimeout = 0x094 - } -} \ No newline at end of file diff --git a/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj b/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj index 9faefffb..97883037 100644 --- a/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj +++ b/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj @@ -3,7 +3,7 @@ CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. This package contains the specific cache handle for Microsoft.Extensions.Caching.Memory. MichaConrad;AuroraDysis - netstandard2.0 + netstandard2.0;net8.0 true true Caching;Cache;CacheManager;MemoryCache @@ -12,6 +12,9 @@ - + + + + \ No newline at end of file diff --git a/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheExtensions.cs b/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheExtensions.cs index 846ac572..5d5a8b29 100644 --- a/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheExtensions.cs +++ b/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheExtensions.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; +using System.Collections.Concurrent; using Microsoft.Extensions.Caching.Memory; namespace CacheManager.MicrosoftCachingMemory @@ -44,4 +41,4 @@ internal static void RemoveChilds(this MemoryCache cache, object region) } } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheHandle`1.cs b/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheHandle`1.cs index 248e4a7d..7f95ad96 100644 --- a/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheHandle`1.cs +++ b/src/CacheManager.Microsoft.Extensions.Caching.Memory/MemoryCacheHandle`1.cs @@ -2,9 +2,8 @@ using System.Collections.Concurrent; using CacheManager.Core; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; using Microsoft.Extensions.Caching.Memory; -using static CacheManager.Core.Utility.Guard; +using Microsoft.Extensions.Logging; namespace CacheManager.MicrosoftCachingMemory { @@ -43,10 +42,17 @@ public MemoryCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheH public MemoryCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory, MemoryCacheOptions memoryCacheOptions) : base(managerConfiguration, configuration) { - NotNull(configuration, nameof(configuration)); - NotNull(loggerFactory, nameof(loggerFactory)); + if (configuration is null) + { + throw new ArgumentNullException(nameof(configuration)); + } + + if (loggerFactory is null) + { + throw new ArgumentNullException(nameof(loggerFactory)); + } - Logger = loggerFactory.CreateLogger(this); + Logger = loggerFactory.CreateLogger(this.GetType()); _cacheName = configuration.Name; MemoryCacheOptions = memoryCacheOptions ?? new MemoryCacheOptions(); _cache = new MemoryCache(MemoryCacheOptions); @@ -82,7 +88,10 @@ public override bool Exists(string key) /// public override bool Exists(string key, string region) { - NotNullOrWhiteSpace(region, nameof(region)); + if (string.IsNullOrWhiteSpace(region)) + { + throw new ArgumentException($"'{nameof(region)}' cannot be null or whitespace.", nameof(region)); + } return _cache.Contains(GetItemKey(key, region)); } @@ -178,7 +187,10 @@ protected override void PutInternalPrepared(CacheItem item) private string GetItemKey(string key, string region = null) { - NotNullOrWhiteSpace(key, nameof(key)); + if (string.IsNullOrWhiteSpace(key)) + { + throw new ArgumentException($"'{nameof(key)}' cannot be null or whitespace.", nameof(key)); + } if (string.IsNullOrWhiteSpace(region)) { @@ -279,4 +291,4 @@ private void ItemRemoved(object key, object value, EvictionReason reason, object } } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj b/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj index d32ecf66..7e0777bf 100644 --- a/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj +++ b/src/CacheManager.Microsoft.Extensions.Configuration/CacheManager.Microsoft.Extensions.Configuration.csproj @@ -2,7 +2,7 @@ CacheManager extension package to use Microsoft.Extensions.Configuration to configure the CacheManager instance. CacheManager is an open source caching abstraction layer for .NET written in C#. This is the ASP.NET Core configuration integration package. - netstandard2.0;net461;net50 + netstandard2.0;net8.0 true true Caching;Cache;CacheManager;Distributed Cache;Configuration @@ -12,15 +12,15 @@ - - - - + + + + - - - - + + + + \ No newline at end of file diff --git a/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs b/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs index b018fcd3..c4faf1dd 100644 --- a/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs +++ b/src/CacheManager.Microsoft.Extensions.Configuration/MicrosoftConfigurationExtensions.cs @@ -31,10 +31,7 @@ public static class MicrosoftConfigurationExtensions private const string TypeMicrosoftLoggerFactory = "CacheManager.Logging.MicrosoftLoggerFactoryAdapter, CacheManager.Microsoft.Extensions.Logging"; private const string TypeRedisBackplane = "CacheManager.Redis.RedisCacheBackplane, CacheManager.StackExchange.Redis"; private const string TypeSystemRuntimeHandle = "CacheManager.SystemRuntimeCaching.MemoryCacheHandle`1, CacheManager.SystemRuntimeCaching"; - private const string TypeSystemWebHandle = "CacheManager.Web.SystemWebCacheHandle`1, CacheManager.Web"; private const string TypeRedisHandle = "CacheManager.Redis.RedisCacheHandle`1, CacheManager.StackExchange.Redis"; - private const string TypeCouchbaseHandle = "CacheManager.Couchbase.BucketCacheHandle`1, CacheManager.Couchbase"; - private const string TypeMemcachedHandle = "CacheManager.Memcached.MemcachedCacheHandle`1, CacheManager.Memcached"; private const string TypeMsExtensionMemoryCacheHandle = "CacheManager.MicrosoftCachingMemory.MemoryCacheHandle`1, CacheManager.Microsoft.Extensions.Caching.Memory"; private const string TypeRedisConfiguration = "CacheManager.Redis.RedisConfiguration, CacheManager.StackExchange.Redis"; private const string TypeRedisConfigurations = "CacheManager.Redis.RedisConfigurations, CacheManager.StackExchange.Redis"; @@ -296,23 +293,12 @@ private static Type GetKnownHandleType(string knownTypeName, string path, out bo case "dictionary": return typeof(DictionaryCacheHandle<>); - case "systemweb": - return Type.GetType(TypeSystemWebHandle, true); - case "msmemory": return Type.GetType(TypeMsExtensionMemoryCacheHandle, true); case "redis": keyRequired = true; return Type.GetType(TypeRedisHandle, true); - - case "couchbase": - keyRequired = true; - return Type.GetType(TypeCouchbaseHandle, true); - - case "memcached": - keyRequired = true; - return Type.GetType(TypeMemcachedHandle, true); } } catch (FileNotFoundException ex) diff --git a/src/CacheManager.Microsoft.Extensions.Configuration/ServiceCollectionExtensions.cs b/src/CacheManager.Microsoft.Extensions.Configuration/ServiceCollectionExtensions.cs index c361426a..91ff34a8 100644 --- a/src/CacheManager.Microsoft.Extensions.Configuration/ServiceCollectionExtensions.cs +++ b/src/CacheManager.Microsoft.Extensions.Configuration/ServiceCollectionExtensions.cs @@ -1,8 +1,8 @@ using System; -using System.Linq; using CacheManager.Core; using CacheManager.Core.Utility; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; namespace Microsoft.Extensions.DependencyInjection { @@ -15,15 +15,15 @@ public static class ServiceCollectionExtensions /// Adds a new as singleton to the DI framework. /// /// The services collection. - /// The used for defining the . + /// The used for defining the . /// The (optional) name to be used for the . - public static IServiceCollection AddCacheManagerConfiguration(this IServiceCollection collection, Action configure, string name = null) + public static IServiceCollection AddCacheManagerConfiguration(this IServiceCollection collection, Action configure, string name = null) { Guard.NotNull(collection, nameof(collection)); Guard.NotNull(configure, nameof(configure)); var builder = string.IsNullOrWhiteSpace(name) ? - new CacheManager.Core.ConfigurationBuilder() : - new CacheManager.Core.ConfigurationBuilder(name); + new CacheManager.Core.CacheConfigurationBuilder() : + new CacheManager.Core.CacheConfigurationBuilder(name); configure(builder); collection.AddSingleton(builder.Build()); @@ -70,7 +70,7 @@ public static IServiceCollection AddCacheManagerConfiguration(this IServiceColle /// The section which contains a cacheManagers section. /// Can be used to further configure the configuration. /// The services collection - public static IServiceCollection AddCacheManagerConfiguration(this IServiceCollection collection, IConfiguration fromConfiguration, Action configure) + public static IServiceCollection AddCacheManagerConfiguration(this IServiceCollection collection, IConfiguration fromConfiguration, Action configure) { Guard.NotNull(collection, nameof(collection)); Guard.NotNull(fromConfiguration, nameof(fromConfiguration)); @@ -90,7 +90,7 @@ public static IServiceCollection AddCacheManagerConfiguration(this IServiceColle /// The name used in the configuration. /// Can be used to further configure the configuration. /// The services collection - public static IServiceCollection AddCacheManagerConfiguration(this IServiceCollection collection, IConfiguration fromConfiguration, string name, Action configure) + public static IServiceCollection AddCacheManagerConfiguration(this IServiceCollection collection, IConfiguration fromConfiguration, string name, Action configure) { Guard.NotNull(collection, nameof(collection)); Guard.NotNull(fromConfiguration, nameof(fromConfiguration)); @@ -133,18 +133,19 @@ public static IServiceCollection AddCacheManager(this IServiceCollection collect /// The name of the to use. /// Can be used to further configure the . /// The services collection. - public static IServiceCollection AddCacheManager(this IServiceCollection collection, IConfiguration fromConfiguration, string configurationName = null, Action configure = null) + public static IServiceCollection AddCacheManager(this IServiceCollection collection, IConfiguration fromConfiguration, string configurationName = null, Action configure = null) { Guard.NotNull(collection, nameof(collection)); Guard.NotNull(fromConfiguration, nameof(fromConfiguration)); collection.AddSingleton, BaseCacheManager>((provider) => { + var loggerFactory = provider.GetService(); var configuration = string.IsNullOrWhiteSpace(configurationName) ? fromConfiguration.GetCacheConfiguration() : fromConfiguration.GetCacheConfiguration(configurationName); configure?.Invoke(configuration.Builder); - return new BaseCacheManager(configuration); + return new BaseCacheManager(configuration, loggerFactory); }); return collection; @@ -158,7 +159,7 @@ public static IServiceCollection AddCacheManager(this IServiceCollection coll /// Used to configure the instance of . /// The (optional) name for the . /// The services collection. - public static IServiceCollection AddCacheManager(this IServiceCollection collection, Action configure, string name = null) + public static IServiceCollection AddCacheManager(this IServiceCollection collection, Action configure, string name = null) { Guard.NotNull(collection, nameof(collection)); Guard.NotNull(configure, nameof(configure)); @@ -167,15 +168,16 @@ public static IServiceCollection AddCacheManager(this IServiceCollection coll { Guard.NotNull(configure, nameof(configure)); var builder = string.IsNullOrWhiteSpace(name) ? - new CacheManager.Core.ConfigurationBuilder() : - new CacheManager.Core.ConfigurationBuilder(name); + new CacheManager.Core.CacheConfigurationBuilder() : + new CacheManager.Core.CacheConfigurationBuilder(name); configure(builder); - - return new BaseCacheManager(builder.Build()); + + var loggerFactory = provider.GetService(); + return new BaseCacheManager(builder.Build(), loggerFactory); }); return collection; } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Microsoft.Extensions.Logging/CacheManager.Microsoft.Extensions.Logging.csproj b/src/CacheManager.Microsoft.Extensions.Logging/CacheManager.Microsoft.Extensions.Logging.csproj deleted file mode 100644 index 0e1d87ba..00000000 --- a/src/CacheManager.Microsoft.Extensions.Logging/CacheManager.Microsoft.Extensions.Logging.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - CacheManager extension package to work with Microsoft.Extensions.Logging as logging provider. CacheManager is an open source caching abstraction layer for .NET written in C#. The ASP.NET Core logging provides a bridge to the Microsoft.Extensions.Logging framework. - netstandard2.0 - true - true - Caching;Cache;CacheManager;Distributed Cache;Logging - - - - - - - - - - - \ No newline at end of file diff --git a/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggerFactory.cs b/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggerFactory.cs deleted file mode 100644 index 4bc972de..00000000 --- a/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggerFactory.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Globalization; -using CacheManager.Core.Utility; -using Microsoft.Extensions.Logging; -using ILogger = CacheManager.Core.Logging.ILogger; -using LogLevel = CacheManager.Core.Logging.LogLevel; - -namespace CacheManager.Logging -{ -#pragma warning disable SA1600 -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - - public class MicrosoftLoggerFactoryAdapter : Core.Logging.ILoggerFactory, IDisposable - { - private readonly Lazy _parentFactory; - - public MicrosoftLoggerFactoryAdapter() - { - _parentFactory = new Lazy(() => new LoggerFactory()); - } - - public MicrosoftLoggerFactoryAdapter(Func parentFactoryFactory) - { - Guard.NotNull(parentFactoryFactory, nameof(parentFactoryFactory)); - _parentFactory = new Lazy(parentFactoryFactory); - } - - ~MicrosoftLoggerFactoryAdapter() - { - // Do not change this code. Put cleanup code in Dispose(bool disposing) above. - Dispose(false); - } - - public ILogger CreateLogger(string categoryName) - { - return new MicrosoftLoggerAdapter(_parentFactory.Value.CreateLogger(categoryName)); - } - - public ILogger CreateLogger(T instance) - { - return new MicrosoftLoggerAdapter(new Logger(_parentFactory.Value)); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - if (_parentFactory.IsValueCreated) - { - _parentFactory.Value.Dispose(); - } - } - } - } - - internal class MicrosoftLoggerAdapter : ILogger - { - private static readonly Func _formatter = MessageFormatter; - private readonly Microsoft.Extensions.Logging.ILogger _logger; - - public MicrosoftLoggerAdapter(Microsoft.Extensions.Logging.ILogger logger) - { - Guard.NotNull(logger, nameof(logger)); - - _logger = logger; - } - - public IDisposable BeginScope(object state) - { - return _logger.BeginScope(state); - } - - public bool IsEnabled(LogLevel logLevel) - { - return _logger.IsEnabled(GetExternalLogLevel(logLevel)); - } - - public void Log(LogLevel logLevel, int eventId, object message, Exception exception) - { - _logger.Log(GetExternalLogLevel(logLevel), eventId, message, exception, _formatter); - } - - private static string MessageFormatter(object state, Exception error) - { - if (state == null && error == null) - { - throw new InvalidOperationException("No message or exception details were found to create a message for the log."); - } - - if (state == null) - { - return error.ToString(); - } - - if (error == null) - { - return state.ToString(); - } - - return string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}", state, Environment.NewLine, error); - } - - private static Microsoft.Extensions.Logging.LogLevel GetExternalLogLevel(LogLevel level) - { - switch (level) - { - case LogLevel.Debug: - return Microsoft.Extensions.Logging.LogLevel.Debug; - - case LogLevel.Trace: - return Microsoft.Extensions.Logging.LogLevel.Trace; - - case LogLevel.Information: - return Microsoft.Extensions.Logging.LogLevel.Information; - - case LogLevel.Warning: - return Microsoft.Extensions.Logging.LogLevel.Warning; - - case LogLevel.Error: - return Microsoft.Extensions.Logging.LogLevel.Error; - - case LogLevel.Critical: - return Microsoft.Extensions.Logging.LogLevel.Critical; - } - - return Microsoft.Extensions.Logging.LogLevel.None; - } - } -#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member -#pragma warning restore SA1600 -} diff --git a/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggingBuilderExtensions.cs b/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggingBuilderExtensions.cs deleted file mode 100644 index 02e92254..00000000 --- a/src/CacheManager.Microsoft.Extensions.Logging/MicrosoftLoggingBuilderExtensions.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Linq; -using CacheManager.Logging; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using static CacheManager.Core.Utility.Guard; - -namespace CacheManager.Core -{ - /// - /// Extensions for the configuration builder for logging. - /// - public static class MicrosoftLoggingBuilderExtensions - { - /// - /// Enables logging for the cache manager instance using an existing Microsoft.Extensions.Logging.ILoggerFactory as target. - /// - /// The builder part. - /// The logger factory which should be used. - /// The builder. - public static ConfigurationBuilderCachePart WithMicrosoftLogging(this ConfigurationBuilderCachePart part, ILoggerFactory loggerFactory) - { - NotNull(part, nameof(part)); - NotNull(loggerFactory, nameof(loggerFactory)); - return part.WithLogging(typeof(MicrosoftLoggerFactoryAdapter), new Func(() => loggerFactory)); - } - } -} diff --git a/src/CacheManager.Serialization.Bond/BondCompactBinaryCacheSerializer.cs b/src/CacheManager.Serialization.Bond/BondCompactBinaryCacheSerializer.cs index c83d313d..751eab83 100644 --- a/src/CacheManager.Serialization.Bond/BondCompactBinaryCacheSerializer.cs +++ b/src/CacheManager.Serialization.Bond/BondCompactBinaryCacheSerializer.cs @@ -35,7 +35,7 @@ public BondCompactBinaryCacheSerializer(int defaultBufferSize) : base(defaultBuf public override byte[] Serialize(T value) { var serializer = _cache.GetSerializer(value.GetType()); - var buffer = OutputBufferPool.Lease(); + var buffer = OutputBufferPool.Get(); var writer = _cache.CreateWriter(buffer); serializer.Serialize(value, writer); diff --git a/src/CacheManager.Serialization.Bond/BondConfigurationBuilderExtensions.cs b/src/CacheManager.Serialization.Bond/BondConfigurationBuilderExtensions.cs index 536db904..05e7aabd 100644 --- a/src/CacheManager.Serialization.Bond/BondConfigurationBuilderExtensions.cs +++ b/src/CacheManager.Serialization.Bond/BondConfigurationBuilderExtensions.cs @@ -1,5 +1,5 @@ -using CacheManager.Serialization.Bond; -using static CacheManager.Core.Utility.Guard; +using System; +using CacheManager.Serialization.Bond; namespace CacheManager.Core { @@ -17,7 +17,10 @@ public static class BondConfigurationBuilderExtensions /// The builder instance. public static ConfigurationBuilderCachePart WithBondCompactBinarySerializer(this ConfigurationBuilderCachePart part, int defaultWriteBufferSize = 1024) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(BondCompactBinaryCacheSerializer), defaultWriteBufferSize); } @@ -31,7 +34,10 @@ public static ConfigurationBuilderCachePart WithBondCompactBinarySerializer(this /// The builder instance. public static ConfigurationBuilderCachePart WithBondFastBinarySerializer(this ConfigurationBuilderCachePart part, int defaultWriteBufferSize = 1024) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(BondFastBinaryCacheSerializer), defaultWriteBufferSize); } @@ -44,9 +50,12 @@ public static ConfigurationBuilderCachePart WithBondFastBinarySerializer(this Co /// The builder instance. public static ConfigurationBuilderCachePart WithBondSimpleJsonSerializer(this ConfigurationBuilderCachePart part) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(BondSimpleJsonCacheSerializer)); } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Serialization.Bond/BondFastBinaryCacheSerializer.cs b/src/CacheManager.Serialization.Bond/BondFastBinaryCacheSerializer.cs index 3a14d0ca..1de861a4 100644 --- a/src/CacheManager.Serialization.Bond/BondFastBinaryCacheSerializer.cs +++ b/src/CacheManager.Serialization.Bond/BondFastBinaryCacheSerializer.cs @@ -35,7 +35,7 @@ public BondFastBinaryCacheSerializer(int defaultWriteBufferSize) : base(defaultW public override byte[] Serialize(T value) { var serializer = _cache.GetSerializer(value.GetType()); - var buffer = OutputBufferPool.Lease(); + var buffer = OutputBufferPool.Get(); var writer = _cache.CreateWriter(buffer); serializer.Serialize(value, writer); diff --git a/src/CacheManager.Serialization.Bond/BondSerializerBase.cs b/src/CacheManager.Serialization.Bond/BondSerializerBase.cs index d5b5a2d4..5a456373 100644 --- a/src/CacheManager.Serialization.Bond/BondSerializerBase.cs +++ b/src/CacheManager.Serialization.Bond/BondSerializerBase.cs @@ -1,9 +1,8 @@ using System; -using System.Linq; using System.Text; using Bond.IO.Unsafe; using CacheManager.Core.Internal; -using CacheManager.Core.Utility; +using Microsoft.Extensions.ObjectPool; namespace CacheManager.Serialization.Bond { @@ -28,8 +27,8 @@ public BondSerializerBase() /// The default buffer size. public BondSerializerBase(int defaultBufferSize) { - OutputBufferPool = new ObjectPool(new OutputBufferPoolPolicy(defaultBufferSize)); - StringBuilderPool = new ObjectPool(new StringBuilderPoolPolicy(defaultBufferSize)); + OutputBufferPool = new DefaultObjectPool(new OutputBufferPoolPolicy(defaultBufferSize)); + StringBuilderPool = new DefaultObjectPool(new StringBuilderPoolPolicy(defaultBufferSize)); } /// @@ -41,6 +40,7 @@ public BondSerializerBase(int defaultBufferSize) /// /// Gets a pool handling s. /// + [CLSCompliant(false)] protected ObjectPool StringBuilderPool { get; } /// @@ -55,7 +55,7 @@ protected override object CreateNewItem(ICacheItemProperties proper return new BondCacheItem(properties, value); } - private class OutputBufferPoolPolicy : IObjectPoolPolicy + private class OutputBufferPoolPolicy : IPooledObjectPolicy { private readonly int _defaultBufferSize; @@ -64,7 +64,7 @@ public OutputBufferPoolPolicy(int defaultBufferSize) _defaultBufferSize = defaultBufferSize; } - public OutputBuffer CreateNew() + public OutputBuffer Create() { return new OutputBuffer(_defaultBufferSize); } @@ -81,7 +81,7 @@ public bool Return(OutputBuffer value) } } - private class StringBuilderPoolPolicy : IObjectPoolPolicy + private class StringBuilderPoolPolicy : IPooledObjectPolicy { private readonly int _defaultBufferSize; @@ -90,7 +90,7 @@ public StringBuilderPoolPolicy(int defaultBufferSize) _defaultBufferSize = defaultBufferSize; } - public StringBuilder CreateNew() + public StringBuilder Create() { return new StringBuilder(_defaultBufferSize); } diff --git a/src/CacheManager.Serialization.Bond/BondSimpleJsonCacheSerializer.cs b/src/CacheManager.Serialization.Bond/BondSimpleJsonCacheSerializer.cs index 07419556..bd8d4ddd 100644 --- a/src/CacheManager.Serialization.Bond/BondSimpleJsonCacheSerializer.cs +++ b/src/CacheManager.Serialization.Bond/BondSimpleJsonCacheSerializer.cs @@ -37,7 +37,7 @@ public BondSimpleJsonCacheSerializer(int defaultWriteBufferSize) : base(defaultW public override byte[] Serialize(T value) { var serializer = _cache.GetSerializer(value.GetType()); - var buffer = StringBuilderPool.Lease(); + var buffer = StringBuilderPool.Get(); using (var stringWriter = new StringWriter(buffer)) { diff --git a/src/CacheManager.Serialization.Bond/CacheManager.Serialization.Bond.csproj b/src/CacheManager.Serialization.Bond/CacheManager.Serialization.Bond.csproj index d9089aec..4de9715d 100644 --- a/src/CacheManager.Serialization.Bond/CacheManager.Serialization.Bond.csproj +++ b/src/CacheManager.Serialization.Bond/CacheManager.Serialization.Bond.csproj @@ -2,7 +2,7 @@ CacheManager extension package providing Microsoft Bond based serialization for distributed caches. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - netstandard2.0;net45 + netstandard2.0;net8.0 true true Caching;Cache;CacheManager;Serialization;Bond @@ -10,9 +10,15 @@ - + + + + - - + + + + + \ No newline at end of file diff --git a/src/CacheManager.Serialization.DataContract/CacheManager.Serialization.DataContract.csproj b/src/CacheManager.Serialization.DataContract/CacheManager.Serialization.DataContract.csproj index 7862d733..403f7c8d 100644 --- a/src/CacheManager.Serialization.DataContract/CacheManager.Serialization.DataContract.csproj +++ b/src/CacheManager.Serialization.DataContract/CacheManager.Serialization.DataContract.csproj @@ -2,7 +2,7 @@ CacheManager extension package providing DataContract serialization for distributed caches. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - net45;netstandard2.0 + netstandard2.0 true true Caching;Cache;CacheManager;Serialization;DataContract @@ -11,9 +11,6 @@ - - - diff --git a/src/CacheManager.Serialization.DataContract/DataContractConfigurationBuilderExtensions.cs b/src/CacheManager.Serialization.DataContract/DataContractConfigurationBuilderExtensions.cs index 1a839aea..d328c44b 100644 --- a/src/CacheManager.Serialization.DataContract/DataContractConfigurationBuilderExtensions.cs +++ b/src/CacheManager.Serialization.DataContract/DataContractConfigurationBuilderExtensions.cs @@ -1,7 +1,7 @@ -using System.Runtime.Serialization; +using System; +using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using CacheManager.Serialization.DataContract; -using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core { @@ -18,7 +18,10 @@ public static class DataContractConfigurationBuilderExtensions /// The builder instance. public static ConfigurationBuilderCachePart WithDataContractSerializer(this ConfigurationBuilderCachePart part, DataContractSerializerSettings serializerSettings = null) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } if (serializerSettings == null) { @@ -38,7 +41,10 @@ public static ConfigurationBuilderCachePart WithDataContractSerializer(this Conf /// The builder instance. public static ConfigurationBuilderCachePart WithDataContractJsonSerializer(this ConfigurationBuilderCachePart part, DataContractJsonSerializerSettings serializerSettings = null) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } if (serializerSettings == null) { @@ -58,7 +64,10 @@ public static ConfigurationBuilderCachePart WithDataContractJsonSerializer(this /// The builder instance. public static ConfigurationBuilderCachePart WithDataContractGzJsonSerializer(this ConfigurationBuilderCachePart part, DataContractJsonSerializerSettings serializerSettings = null) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } if (serializerSettings == null) { @@ -78,7 +87,10 @@ public static ConfigurationBuilderCachePart WithDataContractGzJsonSerializer(thi /// The builder instance. public static ConfigurationBuilderCachePart WithDataContractBinarySerializer(this ConfigurationBuilderCachePart part, DataContractSerializerSettings serializerSettings = null) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } if (serializerSettings == null) { diff --git a/src/CacheManager.Serialization.Json/CacheManager.Serialization.Json.csproj b/src/CacheManager.Serialization.Json/CacheManager.Serialization.Json.csproj index 14ae56b0..bfac5260 100644 --- a/src/CacheManager.Serialization.Json/CacheManager.Serialization.Json.csproj +++ b/src/CacheManager.Serialization.Json/CacheManager.Serialization.Json.csproj @@ -2,7 +2,7 @@ CacheManager extension package providing JSON serialization for distributed caches. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. The Core library contains a Newtonsoft.Json based serializer implementation which can be used instead of the default binary serializer. - netstandard2.0;net45 + netstandard2.0;net8.0 true true Caching;Cache;CacheManager;Distributed Cache;JSON;Serialization @@ -10,10 +10,15 @@ - - + + + + + + - - + + + \ No newline at end of file diff --git a/src/CacheManager.Serialization.Json/GzJsonCacheSerializer.cs b/src/CacheManager.Serialization.Json/GzJsonCacheSerializer.cs index 6f29142a..59d27fef 100644 --- a/src/CacheManager.Serialization.Json/GzJsonCacheSerializer.cs +++ b/src/CacheManager.Serialization.Json/GzJsonCacheSerializer.cs @@ -1,8 +1,6 @@ using System; using System.IO; using System.IO.Compression; -using System.Linq; -using CacheManager.Core.Utility; using Newtonsoft.Json; namespace CacheManager.Serialization.Json @@ -34,7 +32,11 @@ public GzJsonCacheSerializer(JsonSerializerSettings serializationSettings, JsonS /// public override object Deserialize(byte[] data, Type target) { - Guard.NotNull(data, nameof(data)); + if (data is null) + { + throw new ArgumentNullException(nameof(data)); + } + var compressedData = Decompression(data); return base.Deserialize(compressedData, target); @@ -43,7 +45,6 @@ public override object Deserialize(byte[] data, Type target) /// public override byte[] Serialize(T value) { - Guard.NotNull(value, nameof(value)); var data = base.Serialize(value); return Compression(data); diff --git a/src/CacheManager.Serialization.Json/JsonCacheSerializer.cs b/src/CacheManager.Serialization.Json/JsonCacheSerializer.cs index 5577a0ca..4d8e57db 100644 --- a/src/CacheManager.Serialization.Json/JsonCacheSerializer.cs +++ b/src/CacheManager.Serialization.Json/JsonCacheSerializer.cs @@ -1,10 +1,9 @@ using System; using System.IO; -using System.Linq; using System.Text; using CacheManager.Core; using CacheManager.Core.Internal; -using CacheManager.Core.Utility; +using Microsoft.Extensions.ObjectPool; using Newtonsoft.Json; namespace CacheManager.Serialization.Json @@ -35,12 +34,19 @@ public JsonCacheSerializer() /// The settings which should be used during deserialization. public JsonCacheSerializer(JsonSerializerSettings serializationSettings, JsonSerializerSettings deserializationSettings) { - Guard.NotNull(serializationSettings, nameof(serializationSettings)); - Guard.NotNull(deserializationSettings, nameof(deserializationSettings)); + if (serializationSettings is null) + { + throw new ArgumentNullException(nameof(serializationSettings)); + } + + if (deserializationSettings is null) + { + throw new ArgumentNullException(nameof(deserializationSettings)); + } _serializer = JsonSerializer.Create(serializationSettings); _deserializer = JsonSerializer.Create(deserializationSettings); - _stringBuilderPool = new ObjectPool(new StringBuilderPoolPolicy(100)); + _stringBuilderPool = new DefaultObjectPool(new StringBuilderPooledObjectPolicy()); SerializationSettings = serializationSettings; DeserializationSettings = deserializationSettings; } @@ -73,7 +79,12 @@ public override object Deserialize(byte[] data, Type target) /// public override byte[] Serialize(T value) { - var buffer = _stringBuilderPool.Lease(); + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + var buffer = _stringBuilderPool.Get(); using (var stringWriter = new JsonTextWriter(new StringWriter(buffer))) { @@ -96,31 +107,5 @@ protected override object CreateNewItem(ICacheItemProperties proper { return new JsonCacheItem(properties, value); } - - private class StringBuilderPoolPolicy : IObjectPoolPolicy - { - private readonly int _defaultBufferSize; - - public StringBuilderPoolPolicy(int defaultBufferSize) - { - _defaultBufferSize = defaultBufferSize; - } - - public StringBuilder CreateNew() - { - return new StringBuilder(_defaultBufferSize); - } - - public bool Return(StringBuilder value) - { - ////if (value.Data.Count > _defaultBufferSize * 1000) - ////{ - //// return false; - ////} - - value.Clear(); - return true; - } - } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Serialization.Json/JsonConfigurationBuilderExtensions.cs b/src/CacheManager.Serialization.Json/JsonConfigurationBuilderExtensions.cs index 050ff630..85c8027c 100644 --- a/src/CacheManager.Serialization.Json/JsonConfigurationBuilderExtensions.cs +++ b/src/CacheManager.Serialization.Json/JsonConfigurationBuilderExtensions.cs @@ -1,6 +1,6 @@ -using CacheManager.Serialization.Json; +using System; +using CacheManager.Serialization.Json; using Newtonsoft.Json; -using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core { @@ -16,7 +16,10 @@ public static class JsonConfigurationBuilderExtensions /// The builder instance. public static ConfigurationBuilderCachePart WithJsonSerializer(this ConfigurationBuilderCachePart part) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(JsonCacheSerializer)); } @@ -30,7 +33,10 @@ public static ConfigurationBuilderCachePart WithJsonSerializer(this Configuratio /// The builder instance. public static ConfigurationBuilderCachePart WithJsonSerializer(this ConfigurationBuilderCachePart part, JsonSerializerSettings serializationSettings, JsonSerializerSettings deserializationSettings) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(JsonCacheSerializer), serializationSettings, deserializationSettings); } @@ -42,7 +48,10 @@ public static ConfigurationBuilderCachePart WithJsonSerializer(this Configuratio /// The builder instance. public static ConfigurationBuilderCachePart WithGzJsonSerializer(this ConfigurationBuilderCachePart part) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(GzJsonCacheSerializer)); } @@ -56,9 +65,12 @@ public static ConfigurationBuilderCachePart WithGzJsonSerializer(this Configurat /// The builder instance. public static ConfigurationBuilderCachePart WithGzJsonSerializer(this ConfigurationBuilderCachePart part, JsonSerializerSettings serializationSettings, JsonSerializerSettings deserializationSettings) { - NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(GzJsonCacheSerializer), serializationSettings, deserializationSettings); } } -} \ No newline at end of file +} diff --git a/src/CacheManager.Serialization.ProtoBuf/CacheManager.Serialization.ProtoBuf.csproj b/src/CacheManager.Serialization.ProtoBuf/CacheManager.Serialization.ProtoBuf.csproj index fd60f73f..8244c8e5 100644 --- a/src/CacheManager.Serialization.ProtoBuf/CacheManager.Serialization.ProtoBuf.csproj +++ b/src/CacheManager.Serialization.ProtoBuf/CacheManager.Serialization.ProtoBuf.csproj @@ -3,7 +3,7 @@ CacheManager extension package providing ProtoBuf serialization for distributed caches. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features, the ProtoBuf serializer can be used in place of the default Binary Serializer Wenisman;MichaConrad - netstandard2.0;net45 + netstandard2.0;net6.0;net8.0 true true Caching;Cache;CacheManager;Distributed Cache;Serialization;Protobuf @@ -12,6 +12,6 @@ - + \ No newline at end of file diff --git a/src/CacheManager.Serialization.ProtoBuf/ProtoBufConfigurationBuilderExtensions.cs b/src/CacheManager.Serialization.ProtoBuf/ProtoBufConfigurationBuilderExtensions.cs index 2c5402dd..3566389a 100644 --- a/src/CacheManager.Serialization.ProtoBuf/ProtoBufConfigurationBuilderExtensions.cs +++ b/src/CacheManager.Serialization.ProtoBuf/ProtoBufConfigurationBuilderExtensions.cs @@ -1,4 +1,5 @@ -using CacheManager.Serialization.ProtoBuf; +using System; +using CacheManager.Serialization.ProtoBuf; namespace CacheManager.Core { @@ -14,7 +15,10 @@ public static class ProtoBufConfigurationBuilderExtensions /// The builder instance. public static ConfigurationBuilderCachePart WithProtoBufSerializer(this ConfigurationBuilderCachePart part) { - Utility.Guard.NotNull(part, nameof(part)); + if (part is null) + { + throw new ArgumentNullException(nameof(part)); + } return part.WithSerializer(typeof(ProtoBufSerializer)); } diff --git a/src/CacheManager.Serialization.ProtoBuf/ProtoBufSerializer.cs b/src/CacheManager.Serialization.ProtoBuf/ProtoBufSerializer.cs index ca8dee18..0a5c1260 100644 --- a/src/CacheManager.Serialization.ProtoBuf/ProtoBufSerializer.cs +++ b/src/CacheManager.Serialization.ProtoBuf/ProtoBufSerializer.cs @@ -1,7 +1,5 @@ using System; using System.IO; -using System.Linq; -using CacheManager.Core; using CacheManager.Core.Internal; using ProtoBuf; @@ -55,4 +53,4 @@ protected override Type GetOpenGeneric() return _openGenericItemType; } } -} \ No newline at end of file +} diff --git a/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj b/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj index c127bd7b..9d8948e6 100644 --- a/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj +++ b/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj @@ -2,18 +2,18 @@ CacheManager extension package which adds support for Redis as a distributed cache layer. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - net461;netstandard2.0;net50 + net472;netstandard2.0;net80 true true Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached - + - + diff --git a/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs b/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs index a6334a76..c891e853 100644 --- a/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs +++ b/src/CacheManager.StackExchange.Redis/RedisCacheBackplane.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using CacheManager.Core; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using StackExchange.Redis; using static CacheManager.Core.Utility.Guard; @@ -28,7 +28,7 @@ namespace CacheManager.Redis public sealed class RedisCacheBackplane : CacheBackplane { private const int HardLimit = 50000; - private readonly string _channelName; + private readonly RedisChannel _channel; private readonly byte[] _identifier; private readonly ILogger _logger; private readonly RedisConnectionManager _connection; @@ -51,8 +51,8 @@ public RedisCacheBackplane(ICacheManagerConfiguration configuration, ILoggerFact NotNull(configuration, nameof(configuration)); NotNull(loggerFactory, nameof(loggerFactory)); - _logger = loggerFactory.CreateLogger(this); - _channelName = configuration.BackplaneChannelName ?? "CacheManagerBackplane"; + _logger = loggerFactory.CreateLogger(this.GetType()); + _channel = RedisChannel.Literal(configuration.BackplaneChannelName ?? "CacheManagerBackplane"); _identifier = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); var cfg = RedisConfigurations.GetConfiguration(ConfigurationKey); @@ -138,7 +138,7 @@ protected override void Dispose(bool managed) try { _source.Cancel(); - _connection.Subscriber.Unsubscribe(_channelName); + _connection.Subscriber.Unsubscribe(_channel); _timer.Dispose(); } catch @@ -151,7 +151,7 @@ protected override void Dispose(bool managed) private void Publish(byte[] message) { - _connection.Subscriber.Publish(_channelName, message); + _connection.Subscriber.Publish(_channel, message); } private void PublishMessage(BackplaneMessage message) @@ -204,11 +204,10 @@ private void SendMessages(object state) _sending = true; if (state != null && state is bool boolState && boolState == true) { - _logger.LogInfo($"Backplane is sending {_messages.Count} messages triggered by timer."); + _logger.LogInformation($"Backplane is sending {_messages.Count} messages triggered by timer."); } -#if !NET40 + await Task.Delay(50).ConfigureAwait(false); -#endif byte[] msgs = null; lock (_messageLock) { @@ -245,27 +244,18 @@ private void SendMessages(object state) _sending = false; } -#if NET40 - }, - this, - _source.Token, - TaskCreationOptions.None, - TaskScheduler.Default) - .ConfigureAwait(false); -#else }, this, _source.Token, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default) .ConfigureAwait(false); -#endif } private void Subscribe() { _connection.Subscriber.Subscribe( - _channelName, + _channel, (channel, msg) => { try @@ -284,7 +274,7 @@ private void Subscribe() if (_logger.IsEnabled(LogLevel.Information)) { - _logger.LogInfo("Backplane got notified with {0} new messages.", fullMessages.Length); + _logger.LogInformation("Backplane got notified with {0} new messages.", fullMessages.Length); } foreach (var message in fullMessages) @@ -325,7 +315,7 @@ private void Subscribe() } catch (Exception ex) { - _logger.LogWarn(ex, "Error reading backplane message(s)"); + _logger.LogWarning(ex, "Error reading backplane message(s)"); } }, CommandFlags.FireAndForget); diff --git a/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs b/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs index d468a922..92ea0a22 100644 --- a/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs +++ b/src/CacheManager.StackExchange.Redis/RedisCacheHandle.cs @@ -1,10 +1,11 @@ using System; using System.Collections.Generic; +using System.Data.Common; using System.Linq; using System.Text; using CacheManager.Core; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using StackExchange.Redis; using static CacheManager.Core.Utility.Guard; @@ -29,18 +30,32 @@ public class RedisCacheHandle : BaseCacheHandle private static readonly string _scriptAdd = $@" if redis.call('HSETNX', KEYS[1], '{HashFieldValue}', ARGV[1]) == 1 then + if ARGV[7] ~= nil then + if (redis.call('HMSET', ARGV[7], KEYS[1], 'regionKey')) then + else + return -2 + end + end + local result=redis.call('HMSET', KEYS[1], '{HashFieldType}', ARGV[2], '{HashFieldExpirationMode}', ARGV[3], '{HashFieldExpirationTimeout}', ARGV[4], '{HashFieldCreated}', ARGV[5], '{HashFieldVersion}', 1, '{HashFieldUsesDefaultExp}', ARGV[6]) if ARGV[3] > '1' and ARGV[4] ~= '0' then redis.call('PEXPIRE', KEYS[1], ARGV[4]) else redis.call('PERSIST', KEYS[1]) end - return result + return 1 else return nil end"; private static readonly string _scriptPut = $@" +if ARGV[7] ~= nil then + if (redis.call('HMSET', ARGV[7], KEYS[1], 'regionKey')) then + else + return -2 + end +end + local result=redis.call('HMSET', KEYS[1], '{HashFieldValue}', ARGV[1], '{HashFieldType}', ARGV[2], '{HashFieldExpirationMode}', ARGV[3], '{HashFieldExpirationTimeout}', ARGV[4], '{HashFieldCreated}', ARGV[5], '{HashFieldUsesDefaultExp}', ARGV[6]) redis.call('HINCRBY', KEYS[1], '{HashFieldVersion}', 1) if ARGV[3] > '1' and ARGV[4] ~= '0' then @@ -48,7 +63,7 @@ public class RedisCacheHandle : BaseCacheHandle else redis.call('PERSIST', KEYS[1]) end -return result"; +return 1"; // script should also update expire now. If sliding, update the sliding window private static readonly string _scriptUpdate = $@" @@ -101,7 +116,7 @@ public RedisCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHa NotNull(configuration, nameof(configuration)); EnsureNotNull(serializer, "A serializer is required for the redis cache handle"); - Logger = loggerFactory.CreateLogger(this); + Logger = loggerFactory.CreateLogger(this.GetType()); _managerConfiguration = managerConfiguration; _valueConverter = new RedisValueConverter(serializer); _redisConfiguration = RedisConfigurations.GetConfiguration(configuration.Key); @@ -123,13 +138,13 @@ public RedisCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHa { if (!cfg.Value.Contains("E")) { - Logger.LogWarn("Server {0} is missing configuration value 'E' in notify-keyspace-events to enable keyevents.", cfg.Key); + Logger.LogWarning("Server {0} is missing configuration value 'E' in notify-keyspace-events to enable keyevents.", cfg.Key); } if (!(cfg.Value.Contains("A") || (cfg.Value.Contains("x") && cfg.Value.Contains("e")))) { - Logger.LogWarn("Server {0} is missing configuration value 'A' or 'x' and 'e' in notify-keyspace-events to enable keyevents for expired and evicted keys.", cfg.Key); + Logger.LogWarning("Server {0} is missing configuration value 'A' or 'x' and 'e' in notify-keyspace-events to enable keyevents for expired and evicted keys.", cfg.Key); } } } @@ -162,7 +177,7 @@ public override int Count { if (_redisConfiguration.TwemproxyEnabled) { - Logger.LogWarn("'Count' cannot be calculated. Twemproxy mode is enabled which does not support accessing the servers collection."); + Logger.LogWarning("'Count' cannot be calculated. Twemproxy mode is enabled which does not support accessing the servers collection."); return 0; } @@ -497,7 +512,7 @@ private CacheItem GetCacheItemAndVersion(string key, string region, } else { - Logger.LogWarn("Expiration mode and timeout are set but are not valid '{0}', '{1}'.", expirationModeItem, timeoutItem); + Logger.LogWarning("Expiration mode and timeout are set but are not valid '{0}', '{1}'.", expirationModeItem, timeoutItem); } } @@ -580,7 +595,7 @@ protected CacheItem GetCacheItemInternalNoScript(string key, string } else { - Logger.LogWarn("Expiration mode and timeout are set but are not valid '{0}', '{1}'.", expirationModeItem, timeoutItem); + Logger.LogWarning("Expiration mode and timeout are set but are not valid '{0}', '{1}'.", expirationModeItem, timeoutItem); } } @@ -625,7 +640,7 @@ protected CacheItem GetCacheItemInternalNoScript(string key, string /// with the new value. If the item doesn't exist, the item will be added to the cache. /// /// The CacheItem to be added to the cache. - protected override void PutInternal(CacheItem item) + protected internal override void PutInternal(CacheItem item) => base.PutInternal(item); /// @@ -677,22 +692,22 @@ protected override bool RemoveInternal(string key, string region) private void SubscribeKeyspaceNotifications() { _connection.Subscriber.Subscribe( - $"__keyevent@{_redisConfiguration.Database}__:expired", - (channel, key) => - { - var tupple = ParseKey(key); - if (Logger.IsEnabled(LogLevel.Debug)) - { - Logger.LogDebug("Got expired event for key '{0}:{1}'", tupple.Item2, tupple.Item1); - } - - // we cannot return the original value here because we don't have it - TriggerCacheSpecificRemove(tupple.Item1, tupple.Item2, CacheItemRemovedReason.Expired, null); - }); + channel: RedisChannel.Literal($"__keyevent@{_redisConfiguration.Database}__:expired"), + handler: (channel, key) => + { + var tupple = ParseKey(key); + if (Logger.IsEnabled(LogLevel.Debug)) + { + Logger.LogDebug("Got expired event for key '{0}:{1}'", tupple.Item2, tupple.Item1); + } + + // we cannot return the original value here because we don't have it + TriggerCacheSpecificRemove(tupple.Item1, tupple.Item2, CacheItemRemovedReason.Expired, null); + }); _connection.Subscriber.Subscribe( - $"__keyevent@{_redisConfiguration.Database}__:evicted", - (channel, key) => + channel: RedisChannel.Literal($"__keyevent@{_redisConfiguration.Database}__:evicted"), + handler: (channel, key) => { var tupple = ParseKey(key); if (Logger.IsEnabled(LogLevel.Debug)) @@ -705,8 +720,8 @@ private void SubscribeKeyspaceNotifications() }); _connection.Subscriber.Subscribe( - $"__keyevent@{_redisConfiguration.Database}__:del", - (channel, key) => + channel: RedisChannel.Literal($"__keyevent@{_redisConfiguration.Database}__:del"), + handler: (channel, key) => { var tupple = ParseKey(key); if (Logger.IsEnabled(LogLevel.Debug)) @@ -851,7 +866,8 @@ private bool Set(CacheItem item, When when, bool sync = false) (int)item.ExpirationMode, (long)item.ExpirationTimeout.TotalMilliseconds, item.CreatedUtc.Ticks, - item.UsesExpirationDefaults + item.UsesExpirationDefaults, + string.IsNullOrWhiteSpace(item.Region) ? string.Empty : item.Region }; RedisResult result; @@ -864,54 +880,32 @@ private bool Set(CacheItem item, When when, bool sync = false) result = Eval(ScriptType.Put, fullKey, parameters, flags); } - if (result == null) + if (result.IsNull && flags.HasFlag(CommandFlags.FireAndForget)) { - if (flags.HasFlag(CommandFlags.FireAndForget)) - { - if (!string.IsNullOrWhiteSpace(item.Region)) - { - // setting region lookup key if region is being used - _connection.Database.HashSet(item.Region, fullKey, "regionKey", When.Always, CommandFlags.FireAndForget); - } - - // put runs via fire and forget, so we don't get a result back - return true; - } - - // should never happen, something went wrong with the script - throw new InvalidOperationException("Something went wrong adding an item, result must not be null."); + // fire and forget will not return a result. + return true; } - else + + if (result.IsNull && when == When.NotExists) { - if (result.IsNull && when == When.NotExists) + // add failed because element exists already + if (Logger.IsEnabled(LogLevel.Debug)) { - // add failed because element exists already - if (Logger.IsEnabled(LogLevel.Debug)) - { - Logger.LogDebug("DB {0} | Failed to add item [{1}] because it exists.", _connection.Database.Database, item.ToString()); - } - - return false; + Logger.LogDebug("DB {0} | Failed to add item [{1}] because it exists.", _connection.Database.Database, item.ToString()); } - var resultValue = (RedisValue)result; - - if (resultValue.HasValue && resultValue.ToString().Equals("OK", StringComparison.OrdinalIgnoreCase)) - { - // Added successfully: - if (!string.IsNullOrWhiteSpace(item.Region)) - { - // setting region lookup key if region is being used - // we cannot do that within the lua because the region could be on another cluster node! - _connection.Database.HashSet(item.Region, fullKey, "regionKey", When.Always, CommandFlags.FireAndForget); - } + return false; + } - return true; - } + var resultValue = (RedisValue)result; - Logger.LogWarn("DB {0} | Failed to set item [{1}]: {2}.", _connection.Database.Database, item.ToString(), resultValue.ToString()); - return false; + if (resultValue.HasValue && resultValue == 1) + { + return true; } + + Logger.LogWarning("DB {0} | Failed to set item [{1}]: {2}.", _connection.Database.Database, item.ToString(), resultValue.ToString()); + return false; } private bool SetNoScript(CacheItem item, When when, bool sync = false) @@ -1006,7 +1000,7 @@ private RedisResult Eval(ScriptType scriptType, RedisKey redisKey, RedisValue[] } catch (RedisServerException ex) when (ex.Message.StartsWith("NOSCRIPT", StringComparison.OrdinalIgnoreCase)) { - Logger.LogInfo("Received NOSCRIPT from server. Reloading scripts..."); + Logger.LogInformation("Received NOSCRIPT from server. Reloading scripts..."); LoadScripts(); // retry @@ -1018,7 +1012,7 @@ private void LoadScripts() { lock (_lockObject) { - Logger.LogInfo("Loading scripts."); + Logger.LogInformation("Loading scripts."); var putLua = LuaScript.Prepare(_scriptPut); var addLua = LuaScript.Prepare(_scriptAdd); diff --git a/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs b/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs index 983d583b..8665ecbc 100644 --- a/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs +++ b/src/CacheManager.StackExchange.Redis/RedisConnectionManager.cs @@ -4,7 +4,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using StackExchange.Redis; using static CacheManager.Core.Utility.Guard; @@ -18,6 +18,7 @@ internal class RedisConnectionManager private readonly ILogger _logger; private readonly string _connectionString; private readonly RedisConfiguration _configuration; + private readonly ILoggerFactory _loggerFactory; public RedisConnectionManager(RedisConfiguration configuration, ILoggerFactory loggerFactory) { @@ -26,9 +27,10 @@ public RedisConnectionManager(RedisConfiguration configuration, ILoggerFactory l NotNullOrWhiteSpace(configuration.ConnectionString, nameof(RedisConfiguration.ConnectionString)); _configuration = configuration; + _loggerFactory = loggerFactory; _connectionString = configuration.ConnectionString; - _logger = loggerFactory.CreateLogger(this); + _logger = loggerFactory.CreateLogger(this.GetType()); } public IEnumerable Servers @@ -150,10 +152,10 @@ public IConnectionMultiplexer Connect() { if (_logger.IsEnabled(LogLevel.Information)) { - _logger.LogInfo("Trying to connect with the following configuration: '{0}'", RemoveCredentials(_connectionString)); + _logger.LogInformation("Trying to connect with the following configuration: '{0}'", RemoveCredentials(_connectionString)); } - connection = ConnectionMultiplexer.Connect(_connectionString, new LogWriter(_logger)); + connection = ConnectionMultiplexer.Connect(_connectionString, o => o.LoggerFactory = _loggerFactory); if (!connection.IsConnected) { @@ -163,7 +165,7 @@ public IConnectionMultiplexer Connect() connection.ConnectionRestored += (sender, args) => { - _logger.LogInfo(args.Exception, "Connection restored, type: '{0}', failure: '{1}'", args.ConnectionType, args.FailureType); + _logger.LogInformation(args.Exception, "Connection restored, type: '{0}', failure: '{1}'", args.ConnectionType, args.FailureType); }; if (!_configuration.TwemproxyEnabled) @@ -203,30 +205,5 @@ private static string RemoveCredentials(string value) return Regex.Replace(value, @"password\s*=\s*[^,]*", "password=****", RegexOptions.IgnoreCase); } - - private class LogWriter : StringWriter - { - private readonly ILogger _logger; - - public LogWriter(ILogger logger) - { - _logger = logger; - } - - public override void Write(char value) - { - } - - public override void Write(string value) - { - _logger.LogDebug(value); - } - - public override void Write(char[] buffer, int index, int count) - { - var logValue = new string(buffer, index, count); - _logger.LogDebug(RemoveCredentials(logValue)); - } - } } } diff --git a/src/CacheManager.StackExchange.Redis/RetryHelper.cs b/src/CacheManager.StackExchange.Redis/RetryHelper.cs index 278301d1..09406683 100644 --- a/src/CacheManager.StackExchange.Redis/RetryHelper.cs +++ b/src/CacheManager.StackExchange.Redis/RetryHelper.cs @@ -1,6 +1,5 @@ using System; -using System.Threading.Tasks; -using CacheManager.Core.Logging; +using Microsoft.Extensions.Logging; using StackExchange.Redis; namespace CacheManager.Redis @@ -36,14 +35,7 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg throw; } - logger.LogWarn(ex, WarningMessage, tries, retries); - - // Removed all async delay to prevent potential deadlocks -////#if NET40 -//// TaskEx.Delay(timeOut).Wait(); -////#else -//// Task.Delay(timeOut).Wait(); -////#endif + logger.LogWarning(ex, WarningMessage, tries, retries); } catch (RedisConnectionException ex) { @@ -53,14 +45,7 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg throw; } - logger.LogWarn(ex, WarningMessage, tries, retries); - - // Removed all async delay to prevent potential deadlocks -////#if NET40 -//// TaskEx.Delay(timeOut).Wait(); -////#else -//// Task.Delay(timeOut).Wait(); -////#endif + logger.LogWarning(ex, WarningMessage, tries, retries); } catch (TimeoutException ex) { @@ -70,13 +55,7 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg throw; } - logger.LogWarn(ex, WarningMessage, tries, retries); - // Removed all async delay to prevent potential deadlocks -////#if NET40 -//// TaskEx.Delay(timeOut).Wait(); -////#else -//// Task.Delay(timeOut).Wait(); -////#endif + logger.LogWarning(ex, WarningMessage, tries, retries); } catch (AggregateException aggregateException) { @@ -95,18 +74,12 @@ public static T Retry(Func retryme, int timeOut, int retries, ILogger logg if (e is RedisConnectionException || e is System.TimeoutException || e is RedisServerException) { - logger.LogWarn(e, WarningMessage, tries, retries); - // Removed all async delay to prevent potential deadlocks -////#if NET40 -//// TaskEx.Delay(timeOut).Wait(); -////#else -//// Task.Delay(timeOut).Wait(); -////#endif + logger.LogWarning(e, WarningMessage, tries, retries); return true; } - logger.LogCritical("Unhandled exception occurred.", aggregateException); + logger.LogCritical(aggregateException, "Unhandled exception occurred."); return false; }); } diff --git a/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj b/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj index e65faaa9..3c867feb 100644 --- a/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj +++ b/src/CacheManager.SystemRuntimeCaching/CacheManager.SystemRuntimeCaching.csproj @@ -2,7 +2,7 @@ CacheManager extension package which adds System.Runtime.Caching.MemoryCache as an option for a local in-memory cache layer. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - net45;netstandard2.0;net50 + net472;netstandard2.0;net8.0 true true Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached @@ -10,10 +10,13 @@ - + - - + + + + + \ No newline at end of file diff --git a/src/CacheManager.SystemRuntimeCaching/MemoryCacheHandle`1.cs b/src/CacheManager.SystemRuntimeCaching/MemoryCacheHandle`1.cs index ec48653c..d30b9be7 100644 --- a/src/CacheManager.SystemRuntimeCaching/MemoryCacheHandle`1.cs +++ b/src/CacheManager.SystemRuntimeCaching/MemoryCacheHandle`1.cs @@ -4,8 +4,7 @@ using System.Runtime.Caching; using CacheManager.Core; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; -using static CacheManager.Core.Utility.Guard; +using Microsoft.Extensions.Logging; namespace CacheManager.SystemRuntimeCaching { @@ -49,18 +48,23 @@ public MemoryCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheH public MemoryCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory, RuntimeMemoryCacheOptions memoryCacheOptions) : base(managerConfiguration, configuration) { - NotNull(configuration, nameof(configuration)); - NotNull(loggerFactory, nameof(loggerFactory)); - Logger = loggerFactory.CreateLogger(this); + if (configuration is null) + { + throw new ArgumentNullException(nameof(configuration)); + } + + if (loggerFactory is null) + { + throw new ArgumentNullException(nameof(loggerFactory)); + } + + Logger = loggerFactory.CreateLogger(this.GetType()); _cacheName = configuration.Name; //if (_cacheName.ToUpper(CultureInfo.InvariantCulture).Equals(DefaultName.ToUpper(CultureInfo.InvariantCulture))) if (DefaultName.Equals(_cacheName, StringComparison.InvariantCultureIgnoreCase)) { - //we can't change default cache configuration by code, can we? - Ensure(memoryCacheOptions == null, "MemoryCache Default instance can only be configured through app/web.config."); - _cache = MemoryCache.Default; } else @@ -113,7 +117,11 @@ public override bool Exists(string key) /// public override bool Exists(string key, string region) { - NotNullOrWhiteSpace(region, nameof(region)); + if (string.IsNullOrWhiteSpace(region)) + { + throw new ArgumentException($"'{nameof(region)}' cannot be null or whitespace.", nameof(region)); + } + var fullKey = GetItemKey(key, region); return _cache.Contains(fullKey); } @@ -317,7 +325,10 @@ private CacheItemPolicy GetPolicy(CacheItem item) private string GetItemKey(string key, string region = null) { - NotNullOrWhiteSpace(key, nameof(key)); + if (string.IsNullOrWhiteSpace(key)) + { + throw new ArgumentException($"'{nameof(key)}' cannot be null or whitespace.", nameof(key)); + } if (string.IsNullOrWhiteSpace(region)) { diff --git a/src/CacheManager.Web/CacheManager.Web.csproj b/src/CacheManager.Web/CacheManager.Web.csproj deleted file mode 100644 index f6d2de1a..00000000 --- a/src/CacheManager.Web/CacheManager.Web.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - CacheManager extension package which uses System.Web.Caching and also comes with a custom OutputCache provider. CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. - net45 - true - true - Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached - - - - - - - - - \ No newline at end of file diff --git a/src/CacheManager.Web/CacheManagerOutputCacheProvider.cs b/src/CacheManager.Web/CacheManagerOutputCacheProvider.cs deleted file mode 100644 index f6014622..00000000 --- a/src/CacheManager.Web/CacheManagerOutputCacheProvider.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.Collections.Specialized; -using System.Reflection; -using System.Web.Caching; -using CacheManager.Core; -using static CacheManager.Core.Utility.Guard; - -namespace CacheManager.Web -{ - /// - /// Implements a simple System.Web.Caching.OutputCacheProvider which uses a cache manager - /// configured via web.config. - /// - public class CacheManagerOutputCacheProvider : OutputCacheProvider - { - private static readonly object _configLock = new object(); - private static ICacheManager _cacheInstance; - private static bool _isInitialized = false; - - /// - /// Gets the cache. - /// - /// The cache. - /// - /// Output cache provider has not yet been initialized. - /// - public static ICacheManager Cache - { - get - { - Ensure(_isInitialized, "Output cache provider has not yet been initialized."); - - return _cacheInstance; - } - } - - /// - /// Inserts the specified entry into the output cache. - /// - /// A unique identifier for . - /// The content to add to the output cache. - /// The time and date on which the cached entry expires. - /// A reference to the specified provider. - public override object Add(string key, object entry, DateTime utcExpiry) - { - if (!_cacheInstance.Add(GetCacheItem(key, entry, utcExpiry))) - { - return Cache.Get(key); - } - - return null; - } - - /// - /// Returns a reference to the specified entry in the output cache. - /// - /// A unique identifier for a cached entry in the output cache. - /// - /// The value that identifies the specified entry in the cache, or - /// null if the specified entry is not in the cache. - /// - public override object Get(string key) => Cache.Get(key); - - /// - /// Initializes the provider. - /// - /// The friendly name of the provider. - /// - /// A collection of the name/value pairs representing the provider-specific attributes - /// specified in the configuration for this provider. - /// - /// Might be re thrown. - public override void Initialize(string name, NameValueCollection config) - { - NotNull(config, nameof(config)); - - try - { - if (!_isInitialized) - { - lock (_configLock) - { - if (!_isInitialized) - { - var cacheName = config["cacheName"]; - if (string.IsNullOrWhiteSpace(cacheName)) - { - cacheName = "default"; - } - - InitializeStaticCache(cacheName); - _isInitialized = true; - } - } - } - - base.Initialize(name, config); - } - catch (TargetInvocationException ex) - { - if (ex.InnerException != null) - { - throw new InvalidOperationException(ex.InnerException.Message, ex.InnerException); - } - - throw; - } - } - - /// - /// Removes the specified entry from the output cache. - /// - /// The unique identifier for the entry to remove from the output cache. - public override void Remove(string key) - { - Cache.Remove(key); - } - - /// - /// Inserts the specified entry into the output cache, overwriting the entry if it is - /// already cached. - /// - /// A unique identifier for . - /// The content to add to the output cache. - /// - /// The time and date on which the cached expires. - /// - public override void Set(string key, object entry, DateTime utcExpiry) - { - Cache.Put(GetCacheItem(key, entry, utcExpiry)); - } - - private static CacheItem GetCacheItem(string key, object entry, DateTime utcExpiry) - { - CacheItem newItem; - if (utcExpiry != default(DateTime) && utcExpiry != DateTime.MaxValue) - { - var timeout = TimeSpan.FromTicks(utcExpiry.Ticks - DateTime.UtcNow.Ticks); - if (timeout.TotalMilliseconds < 0) - { - timeout = TimeSpan.FromSeconds(1); - } - - newItem = new CacheItem(key, entry, ExpirationMode.Absolute, timeout); - } - else - { - newItem = new CacheItem(key, entry); - } - - return newItem; - } - - private static void InitializeStaticCache(string cacheName) - { - _cacheInstance = CacheFactory.FromConfiguration(cacheName); - } - } -} \ No newline at end of file diff --git a/src/CacheManager.Web/ContextFactory.cs b/src/CacheManager.Web/ContextFactory.cs deleted file mode 100644 index 4a5479e0..00000000 --- a/src/CacheManager.Web/ContextFactory.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Web; - -namespace CacheManager.Web -{ - internal static class ContextFactory - { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "HttpContext", Justification = "External naming")] - public static HttpContextBase CreateContext() - { - if (HttpContext.Current == null) - { - throw new InvalidOperationException("HttpContext.Current is required for System.Web caching and must not be null."); - } - - return new HttpContextWrapper(HttpContext.Current); - } - } -} \ No newline at end of file diff --git a/src/CacheManager.Web/Properties/AssemblyInfo.cs b/src/CacheManager.Web/Properties/AssemblyInfo.cs deleted file mode 100644 index a46fb3be..00000000 --- a/src/CacheManager.Web/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System; - -[assembly: CLSCompliant(true)] \ No newline at end of file diff --git a/src/CacheManager.Web/SystemWebCacheHandle`1.cs b/src/CacheManager.Web/SystemWebCacheHandle`1.cs deleted file mode 100644 index c982a220..00000000 --- a/src/CacheManager.Web/SystemWebCacheHandle`1.cs +++ /dev/null @@ -1,399 +0,0 @@ -using System; -using System.Web; -using System.Web.Caching; -using CacheManager.Core; -using CacheManager.Core.Internal; -using CacheManager.Core.Logging; -using static CacheManager.Core.Utility.Guard; - -// TODO: Make this thing obsolete, not tested, outdated. -namespace CacheManager.Web -{ - /// - /// Implementation based on . - /// - /// The type of the cache value. - /// - /// Although the MemoryCache doesn't support regions nor a RemoveAll/Clear method, we will - /// implement it via cache dependencies. - /// - public class SystemWebCacheHandle : BaseCacheHandle - { - private string _instanceKey = null; - private int _instanceKeyLength; - - /// - /// Initializes a new instance of the class. - /// - /// The manager configuration. - /// The cache handle configuration. - /// The logger factory. - public SystemWebCacheHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory) - : base(managerConfiguration, configuration) - { - NotNull(loggerFactory, nameof(loggerFactory)); - Logger = loggerFactory.CreateLogger(this); - - _instanceKey = Guid.NewGuid().ToString(); - _instanceKeyLength = _instanceKey.Length; - - CreateInstanceToken(); - } - - /// - /// Gets the number of items the cache handle currently maintains. - /// - /// The count. - public override int Count => (int)Context.Cache.Count; - - /// - /// Gets the http context being used to get the Cache instance. - /// This implementation requires to be not null. - /// - /// The http context instance. - protected virtual HttpContextBase Context => ContextFactory.CreateContext(); - - /// - protected override ILogger Logger { get; } - - /// - /// Clears this cache, removing all items in the base cache and all regions. - /// - public override void Clear() - { - Context.Cache.Remove(_instanceKey); - CreateInstanceToken(); - } - - /// - /// Clears the cache region, removing all items from the specified only. - /// - /// The cache region. - public override void ClearRegion(string region) => - Context.Cache.Remove(GetRegionTokenKey(region)); - - /// - public override bool Exists(string key) - { - return GetCacheItemInternal(key) != null; - } - - /// - public override bool Exists(string key, string region) - { - NotNullOrWhiteSpace(region, nameof(region)); - - return GetCacheItemInternal(key, region) != null; - } - - /// - /// Adds a value to the cache. - /// - /// - /// Be aware that sliding expiration for this cache works only if the timeout is set to more than 2000ms. - /// - /// The CacheItem to be added to the cache. - /// - /// true if the key was not already added to the cache, false otherwise. - /// - protected override bool AddInternalPrepared(CacheItem item) - { - var key = GetItemKey(item); - var settings = GetCacheSettings(item); - - if (settings.SlidingExpire.TotalMilliseconds > 0 && settings.SlidingExpire.TotalMilliseconds < 2000) - { - Logger.LogWarn( - "System.Web.Caching.Cache sliding expiration works only with a value larger than 2000ms, " - + $"but you configured '{settings.SlidingExpire.TotalMilliseconds}' for key {item.Key}:{item.Region}."); - } - - var result = Context.Cache.Add( - key: key, - value: item, - dependencies: settings.Dependency, - absoluteExpiration: settings.AbsoluteExpire, - slidingExpiration: settings.SlidingExpire, - priority: CacheItemPriority.Normal, - onRemoveCallback: ItemRemoved); - - // result will be the existing value if the key is already stored, the new value will not override the key - return result == null; - } - - /// - /// Gets a CacheItem for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The CacheItem. - protected override CacheItem GetCacheItemInternal(string key) => GetCacheItemInternal(key, null); - - /// - /// Gets a CacheItem for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The cache region. - /// The CacheItem. - protected override CacheItem GetCacheItemInternal(string key, string region) - { - var fullKey = GetItemKey(key, region); - var item = Context.Cache.Get(fullKey) as CacheItem; - - if (item == null) - { - return null; - } - - // cache.Get eventually triggers eviction callback, but just in case... - if (item.IsExpired) - { - RemoveInternal(item.Key, item.Region); - TriggerCacheSpecificRemove(item.Key, item.Region, Core.Internal.CacheItemRemovedReason.Expired, item.Value); - return null; - } - - return item; - } - - /// - /// Puts the into the cache. If the item exists it will get updated - /// with the new value. If the item doesn't exist, the item will be added to the cache. - /// - /// - /// Be aware that sliding expiration for this cache works only if the timeout is set to more than 2000ms. - /// - /// The CacheItem to be added to the cache. - protected override void PutInternalPrepared(CacheItem item) - { - var key = GetItemKey(item); - var settings = GetCacheSettings(item); - - if (settings.SlidingExpire.TotalMilliseconds > 0 && settings.SlidingExpire.TotalMilliseconds < 2000) - { - Logger.LogWarn( - "System.Web.Caching.Cache sliding expiration works only with a value larger than 2000ms, " - + $"but you configured '{settings.SlidingExpire.TotalMilliseconds}' for key {item.Key}:{item.Region}."); - } - - Context.Cache.Insert( - key: key, - value: item, - dependencies: settings.Dependency, - absoluteExpiration: settings.AbsoluteExpire, - slidingExpiration: settings.SlidingExpire, - priority: CacheItemPriority.Normal, - onRemoveCallback: ItemRemoved); - } - - /// - /// Removes a value from the cache for the specified key. - /// - /// The key being used to identify the item within the cache. - /// - /// true if the key was found and removed from the cache, false otherwise. - /// - protected override bool RemoveInternal(string key) => RemoveInternal(key, null); - - /// - /// Removes a value from the cache for the specified key. - /// - /// The key being used to identify the item within the cache. - /// The cache region. - /// - /// true if the key was found and removed from the cache, false otherwise. - /// - protected override bool RemoveInternal(string key, string region) - { - var fullKey = GetItemKey(key, region); - var obj = Context.Cache.Remove(fullKey); - - return obj != null; - } - - private static bool IsExpired(CacheItem item) - { - var now = DateTime.UtcNow; - if (item.ExpirationMode == ExpirationMode.Absolute - && item.CreatedUtc.Add(item.ExpirationTimeout) < now) - { - return true; - } - else if (item.ExpirationMode == ExpirationMode.Sliding - && item.LastAccessedUtc.Add(item.ExpirationTimeout) < now) - { - return true; - } - - return false; - } - - private void CreateInstanceToken() - { - // don't add a new key while we are disposing our instance - if (!Disposing) - { - CacheItemRemovedCallback callback = (key, item, reason) => - { - _instanceKey = Guid.NewGuid().ToString(); - _instanceKeyLength = _instanceKey.Length; - }; - - var instanceItem = new CacheItem(_instanceKey, _instanceKey); - Context.Cache.Add( - _instanceKey, - instanceItem, - null, - Cache.NoAbsoluteExpiration, - Cache.NoSlidingExpiration, - CacheItemPriority.NotRemovable, - callback); - } - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "We don't own the instance")] - private void CreateRegionToken(string region) - { - var key = GetRegionTokenKey(region); - - // add region token with dependency on our instance token, so that all regions get - // removed whenever the instance gets cleared. - var dependency = new CacheDependency(null, new[] { _instanceKey }); - Context.Cache.Add(key, region, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); - } - - private string GetItemKey(CacheItem item) => GetItemKey(item?.Key, item?.Region); - - private string GetItemKey(string key, string region = null) - { - NotNullOrWhiteSpace(key, nameof(key)); - - if (string.IsNullOrWhiteSpace(region)) - { - return _instanceKey + ":" + key; - } - - return string.Concat(_instanceKey, "@", region.Length, "@", region, ":", key); - } - - private CacheDependency CreateDependency(CacheItem item) - { - string[] cacheKeys; - - if (string.IsNullOrWhiteSpace(item.Region)) - { - cacheKeys = new string[] { _instanceKey }; - } - else - { - var regionKey = GetRegionTokenKey(item.Region); - if (Context.Cache[regionKey] == null) - { - CreateRegionToken(item.Region); - } - - cacheKeys = new string[] { _instanceKey, regionKey }; - } - - return new CacheDependency(null, cacheKeys); - } - - private string GetRegionTokenKey(string region) - { - var key = string.Concat(_instanceKey, "_", region); - return key; - } - - private void ItemRemoved(string fullKey, object item, System.Web.Caching.CacheItemRemovedReason reason) - { - if (string.IsNullOrWhiteSpace(fullKey)) - { - return; - } - - // ignore manually removed items, stats will be updated already - if (reason == System.Web.Caching.CacheItemRemovedReason.Removed) - { - return; - } - - bool isToken; - bool hasRegion; - string key; - string region; - ParseKeyParts(_instanceKeyLength, fullKey, out isToken, out hasRegion, out region, out key); - - if (!isToken) - { - if (hasRegion) - { - Stats.OnRemove(region); - } - else - { - Stats.OnRemove(); - } - - var cacheItem = item as CacheItem; - object originalValue = null; - if (item != null) - { - originalValue = cacheItem.Value; - } - - // trigger cachemanager's remove on evicted and expired items - if (reason == System.Web.Caching.CacheItemRemovedReason.Underused) - { - TriggerCacheSpecificRemove(key, region, Core.Internal.CacheItemRemovedReason.Evicted, originalValue); - } - else if (reason == System.Web.Caching.CacheItemRemovedReason.Expired) - { - TriggerCacheSpecificRemove(key, region, Core.Internal.CacheItemRemovedReason.Expired, originalValue); - } - } - } - - private static void ParseKeyParts(int instanceKeyLength, string fullKey, out bool isToken, out bool hasRegion, out string region, out string key) - { - var relevantKey = fullKey.Substring(instanceKeyLength); - isToken = relevantKey[0] == '_'; - hasRegion = false; - region = null; - key = null; - - if (!isToken) - { - hasRegion = relevantKey[0] == '@'; - var regionLenEnd = hasRegion ? relevantKey.IndexOf('@', 1) : -1; - - int regionLen; - regionLen = hasRegion && regionLenEnd > 0 ? int.TryParse(relevantKey.Substring(1, regionLenEnd - 1), out regionLen) ? regionLen : 0 : 0; - hasRegion = hasRegion && regionLen > 0; - - var restKey = hasRegion ? relevantKey.Substring(regionLenEnd + 1) : relevantKey; - region = hasRegion ? restKey.Substring(0, regionLen) : null; - key = restKey.Substring(regionLen + 1); - } - } - - private CacheSettings GetCacheSettings(CacheItem item) - { - var settings = new CacheSettings() - { - Dependency = CreateDependency(item), - AbsoluteExpire = item.ExpirationMode == ExpirationMode.Absolute ? DateTime.UtcNow.Add(item.ExpirationTimeout) : Cache.NoAbsoluteExpiration, - SlidingExpire = item.ExpirationMode == ExpirationMode.Sliding ? item.ExpirationTimeout : Cache.NoSlidingExpiration, - }; - - return settings; - } - - private class CacheSettings - { - public CacheDependency Dependency { get; set; } - - public DateTime AbsoluteExpire { get; set; } = Cache.NoAbsoluteExpiration; - - public TimeSpan SlidingExpire { get; set; } = Cache.NoSlidingExpiration; - } - } -} diff --git a/src/CacheManager.Web/WebConfigurationBuilderExtensions.cs b/src/CacheManager.Web/WebConfigurationBuilderExtensions.cs deleted file mode 100644 index a4b6044c..00000000 --- a/src/CacheManager.Web/WebConfigurationBuilderExtensions.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using CacheManager.Web; - -namespace CacheManager.Core -{ - /// - /// Extensions for the configuration builder specific to System.Runtime.Caching cache handle. - /// - public static class WebConfigurationBuilderExtensions - { - /// - /// Adds a to the cache manager. - /// This handle uses System.Web.Caching.Cache and requires HttpContext.Current to be not null. - /// - /// The builder part. - /// Set this to true if this cache handle should be the source of the backplane. - /// This setting will be ignored if no backplane is configured. - /// - /// The builder part. - /// - /// The builder part. - public static ConfigurationBuilderCacheHandlePart WithSystemWebCacheHandle(this ConfigurationBuilderCachePart part, bool isBackplaneSource = false) - => WithSystemWebCacheHandle(part, Guid.NewGuid().ToString("N"), isBackplaneSource); - - /// - /// Adds a to the cache manager. - /// This handle uses System.Web.Caching.Cache and requires HttpContext.Current to be not null. - /// - /// The builder part. - /// The name to be used for the cache handle instance. - /// Set this to true if this cache handle should be the source of the backplane. - /// This setting will be ignored if no backplane is configured. - /// - /// The builder part. - /// - /// If part is null. - /// Thrown if is null. - public static ConfigurationBuilderCacheHandlePart WithSystemWebCacheHandle(this ConfigurationBuilderCachePart part, string instanceName, bool isBackplaneSource = false) - => part?.WithHandle(typeof(SystemWebCacheHandle<>), instanceName, isBackplaneSource); - } -} \ No newline at end of file diff --git a/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj b/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj index c7d50f35..41f40995 100644 --- a/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj +++ b/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj @@ -2,8 +2,7 @@ CacheManager.MSConfiguration.TypeLoad.Tests Class Library - Micha - netcoreapp5.0;netcoreapp3.1;netcoreapp2.1 + net8.0 CacheManager.MSConfiguration.TypeLoad.Tests CacheManager.MSConfiguration.TypeLoad.Tests true @@ -30,16 +29,8 @@ - - - - - - - - - - - + + + \ No newline at end of file diff --git a/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs b/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs index cd9250a6..caa54b92 100644 --- a/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs +++ b/test/CacheManager.MSConfiguration.TypeLoad.Tests/MicrosoftConfigurationTests.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using FluentAssertions; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; using Xunit; namespace CacheManager.MSConfiguration.TypeLoad.Tests @@ -37,36 +36,6 @@ public void Configuration_CacheHandle_Redis_NotReferenced() action.Should().Throw().WithMessage("*'Redis' could not be loaded*"); } - [Fact] - public void Configuration_CacheHandle_Memcached_NotReferenced() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Memcached"}, - {"cacheManagers:0:handles:0:key", "key"} - }; - - var config = GetConfiguration(data); - Action action = () => config.GetCacheConfiguration("name"); - action.Should().Throw().WithMessage("*'Memcached' could not be loaded*"); - } - - [Fact] - public void Configuration_CacheHandle_Couchbase_NotReferenced() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Couchbase"}, - {"cacheManagers:0:handles:0:key", "key"} - }; - - var config = GetConfiguration(data); - Action action = () => config.GetCacheConfiguration("name"); - action.Should().Throw().WithMessage("*'Couchbase' could not be loaded*"); - } - [Fact] public void Configuration_CacheHandle_SystemRuntime_NotReferenced() { @@ -82,21 +51,6 @@ public void Configuration_CacheHandle_SystemRuntime_NotReferenced() action.Should().Throw().WithMessage("*'SystemRuntime' could not be loaded*"); } - [Fact] - public void Configuration_CacheHandle_Web_NotReferenced() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "SystemWeb"}, - {"cacheManagers:0:handles:0:key", "key"} - }; - - var config = GetConfiguration(data); - Action action = () => config.GetCacheConfiguration("name"); - action.Should().Throw().WithMessage("*'SystemWeb' could not be loaded*"); - } - [Fact] public void Configuration_Serializer_Json_NotReferenced() { diff --git a/test/CacheManager.Tests/CacheFactoryTests.cs b/test/CacheManager.Tests/CacheFactoryTests.cs index 4374abca..8bd75861 100644 --- a/test/CacheManager.Tests/CacheFactoryTests.cs +++ b/test/CacheManager.Tests/CacheFactoryTests.cs @@ -16,7 +16,7 @@ public class CacheFactoryTests [Fact] public void ConfigurationBuilder_EmptyCtor() { - var builder = new ConfigurationBuilder(); + var builder = new CacheConfigurationBuilder(); var cfg = builder.Build(); cfg.Should().NotBeNull(); @@ -26,7 +26,7 @@ public void ConfigurationBuilder_EmptyCtor() [Fact] public void ConfigurationBuilder_NamedCtorNull() { - Action act = () => new ConfigurationBuilder((string)null); + Action act = () => new CacheConfigurationBuilder((string)null); act.Should().Throw() .And.ParamName.Equals("name"); @@ -35,7 +35,7 @@ public void ConfigurationBuilder_NamedCtorNull() [Fact] public void ConfigurationBuilder_ForConfigCtorNull() { - Action act = () => new ConfigurationBuilder((ICacheManagerConfiguration)null); + Action act = () => new CacheConfigurationBuilder((ICacheManagerConfiguration)null); act.Should().Throw() .And.ParamName.Equals("forConfiguration"); @@ -44,7 +44,7 @@ public void ConfigurationBuilder_ForConfigCtorNull() [Fact] public void ConfigurationBuilder_NamedForConfigCtorNull() { - Action act = () => new ConfigurationBuilder(null, null); + Action act = () => new CacheConfigurationBuilder(null, null); act.Should().Throw() .And.ParamName.Equals("name"); @@ -53,7 +53,7 @@ public void ConfigurationBuilder_NamedForConfigCtorNull() [Fact] public void ConfigurationBuilder_NamedForConfigCtorNullB() { - Action act = () => new ConfigurationBuilder("name", null); + Action act = () => new CacheConfigurationBuilder("name", null); act.Should().Throw() .And.ParamName.Equals("forConfiguration"); @@ -62,7 +62,7 @@ public void ConfigurationBuilder_NamedForConfigCtorNullB() [Fact] public void ConfigurationBuilder_EmptyCtorAdd() { - var builder = new ConfigurationBuilder(); + var builder = new CacheConfigurationBuilder(); builder.WithDictionaryHandle(); var cfg = builder.Build(); @@ -72,12 +72,12 @@ public void ConfigurationBuilder_EmptyCtorAdd() [Fact] public void ConfigurationBuilder_ForConfiguration() { - var builder = new ConfigurationBuilder("name"); + var builder = new CacheConfigurationBuilder("name"); builder.WithDictionaryHandle().WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(10)); builder.WithJsonSerializer(); var cfg = builder.Build(); - var forCfg = new ConfigurationBuilder("newName", cfg); + var forCfg = new CacheConfigurationBuilder("newName", cfg); forCfg.WithDictionaryHandle().WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1)); forCfg.WithGzJsonSerializer(); @@ -122,7 +122,7 @@ public void CacheFactory_FromConfig_NullCheck_B() public void CacheFactory_FromConfig_TestInit_A() { // arrange - var config = ConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle()); + var config = CacheConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle()); // act Action act = () => CacheFactory.FromConfiguration(config); @@ -136,7 +136,7 @@ public void CacheFactory_FromConfig_TestInit_A() public void CacheFactory_FromConfig_TestInit_B() { // arrange - var config = ConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle()); + var config = CacheConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle()); // act var cache = CacheFactory.FromConfiguration("custom name", config); @@ -150,7 +150,7 @@ public void CacheFactory_FromConfig_TestInit_B() public void CacheFactory_FromConfig_TestInit_C() { // arrange - var config = ConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle()); + var config = CacheConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle()); // act var cache = CacheFactory.FromConfiguration(typeof(object), "custom name", config) as ICacheManager; @@ -626,7 +626,7 @@ public void CacheFactory_FromConfig_NonGeneric_C() { var cache = CacheFactory.FromConfiguration( typeof(string), - ConfigurationBuilder.BuildConfiguration(cfg => cfg.WithSystemRuntimeCacheHandle())) as ICacheManager; + CacheConfigurationBuilder.BuildConfiguration(cfg => cfg.WithSystemRuntimeCacheHandle())) as ICacheManager; cache.Should().NotBeNull(); cache.CacheHandles.Count().Should().Be(1); diff --git a/test/CacheManager.Tests/CacheManager.Tests.csproj b/test/CacheManager.Tests/CacheManager.Tests.csproj index 2d3e21d1..dd07596c 100644 --- a/test/CacheManager.Tests/CacheManager.Tests.csproj +++ b/test/CacheManager.Tests/CacheManager.Tests.csproj @@ -2,7 +2,7 @@ - net461;netcoreapp2.1;netcoreapp3.1;net50 + net481;net8.0 1.0.0 CacheManager.Tests @@ -42,26 +42,10 @@ - - - - - - - - - - - - - - - - @@ -74,36 +58,25 @@ - - - + + + + + - - - - - - - - - - - + + + + + + - - $(DefineConstants);REDISENABLED;MOCK_HTTPCONTEXT_ENABLED; - - - $(DefineConstants);REDISENABLED; - - + $(DefineConstants);REDISENABLED; - + $(DefineConstants);REDISENABLED; - - \ No newline at end of file diff --git a/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs b/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs index 692f846c..f4b66d92 100644 --- a/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs +++ b/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs @@ -3,8 +3,9 @@ using System.Linq; using CacheManager.Core; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; + using FluentAssertions; +using Microsoft.Extensions.Logging; using Xunit; namespace CacheManager.Tests @@ -289,7 +290,7 @@ public class MockCacheHandle : BaseCacheHandle public MockCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory) : base(managerConfiguration, configuration) { - this.Logger = loggerFactory.CreateLogger(this); + this.Logger = loggerFactory.CreateLogger(this.GetType()); this.AddCall = () => true; this.PutCall = () => { }; this.RemoveCall = () => { }; diff --git a/test/CacheManager.Tests/CacheManagerEventsTest.cs b/test/CacheManager.Tests/CacheManagerEventsTest.cs index affe1967..7c179f4e 100644 --- a/test/CacheManager.Tests/CacheManagerEventsTest.cs +++ b/test/CacheManager.Tests/CacheManagerEventsTest.cs @@ -7,9 +7,10 @@ using System.Threading.Tasks; using CacheManager.Core; using CacheManager.Core.Internal; - using CacheManager.Core.Logging; + using CacheManager.Core.Utility; using FluentAssertions; + using Microsoft.Extensions.Logging; using StackExchange.Redis; using Xunit; using Xunit.Abstractions; @@ -244,7 +245,7 @@ public class SystemRuntimeSpecific : LongRunningEventTestBase [Fact] public async Task Events_SysRuntime_ExpireTriggers() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithSystemRuntimeCacheHandle() .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1)) .Build(); @@ -263,7 +264,7 @@ public async Task Events_SysRuntime_ExpireTriggers() [Trait("category", "Unreliable")] public async Task Events_SysRuntime_ExpireEvictsAbove() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithDictionaryHandle() .And .WithSystemRuntimeCacheHandle() @@ -287,7 +288,7 @@ public class DictionarySpecific : LongRunningEventTestBase [Fact] public async Task Events_Dic_ExpireTriggers() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithDictionaryHandle() .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1)) .Build(); @@ -306,7 +307,7 @@ public async Task Events_Dic_ExpireTriggers() [Trait("category", "Unreliable")] public async Task Events_Dic_ExpireEvictsAbove() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithDictionaryHandle(options: new DictionaryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromMilliseconds(10) }) .And .WithDictionaryHandle(options: new DictionaryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromMilliseconds(10) }) @@ -330,7 +331,7 @@ public class MsMemorySpecific : LongRunningEventTestBase [Fact] public async Task Events_MsMemory_ExpireTriggers() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithMicrosoftMemoryCacheHandle() .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1)) .Build(); @@ -349,7 +350,7 @@ public async Task Events_MsMemory_ExpireTriggers() [Trait("category", "Unreliable")] public async Task Events_MsMemory_ExpireEvictsAbove() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithDictionaryHandle() .And .WithMicrosoftMemoryCacheHandle() @@ -368,52 +369,6 @@ public async Task Events_MsMemory_ExpireEvictsAbove() } } -#if MOCK_HTTPCONTEXT_ENABLED - - // exclusive inner class for parallel exec of this long running test - public class WebCacheSpecific : LongRunningEventTestBase - { - [Fact] - public async Task Events_WebCache_ExpireTriggers() - { - var cfg = new ConfigurationBuilder() - .WithHandle(typeof(SystemWebCacheHandleWrapper<>)) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1)) - .Build(); - - var useKey = Guid.NewGuid().ToString(); - var useRegion = Guid.NewGuid().ToString(); - var result = await RunTest(cfg, useKey, useRegion); - - result.Reason.Should().Be(CacheItemRemovedReason.Expired); - result.Level.Should().Be(1); - result.Key.Should().Be(useKey); - result.Region.Should().Be(useRegion); - } - - [Fact] - [Trait("category", "Unreliable")] - public async Task Events_WebCache_ExpireEvictsAbove() - { - var cfg = new ConfigurationBuilder() - .WithDictionaryHandle() - .And - .WithHandle(typeof(SystemWebCacheHandleWrapper<>)) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1)) - .Build(); - - var useKey = Guid.NewGuid().ToString(); - - var result = await RunTest(cfg, useKey, null, true, false); - - result.Reason.Should().Be(CacheItemRemovedReason.Expired); - result.Level.Should().Be(2); - result.Key.Should().Be(useKey); - result.Region.Should().BeNull(); - } - } -#endif - // exclusive inner class for parallel exec of this long running test public class RedisSpecific : LongRunningEventTestBase { @@ -422,7 +377,7 @@ public class RedisSpecific : LongRunningEventTestBase [Trait("category", "Unreliable")] public async Task Events_Redis_ExpireTriggers() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithRedisConfiguration("redis", $"{TestManagers.RedisHost}:{TestManagers.RedisPort}, allowAdmin=true", 0, true) .WithJsonSerializer() .WithRedisCacheHandle("redis") @@ -444,7 +399,7 @@ public async Task Events_Redis_ExpireTriggers() [Trait("category", "Unreliable")] public async Task Events_Redis_ExpireEvictsAbove() { - var cfg = new ConfigurationBuilder() + var cfg = new CacheConfigurationBuilder() .WithDictionaryHandle(options: new DictionaryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromMilliseconds(10) }) .And .WithRedisConfiguration("redis", $"{TestManagers.RedisHost}:{TestManagers.RedisPort}, allowAdmin=true", 0, true) @@ -585,7 +540,7 @@ public async Task Events_OnRemoveExternal_Redis_UpHandling() { var client = ConnectionMultiplexer.Connect("localhost"); - var config = new ConfigurationBuilder() + var config = new CacheConfigurationBuilder() .WithDictionaryHandle(options: new DictionaryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromMilliseconds(10) }) .And .WithJsonSerializer() @@ -640,7 +595,7 @@ public async Task Events_OnRemoveExternal_Redis_NoneHandling() { var client = ConnectionMultiplexer.Connect("localhost"); - var config = new ConfigurationBuilder() + var config = new CacheConfigurationBuilder() .WithUpdateMode(CacheUpdateMode.None) .WithDictionaryHandle(options: new DictionaryCacheOptions() { ExpirationScanFrequency = TimeSpan.FromMilliseconds(10) }) .And @@ -1185,9 +1140,10 @@ internal void AddCall() private class CustomRemoveEventTestHandle : BaseCacheHandle { - public CustomRemoveEventTestHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration) + public CustomRemoveEventTestHandle(ICacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory) : base(managerConfiguration, configuration) { + this.Logger = loggerFactory.CreateLogger(this.GetType()); } public void TestTrigger(string key, string region, CacheItemRemovedReason reason, object value) @@ -1203,13 +1159,7 @@ public override int Count } } - protected override ILogger Logger - { - get - { - return new NullLogger(); - } - } + protected override ILogger Logger { get; } public override void Clear() { diff --git a/test/CacheManager.Tests/CacheManagerExpirationTest.cs b/test/CacheManager.Tests/CacheManagerExpirationTest.cs index 22bf2d1e..de57bb69 100644 --- a/test/CacheManager.Tests/CacheManagerExpirationTest.cs +++ b/test/CacheManager.Tests/CacheManagerExpirationTest.cs @@ -21,13 +21,6 @@ public async Task Expiration_Sliding_DoesNotExpire_OnGet(T cache) { using (cache) { -#if MOCK_HTTPCONTEXT_ENABLED - if (cache.CacheHandles.OfType>().Any()) - { - // system.web caching doesn't support short sliding expiration. must be higher than 2000ms for some strange reason... - return; - } -#endif var timeout = 100; await TestSlidingExpiration( timeout, @@ -45,13 +38,6 @@ public async Task Expiration_Sliding_DoesNotExpire_OnUpdate(T cache) // see #50, update doesn't copy custom expire settings per item using (cache) { -#if MOCK_HTTPCONTEXT_ENABLED - if (cache.CacheHandles.OfType>().Any()) - { - // system.web caching doesn't support short sliding expiration. must be higher than 2000ms for some strange reason... - return; - } -#endif var timeout = 100; try { @@ -114,55 +100,6 @@ await TestSlidingExpiration( } } } -#if MEMCACHEDENABLED - - public class Memcached - { - [Fact] - [Trait("category", "Memcached")] - [Trait("category", "Unreliable")] - public async Task Memcached_Absolute_DoesExpire() - { - var timeout = 100; - var cache = CacheFactory.Build(settings => - { - settings - .WithMemcachedCacheHandle(MemcachedTests.Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMilliseconds(timeout)); - }); - - using (cache) - { - await TestAbsoluteExpiration( - timeout, - (key) => cache.Add(key, "value"), - (key) => cache.Get(key)); - } - } - - [Fact] - [Trait("category", "Memcached")] - [Trait("category", "Unreliable")] - public async Task Memcached_Sliding_DoesExpire() - { - var timeout = 100; - var cache = CacheFactory.Build(settings => - { - settings - .WithMemcachedCacheHandle(MemcachedTests.Configuration) - .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMilliseconds(timeout)); - }); - - using (cache) - { - await TestSlidingExpiration( - timeout, - (key) => cache.Add(key, "value"), - (key) => cache.Get(key)); - } - } - } -#endif public class MsMemory { diff --git a/test/CacheManager.Tests/CacheManagerSimpleTests.cs b/test/CacheManager.Tests/CacheManagerSimpleTests.cs index c2acb116..d026e646 100644 --- a/test/CacheManager.Tests/CacheManagerSimpleTests.cs +++ b/test/CacheManager.Tests/CacheManagerSimpleTests.cs @@ -26,7 +26,7 @@ public class CacheManagerSimpleTests [Fact] public void CacheManager_NullableTypes_ShouldNotAllowNulls() { - var manager = new BaseCacheManager(ConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle())); + var manager = new BaseCacheManager(CacheConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle())); DateTime? value = new Nullable(); Assert.Null(value); @@ -64,7 +64,7 @@ public void CacheManager_CtorA_NoConfig() public void CacheManager_CtorA_ConfigNoName() { // name should be set from config and default is a Guid - var manager = new BaseCacheManager(ConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle())); + var manager = new BaseCacheManager(CacheConfigurationBuilder.BuildConfiguration(s => s.WithDictionaryHandle())); manager.Name.Should().NotBeNullOrWhiteSpace(); } @@ -74,7 +74,7 @@ public void CacheManager_CtorA_ConfigWithName() { // name should be implicitly set var manager = new BaseCacheManager( - ConfigurationBuilder.BuildConfiguration("newName", s => s.WithDictionaryHandle())); + CacheConfigurationBuilder.BuildConfiguration("newName", s => s.WithDictionaryHandle())); manager.Name.Should().Be("newName"); } diff --git a/test/CacheManager.Tests/InvalidConfigurationValidationTests.cs b/test/CacheManager.Tests/InvalidConfigurationValidationTests.cs index fa605434..f651a3dc 100644 --- a/test/CacheManager.Tests/InvalidConfigurationValidationTests.cs +++ b/test/CacheManager.Tests/InvalidConfigurationValidationTests.cs @@ -20,7 +20,7 @@ public class InvalidConfigurationValidationTests public void Cfg_BuildConfiguration_MissingSettings() { // arrange act - Action act = () => ConfigurationBuilder.BuildConfiguration(null); + Action act = () => CacheConfigurationBuilder.BuildConfiguration(null); // assert act.Should().Throw() @@ -35,7 +35,7 @@ public void Cfg_LoadConfiguration_EmptyString() string cfgName = string.Empty; // act - Action act = () => ConfigurationBuilder.LoadConfiguration(cfgName); + Action act = () => CacheConfigurationBuilder.LoadConfiguration(cfgName); // assert act.Should().Throw() @@ -50,7 +50,7 @@ public void Cfg_LoadConfiguration_NullString() string cfgName = null; // act - Action act = () => ConfigurationBuilder.LoadConfiguration(cfgName); + Action act = () => CacheConfigurationBuilder.LoadConfiguration(cfgName); // assert act.Should().Throw() @@ -68,7 +68,7 @@ public void Cfg_LoadConfiguration_NotExistingCacheCfgName() string cfgName = Guid.NewGuid().ToString(); // act - Action act = () => ConfigurationBuilder.LoadConfiguration(cfgName); + Action act = () => CacheConfigurationBuilder.LoadConfiguration(cfgName); // assert act.Should().Throw() @@ -82,7 +82,7 @@ public void Cfg_LoadConfiguration_NotExistingCacheCfgName() public void Cfg_LoadConfiguration_InvalidSectionName() { // arrange act - Action act = () => ConfigurationBuilder.LoadConfiguration(null, "config"); + Action act = () => CacheConfigurationBuilder.LoadConfiguration(null, "config"); // assert act.Should().Throw() @@ -94,7 +94,7 @@ public void Cfg_LoadConfiguration_InvalidSectionName() public void Cfg_LoadConfiguration_InvalidConfigName() { // arrange act - Action act = () => ConfigurationBuilder.LoadConfiguration("cacheManager", string.Empty); + Action act = () => CacheConfigurationBuilder.LoadConfiguration("cacheManager", string.Empty); // assert act.Should().Throw() @@ -109,7 +109,7 @@ public void Cfg_LoadConfiguration_SectionDoesNotExist() var sectionName = Guid.NewGuid().ToString(); // act - Action act = () => ConfigurationBuilder.LoadConfiguration(sectionName, "configName"); + Action act = () => CacheConfigurationBuilder.LoadConfiguration(sectionName, "configName"); // assert act.Should().Throw() @@ -121,7 +121,7 @@ public void Cfg_LoadConfiguration_SectionDoesNotExist() public void Cfg_LoadConfigurationFile_EmptyCfgFileName() { // arrange act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(string.Empty, "configName"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(string.Empty, "configName"); // assert act.Should().Throw() @@ -133,7 +133,7 @@ public void Cfg_LoadConfigurationFile_EmptyCfgFileName() public void Cfg_LoadConfigurationFile_EmptySectionName() { // arrange act - Action act = () => ConfigurationBuilder.LoadConfigurationFile("file", null, "configName"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile("file", null, "configName"); // assert act.Should().Throw() @@ -145,7 +145,7 @@ public void Cfg_LoadConfigurationFile_EmptySectionName() public void Cfg_LoadConfigurationFile_EmptyConfigName() { // arrange act - Action act = () => ConfigurationBuilder.LoadConfigurationFile("file", "section", null); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile("file", "section", null); // assert act.Should().Throw() @@ -160,7 +160,7 @@ public void Cfg_LoadConfigurationFile_NotExistingCfgFileName() string fileName = "notexistingconfiguration.config"; // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "configName"); // assert act.Should().Throw() @@ -175,7 +175,7 @@ public void Cfg_InvalidCfgFile_MissingCacheManagerCfgName() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.missingName.config"); // act - var exception = Record.Exception(() => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName")); + var exception = Record.Exception(() => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "configName")); // assert exception.Should().NotBeNull(); @@ -189,7 +189,7 @@ public void Cfg_InvalidCfgFile_NoSection() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.noSection.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "configName"); // assert act.Should().Throw() @@ -206,7 +206,7 @@ public void Cfg_InvalidCfgFile_MissingDefId() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.missingDefId.config"); // act - var exception = Record.Exception(() => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName")); + var exception = Record.Exception(() => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "configName")); // assert exception.Should().NotBeNull(); @@ -221,7 +221,7 @@ public void Cfg_InvalidCfgFile_InvalidType() // act var exception = Record.Exception(() => CacheFactory.FromConfiguration( - ConfigurationBuilder.LoadConfigurationFile(fileName, "configName"))); + CacheConfigurationBuilder.LoadConfigurationFile(fileName, "configName"))); // assert exception.Should().NotBeNull(); @@ -235,7 +235,7 @@ public void Cfg_InvalidCfgFile_InvalidType_NumberOfGenericArgs() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidType.config"); // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, "cacheManager2", "configName"); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, "cacheManager2", "configName"); Action act = () => CacheFactory.FromConfiguration(cfg); // assert @@ -251,7 +251,7 @@ public void Cfg_InvalidCfgFile_InvalidType_HandleType() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidType.config"); // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, "cacheManager4", "configName"); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, "cacheManager4", "configName"); Action act = () => CacheFactory.FromConfiguration(cfg); @@ -269,7 +269,7 @@ public void Cfg_InvalidCfgFile_InvalidType_WrongNumberOfGenericTypeArgs() // act var exception = Record.Exception(() => CacheFactory.FromConfiguration( - ConfigurationBuilder.LoadConfigurationFile(fileName, "configName"))); + CacheConfigurationBuilder.LoadConfigurationFile(fileName, "configName"))); // assert exception.Should().NotBeNull(); @@ -283,7 +283,7 @@ public void Cfg_InvalidCfgFile_NoHandleDef() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.emptyHandleDefinition.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "configName"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "configName"); // assert act.Should().Throw() @@ -298,7 +298,7 @@ public void Cfg_InvalidCfgFile_CacheManagerWithoutLinkedHandles() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.managerWithoutHandles.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -313,7 +313,7 @@ public void Cfg_InvalidCfgFile_CacheManagerWithOneInvalidRef() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidRef.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -328,7 +328,7 @@ public void Cfg_InvalidCfgFile_HandleDefInvalidExpirationMode() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidDefExpMode.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -343,7 +343,7 @@ public void Cfg_InvalidCfgFile_HandleDefInvalidTimeout() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.invalidDefTimeout.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -358,7 +358,7 @@ public void Cfg_InvalidCfgFile_InvalidExpirationMode() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidExpMode.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -373,7 +373,7 @@ public void Cfg_InvalidCfgFile_InvalidEnableStats() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidEnableStats.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -388,7 +388,7 @@ public void Cfg_InvalidCfgFile_ManagerInvalidTimeout() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidTimeout.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -403,7 +403,7 @@ public void Cfg_InvalidCfgFile_ManagerInvalidUpdateMode() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.InvalidUpdateMode.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -418,7 +418,7 @@ public void Cfg_InvalidCfgFile_ExpirationModeWithoutTimeout() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.ExpirationWithoutTimeout.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -433,7 +433,7 @@ public void Cfg_InvalidCfgFile_MaxRetriesLessThanOne() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.MaxRetries.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -448,7 +448,7 @@ public void Cfg_InvalidCfgFile_RetryTimeoutLessThanZero() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.RetryTimeout.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -463,7 +463,7 @@ public void Cfg_InvalidCfgFile_BackplaneNameButNoType() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneNameNoType.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -478,7 +478,7 @@ public void Cfg_InvalidCfgFile_BackplaneTypeButNoName() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneTypeNoName.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1"); // assert act.Should().Throw() @@ -493,7 +493,7 @@ public void Cfg_InvalidCfgFile_BackplaneInvalidType() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneTypeNoName.config"); // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, "invalidType"); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, "invalidType"); Action act = () => new BaseCacheManager(cfg); // assert @@ -509,7 +509,7 @@ public void Cfg_InvalidCfgFile_BackplaneTypeNotFound() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.backplaneTypeNoName.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "typeNotFound"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "typeNotFound"); // assert act.Should().Throw() @@ -524,7 +524,7 @@ public void Cfg_InvalidCfgFile_SerializerType_A() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.serializerType.config"); // act - Action act = () => CacheFactory.FromConfiguration(ConfigurationBuilder.LoadConfigurationFile(fileName, "c1")); + Action act = () => CacheFactory.FromConfiguration(CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c1")); // assert act.Should().Throw() @@ -539,7 +539,7 @@ public void Cfg_InvalidCfgFile_SerializerType_B() string fileName = TestConfigurationHelper.GetCfgFileName(@"/Configuration/configuration.invalid.serializerType.config"); // act - Action act = () => ConfigurationBuilder.LoadConfigurationFile(fileName, "c2"); + Action act = () => CacheConfigurationBuilder.LoadConfigurationFile(fileName, "c2"); // assert act.Should().Throw() diff --git a/test/CacheManager.Tests/LoggingTests.cs b/test/CacheManager.Tests/LoggingTests.cs index aa4e68bb..f484afc1 100644 --- a/test/CacheManager.Tests/LoggingTests.cs +++ b/test/CacheManager.Tests/LoggingTests.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; -using CacheManager.Core; -using CacheManager.Core.Logging; using FluentAssertions; +using Microsoft.Extensions.Logging; using Xunit; namespace CacheManager.Tests @@ -220,7 +219,7 @@ public void Logging_ExtensionTest_InfoA() { var logger = new TestLogger(); - logger.LogInfo("some message."); + logger.LogInformation("some message."); logger.Last.EventId.Should().Be(0); logger.Last.Exception.Should().BeNull(); @@ -233,7 +232,7 @@ public void Logging_ExtensionTest_InfoB() { var logger = new TestLogger(); - logger.LogInfo("message {0} {1}.", "a", "b"); + logger.LogInformation("message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(0); logger.Last.Exception.Should().BeNull(); @@ -246,7 +245,7 @@ public void Logging_ExtensionTest_InfoC() { var logger = new TestLogger(); - logger.LogInfo(11, "message {0} {1}.", "a", "b"); + logger.LogInformation(11, "message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(11); logger.Last.Exception.Should().BeNull(); @@ -259,7 +258,7 @@ public void Logging_ExtensionTest_InfoD() { var logger = new TestLogger(); - logger.LogInfo(new InvalidCastException(), "message {0} {1}.", "a", "b"); + logger.LogInformation(new InvalidCastException(), "message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(0); logger.Last.Exception.Should().BeOfType(); @@ -272,7 +271,7 @@ public void Logging_ExtensionTest_InfoE() { var logger = new TestLogger(); - logger.LogInfo(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); + logger.LogInformation(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(33); logger.Last.Exception.Should().BeOfType(); @@ -354,7 +353,7 @@ public void Logging_ExtensionTest_WarnA() { var logger = new TestLogger(); - logger.LogWarn("some message."); + logger.LogWarning("some message."); logger.Last.EventId.Should().Be(0); logger.Last.Exception.Should().BeNull(); @@ -367,7 +366,7 @@ public void Logging_ExtensionTest_WarnB() { var logger = new TestLogger(); - logger.LogWarn("message {0} {1}.", "a", "b"); + logger.LogWarning("message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(0); logger.Last.Exception.Should().BeNull(); @@ -380,7 +379,7 @@ public void Logging_ExtensionTest_WarnC() { var logger = new TestLogger(); - logger.LogWarn(11, "message {0} {1}.", "a", "b"); + logger.LogWarning(11, "message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(11); logger.Last.Exception.Should().BeNull(); @@ -393,7 +392,7 @@ public void Logging_ExtensionTest_WarnD() { var logger = new TestLogger(); - logger.LogWarn(new InvalidCastException(), "message {0} {1}.", "a", "b"); + logger.LogWarning(new InvalidCastException(), "message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(0); logger.Last.Exception.Should().BeOfType(); @@ -406,7 +405,7 @@ public void Logging_ExtensionTest_WarnE() { var logger = new TestLogger(); - logger.LogWarn(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); + logger.LogWarning(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); logger.Last.EventId.Should().Be(33); logger.Last.Exception.Should().BeOfType(); @@ -414,24 +413,24 @@ public void Logging_ExtensionTest_WarnE() logger.Last.Message.ToString().Should().Be("message a b."); } - [Fact] - public void Logging_Builder_ValidFactory() - { - var cfg = ConfigurationBuilder.BuildConfiguration( - s => s.WithLogging(typeof(NullLoggerFactory))); + //[Fact] + //public void Logging_Builder_ValidFactory() + //{ + // var cfg = ConfigurationBuilder.BuildConfiguration( + // s => s.WithLogging(typeof(NullLoggerFactory))); - cfg.LoggerFactoryType.Should().NotBeNull(); - cfg.LoggerFactoryType.Should().Be(typeof(NullLoggerFactory)); - } + // cfg.LoggerFactoryType.Should().NotBeNull(); + // cfg.LoggerFactoryType.Should().Be(typeof(NullLoggerFactory)); + //} - [Fact] - public void Logging_TypedLogger() - { - var cfg = ConfigurationBuilder.BuildConfiguration( - s => s.WithLogging(typeof(NullLoggerFactory))); + //[Fact] + //public void Logging_TypedLogger() + //{ + // var cfg = ConfigurationBuilder.BuildConfiguration( + // s => s.WithLogging(typeof(NullLoggerFactory))); - cfg.LoggerFactoryType.Should().NotBeNull(); - } + // cfg.LoggerFactoryType.Should().NotBeNull(); + //} } [ExcludeFromCodeCoverage] @@ -444,6 +443,10 @@ public TestLoggerFactory(TestLogger useLogger) this.useLogger = useLogger; } + public void AddProvider(ILoggerProvider provider) + { + } + public ILogger CreateLogger(string categoryName) { return this.useLogger; @@ -453,10 +456,12 @@ public ILogger CreateLogger(T instance) { return this.useLogger; } + + public void Dispose() => throw new NotImplementedException(); } [ExcludeFromCodeCoverage] - public class TestLogger : ILogger + public class TestLogger : ILogger { public TestLogger() { @@ -467,10 +472,7 @@ public TestLogger() public LogMessage Last => this.LogMessages.Last(); - public IDisposable BeginScope(object state) - { - throw new NotImplementedException(); - } + public IDisposable BeginScope(TState state) => null; public bool IsEnabled(LogLevel logLevel) { @@ -481,6 +483,8 @@ public void Log(LogLevel logLevel, int eventId, object message, Exception except { this.LogMessages.Add(new LogMessage(logLevel, eventId, message, exception)); } + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) => throw new NotImplementedException(); } [ExcludeFromCodeCoverage] @@ -502,4 +506,4 @@ public LogMessage(LogLevel level, int eventId, object message, Exception excepti public Exception Exception { get; } } -} \ No newline at end of file +} diff --git a/test/CacheManager.Tests/MemoryCacheTests.cs b/test/CacheManager.Tests/MemoryCacheTests.cs index 09ea4178..5afaf771 100644 --- a/test/CacheManager.Tests/MemoryCacheTests.cs +++ b/test/CacheManager.Tests/MemoryCacheTests.cs @@ -20,7 +20,7 @@ public class MemoryCacheTests public void MsMemory_Extensions_Simple() { var expectedCacheOptions = new MemoryCacheOptions(); - var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle().Build(); + var cfg = new CacheConfigurationBuilder().WithMicrosoftMemoryCacheHandle().Build(); var cache = new BaseCacheManager(cfg); // disabling cfg check as they seem to alter the configuration internally after adding it... internal ms bs implementation @@ -38,7 +38,7 @@ public void MsMemory_Extensions_Named() { string name = "some instance name"; var expectedCacheOptions = new MemoryCacheOptions(); - var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name).Build(); + var cfg = new CacheConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name).Build(); var cache = new BaseCacheManager(cfg); // disabling cfg check as they seem to alter the configuration internally after adding it... internal ms bs implementation @@ -56,7 +56,7 @@ public void MsMemory_Extensions_NamedB() { string name = "some instance name"; var expectedCacheOptions = new MemoryCacheOptions(); - var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name, true).Build(); + var cfg = new CacheConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name, true).Build(); var cache = new BaseCacheManager(cfg); // disabling cfg check as they seem to alter the configuration internally after adding it... internal ms bs implementation @@ -79,7 +79,7 @@ public void MsMemory_Extensions_SimpleWithCfg() ExpirationScanFrequency = TimeSpan.FromSeconds(20) }; - var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(expectedCacheOptions).Build(); + var cfg = new CacheConfigurationBuilder().WithMicrosoftMemoryCacheHandle(expectedCacheOptions).Build(); var cache = new BaseCacheManager(cfg); cfg.CacheHandleConfigurations.First() @@ -103,7 +103,7 @@ public void MsMemory_Extensions_SimpleWithCfgNamed() ExpirationScanFrequency = TimeSpan.FromSeconds(20) }; - var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name, expectedCacheOptions).Build(); + var cfg = new CacheConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name, expectedCacheOptions).Build(); var cache = new BaseCacheManager(cfg); cfg.CacheHandleConfigurations.First() @@ -127,7 +127,7 @@ public void MsMemory_Extensions_SimpleWithCfgNamedB() ExpirationScanFrequency = TimeSpan.FromSeconds(20) }; - var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name, true, expectedCacheOptions).Build(); + var cfg = new CacheConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name, true, expectedCacheOptions).Build(); var cache = new BaseCacheManager(cfg); cfg.CacheHandleConfigurations.First() @@ -147,7 +147,7 @@ public void MsMemory_Extensions_SimpleWithCfgNamedB() [Fact] public void SysRuntime_Extensions_Simple() { - var cfg = new ConfigurationBuilder().WithSystemRuntimeCacheHandle().Build(); + var cfg = new CacheConfigurationBuilder().WithSystemRuntimeCacheHandle().Build(); var cache = new BaseCacheManager(cfg); cfg.CacheHandleConfigurations.Count.Should().Be(1); @@ -161,7 +161,7 @@ public void SysRuntime_Extensions_Simple() public void SysRuntime_Extensions_Named() { string name = "instanceName"; - var cfg = new ConfigurationBuilder().WithSystemRuntimeCacheHandle(name).Build(); + var cfg = new CacheConfigurationBuilder().WithSystemRuntimeCacheHandle(name).Build(); var cache = new BaseCacheManager(cfg); cfg.CacheHandleConfigurations.Count.Should().Be(1); @@ -175,7 +175,7 @@ public void SysRuntime_Extensions_Named() public void SysRuntime_Extensions_NamedB() { string name = "instanceName"; - var cfg = new ConfigurationBuilder().WithSystemRuntimeCacheHandle(name, true).Build(); + var cfg = new CacheConfigurationBuilder().WithSystemRuntimeCacheHandle(name, true).Build(); var cache = new BaseCacheManager(cfg); cfg.CacheHandleConfigurations.Count.Should().Be(1); diff --git a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs index b8339e4d..6dfa2e73 100644 --- a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs +++ b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs @@ -372,155 +372,6 @@ public void Configuration_CacheHandle_KnownType_RedisB() config.CacheHandleConfigurations[0].Key.Should().Be("name"); // now key gets set to name } - [Fact] - public void Configuration_CacheHandle_KnownType_CouchbaseNoKey() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Couchbase"}, - }; - - var config = GetConfiguration(data); - Action action = () => config.GetCacheConfiguration("name"); - action.Should().Throw().WithMessage("*'key' or 'name'*"); - } - - [Fact] - public void Configuration_CacheHandle_KnownType_Couchbase() - { - var key = Guid.NewGuid().ToString(); - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Couchbase"}, - {"cacheManagers:0:handles:0:key", key}, - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - config.Name.Should().Be("name"); - config.CacheHandleConfigurations.Count.Should().Be(1); - config.CacheHandleConfigurations[0].HandleType.Should().Be(typeof(Couchbase.BucketCacheHandle<>)); - config.CacheHandleConfigurations[0].Key.Should().Be(key); - config.CacheHandleConfigurations[0].Name.Should().NotBeNullOrWhiteSpace(); // name is random in this case - - var cache = new BaseCacheManager(config); - } - - [Fact] - public void Configuration_CacheHandle_KnownType_CouchbaseB() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Couchbase"}, - {"cacheManagers:0:handles:0:name", "name"}, - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - config.Name.Should().Be("name"); - config.CacheHandleConfigurations.Count.Should().Be(1); - config.CacheHandleConfigurations[0].HandleType.Should().Be(typeof(Couchbase.BucketCacheHandle<>)); - config.CacheHandleConfigurations[0].Name.Should().Be("name"); - config.CacheHandleConfigurations[0].Key.Should().Be("name"); // now key gets set to name - - var cache = new BaseCacheManager(config); - } - -#if MEMCACHEDENABLED - [Fact] - [Trait("category", "memcached")] - public void Configuration_CacheHandle_KnownType_Memcached() - { - var key = "default"; - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Memcached"}, - {"cacheManagers:0:handles:0:key", key}, - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - config.Name.Should().Be("name"); - config.CacheHandleConfigurations.Count.Should().Be(1); - config.CacheHandleConfigurations[0].HandleType.Should().Be(typeof(Memcached.MemcachedCacheHandle<>)); - config.CacheHandleConfigurations[0].Key.Should().Be(key); - config.CacheHandleConfigurations[0].Name.Should().NotBeNullOrWhiteSpace(); // name is random in this case - - var cache = new BaseCacheManager(config); - cache.Add(Guid.NewGuid().ToString(), "value").Should().BeTrue(); - } - -#endif -#if NET461 - - [Fact] - public void Configuration_CacheHandle_KnownType_MemcachedNoKey() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Memcached"}, - }; - - var config = GetConfiguration(data); - Action action = () => config.GetCacheConfiguration("name"); - action.Should().Throw().WithMessage("*'key' or 'name'*"); - } - - [Fact] - public void Configuration_CacheHandle_KnownType_MemcachedB() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Memcached"}, - {"cacheManagers:0:handles:0:name", "name"}, - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - config.Name.Should().Be("name"); - config.CacheHandleConfigurations.Count.Should().Be(1); - config.CacheHandleConfigurations[0].HandleType.Should().Be(typeof(Memcached.MemcachedCacheHandle<>)); - config.CacheHandleConfigurations[0].Name.Should().Be("name"); - config.CacheHandleConfigurations[0].Key.Should().Be("name"); // now key gets set to name - } - - [Fact] - public void Configuration_CacheHandle_Type_MemcachedB() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:type", "CacheManager.Memcached.MemcachedCacheHandle`1, CacheManager.Memcached"}, - {"cacheManagers:0:handles:0:name", "name"}, - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - config.Name.Should().Be("name"); - config.CacheHandleConfigurations.Count.Should().Be(1); - config.CacheHandleConfigurations[0].HandleType.Should().Be(typeof(Memcached.MemcachedCacheHandle<>)); - config.CacheHandleConfigurations[0].Name.Should().Be("name"); - config.CacheHandleConfigurations[0].Key.Should().Be("name"); // now key gets set to name - } - - [Fact] - public void Configuration_CacheHandle_KnownType_Web() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "SystemWeb"}, - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - config.Name.Should().Be("name"); - config.CacheHandleConfigurations.Count.Should().Be(1); - config.CacheHandleConfigurations[0].HandleType.Should().Be(typeof(Web.SystemWebCacheHandle<>)); - } - -#endif - [Fact] public void Configuration_CacheHandle_KnownType_Dictionary() { @@ -844,23 +695,6 @@ public void Configuration_LoggerFactory_SomeType_Valid() config.LoggerFactoryType.Should().Be(typeof(object)); } - [Fact] - public void Configuration_LoggerFactory_KnownType_Valid() - { - var data = new Dictionary - { - {"cacheManagers:0:name", "name"}, - {"cacheManagers:0:handles:0:knownType", "Dictionary"}, - {"cacheManagers:0:loggerFactory:knownType", "Microsoft"} - }; - - var config = GetConfiguration(data).GetCacheConfiguration("name"); - config.LoggerFactoryType.Should().Be(typeof(Logging.MicrosoftLoggerFactoryAdapter)); - - var cache = new BaseCacheManager(config); - cache.Add("key", "value").Should().BeTrue(); - } - [Fact] public void Configuration_Serializer_Invalid() { diff --git a/test/CacheManager.Tests/MicrosoftLoggingTests.cs b/test/CacheManager.Tests/MicrosoftLoggingTests.cs index f64f6953..3e4bee1b 100644 --- a/test/CacheManager.Tests/MicrosoftLoggingTests.cs +++ b/test/CacheManager.Tests/MicrosoftLoggingTests.cs @@ -1,158 +1,156 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using CacheManager.Core; -using CacheManager.Logging; -using FluentAssertions; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Xunit; - -namespace CacheManager.Tests -{ - [ExcludeFromCodeCoverage] - public class MicrosoftLoggingTests - { - private class TestLoggingBuilder : ILoggingBuilder - { - public TestLoggingBuilder() - { - Services = new ServiceCollection(); - } - - public IServiceCollection Services { get; } - } - - [Fact] - public void AspNetCoreLogging_MinLogLevel_Trace() - { - var services = new ServiceCollection(); - var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Trace)).BuildServiceProvider(); - var external = provider.GetRequiredService(); - - var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); - var logger = loggerFactory.CreateLogger("cat"); - - logger.Should().NotBeNull(); - logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); - } - - [Fact] - public void AspNetCoreLogging_MinLogLevel_Debug() - { - var services = new ServiceCollection(); - var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Debug)).BuildServiceProvider(); - var external = provider.GetRequiredService(); - - var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); - var logger = loggerFactory.CreateLogger("cat"); - - logger.Should().NotBeNull(); - logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); - } - - [Fact] - public void AspNetCoreLogging_MinLogLevel_Info() - { - var services = new ServiceCollection(); - var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Information)).BuildServiceProvider(); - var external = provider.GetRequiredService(); - - var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); - var logger = loggerFactory.CreateLogger("cat"); - - logger.Should().NotBeNull(); - logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); - } - - [Fact] - public void AspNetCoreLogging_MinLogLevel_Warn() - { - var services = new ServiceCollection(); - var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)).BuildServiceProvider(); - var external = provider.GetRequiredService(); - - var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); - var logger = loggerFactory.CreateLogger("cat"); - - logger.Should().NotBeNull(); - logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); - } - - [Fact] - public void AspNetCoreLogging_MinLogLevel_Error() - { - var services = new ServiceCollection(); - var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Error)).BuildServiceProvider(); - var external = provider.GetRequiredService(); - - var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); - var logger = loggerFactory.CreateLogger("cat"); - - logger.Should().NotBeNull(); - logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); - logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); - } - - [Fact] - public void AspNetCoreLogging_MinLogLevel_Critical() - { - var services = new ServiceCollection(); - var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Critical)).BuildServiceProvider(); - var external = provider.GetRequiredService(); - - var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); - var logger = loggerFactory.CreateLogger("cat"); - - logger.Should().NotBeNull(); - logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeFalse(); - logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); - } - - [Fact] - public void AspNetCoreLogging_Builder_InvalidLoggerFactory() - { - Action act = () => ConfigurationBuilder.BuildConfiguration( - s => s.WithMicrosoftLogging(null)); - - act.Should().Throw() - .And.ParamName.Equals("loggerFactory"); - } - - [Fact] - public void AspNetCoreLogging_TypedLogger() - { - var loggerFactory = new MicrosoftLoggerFactoryAdapter(); - var logger = (loggerFactory as Core.Logging.ILoggerFactory).CreateLogger(this) as Core.Logging.ILogger; - logger.Should().NotBeNull(); - } - } -} +////using System; +////using System.Diagnostics.CodeAnalysis; +////using CacheManager.Core; +////using FluentAssertions; +////using Microsoft.Extensions.DependencyInjection; +////using Microsoft.Extensions.Logging; +////using Xunit; + +////namespace CacheManager.Tests +////{ +//// [ExcludeFromCodeCoverage] +//// public class MicrosoftLoggingTests +//// { +//// private class TestLoggingBuilder : ILoggingBuilder +//// { +//// public TestLoggingBuilder() +//// { +//// Services = new ServiceCollection(); +//// } + +//// public IServiceCollection Services { get; } +//// } + +//// [Fact] +//// public void AspNetCoreLogging_MinLogLevel_Trace() +//// { +//// var services = new ServiceCollection(); +//// var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Trace)).BuildServiceProvider(); +//// var external = provider.GetRequiredService(); + +//// var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); +//// var logger = loggerFactory.CreateLogger("cat"); + +//// logger.Should().NotBeNull(); +//// logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); +//// } + +//// [Fact] +//// public void AspNetCoreLogging_MinLogLevel_Debug() +//// { +//// var services = new ServiceCollection(); +//// var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Debug)).BuildServiceProvider(); +//// var external = provider.GetRequiredService(); + +//// var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); +//// var logger = loggerFactory.CreateLogger("cat"); + +//// logger.Should().NotBeNull(); +//// logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); +//// } + +//// [Fact] +//// public void AspNetCoreLogging_MinLogLevel_Info() +//// { +//// var services = new ServiceCollection(); +//// var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Information)).BuildServiceProvider(); +//// var external = provider.GetRequiredService(); + +//// var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); +//// var logger = loggerFactory.CreateLogger("cat"); + +//// logger.Should().NotBeNull(); +//// logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); +//// } + +//// [Fact] +//// public void AspNetCoreLogging_MinLogLevel_Warn() +//// { +//// var services = new ServiceCollection(); +//// var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)).BuildServiceProvider(); +//// var external = provider.GetRequiredService(); + +//// var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); +//// var logger = loggerFactory.CreateLogger("cat"); + +//// logger.Should().NotBeNull(); +//// logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); +//// } + +//// [Fact] +//// public void AspNetCoreLogging_MinLogLevel_Error() +//// { +//// var services = new ServiceCollection(); +//// var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Error)).BuildServiceProvider(); +//// var external = provider.GetRequiredService(); + +//// var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); +//// var logger = loggerFactory.CreateLogger("cat"); + +//// logger.Should().NotBeNull(); +//// logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeTrue(); +//// logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); +//// } + +//// [Fact] +//// public void AspNetCoreLogging_MinLogLevel_Critical() +//// { +//// var services = new ServiceCollection(); +//// var provider = services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Critical)).BuildServiceProvider(); +//// var external = provider.GetRequiredService(); + +//// var loggerFactory = new MicrosoftLoggerFactoryAdapter(() => external); +//// var logger = loggerFactory.CreateLogger("cat"); + +//// logger.Should().NotBeNull(); +//// logger.IsEnabled(Core.Logging.LogLevel.Trace).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Debug).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Information).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Warning).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Error).Should().BeFalse(); +//// logger.IsEnabled(Core.Logging.LogLevel.Critical).Should().BeTrue(); +//// } + +//// [Fact] +//// public void AspNetCoreLogging_Builder_InvalidLoggerFactory() +//// { +//// Action act = () => ConfigurationBuilder.BuildConfiguration( +//// s => s.WithMicrosoftLogging(null)); + +//// act.Should().Throw() +//// .And.ParamName.Equals("loggerFactory"); +//// } + +//// [Fact] +//// public void AspNetCoreLogging_TypedLogger() +//// { +//// var loggerFactory = new MicrosoftLoggerFactoryAdapter(); +//// var logger = (loggerFactory as Core.Logging.ILoggerFactory).CreateLogger(this) as Core.Logging.ILogger; +//// logger.Should().NotBeNull(); +//// } +//// } +////} diff --git a/test/CacheManager.Tests/RedisTests.cs b/test/CacheManager.Tests/RedisTests.cs index 7d466d4c..f67d6a1e 100644 --- a/test/CacheManager.Tests/RedisTests.cs +++ b/test/CacheManager.Tests/RedisTests.cs @@ -32,7 +32,7 @@ private enum CacheEvent [Fact] public void Redis_WithoutSerializer_ShouldThrow() { - var cfg = ConfigurationBuilder.BuildConfiguration( + var cfg = CacheConfigurationBuilder.BuildConfiguration( settings => settings .WithRedisConfiguration("redis-key", "localhost") @@ -177,7 +177,7 @@ public void Redis_UseExistingConnection() var multiplexer = ConnectionMultiplexer.Connect(conConfig); - var cfg = ConfigurationBuilder.BuildConfiguration( + var cfg = CacheConfigurationBuilder.BuildConfiguration( s => s .WithJsonSerializer() .WithRedisConfiguration("redisKey", multiplexer) @@ -684,7 +684,7 @@ await TestBackplaneEventInMemory( [Fact] public void Redis_Configuration_NoEndpoint() { - Action act = () => ConfigurationBuilder.BuildConfiguration( + Action act = () => CacheConfigurationBuilder.BuildConfiguration( s => s.WithRedisConfiguration( "key", c => c.WithAllowAdmin())); @@ -902,11 +902,10 @@ await RedisTests.RunMultipleCaches( public void Redis_Verify_NoCredentialsLoggedOrThrown() { var testLogger = new TestLogger(); - var cfg = ConfigurationBuilder.BuildConfiguration(settings => + var cfg = CacheConfigurationBuilder.BuildConfiguration(settings => { settings .WithRedisBackplane("redis.config") - .WithLogging(typeof(TestLoggerFactory), testLogger) .WithJsonSerializer() .WithRedisCacheHandle("redis.config", true) .And @@ -1049,7 +1048,7 @@ public void Redis_StrictMode_EmptyString_DoesnTThrow() var redisConfig = new RedisConfiguration(redisConfigKey, "localhost", strictCompatibilityModeVersion: ""); RedisConfigurations.AddConfiguration(redisConfig); - var cacheConfig = new ConfigurationBuilder() + var cacheConfig = new CacheConfigurationBuilder() .WithJsonSerializer() .WithRedisCacheHandle(redisConfigKey) .Build(); @@ -1072,7 +1071,7 @@ public void Redis_Valid_CfgFile_LoadWithRedisBackplane() var redisConfig = RedisConfigurations.GetConfiguration("redisFromCfgConfigurationId"); // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); // assert redisConfig.Database.Should().Be(113); @@ -1096,7 +1095,7 @@ public void Redis_Valid_CfgFile_LoadWithConnectionString() var redisConfig = RedisConfigurations.GetConfiguration("redisConnectionString"); // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); // assert @@ -1121,7 +1120,7 @@ public void Redis_LoadWithRedisBackplane_FromAppConfig() string cacheName = "redisWithBackplaneAppConfig"; // act - var cfg = ConfigurationBuilder.LoadConfiguration(cacheName); + var cfg = CacheConfigurationBuilder.LoadConfiguration(cacheName); var cache = CacheFactory.FromConfiguration(cfg); var handle = cache.CacheHandles.First(p => p.Configuration.IsBackplaneSource) as RedisCacheHandle; @@ -1142,7 +1141,7 @@ public void Redis_LoadWithRedisBackplane_FromAppConfigConnectionStrings() string cacheName = "redisWithBackplaneAppConfigConnectionStrings"; // act - var cfg = ConfigurationBuilder.LoadConfiguration(cacheName); + var cfg = CacheConfigurationBuilder.LoadConfiguration(cacheName); var cache = CacheFactory.FromConfiguration(cfg); var handle = cache.CacheHandles.First(p => p.Configuration.IsBackplaneSource) as RedisCacheHandle; @@ -1163,7 +1162,7 @@ public void Redis_LoadWithRedisBackplane_FromAppConfigConnectionStrings_WithDefa string cacheName = "redisWithBackplaneAppConfigConnectionStringsWithDefaultDb"; // act - var cfg = ConfigurationBuilder.LoadConfiguration(cacheName); + var cfg = CacheConfigurationBuilder.LoadConfiguration(cacheName); var cache = CacheFactory.FromConfiguration(cfg); var redisConfig = RedisConfigurations.GetConfiguration("redisFromConnectionStringsWithDefaultDb"); var handle = cache.CacheHandles.First(p => p.Configuration.IsBackplaneSource) as RedisCacheHandle; diff --git a/test/CacheManager.Tests/SerializerTests.cs b/test/CacheManager.Tests/SerializerTests.cs index 28350943..608c3b6b 100644 --- a/test/CacheManager.Tests/SerializerTests.cs +++ b/test/CacheManager.Tests/SerializerTests.cs @@ -8,12 +8,13 @@ using System.Runtime.Serialization.Json; using CacheManager.Core; using CacheManager.Core.Internal; -using CacheManager.Core.Logging; + using CacheManager.Serialization.Bond; using CacheManager.Serialization.DataContract; using CacheManager.Serialization.Json; using CacheManager.Serialization.ProtoBuf; using FluentAssertions; +using Microsoft.Extensions.Logging; using Newtonsoft.Json; using ProtoBuf; using Xunit; @@ -1488,13 +1489,7 @@ public override int Count } } - protected override ILogger Logger - { - get - { - throw new NotImplementedException(); - } - } + protected override ILogger Logger { get; } public override void Clear() { diff --git a/test/CacheManager.Tests/SystemWebCacheHandleWrapper.cs b/test/CacheManager.Tests/SystemWebCacheHandleWrapper.cs index 3334e98f..7eeed2d5 100644 --- a/test/CacheManager.Tests/SystemWebCacheHandleWrapper.cs +++ b/test/CacheManager.Tests/SystemWebCacheHandleWrapper.cs @@ -1,34 +1,34 @@ -// disabling it for builds on Mono because setting the HttpContext.Current causes all kinds of strange exceptions -#if MOCK_HTTPCONTEXT_ENABLED -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Web; -using CacheManager.Core; -using CacheManager.Core.Logging; -using CacheManager.Web; +////// disabling it for builds on Mono because setting the HttpContext.Current causes all kinds of strange exceptions +////#if MOCK_HTTPCONTEXT_ENABLED +////using System.Diagnostics.CodeAnalysis; +////using System.IO; +////using System.Web; +////using CacheManager.Core; -namespace CacheManager.Tests -{ - [ExcludeFromCodeCoverage] - internal class SystemWebCacheHandleWrapper : SystemWebCacheHandle - { - public SystemWebCacheHandleWrapper(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory) - : base(managerConfiguration, configuration, loggerFactory) - { - } +////using CacheManager.Web; - protected override HttpContextBase Context - { - get - { - if (HttpContext.Current == null) - { - HttpContext.Current = new HttpContext(new HttpRequest("test", "http://test", string.Empty), new HttpResponse(new StringWriter())); - } +////namespace CacheManager.Tests +////{ +//// [ExcludeFromCodeCoverage] +//// internal class SystemWebCacheHandleWrapper : SystemWebCacheHandle +//// { +//// public SystemWebCacheHandleWrapper(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory) +//// : base(managerConfiguration, configuration, loggerFactory) +//// { +//// } - return new HttpContextWrapper(HttpContext.Current); - } - } - } -} -#endif \ No newline at end of file +//// protected override HttpContextBase Context +//// { +//// get +//// { +//// if (HttpContext.Current == null) +//// { +//// HttpContext.Current = new HttpContext(new HttpRequest("test", "http://test", string.Empty), new HttpResponse(new StringWriter())); +//// } + +//// return new HttpContextWrapper(HttpContext.Current); +//// } +//// } +//// } +////} +////#endif diff --git a/test/CacheManager.Tests/TestCacheManagers.cs b/test/CacheManager.Tests/TestCacheManagers.cs index d4a07b68..70f8edc8 100644 --- a/test/CacheManager.Tests/TestCacheManagers.cs +++ b/test/CacheManager.Tests/TestCacheManagers.cs @@ -2,18 +2,9 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using CacheManager.Core; -#if MEMCACHEDENABLED -using Enyim.Caching.Configuration; -#endif -#if COUCHBASEENABLED -using Couchbase; -using Couchbase.Configuration.Client; -#endif - namespace CacheManager.Tests { [ExcludeFromCodeCoverage] @@ -45,24 +36,6 @@ public IEnumerator GetEnumerator() yield return new object[] { TestManagers.WithRedisCacheJsonNoLua }; yield return new object[] { TestManagers.WithDicAndRedisCacheNoLua }; -#endif -#if MEMCACHEDENABLED -#if NET461 - yield return new object[] { TestManagers.WithMemcachedBinary }; -#endif - yield return new object[] { TestManagers.WithMemcachedJson }; - //yield return new object[] { TestManagers.WithMemcachedGzJson }; - //yield return new object[] { TestManagers.WithMemcachedProto }; - yield return new object[] { TestManagers.WithMemcachedBondBinary }; -#endif -#if COUCHBASEENABLED - // requires one "default" couchbase bucket without auth or password and one "secret-bucket" with pw: "secret" - yield return new object[] { TestManagers.WithCouchbaseDefault }; - yield return new object[] { TestManagers.WithCouchbaseDefaultViaHelper }; - yield return new object[] { TestManagers.WithCouchbaseSecret }; -#endif -#if MOCK_HTTPCONTEXT_ENABLED - yield return new object[] { TestManagers.WithSystemWebCache }; #endif } @@ -79,7 +52,7 @@ public static class TestManagers private const int NumDatabases = 100; public static ICacheManagerConfiguration BaseConfiguration - => new ConfigurationBuilder() + => new CacheConfigurationBuilder() ////.WithMicrosoftLogging(f => f.AddSerilog()) .Build(); @@ -318,92 +291,6 @@ public static ICacheManager WithTwoNamedMemoryCaches .EnableStatistics() .Build()); -#if MOCK_HTTPCONTEXT_ENABLED - - public static ICacheManager WithSystemWebCache - => CacheFactory.FromConfiguration( - BaseConfiguration - .Builder - .WithHandle(typeof(SystemWebCacheHandleWrapper<>)) - .EnableStatistics() - .Build()); - -#endif - -#if COUCHBASEENABLED - - public static ICacheManager WithCouchbaseDefault - { - get - { - var clientConfiguration = new ClientConfiguration() - { - Servers = new List() - { - new Uri("http://127.0.0.1:8091/pools") - }, - UseSsl = false, - BucketConfigs = new Dictionary - { - { - "default", - new BucketConfiguration - { - BucketName = "default", - UseSsl = false, - PoolConfiguration = new PoolConfiguration - { - MaxSize = 10, - MinSize = 5 - } - } - } - } - }; - - var cache = CacheFactory.Build(settings => - { - settings - .WithCouchbaseConfiguration("couchbase", clientConfiguration) - .WithCouchbaseCacheHandle("couchbase") // using default bucket without pw or auth - .EnableStatistics(); - }); - - return cache; - } - } - - public static ICacheManager WithCouchbaseDefaultViaHelper - { - get - { - ClusterHelper.Initialize(); - - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseCacheHandle("somekeywhichdoesntexist") // using default bucket again - .EnableStatistics() - .Build(); - - return new BaseCacheManager(cacheConfig); - } - } - - public static ICacheManager WithCouchbaseSecret - { - get - { - var cacheConfig = new ConfigurationBuilder() - .WithCouchbaseConfiguration("cb", new ClientConfiguration()) - .WithCouchbaseCacheHandle("cb", "secret-bucket", "secret") - .EnableStatistics() - .Build(); - - return new BaseCacheManager(cacheConfig); - } - } - -#endif - public static ICacheManager CreateRedisAndDicCacheWithBackplane(int database = 0, bool sharedRedisConfig = true, string channelName = null, Serializer serializer = Serializer.Proto, bool useLua = true) { if (database > NumDatabases) @@ -547,34 +434,6 @@ public static ICacheManager CreateRedisCache(int database = 0, bool shared return cache; } -#if MEMCACHEDENABLED - - public static ICacheManager WithMemcachedBinary => CreateMemcachedCache(Serializer.Binary); - - public static ICacheManager WithMemcachedJson => CreateMemcachedCache(Serializer.Json); - - public static ICacheManager WithMemcachedGzJson => CreateMemcachedCache(Serializer.GzJson); - - public static ICacheManager WithMemcachedProto => CreateMemcachedCache(Serializer.Proto); - - public static ICacheManager WithMemcachedBondBinary => CreateMemcachedCache(Serializer.BondBinary); - - public static ICacheManager CreateMemcachedCache(Serializer serializer = Serializer.Json) - { - var memConfig = new MemcachedClientConfiguration(); - memConfig.AddServer("localhost", 11211); - return CacheFactory.FromConfiguration( - BaseConfiguration.Builder - .WithUpdateMode(CacheUpdateMode.Up) - .TestSerializer(serializer) - .WithMemcachedCacheHandle(memConfig) - .EnableStatistics() - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1000)) - .Build()); - } - -#endif - private static string NewKey() => Guid.NewGuid().ToString(); } diff --git a/test/CacheManager.Tests/ValidConfigurationValidationTests.cs b/test/CacheManager.Tests/ValidConfigurationValidationTests.cs index 4c6f2c5b..fe372a67 100644 --- a/test/CacheManager.Tests/ValidConfigurationValidationTests.cs +++ b/test/CacheManager.Tests/ValidConfigurationValidationTests.cs @@ -20,7 +20,7 @@ public void Cfg_Valid_AppConfig_ByNameByLoader() string cacheName = "C1"; // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); // assert @@ -39,7 +39,7 @@ public void Cfg_Valid_AppConfig_ByName() string cacheName = "C1"; // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); // assert @@ -58,7 +58,7 @@ public void Cfg_Valid_CfgFile_ExpirationVariances() string cacheName = "ExpirationVariances"; // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); // assert @@ -81,7 +81,7 @@ public void Cfg_Valid_CfgFile_DefaultSysMemCache() string cacheName = "DefaultSysMemCache"; // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); var memHandle = cache.CacheHandles.ElementAt(0) as MemoryCacheHandle; @@ -106,7 +106,7 @@ public void Cfg_Valid_CfgFile_EnabledStats() string cacheName = "ExpirationVariances"; // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); // assert @@ -122,7 +122,7 @@ public void Cfg_Valid_CfgFile_DisableStats() string cacheName = "c3"; // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); // assert @@ -139,7 +139,7 @@ public void Cfg_Valid_CfgFile_AllDefaults() string cacheName = "onlyDefaultsCache"; // act - var cfg = ConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); + var cfg = CacheConfigurationBuilder.LoadConfigurationFile(fileName, cacheName); var cache = CacheFactory.FromConfiguration(cfg); // assert diff --git a/test/CacheManager.Tests/app.config b/test/CacheManager.Tests/app.config index e907c628..e4bf9568 100644 --- a/test/CacheManager.Tests/app.config +++ b/test/CacheManager.Tests/app.config @@ -3,13 +3,6 @@
- - -
- - -
- @@ -66,28 +59,6 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/test/CacheManager.Tests/testhost.dll.config b/test/CacheManager.Tests/testhost.dll.config index ed981526..2ec19a76 100644 --- a/test/CacheManager.Tests/testhost.dll.config +++ b/test/CacheManager.Tests/testhost.dll.config @@ -7,13 +7,6 @@
- - -
- - -
- @@ -70,28 +63,6 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/test/CacheManager.Tests/testhost.x86.dll.config b/test/CacheManager.Tests/testhost.x86.dll.config index ed981526..2ec19a76 100644 --- a/test/CacheManager.Tests/testhost.x86.dll.config +++ b/test/CacheManager.Tests/testhost.x86.dll.config @@ -7,13 +7,6 @@
- - -
- - -
- @@ -70,28 +63,6 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/tools/cacheManager.json b/tools/cacheManager.json index ca1f5f8a..b9f521ed 100644 --- a/tools/cacheManager.json +++ b/tools/cacheManager.json @@ -129,7 +129,7 @@ "properties": { "knownType": { "type": "string", - "enum": [ "Redis", "Couchbase", "Memcached" ], + "enum": [ "Redis" ], "description": "Shortcut to the known cache handle types. This requires the corresponding packages are installed." }, "key": { diff --git a/tools/common.props b/tools/common.props index 3c1d16ff..6ad2ffd5 100644 --- a/tools/common.props +++ b/tools/common.props @@ -2,20 +2,23 @@ - Copyright (c) 2021 Michael Conrad - MichaConrad - true - + Copyright (c) 2024 Michael Conrad + MichaConrad CacheManager.NET - Apache-2.0 icon.png - - http://cachemanager.michaco.net + README.md + Apache-2.0 + https://cachemanager.michaco.net http://cachemanager.michaco.net + true + true + true + true - git - https://github.com/MichaCo/CacheManager + true + snupkg + portable $(MSBuildThisFileDirectory)key.snk true @@ -26,5 +29,6 @@ + diff --git a/tools/redis/install.cmd b/tools/redis/install.cmd index 9783c5ad..8a6ca11e 100644 --- a/tools/redis/install.cmd +++ b/tools/redis/install.cmd @@ -2,7 +2,7 @@ cd %~dp0 SETLOCAL -SET NUGET_VERSION=latest +SET NUGET_VERSION=v6.10.1 SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe IF EXIST %CACHED_NUGET% goto copynuget From 6a1642d9d2682a7e2f41d3e6422871ed9061d4cf Mon Sep 17 00:00:00 2001 From: MichaC Date: Fri, 9 Aug 2024 16:34:23 +0200 Subject: [PATCH 12/13] more fixes --- .../CacheManager.Config.Tests.csproj | 2 +- .../CacheConfigurationBuilder.cs | 5 +- test/CacheManager.Tests/CacheFactoryTests.cs | 4 +- test/CacheManager.Tests/LoggingTests.cs | 439 +----------------- test/CacheManager.Tests/MemoryCacheTests.cs | 2 +- .../MicrosoftConfigurationTests.cs | 2 +- test/CacheManager.Tests/RedisTests.cs | 4 +- 7 files changed, 17 insertions(+), 441 deletions(-) diff --git a/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj b/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj index 4b2b1a11..eeadd428 100644 --- a/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj +++ b/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj @@ -4,7 +4,7 @@ CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features. 2.0.0 MichaConrad - net8.0 + net8.0 CacheManager.Config.Tests Exe ../../tools/key.snk diff --git a/src/CacheManager.Core/Configuration/CacheConfigurationBuilder.cs b/src/CacheManager.Core/Configuration/CacheConfigurationBuilder.cs index f6e3a4ee..f0f3e4fc 100644 --- a/src/CacheManager.Core/Configuration/CacheConfigurationBuilder.cs +++ b/src/CacheManager.Core/Configuration/CacheConfigurationBuilder.cs @@ -7,6 +7,7 @@ using System.Text.RegularExpressions; using CacheManager.Core.Configuration; using CacheManager.Core.Internal; +using Microsoft.Extensions.Logging; using static CacheManager.Core.Utility.Guard; namespace CacheManager.Core @@ -75,7 +76,7 @@ public CacheConfigurationBuilder(string name, ICacheManagerConfiguration forConf /// Builds a which can be used to create a new cache /// manager instance. /// - /// Pass the configuration to + /// Pass the configuration to /// to create a valid cache manager. /// /// @@ -96,7 +97,7 @@ public static ICacheManagerConfiguration BuildConfiguration(Action which can be used to create a new cache /// manager instance. /// - /// Pass the configuration to + /// Pass the configuration to /// to create a valid cache manager. /// /// diff --git a/test/CacheManager.Tests/CacheFactoryTests.cs b/test/CacheManager.Tests/CacheFactoryTests.cs index 8bd75861..cd396c7e 100644 --- a/test/CacheManager.Tests/CacheFactoryTests.cs +++ b/test/CacheManager.Tests/CacheFactoryTests.cs @@ -451,7 +451,7 @@ public void CacheFactory_Build_WithRedisConfigurationConnectionString() var config = RedisConfigurations.GetConfiguration(name); // assert - config.ConfigurationOptions.Should().BeEquivalentTo(expected); + config.ConfigurationOptions.ToString().Should().BeEquivalentTo(expected.ToString()); config.TwemproxyEnabled.Should().BeFalse(); config.AllowAdmin.Should().BeTrue(); config.IsSsl.Should().BeFalse(); @@ -478,7 +478,7 @@ public void CacheFactory_Build_WithRedisConnectionStringWithProxy() var config = RedisConfigurations.GetConfiguration(name); // assert - config.ConfigurationOptions.Should().BeEquivalentTo(expected); + config.ConfigurationOptions.ToString().Should().BeEquivalentTo(expected.ToString()); config.TwemproxyEnabled.Should().BeTrue(); config.AllowAdmin.Should().BeFalse(); config.IsSsl.Should().BeTrue(); diff --git a/test/CacheManager.Tests/LoggingTests.cs b/test/CacheManager.Tests/LoggingTests.cs index f484afc1..a91e0344 100644 --- a/test/CacheManager.Tests/LoggingTests.cs +++ b/test/CacheManager.Tests/LoggingTests.cs @@ -8,431 +8,6 @@ namespace CacheManager.Tests { - [ExcludeFromCodeCoverage] - public class LoggingTests - { - //// Critical - - [Fact] - public void Logging_ExtensionTest_CriticalA() - { - var logger = new TestLogger(); - - logger.LogCritical("some message."); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Critical); - logger.Last.Message.ToString().Should().Be("some message."); - } - - [Fact] - public void Logging_ExtensionTest_CriticalB() - { - var logger = new TestLogger(); - - logger.LogCritical("message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Critical); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_CriticalC() - { - var logger = new TestLogger(); - - logger.LogCritical(11, "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(11); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Critical); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_CriticalD() - { - var logger = new TestLogger(); - - logger.LogCritical(new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Critical); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_CriticalE() - { - var logger = new TestLogger(); - - logger.LogCritical(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(33); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Critical); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - //// Debug - - [Fact] - public void Logging_ExtensionTest_DebugA() - { - var logger = new TestLogger(); - - logger.LogDebug("some message."); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Debug); - logger.Last.Message.ToString().Should().Be("some message."); - } - - [Fact] - public void Logging_ExtensionTest_DebugB() - { - var logger = new TestLogger(); - - logger.LogDebug("message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Debug); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_DebugC() - { - var logger = new TestLogger(); - - logger.LogDebug(11, "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(11); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Debug); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_DebugD() - { - var logger = new TestLogger(); - - logger.LogDebug(new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Debug); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_DebugE() - { - var logger = new TestLogger(); - - logger.LogDebug(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(33); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Debug); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - //// Error - - [Fact] - public void Logging_ExtensionTest_ErrorA() - { - var logger = new TestLogger(); - - logger.LogError("some message."); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Error); - logger.Last.Message.ToString().Should().Be("some message."); - } - - [Fact] - public void Logging_ExtensionTest_ErrorB() - { - var logger = new TestLogger(); - - logger.LogError("message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Error); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_ErrorC() - { - var logger = new TestLogger(); - - logger.LogError(11, "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(11); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Error); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_ErrorD() - { - var logger = new TestLogger(); - - logger.LogError(new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Error); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_ErrorE() - { - var logger = new TestLogger(); - - logger.LogError(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(33); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Error); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - //// Info - - [Fact] - public void Logging_ExtensionTest_InfoA() - { - var logger = new TestLogger(); - - logger.LogInformation("some message."); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Information); - logger.Last.Message.ToString().Should().Be("some message."); - } - - [Fact] - public void Logging_ExtensionTest_InfoB() - { - var logger = new TestLogger(); - - logger.LogInformation("message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Information); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_InfoC() - { - var logger = new TestLogger(); - - logger.LogInformation(11, "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(11); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Information); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_InfoD() - { - var logger = new TestLogger(); - - logger.LogInformation(new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Information); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_InfoE() - { - var logger = new TestLogger(); - - logger.LogInformation(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(33); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Information); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - //// Trace - - [Fact] - public void Logging_ExtensionTest_TraceA() - { - var logger = new TestLogger(); - - logger.LogTrace("some message."); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Trace); - logger.Last.Message.ToString().Should().Be("some message."); - } - - [Fact] - public void Logging_ExtensionTest_TraceB() - { - var logger = new TestLogger(); - - logger.LogTrace("message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Trace); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_TraceC() - { - var logger = new TestLogger(); - - logger.LogTrace(11, "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(11); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Trace); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_TraceD() - { - var logger = new TestLogger(); - - logger.LogTrace(new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Trace); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_TraceE() - { - var logger = new TestLogger(); - - logger.LogTrace(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(33); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Trace); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - //// Warning - - [Fact] - public void Logging_ExtensionTest_WarnA() - { - var logger = new TestLogger(); - - logger.LogWarning("some message."); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Warning); - logger.Last.Message.ToString().Should().Be("some message."); - } - - [Fact] - public void Logging_ExtensionTest_WarnB() - { - var logger = new TestLogger(); - - logger.LogWarning("message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Warning); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_WarnC() - { - var logger = new TestLogger(); - - logger.LogWarning(11, "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(11); - logger.Last.Exception.Should().BeNull(); - logger.Last.LogLevel.Should().Be(LogLevel.Warning); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_WarnD() - { - var logger = new TestLogger(); - - logger.LogWarning(new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(0); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Warning); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - [Fact] - public void Logging_ExtensionTest_WarnE() - { - var logger = new TestLogger(); - - logger.LogWarning(33, new InvalidCastException(), "message {0} {1}.", "a", "b"); - - logger.Last.EventId.Should().Be(33); - logger.Last.Exception.Should().BeOfType(); - logger.Last.LogLevel.Should().Be(LogLevel.Warning); - logger.Last.Message.ToString().Should().Be("message a b."); - } - - //[Fact] - //public void Logging_Builder_ValidFactory() - //{ - // var cfg = ConfigurationBuilder.BuildConfiguration( - // s => s.WithLogging(typeof(NullLoggerFactory))); - - // cfg.LoggerFactoryType.Should().NotBeNull(); - // cfg.LoggerFactoryType.Should().Be(typeof(NullLoggerFactory)); - //} - - //[Fact] - //public void Logging_TypedLogger() - //{ - // var cfg = ConfigurationBuilder.BuildConfiguration( - // s => s.WithLogging(typeof(NullLoggerFactory))); - - // cfg.LoggerFactoryType.Should().NotBeNull(); - //} - } - [ExcludeFromCodeCoverage] public class TestLoggerFactory : ILoggerFactory { @@ -457,7 +32,9 @@ public ILogger CreateLogger(T instance) return this.useLogger; } - public void Dispose() => throw new NotImplementedException(); + public void Dispose() + { + } } [ExcludeFromCodeCoverage] @@ -479,18 +56,16 @@ public bool IsEnabled(LogLevel logLevel) return true; } - public void Log(LogLevel logLevel, int eventId, object message, Exception exception) + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { - this.LogMessages.Add(new LogMessage(logLevel, eventId, message, exception)); + this.LogMessages.Add(new LogMessage(logLevel, eventId, formatter(state, exception), exception)); } - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) => throw new NotImplementedException(); } [ExcludeFromCodeCoverage] public class LogMessage { - public LogMessage(LogLevel level, int eventId, object message, Exception exception) + public LogMessage(LogLevel level, EventId eventId, object message, Exception exception) { this.LogLevel = level; this.EventId = eventId; @@ -500,7 +75,7 @@ public LogMessage(LogLevel level, int eventId, object message, Exception excepti public LogLevel LogLevel { get; } - public int EventId { get; } + public EventId EventId { get; } public object Message { get; } diff --git a/test/CacheManager.Tests/MemoryCacheTests.cs b/test/CacheManager.Tests/MemoryCacheTests.cs index 5afaf771..8ba708d9 100644 --- a/test/CacheManager.Tests/MemoryCacheTests.cs +++ b/test/CacheManager.Tests/MemoryCacheTests.cs @@ -207,7 +207,7 @@ public void SysRuntime_Extensions_NamedWithCodeCfg() } } - [Fact] + [Fact(Skip = "not throwing anymore, ¯\\_(ツ)_/¯")] public void SysRuntime_Extensions_DefaultWithCodeCfg() { var expectedCacheOptions = new CacheManager.SystemRuntimeCaching.RuntimeMemoryCacheOptions() diff --git a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs index 6dfa2e73..83e23768 100644 --- a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs +++ b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs @@ -270,7 +270,7 @@ public void Configuration_CacheHandle_InvalidType() var config = GetConfiguration(data); Action action = () => config.GetCacheConfiguration("name"); - action.Should().Throw().WithMessage("*Could not load type 'SomeType'*"); + action.Should().Throw().WithMessage("*Could not * type 'SomeType'*"); } [Fact] diff --git a/test/CacheManager.Tests/RedisTests.cs b/test/CacheManager.Tests/RedisTests.cs index f67d6a1e..ae13bcda 100644 --- a/test/CacheManager.Tests/RedisTests.cs +++ b/test/CacheManager.Tests/RedisTests.cs @@ -48,7 +48,7 @@ public void Redis_WithoutSerializer_ShouldThrow() public void Redis_Extensions_WithClient() { var configKey = Guid.NewGuid().ToString(); - var client = ConnectionMultiplexer.Connect("localhost"); + var client = ConnectionMultiplexer.Connect("localhost:6379"); var cache = CacheFactory.Build( s => s .WithJsonSerializer() @@ -73,7 +73,7 @@ public void Redis_Extensions_WithClient() public void Redis_Extensions_WithClientWithDb() { var configKey = Guid.NewGuid().ToString(); - var client = ConnectionMultiplexer.Connect("localhost"); + var client = ConnectionMultiplexer.Connect("localhost:6379"); var cache = CacheFactory.Build( s => s .WithJsonSerializer() From 80e09a89c67ad0f71b3d4ee6bba05a9540a71835 Mon Sep 17 00:00:00 2001 From: MichaC Date: Sun, 2 Mar 2025 15:11:40 +0100 Subject: [PATCH 13/13] using Microsoft.Garnet (https://github.com/microsoft/garnet) for running redis in proc, for testing, benchmarking and unit tests. The server has some limitations, no keyspace notifications for example. --- Benchmarks.md | 2 + CacheManager.sln | 1 - _disable_.travis.yml | 28 -- appveyor.yml | 32 -- azure-pipelines-ci.yml | 74 +++ .../BaseCacheManagerBenchmark.cs | 12 +- .../CacheManager.Config.Tests.csproj | 4 + .../CacheManager.Config.Tests/Program.cs | 168 ++++--- .../CacheManager.Config.Tests/cache.json | 2 +- .../CacheManager.Events.Tests.csproj | 1 + .../CacheManager.Events.Tests/Program.cs | 85 ++-- .../Properties/launchSettings.json | 4 +- samples/AspNetCore/Program.cs | 44 +- samples/AspNetCore/Web.csproj | 3 +- .../CacheManager.Examples.csproj | 4 + samples/CacheManager.Examples/Program.cs | 470 +++++++++--------- ...Microsoft.Extensions.Caching.Memory.csproj | 4 +- .../CacheManager.StackExchange.Redis.csproj | 2 +- ...ager.MSConfiguration.TypeLoad.Tests.csproj | 1 + .../CacheManager.Tests.csproj | 11 +- .../CacheManagerAdvancedUpdateTests.cs | 2 +- .../CacheManagerEventsTest.cs | 17 +- .../CacheManagerExpirationTest.cs | 17 +- .../CacheManagerRegionTests.cs | 2 +- .../CacheManagerSimpleTests.cs | 2 +- .../CacheManagerStatsTest.cs | 4 +- .../configuration.valid.allFeatures.config | 2 +- test/CacheManager.Tests/MemcachedTests.cs | 435 ---------------- .../MicrosoftConfigurationTests.cs | 4 +- test/CacheManager.Tests/RedisTestFixture.cs | 72 +++ test/CacheManager.Tests/RedisTests.cs | 20 +- test/CacheManager.Tests/SerializerTests.cs | 63 +-- test/CacheManager.Tests/TestCacheManagers.cs | 12 +- .../ThreadRandomReadWriteTestBase.cs | 4 +- test/CacheManager.Tests/app.config | 4 +- test/CacheManager.Tests/testhost.dll.config | 4 +- .../testhost.x86.dll.config | 4 +- tools/common.props | 2 +- tools/memcached-amd64/RunMemcachd.bat | 2 - tools/memcached-amd64/StopMemcached.bat | 2 - tools/memcached-amd64/run_memcached.sh | 14 - tools/memcached-amd64/stop_memcached.sh | 6 - tools/redis/Cluster/7000/nodes.conf | 7 - tools/redis/Cluster/7000/redis.conf | 6 - tools/redis/Cluster/7001/nodes.conf | 7 - tools/redis/Cluster/7001/redis.conf | 6 - tools/redis/Cluster/7002/nodes.conf | 7 - tools/redis/Cluster/7002/redis.conf | 6 - tools/redis/Cluster/7003/nodes.conf | 7 - tools/redis/Cluster/7003/redis.conf | 6 - tools/redis/Cluster/7004/nodes.conf | 7 - tools/redis/Cluster/7004/redis.conf | 6 - tools/redis/Cluster/7005/nodes.conf | 7 - tools/redis/Cluster/7005/redis.conf | 6 - tools/redis/install-service.cmd | 4 - tools/redis/install.cmd | 23 - tools/redis/master-debug.conf | 8 - tools/redis/master.conf | 14 - tools/redis/redis-cli master.cmd | 1 - tools/redis/redis-server cluster.cmd | 21 - tools/redis/redis-server-full.cmd | 7 - tools/redis/redis-server-master-debug.cmd | 1 - tools/redis/redis-server-master.cmd | 3 - tools/redis/redis-server-sentinel.cmd | 5 - tools/redis/redis-server-slave.cmd | 1 - tools/redis/sentinel1.conf | 9 - tools/redis/sentinel2.conf | 9 - tools/redis/sentinel3.conf | 9 - tools/redis/slave.conf | 6 - 69 files changed, 687 insertions(+), 1158 deletions(-) delete mode 100644 _disable_.travis.yml delete mode 100644 appveyor.yml create mode 100644 azure-pipelines-ci.yml delete mode 100644 test/CacheManager.Tests/MemcachedTests.cs create mode 100644 test/CacheManager.Tests/RedisTestFixture.cs delete mode 100644 tools/memcached-amd64/RunMemcachd.bat delete mode 100644 tools/memcached-amd64/StopMemcached.bat delete mode 100644 tools/memcached-amd64/run_memcached.sh delete mode 100644 tools/memcached-amd64/stop_memcached.sh delete mode 100644 tools/redis/Cluster/7000/nodes.conf delete mode 100644 tools/redis/Cluster/7000/redis.conf delete mode 100644 tools/redis/Cluster/7001/nodes.conf delete mode 100644 tools/redis/Cluster/7001/redis.conf delete mode 100644 tools/redis/Cluster/7002/nodes.conf delete mode 100644 tools/redis/Cluster/7002/redis.conf delete mode 100644 tools/redis/Cluster/7003/nodes.conf delete mode 100644 tools/redis/Cluster/7003/redis.conf delete mode 100644 tools/redis/Cluster/7004/nodes.conf delete mode 100644 tools/redis/Cluster/7004/redis.conf delete mode 100644 tools/redis/Cluster/7005/nodes.conf delete mode 100644 tools/redis/Cluster/7005/redis.conf delete mode 100644 tools/redis/install-service.cmd delete mode 100644 tools/redis/install.cmd delete mode 100644 tools/redis/master-debug.conf delete mode 100644 tools/redis/master.conf delete mode 100644 tools/redis/redis-cli master.cmd delete mode 100644 tools/redis/redis-server cluster.cmd delete mode 100644 tools/redis/redis-server-full.cmd delete mode 100644 tools/redis/redis-server-master-debug.cmd delete mode 100644 tools/redis/redis-server-master.cmd delete mode 100644 tools/redis/redis-server-sentinel.cmd delete mode 100644 tools/redis/redis-server-slave.cmd delete mode 100644 tools/redis/sentinel1.conf delete mode 100644 tools/redis/sentinel2.conf delete mode 100644 tools/redis/sentinel3.conf delete mode 100644 tools/redis/slave.conf diff --git a/Benchmarks.md b/Benchmarks.md index c626dca1..a7321c58 100644 --- a/Benchmarks.md +++ b/Benchmarks.md @@ -1,6 +1,8 @@ ## Benchmarks +TODO: needs update + Benchmarks have been implemented with [BenchmarkDotNet](https://github.com/PerfDotNet/BenchmarkDotNet). All CacheManager instances used in the benchmarks have only one cache handle configured, either the Dictionary, System.Runtime or Redis handle. diff --git a/CacheManager.sln b/CacheManager.sln index 43460c18..51aae70e 100644 --- a/CacheManager.sln +++ b/CacheManager.sln @@ -58,7 +58,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CacheManager.Serialization. EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{CB286D98-C974-4266-B8F2-1F9DE8B2B0EC}" ProjectSection(SolutionItems) = preProject - appveyor.yml = appveyor.yml tools\common.props = tools\common.props NuGet.Config = NuGet.Config tools\version.props = tools\version.props diff --git a/_disable_.travis.yml b/_disable_.travis.yml deleted file mode 100644 index 96ab1d45..00000000 --- a/_disable_.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: csharp -sudo: required -dist: trusty -os: - - linux - - osx -addons: - apt: - packages: - - gettext - - libcurl4-openssl-dev - - libicu-dev - - libssl-dev - - libunwind8 - - zlib1g -mono: - - 4.0.5 -osx_image: xcode7.1 -services: - - redis-server -before_install: - - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install icu4c; brew install openssl; ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/; fi -env: - - KOREBUILD_TEST_SKIPMONO=1 -script: - - chmod a+x ./build.sh - - ./build.sh --quiet verify - \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index f6c296b5..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: 2.0.0-beta-{build} -skip_tags: true -image: Visual Studio 2019 -configuration: Release -clone_folder: C:\projects\CacheManager\ -init: -- cmd: if "%APPVEYOR_REPO_BRANCH%" == "master" (set VersionSuffix=) else (set VersionSuffix=beta) -environment: - BuildNumber: $(APPVEYOR_BUILD_NUMBER) -install: -- ps: C:\projects\CacheManager\tools\redis\install-service.cmd -before_build: -- cmd: dotnet restore -build: - project: CacheManager.sln - parallel: true - verbosity: minimal -after_build: -- cmd: "dotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Core \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Couchbase \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Memcached \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Microsoft.Extensions.Caching.Memory \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Microsoft.Extensions.Configuration \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Microsoft.Extensions.Logging \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Serialization.Json \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Serialization.ProtoBuf \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.StackExchange.Redis \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.SystemRuntimeCaching \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Web \ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Serialization.Bond\ndotnet pack -o C:\\projects\\CacheManager\\artifacts -c Release src\\CacheManager.Serialization.DataContract" -test_script: -- cmd: >- - dotnet test test\CacheManager.Tests\CacheManager.Tests.csproj -c Release --no-build --filter "category!=Unreliable&category!=memcached&category!=Redis" - - dotnet test test\CacheManager.MSConfiguration.TypeLoad.Tests\CacheManager.MSConfiguration.TypeLoad.Tests.csproj --no-build -c Release -artifacts: -- path: artifacts\*.nupkg - name: nugets -deploy: -- provider: NuGet - server: https://www.myget.org/F/cachemanager/api/v2/package - symbol_server: https://www.myget.org/F/cachemanager/api/v2/package - artifact: nugets diff --git a/azure-pipelines-ci.yml b/azure-pipelines-ci.yml new file mode 100644 index 00000000..62109ad5 --- /dev/null +++ b/azure-pipelines-ci.yml @@ -0,0 +1,74 @@ +name: '$(Date:yyyyMMdd)$(Rev:.r)' + +trigger: +- dev +- master + +pr: + autoCancel: false + branches: + include: + - '*' + +# pool: +# vmImage: 'windows-latest' + +variables: + buildPlatform: 'Any CPU' + buildConfiguration: 'Release' + ${{ if not(eq(variables['Build.SourceBranch'], 'refs/heads/master')) }}: + versionSuffix: 'beta-$(Build.BuildNumber)' + ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/master') }}: + versionSuffix: '' + +jobs: +- job: 'Linux' + displayName: 'Build on Ubuntu' + pool: + vmImage: 'ubuntu-latest' + steps: + - task: DotNetCoreCLI@2 + inputs: + command: 'build' + projects: | + DnsClientDotNet.sln + arguments: '-c Release' + name: 'Build' + displayName: 'dotnet build' + - task: DotNetCoreCLI@2 + displayName: "dotnet test" + inputs: + command: 'test' + projects: 'test/**/*.csproj' + publishTestResults: true + arguments: '-c Release --no-build --no-restore -f net8.0' + +- job: Windows + displayName: 'Build & Test on Windows' + pool: + vmImage: 'windows-latest' + + steps: + - task: DotNetCoreCLI@2 + displayName: 'dotnet build' + inputs: + command: 'build' + projects: | + DnsClientDotNet.sln + arguments: '-c Release' + name: 'Build' + - task: DotNetCoreCLI@2 + displayName: "dotnet test" + inputs: + command: 'test' + projects: 'test/**/*.csproj' + publishTestResults: true + arguments: '-c Release --no-build --no-restore --collect "Code coverage" --settings:.runsettings' + - script: 'dotnet pack src\DnsClient\DnsClient.csproj -c Release --no-build --no-restore --version-suffix "$(versionSuffix)" -v normal -o $(Build.ArtifactStagingDirectory)' + name: 'PackBeta' + displayName: 'dotnet pack' + - task: PublishBuildArtifacts@1 + displayName: 'publish' + inputs: + pathtoPublish: '$(Build.ArtifactStagingDirectory)' + artifactName: 'beta' diff --git a/benchmarks/CacheManager.Benchmarks/BaseCacheManagerBenchmark.cs b/benchmarks/CacheManager.Benchmarks/BaseCacheManagerBenchmark.cs index 43fc3027..11d655db 100644 --- a/benchmarks/CacheManager.Benchmarks/BaseCacheManagerBenchmark.cs +++ b/benchmarks/CacheManager.Benchmarks/BaseCacheManagerBenchmark.cs @@ -10,11 +10,11 @@ public abstract class BaseCacheBenchmark { private static ICacheManagerConfiguration BaseConfig => new CacheConfigurationBuilder() - .WithMaxRetries(10) - .WithRetryTimeout(500) - .WithJsonSerializer() - .WithUpdateMode(CacheUpdateMode.Up) - .Build(); + .WithMaxRetries(10) + .WithRetryTimeout(500) + .WithJsonSerializer() + .WithUpdateMode(CacheUpdateMode.Up) + .Build(); protected ICacheManager DictionaryCache = new BaseCacheManager(BaseConfig.Builder.WithDictionaryHandle().Build()); @@ -22,7 +22,7 @@ private static ICacheManagerConfiguration BaseConfig protected ICacheManager RuntimeCache = new BaseCacheManager(BaseConfig.Builder.WithSystemRuntimeCacheHandle().Build()); protected ICacheManager RedisCache = new BaseCacheManager( - BaseConfig + BaseConfig .Builder .WithRedisConfiguration("redisKey", "localhost:6379,allowAdmin=true") .WithRedisCacheHandle("redisKey") diff --git a/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj b/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj index eeadd428..81077500 100644 --- a/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj +++ b/benchmarks/CacheManager.Config.Tests/CacheManager.Config.Tests.csproj @@ -30,4 +30,8 @@ + + + + \ No newline at end of file diff --git a/benchmarks/CacheManager.Config.Tests/Program.cs b/benchmarks/CacheManager.Config.Tests/Program.cs index 4444f299..41836cd2 100644 --- a/benchmarks/CacheManager.Config.Tests/Program.cs +++ b/benchmarks/CacheManager.Config.Tests/Program.cs @@ -1,106 +1,122 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Net; using System.Threading; +using System.Threading.Tasks; using CacheManager.Core; -using CacheManager.Redis; +using Garnet; +using Garnet.client; +using Garnet.server; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace CacheManager.Config.Tests +namespace CacheManager.Config.Tests; + +internal class Program { - internal class Program + public static GarnetServer StartServer(ILoggerFactory loggerFactory) { - public static void Main(string[] args) + var server = new GarnetServer(new GarnetServerOptions() { - ThreadPool.SetMinThreads(100, 100); + EnableLua = true, + LuaOptions = new LuaOptions(LuaMemoryManagementMode.Native, string.Empty, TimeSpan.FromSeconds(5)), + EndPoint = new IPEndPoint(IPAddress.Loopback, 6379) + }, + loggerFactory: loggerFactory); + + server.Start(); + + return server; + } - var iterations = 100; - try + public static void Main(string[] args) + { + ThreadPool.SetMinThreads(100, 100); + + var iterations = 100; + try + { + var services = new ServiceCollection(); + + services.AddLogging(c => { - var services = new ServiceCollection(); - + c.AddSystemdConsole(); + c.SetMinimumLevel(LogLevel.Information); + }); - services.AddLogging(c => - { - c.AddSystemdConsole(); - c.SetMinimumLevel(LogLevel.Information); - }); + var provider = services.BuildServiceProvider(); + var loggerFactory = provider.GetRequiredService(); - var provider = services.BuildServiceProvider(); - var loggerFactory = provider.GetRequiredService(); + using var server = StartServer(loggerFactory); - var builder = new Core.CacheConfigurationBuilder("myCache"); + var builder = new Core.CacheConfigurationBuilder("myCache"); - builder - .WithRetryTimeout(500) - .WithMaxRetries(3); + builder + .WithRetryTimeout(500) + .WithMaxRetries(3); - builder - .WithDictionaryHandle() - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(20)) - .DisableStatistics(); + builder + .WithDictionaryHandle() + .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(20)) + .DisableStatistics(); - builder - .WithRedisCacheHandle("redis", true) - .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(60)) - .DisableStatistics(); + builder + .WithRedisCacheHandle("redis", true) + .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(60)) + .DisableStatistics(); - builder.WithRedisBackplane("redis"); + builder.WithRedisBackplane("redis"); - builder.WithRedisConfiguration("redis", config => - { - config - //.UseTwemproxy() - //.UseCompatibilityMode("2.4") - .WithAllowAdmin() - .WithDatabase(0) - .WithConnectionTimeout(5000) - .EnableKeyspaceEvents() - .WithEndpoint("127.0.0.1", 6379); - }); + builder.WithRedisConfiguration("redis", config => + { + config + //.UseTwemproxy() + //.UseCompatibilityMode("2.4") + .WithAllowAdmin() + .WithDatabase(0) + .WithConnectionTimeout(5000) + .EnableKeyspaceEvents() + .WithEndpoint("127.0.0.1", 6379); + }); - //builder.WithRedisConfiguration("redis", "localhost:22121"); + //builder.WithRedisConfiguration("redis", "localhost:22121"); - builder.WithBondCompactBinarySerializer(); + builder.WithBondCompactBinarySerializer(); - var cacheA = new BaseCacheManager(builder.Build()); - cacheA.Clear(); + var cacheA = new BaseCacheManager(builder.Build()); + cacheA.Clear(); - for (var i = 0; i < iterations; i++) + for (var i = 0; i < iterations; i++) + { + try { - try - { - Tests.PumpData(cacheA).GetAwaiter().GetResult(); - break; // specified runtime (todo: rework this anyways) - } - catch (AggregateException ex) - { - ex.Handle((e) => - { - Console.WriteLine(e); - return true; - }); - } - catch (Exception e) + Tests.PumpData(cacheA).GetAwaiter().GetResult(); + break; // specified runtime (todo: rework this anyways) + } + catch (AggregateException ex) + { + ex.Handle((e) => { - Console.WriteLine("Error: " + e.Message + "\n" + e.StackTrace); - Thread.Sleep(1000); - } - - Console.WriteLine("---------------------------------------------------------"); + Console.WriteLine(e); + return true; + }); + } + catch (Exception e) + { + Console.WriteLine("Error: " + e.Message + "\n" + e.StackTrace); + Thread.Sleep(1000); } - } - catch (Exception ex) - { - Console.WriteLine(ex); - } - Console.ForegroundColor = ConsoleColor.DarkGreen; - Console.WriteLine("We are done..."); - Console.ForegroundColor = ConsoleColor.Gray; - Console.ReadKey(); + Console.WriteLine("---------------------------------------------------------"); + } } + catch (Exception ex) + { + Console.WriteLine(ex); + } + + Console.ForegroundColor = ConsoleColor.DarkGreen; + Console.WriteLine("We are done..."); + Console.ForegroundColor = ConsoleColor.Gray; + Console.ReadKey(); } } diff --git a/benchmarks/CacheManager.Config.Tests/cache.json b/benchmarks/CacheManager.Config.Tests/cache.json index e773cfaa..28afbcbe 100644 --- a/benchmarks/CacheManager.Config.Tests/cache.json +++ b/benchmarks/CacheManager.Config.Tests/cache.json @@ -18,7 +18,7 @@ "maxRetries": 1000, "name": "cachename", "retryTimeout": 100, - "updateMode": "Full", + "updateMode": "Up", "backplane": { "key": "redisConnection", "knownType": "Redis", diff --git a/benchmarks/CacheManager.Events.Tests/CacheManager.Events.Tests.csproj b/benchmarks/CacheManager.Events.Tests/CacheManager.Events.Tests.csproj index 574f8c81..823a5560 100644 --- a/benchmarks/CacheManager.Events.Tests/CacheManager.Events.Tests.csproj +++ b/benchmarks/CacheManager.Events.Tests/CacheManager.Events.Tests.csproj @@ -7,6 +7,7 @@ + diff --git a/benchmarks/CacheManager.Events.Tests/Program.cs b/benchmarks/CacheManager.Events.Tests/Program.cs index 508d1b7e..9b523dd7 100644 --- a/benchmarks/CacheManager.Events.Tests/Program.cs +++ b/benchmarks/CacheManager.Events.Tests/Program.cs @@ -1,43 +1,64 @@ using System; +using System.Net; +using Garnet; +using Garnet.server; using McMaster.Extensions.CommandLineUtils; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace CacheManager.Events.Tests +namespace CacheManager.Events.Tests; + + +internal class Program { - internal class Program + public static GarnetServer StartServer(ILoggerFactory loggerFactory) + { + var server = new GarnetServer(new GarnetServerOptions() + { + EnableLua = true, + LuaOptions = new LuaOptions(LuaMemoryManagementMode.Native, string.Empty, TimeSpan.FromSeconds(5)), + EndPoint = new IPEndPoint(IPAddress.Loopback, 6379) + }, + loggerFactory: loggerFactory); + + server.Start(); + + return server; + } + + private static void Main(string[] args) { - private static void Main(string[] args) + + var services = new ServiceCollection(); + services.AddLogging(c => + { + c.AddConsole(); + c.SetMinimumLevel(LogLevel.Warning); + }); + + var provider = services.BuildServiceProvider(); + var loggerFactory = provider.GetRequiredService(); + + using var server = StartServer(loggerFactory); + + var app = new CommandLineApplication(false); + app.Command("redis", (cmdApp) => new RedisCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); + app.Command("redisAndMemory", (cmdApp) => new RedisAndMemoryCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); + app.Command("redisAndMemoryNoMessages", (cmdApp) => new RedisAndMemoryNoMessagingCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); + app.Command("memoryOnly", (cmdApp) => new MemoryOnlyCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); + app.HelpOption("-h|--help"); + if (args.Length == 0) + { + app.ShowHelp(); + } + + try + { + app.Execute(args); + } + catch (Exception ex) { - var services = new ServiceCollection(); - services.AddLogging(c => - { - c.AddConsole(); - c.SetMinimumLevel(LogLevel.Warning); - }); - - var provider = services.BuildServiceProvider(); - var loggerFactory = provider.GetRequiredService(); - - var app = new CommandLineApplication(false); - app.Command("redis", (cmdApp) => new RedisCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); - app.Command("redisAndMemory", (cmdApp) => new RedisAndMemoryCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); - app.Command("redisAndMemoryNoMessages", (cmdApp) => new RedisAndMemoryNoMessagingCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); - app.Command("memoryOnly", (cmdApp) => new MemoryOnlyCommand(cmdApp, loggerFactory), throwOnUnexpectedArg: true); - app.HelpOption("-h|--help"); - if (args.Length == 0) - { - app.ShowHelp(); - } - - try - { - app.Execute(args); - } - catch (Exception ex) - { - Console.WriteLine(ex); - } + Console.WriteLine(ex); } } } diff --git a/benchmarks/CacheManager.Events.Tests/Properties/launchSettings.json b/benchmarks/CacheManager.Events.Tests/Properties/launchSettings.json index a8986eb0..63b7de9b 100644 --- a/benchmarks/CacheManager.Events.Tests/Properties/launchSettings.json +++ b/benchmarks/CacheManager.Events.Tests/Properties/launchSettings.json @@ -2,7 +2,7 @@ "profiles": { "CacheManager.Events.Tests": { "commandName": "Project", - "commandLineArgs": "redis -r 20 -j 10" + "commandLineArgs": "redisAndMemory -r 20 -j 10" } } -} \ No newline at end of file +} diff --git a/samples/AspNetCore/Program.cs b/samples/AspNetCore/Program.cs index 033840c5..a6a5beb2 100644 --- a/samples/AspNetCore/Program.cs +++ b/samples/AspNetCore/Program.cs @@ -1,25 +1,45 @@ using System; using System.Linq; +using System.Net; +using Garnet; +using Garnet.server; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; -namespace AspnetCore.WebApp +using Microsoft.Extensions.Logging; + +namespace AspnetCore.WebApp; + +public class Program { - public class Program + public static GarnetServer StartServer(ILoggerFactory loggerFactory = null) { - public static void Main(string[] args) + var server = new GarnetServer(new GarnetServerOptions() { - CreateHostBuilder(args).Build().Run(); - } + EnableLua = true, + LuaOptions = new LuaOptions(LuaMemoryManagementMode.Native, string.Empty, TimeSpan.FromSeconds(5)), + EndPoint = new IPEndPoint(IPAddress.Loopback, 6379) + }, + loggerFactory: loggerFactory); - public static IWebHostBuilder CreateHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup() - .ConfigureAppConfiguration((ctx, builder) => - { - builder.AddJsonFile("cache.json", optional: false); - }); + server.Start(); + + return server; } + + public static void Main(string[] args) + { + using var server = StartServer(); + CreateHostBuilder(args).Build().Run(); + } + + public static IWebHostBuilder CreateHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup() + .ConfigureAppConfiguration((ctx, builder) => + { + builder.AddJsonFile("cache.json", optional: false); + }); } diff --git a/samples/AspNetCore/Web.csproj b/samples/AspNetCore/Web.csproj index ec0ca829..7b1f9281 100644 --- a/samples/AspNetCore/Web.csproj +++ b/samples/AspNetCore/Web.csproj @@ -16,6 +16,7 @@ - + + \ No newline at end of file diff --git a/samples/CacheManager.Examples/CacheManager.Examples.csproj b/samples/CacheManager.Examples/CacheManager.Examples.csproj index fa264379..93231a7d 100644 --- a/samples/CacheManager.Examples/CacheManager.Examples.csproj +++ b/samples/CacheManager.Examples/CacheManager.Examples.csproj @@ -27,4 +27,8 @@ + + + + \ No newline at end of file diff --git a/samples/CacheManager.Examples/Program.cs b/samples/CacheManager.Examples/Program.cs index 1f0b1c14..3752d825 100644 --- a/samples/CacheManager.Examples/Program.cs +++ b/samples/CacheManager.Examples/Program.cs @@ -3,292 +3,310 @@ using CacheManager.Core; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; +using System.Net; +using Garnet.server; +using Garnet; -namespace CacheManager.Examples +namespace CacheManager.Examples; + +public class Program { - public class Program + public static GarnetServer StartServer(ILoggerFactory loggerFactory = null) { - private static void Main() + var server = new GarnetServer(new GarnetServerOptions() { - EventsExample(); - MostSimpleCacheManagerWithLogging(); - SimpleCustomBuildConfigurationUsingConfigBuilder(); - SimpleCustomBuildConfigurationUsingFactory(); - UpdateTest(); - UpdateCounterTest(); - LoggingSample(); - } + EnableLua = true, + LuaOptions = new LuaOptions(LuaMemoryManagementMode.Native, string.Empty, TimeSpan.FromSeconds(5)), + EndPoint = new IPEndPoint(IPAddress.Loopback, 6379) + }, + loggerFactory: loggerFactory); - private static void MostSimpleCacheManager() - { - var config = new CacheConfigurationBuilder() - .WithSystemRuntimeCacheHandle() - .Build(); + server.Start(); - var cache = new BaseCacheManager(config); - // or - var cache2 = CacheFactory.FromConfiguration(config); - } + return server; + } - private static void MostSimpleCacheManagerB() - { - var cache = new BaseCacheManager( - new CacheManagerConfiguration() - .Builder - .WithSystemRuntimeCacheHandle() - .Build()); - } + private static void Main() + { + using var server = StartServer(); + EventsExample(); + MostSimpleCacheManagerWithLogging(); + SimpleCustomBuildConfigurationUsingConfigBuilder(); + SimpleCustomBuildConfigurationUsingFactory(); + UpdateTest(); + UpdateCounterTest(); + LoggingSample(); + } - private static void MostSimpleCacheManagerC() - { - var cache = CacheFactory.Build( - p => p.WithSystemRuntimeCacheHandle()); - } + private static void MostSimpleCacheManager() + { + var config = new CacheConfigurationBuilder() + .WithSystemRuntimeCacheHandle() + .Build(); - private static void MostSimpleCacheManagerWithLogging() - { - var services = new ServiceCollection(); - services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Trace)); - var loggerFactory = services.BuildServiceProvider().GetService(); + var cache = new BaseCacheManager(config); + // or + var cache2 = CacheFactory.FromConfiguration(config); + } - var config = new CacheConfigurationBuilder() + private static void MostSimpleCacheManagerB() + { + var cache = new BaseCacheManager( + new CacheManagerConfiguration() + .Builder .WithSystemRuntimeCacheHandle() - .Build(); - - ICacheManager cache = new BaseCacheManager(config, loggerFactory); - cache.Add("test", "test"); - cache.Exists("test no"); - cache.Remove("test"); + .Build()); + } - // or - cache = CacheFactory.FromConfiguration(config, loggerFactory); + private static void MostSimpleCacheManagerC() + { + var cache = CacheFactory.Build( + p => p.WithSystemRuntimeCacheHandle()); + } - cache.Add("test", "test"); - cache.Exists("test no"); - cache.Remove("test"); - } + private static void MostSimpleCacheManagerWithLogging() + { + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Trace)); + var loggerFactory = services.BuildServiceProvider().GetService(); - private static void EditExistingConfiguration() - { - var config = new CacheConfigurationBuilder() - .WithSystemRuntimeCacheHandle() - .EnableStatistics() - .Build(); + var config = new CacheConfigurationBuilder() + .WithSystemRuntimeCacheHandle() + .Build(); - config = new CacheConfigurationBuilder(config) - .Build(); - } + ICacheManager cache = new BaseCacheManager(config, loggerFactory); + cache.Add("test", "test"); + cache.Exists("test no"); + cache.Remove("test"); - private static void LoggingSample() - { - var services = new ServiceCollection(); - services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Trace)); - var loggerFactory = services.BuildServiceProvider().GetService(); - - var cache = CacheFactory.Build( - c => c.WithDictionaryHandle() - .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)), - loggerFactory); - - cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value"); - cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value"); - cache.Expire("myKey", "someregion", TimeSpan.FromMinutes(10)); - var val = cache.Get("myKey", "someregion"); - } + // or + cache = CacheFactory.FromConfiguration(config, loggerFactory); - private static void AppConfigLoadInstalledCacheCfg() - { - var services = new ServiceCollection(); - services.AddLogging(c => c.AddConsole()); - var loggerFactory = services.BuildServiceProvider().GetService(); + cache.Add("test", "test"); + cache.Exists("test no"); + cache.Remove("test"); + } - var cache = CacheFactory.FromConfiguration("myCache", loggerFactory); - cache.Add("key", "value"); - } + private static void EditExistingConfiguration() + { + var config = new CacheConfigurationBuilder() + .WithSystemRuntimeCacheHandle() + .EnableStatistics() + .Build(); - private static void EventsExample() - { - var services = new ServiceCollection(); - services.AddLogging(c => c.AddConsole()); - var loggerFactory = services.BuildServiceProvider().GetService(); - - var cache = CacheFactory.Build(s => s.WithDictionaryHandle(), loggerFactory); - cache.OnAdd += (sender, args) => Console.WriteLine("Added " + args.Key); - cache.OnGet += (sender, args) => Console.WriteLine("Got " + args.Key); - cache.OnRemove += (sender, args) => Console.WriteLine("Removed " + args.Key); - - cache.Add("key", "value"); - var val = cache.Get("key"); - cache.Remove("key"); - } + config = new CacheConfigurationBuilder(config) + .Build(); + } - private static void RedisSample() - { - var services = new ServiceCollection(); - services.AddLogging(c => c.AddConsole()); - var loggerFactory = services.BuildServiceProvider().GetService(); + private static void LoggingSample() + { + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Trace)); + var loggerFactory = services.BuildServiceProvider().GetService(); - var cache = CacheFactory.Build(settings => - { - settings - .WithSystemRuntimeCacheHandle() - .And - .WithRedisConfiguration("redis", config => - { - config.WithAllowAdmin() - .WithDatabase(0) - .WithEndpoint("localhost", 6379); - }) - .WithMaxRetries(1000) - .WithRetryTimeout(100) - .WithRedisBackplane("redis") - .WithRedisCacheHandle("redis", true); - }, + var cache = CacheFactory.Build( + c => c.WithDictionaryHandle() + .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)), loggerFactory); - cache.Add("test", 123456); + cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value"); + cache.AddOrUpdate("myKey", "someregion", "value", _ => "new value"); + cache.Expire("myKey", "someregion", TimeSpan.FromMinutes(10)); + var val = cache.Get("myKey", "someregion"); + } - cache.Update("test", p => p + 1); + private static void AppConfigLoadInstalledCacheCfg() + { + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole()); + var loggerFactory = services.BuildServiceProvider().GetService(); - var result = cache.Get("test"); - } + var cache = CacheFactory.FromConfiguration("myCache", loggerFactory); + cache.Add("key", "value"); + } + + private static void EventsExample() + { + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole()); + var loggerFactory = services.BuildServiceProvider().GetService(); + + var cache = CacheFactory.Build(s => s.WithDictionaryHandle(), loggerFactory); + cache.OnAdd += (sender, args) => Console.WriteLine("Added " + args.Key); + cache.OnGet += (sender, args) => Console.WriteLine("Got " + args.Key); + cache.OnRemove += (sender, args) => Console.WriteLine("Removed " + args.Key); + + cache.Add("key", "value"); + var val = cache.Get("key"); + cache.Remove("key"); + } + + private static void RedisSample() + { + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole()); + var loggerFactory = services.BuildServiceProvider().GetService(); - private static void SimpleCustomBuildConfigurationUsingConfigBuilder() + var cache = CacheFactory.Build(settings => { - // this is using the CacheManager.Core.Configuration.ConfigurationBuilder to build a - // custom config you can do the same with the CacheFactory - var cfg = CacheConfigurationBuilder.BuildConfiguration(settings => + settings + .WithSystemRuntimeCacheHandle() + .And + .WithRedisConfiguration("redis", config => { - settings.WithUpdateMode(CacheUpdateMode.Up) - .WithDictionaryHandle() - .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); - }); - - var cache = CacheFactory.FromConfiguration(cfg); - cache.Add("key", "value"); - - // reusing the configuration and using the same cache for different types: - var numbers = CacheFactory.FromConfiguration(cfg); - numbers.Add("intKey", 2323); - numbers.Update("intKey", v => v + 1); - } + config.WithAllowAdmin() + .WithDatabase(0) + .WithEndpoint("localhost", 6379); + }) + .WithMaxRetries(1000) + .WithRetryTimeout(100) + .WithRedisBackplane("redis") + .WithRedisCacheHandle("redis", true); + }, + loggerFactory); + + cache.Add("test", 123456); + + cache.Update("test", p => p + 1); + + var result = cache.Get("test"); + } - private static void SimpleCustomBuildConfigurationUsingFactory() - { - var cache = CacheFactory.Build(settings => + private static void SimpleCustomBuildConfigurationUsingConfigBuilder() + { + // this is using the CacheManager.Core.Configuration.ConfigurationBuilder to build a + // custom config you can do the same with the CacheFactory + var cfg = CacheConfigurationBuilder.BuildConfiguration(settings => { - settings - .WithUpdateMode(CacheUpdateMode.Up) + settings.WithUpdateMode(CacheUpdateMode.Up) .WithDictionaryHandle() .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); }); - cache.Add("key", "value"); - } + var cache = CacheFactory.FromConfiguration(cfg); + cache.Add("key", "value"); + + // reusing the configuration and using the same cache for different types: + var numbers = CacheFactory.FromConfiguration(cfg); + numbers.Add("intKey", 2323); + numbers.Update("intKey", v => v + 1); + } - private static void UpdateTest() + private static void SimpleCustomBuildConfigurationUsingFactory() + { + var cache = CacheFactory.Build(settings => { - var cache = CacheFactory.Build(s => s.WithDictionaryHandle()); + settings + .WithUpdateMode(CacheUpdateMode.Up) + .WithDictionaryHandle() + .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10)); + }); - Console.WriteLine("Testing update..."); + cache.Add("key", "value"); + } - if (!cache.TryUpdate("test", v => "item has not yet been added", out string newValue)) - { - Console.WriteLine("Value not added?: {0}", newValue == null); - } + private static void UpdateTest() + { + var cache = CacheFactory.Build(s => s.WithDictionaryHandle()); - cache.Add("test", "start"); - Console.WriteLine("Initial value: {0}", cache["test"]); + Console.WriteLine("Testing update..."); - cache.AddOrUpdate("test", "adding again?", v => "updating and not adding"); - Console.WriteLine("After AddOrUpdate: {0}", cache["test"]); + if (!cache.TryUpdate("test", v => "item has not yet been added", out string newValue)) + { + Console.WriteLine("Value not added?: {0}", newValue == null); + } - cache.Remove("test"); - try - { - var removeValue = cache.Update("test", v => "updated?"); - } - catch - { - Console.WriteLine("Error as expected because item didn't exist."); - } + cache.Add("test", "start"); + Console.WriteLine("Initial value: {0}", cache["test"]); - // use try update to not deal with exceptions - if (!cache.TryUpdate("test", v => v, out string removedValue)) - { - Console.WriteLine("Value after remove is null?: {0}", removedValue == null); - } + cache.AddOrUpdate("test", "adding again?", v => "updating and not adding"); + Console.WriteLine("After AddOrUpdate: {0}", cache["test"]); + + cache.Remove("test"); + try + { + var removeValue = cache.Update("test", v => "updated?"); + } + catch + { + Console.WriteLine("Error as expected because item didn't exist."); } - private static void UpdateCounterTest() + // use try update to not deal with exceptions + if (!cache.TryUpdate("test", v => v, out string removedValue)) { - var cache = CacheFactory.Build(s => s.WithDictionaryHandle()); + Console.WriteLine("Value after remove is null?: {0}", removedValue == null); + } + } - Console.WriteLine("Testing update counter..."); + private static void UpdateCounterTest() + { + var cache = CacheFactory.Build(s => s.WithDictionaryHandle()); - cache.AddOrUpdate("counter", 0, v => v + 1); + Console.WriteLine("Testing update counter..."); - Console.WriteLine("Initial value: {0}", cache.Get("counter")); + cache.AddOrUpdate("counter", 0, v => v + 1); - for (var i = 0; i < 12345; i++) - { - cache.Update("counter", v => v + 1); - } + Console.WriteLine("Initial value: {0}", cache.Get("counter")); - Console.WriteLine("Final value: {0}", cache.Get("counter")); + for (var i = 0; i < 12345; i++) + { + cache.Update("counter", v => v + 1); } - private static void MultiCacheEvictionWithoutRedisCacheHandle() - { - var config = new CacheConfigurationBuilder("Redis with Redis Backplane") - .WithDictionaryHandle(true) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(5)) - .And - .WithRedisBackplane("redisConfig") - .WithRedisConfiguration("redisConfig", "localhost,allowadmin=true", enableKeyspaceNotifications: true) - //.WithMicrosoftLogging(new LoggerFactory().AddConsole(LogLevel.Debug)) - .Build(); + Console.WriteLine("Final value: {0}", cache.Get("counter")); + } - var cacheA = new BaseCacheManager(config); - var cacheB = new BaseCacheManager(config); + private static void MultiCacheEvictionWithoutRedisCacheHandle() + { + var config = new CacheConfigurationBuilder("Redis with Redis Backplane") + .WithDictionaryHandle(true) + .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(5)) + .And + .WithRedisBackplane("redisConfig") + .WithRedisConfiguration("redisConfig", "localhost,allowadmin=true", enableKeyspaceNotifications: true) + //.WithMicrosoftLogging(new LoggerFactory().AddConsole(LogLevel.Debug)) + .Build(); - var key = "someKey"; + var cacheA = new BaseCacheManager(config); + var cacheB = new BaseCacheManager(config); - cacheA.OnRemove += (s, args) => - { - Console.WriteLine("A triggered remove: " + args.ToString() + " - key still exists? " + cacheA.Exists(key)); - }; - cacheB.OnRemove += (s, args) => - { - Console.WriteLine("B triggered remove: " + args.ToString() + " - key still exists? " + cacheB.Exists(key)); - }; + var key = "someKey"; - cacheA.OnRemoveByHandle += (s, args) => - { - cacheA.Remove(args.Key); - Console.WriteLine("A triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key)); - }; + cacheA.OnRemove += (s, args) => + { + Console.WriteLine("A triggered remove: " + args.ToString() + " - key still exists? " + cacheA.Exists(key)); + }; + cacheB.OnRemove += (s, args) => + { + Console.WriteLine("B triggered remove: " + args.ToString() + " - key still exists? " + cacheB.Exists(key)); + }; - cacheB.OnRemoveByHandle += (s, args) => - { - Console.WriteLine("B triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key) + " in A? " + cacheA.Exists(key)); - }; + cacheA.OnRemoveByHandle += (s, args) => + { + cacheA.Remove(args.Key); + Console.WriteLine("A triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key)); + }; - cacheA.OnAdd += (s, args) => - { - Console.WriteLine("A triggered add: " + args.ToString()); - }; + cacheB.OnRemoveByHandle += (s, args) => + { + Console.WriteLine("B triggered removeByHandle: " + args.ToString() + " - key still exists? " + cacheA.Exists(key) + " in A? " + cacheA.Exists(key)); + }; - cacheB.OnAdd += (s, args) => - { - Console.WriteLine("B triggered add: " + args.ToString()); - }; + cacheA.OnAdd += (s, args) => + { + Console.WriteLine("A triggered add: " + args.ToString()); + }; - Console.WriteLine("Add to A: " + cacheA.Add(key, "some value")); - Console.WriteLine("Add to B: " + cacheB.Add(key, "some value")); + cacheB.OnAdd += (s, args) => + { + Console.WriteLine("B triggered add: " + args.ToString()); + }; - Thread.Sleep(2000); - cacheA.Remove(key); - } + Console.WriteLine("Add to A: " + cacheA.Add(key, "some value")); + Console.WriteLine("Add to B: " + cacheB.Add(key, "some value")); + + Thread.Sleep(2000); + cacheA.Remove(key); } } diff --git a/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj b/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj index 97883037..bf56cba7 100644 --- a/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj +++ b/src/CacheManager.Microsoft.Extensions.Caching.Memory/CacheManager.Microsoft.Extensions.Caching.Memory.csproj @@ -12,9 +12,9 @@ - + - + \ No newline at end of file diff --git a/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj b/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj index 9d8948e6..a1109179 100644 --- a/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj +++ b/src/CacheManager.StackExchange.Redis/CacheManager.StackExchange.Redis.csproj @@ -8,7 +8,7 @@ Caching;Cache;CacheManager;Distributed Cache;StackExchange Redis;Azure AppFabric;Memcached - + diff --git a/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj b/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj index 41f40995..b1f3b8db 100644 --- a/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj +++ b/test/CacheManager.MSConfiguration.TypeLoad.Tests/CacheManager.MSConfiguration.TypeLoad.Tests.csproj @@ -6,6 +6,7 @@ CacheManager.MSConfiguration.TypeLoad.Tests CacheManager.MSConfiguration.TypeLoad.Tests true + $(NoWarn);CA2021 diff --git a/test/CacheManager.Tests/CacheManager.Tests.csproj b/test/CacheManager.Tests/CacheManager.Tests.csproj index dd07596c..5f166f12 100644 --- a/test/CacheManager.Tests/CacheManager.Tests.csproj +++ b/test/CacheManager.Tests/CacheManager.Tests.csproj @@ -2,7 +2,7 @@ - net481;net8.0 + ;net8.0 1.0.0 CacheManager.Tests @@ -11,6 +11,7 @@ true CacheManager.Tests true + $(NoWarn);CA2021 @@ -60,6 +61,7 @@ + @@ -67,16 +69,9 @@ - - - $(DefineConstants);REDISENABLED; - - - $(DefineConstants);REDISENABLED; - \ No newline at end of file diff --git a/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs b/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs index f4b66d92..d64ab0dc 100644 --- a/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs +++ b/test/CacheManager.Tests/CacheManagerAdvancedUpdateTests.cs @@ -11,7 +11,7 @@ namespace CacheManager.Tests { [ExcludeFromCodeCoverage] - public class CacheManagerAdvancedUpdateTests + public class CacheManagerAdvancedUpdateTests : IClassFixture { [Theory] [ClassData(typeof(TestCacheManagers))] diff --git a/test/CacheManager.Tests/CacheManagerEventsTest.cs b/test/CacheManager.Tests/CacheManagerEventsTest.cs index 7c179f4e..1874fc43 100644 --- a/test/CacheManager.Tests/CacheManagerEventsTest.cs +++ b/test/CacheManager.Tests/CacheManagerEventsTest.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using CacheManager.Core; using CacheManager.Core.Internal; - using CacheManager.Core.Utility; using FluentAssertions; using Microsoft.Extensions.Logging; @@ -17,7 +16,7 @@ using static TestHelper; [ExcludeFromCodeCoverage] - public class CacheManagerEventsTest + public class CacheManagerEventsTest : IClassFixture { private readonly ITestOutputHelper _testOutputHelper; @@ -369,10 +368,11 @@ public async Task Events_MsMemory_ExpireEvictsAbove() } } +#if NET8_0_OR_GREATER // exclusive inner class for parallel exec of this long running test - public class RedisSpecific : LongRunningEventTestBase + public class RedisSpecific : LongRunningEventTestBase, IClassFixture { - [Fact] + [Fact(Skip = "Garnet currently does not support keyspace notifications - cannot test...")] [Trait("category", "Redis")] [Trait("category", "Unreliable")] public async Task Events_Redis_ExpireTriggers() @@ -394,7 +394,7 @@ public async Task Events_Redis_ExpireTriggers() result.Region.Should().Be(useRegion); } - [Fact] + [Fact(Skip = "Garnet currently does not support keyspace notifications - cannot test...")] [Trait("category", "Redis")] [Trait("category", "Unreliable")] public async Task Events_Redis_ExpireEvictsAbove() @@ -418,6 +418,7 @@ public async Task Events_Redis_ExpireEvictsAbove() result.Region.Should().BeNull(); } } +#endif [Theory] [ClassData(typeof(TestCacheManagers))] @@ -533,7 +534,7 @@ public void Events_OnGetManyHandles(T cache) } } - [Fact] + [Fact(Skip = "Garnet currently does not support keyspace notifications - cannot test...")] [Trait("category", "Redis")] [Trait("category", "Unreliable")] public async Task Events_OnRemoveExternal_Redis_UpHandling() @@ -588,7 +589,7 @@ await WaitUntilCancel((source) => cache.CacheHandles.First().Get(key).Should().BeNull(); } - [Fact] + [Fact(Skip = "Garnet currently does not support keyspace notifications - cannot test...")] [Trait("category", "Redis")] [Trait("category", "Unreliable")] public async Task Events_OnRemoveExternal_Redis_NoneHandling() @@ -610,7 +611,7 @@ public async Task Events_OnRemoveExternal_Redis_NoneHandling() var cache = new BaseCacheManager(config); await RetryWithCondition( - 5, + 1, async () => { key = Guid.NewGuid().ToString(); diff --git a/test/CacheManager.Tests/CacheManagerExpirationTest.cs b/test/CacheManager.Tests/CacheManagerExpirationTest.cs index de57bb69..81d53f72 100644 --- a/test/CacheManager.Tests/CacheManagerExpirationTest.cs +++ b/test/CacheManager.Tests/CacheManagerExpirationTest.cs @@ -9,9 +9,9 @@ using Xunit; [ExcludeFromCodeCoverage] - public class CacheManagerExpirationTest + public class CacheManagerExpirationTest : IClassFixture { - public class AllCaches + public class AllCaches : IClassFixture { [Trait("category", "Unreliable")] [Theory] @@ -174,8 +174,8 @@ await TestSlidingExpiration( } } } - - public class Redis +#if NET8_0_OR_GREATER + public class Redis : IClassFixture { [Fact] [Trait("category", "Redis")] @@ -278,6 +278,7 @@ await TestSlidingExpiration( } } } +#endif public class ExpireTests { @@ -519,7 +520,7 @@ public void Expiration_DoesNotBreak_OnVeryPreciseValue(T cache) } } - public class RemoveExpiration + public class RemoveExpiration : IClassFixture { // Issue #9 - item still expires [Theory] @@ -621,7 +622,7 @@ await TestRemoveExpiration( } } - public class RemoveExpirationExplicit + public class RemoveExpirationExplicit : IClassFixture { [Theory] [ClassData(typeof(TestCacheManagers))] @@ -686,7 +687,7 @@ await TestRemoveExpiration( } } - public class ValidateExpire + public class ValidateExpire : IClassFixture { [Theory] [ClassData(typeof(TestCacheManagers))] @@ -812,6 +813,7 @@ public void Expiration_Remove_ForKeyRegion_Validate(T cache) } } +#if NET8_0_OR_GREATER /* General expiration tests */ /// @@ -834,6 +836,7 @@ public void Redis_ExpirationTimeoutLimit() act.Should().Throw().WithMessage("*not supported*"); } } +#endif // Related to #136 [Fact] diff --git a/test/CacheManager.Tests/CacheManagerRegionTests.cs b/test/CacheManager.Tests/CacheManagerRegionTests.cs index 6b9fbff9..ea02e28c 100644 --- a/test/CacheManager.Tests/CacheManagerRegionTests.cs +++ b/test/CacheManager.Tests/CacheManagerRegionTests.cs @@ -14,7 +14,7 @@ namespace CacheManager.Tests /// removes an item from all handles defined. /// [ExcludeFromCodeCoverage] - public class CacheManagerRegionTests + public class CacheManagerRegionTests : IClassFixture { [Theory] [ClassData(typeof(TestCacheManagers))] diff --git a/test/CacheManager.Tests/CacheManagerSimpleTests.cs b/test/CacheManager.Tests/CacheManagerSimpleTests.cs index d026e646..549f726b 100644 --- a/test/CacheManager.Tests/CacheManagerSimpleTests.cs +++ b/test/CacheManager.Tests/CacheManagerSimpleTests.cs @@ -17,7 +17,7 @@ namespace CacheManager.Tests /// removes an item from all handles defined. /// [ExcludeFromCodeCoverage] - public class CacheManagerSimpleTests + public class CacheManagerSimpleTests : IClassFixture { private static object runLock = new object(); diff --git a/test/CacheManager.Tests/CacheManagerStatsTest.cs b/test/CacheManager.Tests/CacheManagerStatsTest.cs index 788bee27..0a2c73be 100644 --- a/test/CacheManager.Tests/CacheManagerStatsTest.cs +++ b/test/CacheManager.Tests/CacheManagerStatsTest.cs @@ -11,7 +11,7 @@ namespace CacheManager.Tests { [ExcludeFromCodeCoverage] - public class CacheManagerStatsTest + public class CacheManagerStatsTest : IClassFixture { [Theory] [ClassData(typeof(TestCacheManagers))] @@ -248,4 +248,4 @@ await ThreadTestHelper.RunAsync( Enumerable.Repeat((long)(threads * iterations), cache.CacheHandles.Count())); } } -} \ No newline at end of file +} diff --git a/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config b/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config index 63bf0d16..f685b8e2 100644 --- a/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config +++ b/test/CacheManager.Tests/Configuration/configuration.valid.allFeatures.config @@ -21,7 +21,7 @@ - + diff --git a/test/CacheManager.Tests/MemcachedTests.cs b/test/CacheManager.Tests/MemcachedTests.cs deleted file mode 100644 index 0848173d..00000000 --- a/test/CacheManager.Tests/MemcachedTests.cs +++ /dev/null @@ -1,435 +0,0 @@ -#if MEMCACHEDENABLED -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using CacheManager.Core; -using CacheManager.Memcached; -using Enyim.Caching; -using Enyim.Caching.Configuration; -using FluentAssertions; -using Xunit; - -namespace CacheManager.Tests -{ - [ExcludeFromCodeCoverage] - public class MemcachedTests - { - private object logObj = new object(); - - public static MemcachedClientConfiguration Configuration - { - get - { - var memConfig = new MemcachedClientConfiguration(); - memConfig.AddServer("localhost", 11211); - return memConfig; - } - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_ExtensionsWork_FromSection() - { - var cache = CacheFactory.Build( - settings => - settings.WithMemcachedCacheHandle("default")); - - Assert.NotNull(cache); - cache.Put("key", "value"); - Assert.NotNull(cache.Get("key")); - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_ExtensionsWork_WithClient() - { - var client = new MemcachedClient(Configuration); - var cache = CacheFactory.Build( - settings => - settings.WithMemcachedCacheHandle(client)); - - Assert.NotNull(cache); - var handle = cache.CacheHandles.OfType>().First(); - Assert.Equal(client, handle.Cache); - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_ExtensionsWork_WithClientNamed() - { - var client = new MemcachedClient(Configuration); - var cache = CacheFactory.Build( - settings => - settings.WithMemcachedCacheHandle("memcachedname", client)); - - Assert.NotNull(cache); - var handle = cache.CacheHandles.OfType>().First(); - Assert.Equal(client, handle.Cache); - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_ExtensionsWork_WithClientNull() - { - Action act = () => CacheFactory.Build( - settings => - settings.WithMemcachedCacheHandle("name", (MemcachedClient)null)); - - var ex = Record.Exception(act); - - // doesn't actually throw check on client because it hits the standard ctor without the client because of the Null value. - Assert.IsType(ex); - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_ExtensionsWork_WithConfiguration() - { - var cache = CacheFactory.Build( - settings => - settings.WithMemcachedCacheHandle(Configuration)); - - Assert.NotNull(cache); - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_ExtensionsWork_WithConfigurationNamed() - { - var cache = CacheFactory.Build( - settings => - settings.WithMemcachedCacheHandle("cachename", Configuration)); - - Assert.NotNull(cache); - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_ExtensionsWork_WithConfigurationNull() - { - Action act = () => CacheFactory.Build( - settings => - settings.WithMemcachedCacheHandle("name", (MemcachedClientConfiguration)null)); - - var ex = Record.Exception(act); - - // doesn't actually throw check on client because it hits the standard ctor without the client because of the Null value. - Assert.IsType(ex); - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_KeySizeLimit() - { - // arrange - var longKey = string.Join(string.Empty, Enumerable.Repeat("a", 300)); - - var item = new CacheItem(longKey, "something"); - var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithUpdateMode(CacheUpdateMode.Up) - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1)) - .Build()); - - // act - using (cache) - { - try - { - cache.Remove(item.Key); - Func act = () => cache.Add(item); - Func act2 = () => cache[item.Key]; - - // assert - act().Should().BeTrue(); - act2().Should().Be(item.Value); - } - catch - { - throw; - } - } - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_KeySizeLimit_WithRegion() - { - // arrange - var longKey = string.Join(string.Empty, Enumerable.Repeat("a", 300)); - - var item = new CacheItem(longKey, "someRegion", "something"); - var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithUpdateMode(CacheUpdateMode.Up) - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(1)) - .Build()); - - // act - using (cache) - { - cache.Remove(item.Key, item.Region); - Func act = () => cache.Add(item); - Func act2 = () => cache[item.Key, item.Region]; - - // assert - act().Should().BeTrue(); - act2().Should().Be(item.Value); - } - } - - [Fact] - [Trait("category", "Memcached")] - public async Task Memcached_NoRaceCondition_WithCasButTooFiewRetries() - { - // arrange - using (var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithUpdateMode(CacheUpdateMode.Up) - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(10)) - .Build())) - { - cache.Remove("myCounter"); - cache.Add("myCounter", new RaceConditionTestElement() { Counter = 0 }); - int numThreads = 5; - int iterations = 10; - int numInnerIterations = 10; - int countCasModifyCalls = 0; - int retries = 0; - - // act - await ThreadTestHelper.RunAsync( - async () => - { - for (int i = 0; i < numInnerIterations; i++) - { - RaceConditionTestElement newValue; - cache.TryUpdate( - "myCounter", - (value) => - { - value.Counter++; - Interlocked.Increment(ref countCasModifyCalls); - return value; - }, - retries, - out newValue); - } - - await Task.Delay(10); - }, - numThreads, - iterations); - - // assert - var result = cache.Get("myCounter"); - result.Should().NotBeNull(); - Trace.TraceInformation("Counter increased to " + result.Counter + " cas calls needed " + countCasModifyCalls); - result.Counter.Should().BeLessThan( - numThreads * numInnerIterations * iterations, - "counter should NOT be exactly the expected value"); - countCasModifyCalls.Should().Be( - numThreads * numInnerIterations * iterations, - "with one try, we exactly one update call per iteration"); - } - } - - [Fact] - [Trait("category", "Memcached")] - public async Task Memcached_NoRaceCondition_WithCasHandling() - { - // arrange - using (var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithMaxRetries(int.MaxValue) - .WithSystemRuntimeCacheHandle() - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMilliseconds(1)) - .And - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(60)) - .Build())) - { - var key = Guid.NewGuid().ToString(); - cache.Remove(key); - cache.Add(key, new RaceConditionTestElement() { Counter = 0 }).Should().BeTrue(); - int numThreads = 5; - int iterations = 10; - int numInnerIterations = 10; - int countCasModifyCalls = 0; - - // act - await ThreadTestHelper.RunAsync( - async () => - { - for (int i = 0; i < numInnerIterations; i++) - { - cache.Update( - key, - (value) => - { - value.Counter++; - Interlocked.Increment(ref countCasModifyCalls); - return value; - }); - } - - await Task.Delay(10); - }, - numThreads, - iterations); - - // assert - var result = cache.Get(key); - result.Should().NotBeNull(); - Trace.WriteLine("Counter increased to " + result.Counter + " cas calls needed " + countCasModifyCalls); - result.Counter.Should().Be(numThreads * numInnerIterations * iterations, "counter should be exactly the expected value"); - countCasModifyCalls.Should().BeGreaterThan((int)result.Counter, "we expect many version collisions, so cas calls should be way higher then the count result"); - } - } - - [Fact] - [Trait("category", "Memcached")] - public async Task Memcached_NoRaceCondition_WithCasHandling_WithRegion() - { - // arrange - using (var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithMaxRetries(int.MaxValue) - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(10)) - .Build())) - { - var region = Guid.NewGuid().ToString(); - var key = Guid.NewGuid().ToString(); - cache.Remove(key, region); - cache.Add(key, new RaceConditionTestElement() { Counter = 0 }, region); - int numThreads = 5; - int iterations = 10; - int numInnerIterations = 10; - int countCasModifyCalls = 0; - - // act - await ThreadTestHelper.RunAsync( - async () => - { - for (int i = 0; i < numInnerIterations; i++) - { - cache.Update( - key, - region, - (value) => - { - value.Counter++; - Interlocked.Increment(ref countCasModifyCalls); - return value; - }); - } - await Task.Delay(10); - }, - numThreads, - iterations); - - // assert - var result = cache.Get(key, region); - result.Should().NotBeNull(); - Trace.TraceInformation("Counter increased to " + result.Counter + " cas calls needed " + countCasModifyCalls); - result.Counter.Should().Be(numThreads * numInnerIterations * iterations, "counter should be exactly the expected value"); - countCasModifyCalls.Should().BeGreaterThan((int)result.Counter, "we expect many version collisions, so cas calls should be way higher then the count result"); - } - } - - [Fact] - [Trait("category", "Memcached")] - public async Task Memcached_RaceCondition_WithoutCasHandling() - { - // arrange - using (var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithUpdateMode(CacheUpdateMode.Up) - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(20)) - .Build())) - { - var key = Guid.NewGuid().ToString(); - cache.Remove(key); - cache.Add(key, new RaceConditionTestElement() { Counter = 0 }); - int numThreads = 5; - int iterations = 10; - int numInnerIterations = 10; - - // act - await ThreadTestHelper.RunAsync( - async () => - { - for (int i = 0; i < numInnerIterations; i++) - { - var val = cache.Get(key); - val.Should().NotBeNull(); - val.Counter++; - - cache.Put(key, val); - } - - await Task.Delay(10); - }, - numThreads, - iterations); - - // assert - var result = cache.Get(key); - result.Should().NotBeNull(); - Trace.TraceInformation("Counter increased to " + result.Counter); - result.Counter.Should().NotBe(numThreads * numInnerIterations * iterations); - } - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_Update_ItemNotAdded() - { - // arrange - using (var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithUpdateMode(CacheUpdateMode.Up) - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(20)) - .Build())) - { - RaceConditionTestElement value; - - // act - Func act = () => cache.TryUpdate(Guid.NewGuid().ToString(), item => item, out value); - - // assert - act().Should().BeFalse("Item has not been added to the cache"); - } - } - - [Fact] - [Trait("category", "Memcached")] - public void Memcached_TimeoutNotBeGreaterThan30Days() - { - // arrange - using (var cache = CacheFactory.FromConfiguration( - TestManagers.BaseConfiguration.Builder - .WithUpdateMode(CacheUpdateMode.Up) - .WithMemcachedCacheHandle(Configuration) - .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(40)) - .Build())) - { - // act - Action act = () => cache.Add(Guid.NewGuid().ToString(), "test"); - - // assert - act.Should().Throw("*30 days*"); - } - } - } -} -#endif \ No newline at end of file diff --git a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs index 83e23768..0a34e354 100644 --- a/test/CacheManager.Tests/MicrosoftConfigurationTests.cs +++ b/test/CacheManager.Tests/MicrosoftConfigurationTests.cs @@ -11,7 +11,7 @@ namespace CacheManager.Tests { [ExcludeFromCodeCoverage] - public class MicrosoftConfigurationTests + public class MicrosoftConfigurationTests : IClassFixture { [Fact] public void Configuration_CacheManager_ComplexSingleManager() @@ -582,7 +582,7 @@ public void Configuration_Backplane_Redis_MissingKey() act.Should().Throw().WithMessage("*The key property is required*"); } -#if REDISENABLED +#if NET8_0_OR_GREATER [Fact] [Trait("category", "Redis")] diff --git a/test/CacheManager.Tests/RedisTestFixture.cs b/test/CacheManager.Tests/RedisTestFixture.cs new file mode 100644 index 00000000..3c252091 --- /dev/null +++ b/test/CacheManager.Tests/RedisTestFixture.cs @@ -0,0 +1,72 @@ +#if NET8_0_OR_GREATER + +using System; +using System.Threading.Tasks; +using System.Threading; +using Garnet; +using Garnet.server; +using System.Net; +using Microsoft.Extensions.Logging; + +#endif + +namespace CacheManager.Tests +{ + public class RedisTestFixture : IDisposable + { +#if NET8_0_OR_GREATER + + private static Lazy server = new Lazy(() => StartServer()); + + private static int InstanceCount = 0; + + public static GarnetServer StartServer(ILoggerFactory loggerFactory = null) + { + Console.WriteLine("Starting server..."); + var server = new GarnetServer(new GarnetServerOptions() + { + EnableLua = true, + LuaOptions = new LuaOptions(LuaMemoryManagementMode.Native, string.Empty, TimeSpan.FromSeconds(20)), + EndPoint = new IPEndPoint(IPAddress.Loopback, 6379), + }, + loggerFactory: loggerFactory); + try + { + server.Start(); + Task.Delay(1000).GetAwaiter().GetResult(); + } + catch(Exception ex) + { + Console.WriteLine(ex); + } + + return server; + } + + public RedisTestFixture() + { + Interlocked.Increment(ref InstanceCount); + + var info = server.Value.Metrics.GetInfoMetrics(); + } + + public void Dispose() + { + var current = Interlocked.Decrement(ref InstanceCount); + Console.WriteLine($"Disposing... {current}"); + if (current == 0) + { + server.Value.Dispose(); + server = new Lazy(() => StartServer()); + } + } + +#else + + public void Dispose() + { + } + +#endif + } +} diff --git a/test/CacheManager.Tests/RedisTests.cs b/test/CacheManager.Tests/RedisTests.cs index ae13bcda..bbcb830a 100644 --- a/test/CacheManager.Tests/RedisTests.cs +++ b/test/CacheManager.Tests/RedisTests.cs @@ -1,4 +1,6 @@ -using System; +#if NET8_0_OR_GREATER + +using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -17,7 +19,7 @@ namespace CacheManager.Tests /// To run the redis tests, make sure a local redis server instance is running. See redis folder under tools. /// [ExcludeFromCodeCoverage] - public class RedisTests + public class RedisTests : IClassFixture { private enum CacheEvent { @@ -729,7 +731,7 @@ public void Redis_Configurations_LoadWConnectionString_WithDefaultDb() cfg.ConnectionString.ToLower().Should().Contain("127.0.0.1:6379"); cfg.ConnectionString.ToLower().Should().Contain("allowadmin=true"); cfg.ConnectionString.ToLower().Should().Contain("ssl=false"); - cfg.Database.Should().Be(42); + cfg.Database.Should().Be(0); cfg.StrictCompatibilityModeVersion.Should().Be("2.9"); } @@ -914,7 +916,7 @@ public void Redis_Verify_NoCredentialsLoggedOrThrown() config .WithConnectionTimeout(10) .WithAllowAdmin() - .WithDatabase(7) + //.WithDatabase(7) .WithEndpoint("doesnotexist", 6379) .WithPassword("mysupersecret") .WithSsl(); @@ -943,7 +945,7 @@ public async Task Redis_NoRaceCondition_WithUpdate() settings.WithRedisConfiguration("default", config => { config.WithAllowAdmin() - .WithDatabase(7) + //.WithDatabase(7) .WithEndpoint("127.0.0.1", 6379); }); })) @@ -1001,7 +1003,7 @@ public async Task Redis_RaceCondition_WithoutUpdate() settings.WithRedisConfiguration("default", config => { config.WithAllowAdmin() - .WithDatabase(8) + //.WithDatabase(8) .WithEndpoint("127.0.0.1", 6379); }); })) @@ -1173,7 +1175,7 @@ public void Redis_LoadWithRedisBackplane_FromAppConfigConnectionStrings_WithDefa // assert handle.Should().NotBeNull(); count.Should().NotThrow(); - redisConfig.Database.Should().Be(44); + redisConfig.Database.Should().Be(0); redisConfig.AllowAdmin.Should().BeTrue(); redisConfig.ConnectionTimeout.Should().Be(11); } @@ -1249,7 +1251,7 @@ public void Redis_ValueConverter_ValidateValuesTypesNotUsingSerializer(T valu .WithRedisConfiguration(redisKey, config => { config - .WithDatabase(66) + //.WithDatabase(66) .WithEndpoint("127.0.0.1", 6379); }) .WithRedisCacheHandle(redisKey, true); @@ -1519,3 +1521,5 @@ public byte[] SerializeCacheItem(CacheItem value) } } } + +#endif diff --git a/test/CacheManager.Tests/SerializerTests.cs b/test/CacheManager.Tests/SerializerTests.cs index 608c3b6b..88c7f404 100644 --- a/test/CacheManager.Tests/SerializerTests.cs +++ b/test/CacheManager.Tests/SerializerTests.cs @@ -3,8 +3,6 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters; -using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Json; using CacheManager.Core; using CacheManager.Core.Internal; @@ -22,11 +20,9 @@ namespace CacheManager.Tests { [ExcludeFromCodeCoverage] - public class SerializerTests + public class SerializerTests : IClassFixture { - - -#if NET461 +#if NET481_OR_GREATER // Bug #327 [Theory] @@ -36,19 +32,16 @@ public class SerializerTests [InlineData(typeof(IList), "System.Collections.Generic.IList`1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e")] [InlineData(typeof(Dictionary), "System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.IO.TextWriter, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e")] [InlineData(typeof(Dictionary), "System.Collections.Generic.Dictionary`2[[System.DateTime, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Text.UTF8Encoding, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e")] - // There are still types which will not work, like HashSet, which cannot load without an assembly and is actually in "System.Core" in previous .NET versions... - // So this "fix" will only work for some common types... - //[InlineData(typeof(HashSet>>), "System.Collections.Generic.HashSet`1[[System.Collections.Generic.List`1[[System.Collections.Generic.ICollection`1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e")] public void TypeCache_LoadBadAssembly(Type type, string typeString) { var result = TypeCache.GetType(typeString); - Assert.Equal(type, result); } + #endif -#if NET5_0 +#if NET8_0_OR_GREATER [Theory] [InlineData(typeof(string), "System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] [InlineData(typeof(int), "System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] @@ -250,9 +243,9 @@ public void JsonSerializer_List() result.Should().BeEquivalentTo(items); } -#endregion newtonsoft json serializer + #endregion newtonsoft json serializer -#region newtonsoft json with GZ serializer + #region newtonsoft json with GZ serializer [Fact] public void GzJsonSerializer_RespectJsonSerializerSettings() @@ -437,9 +430,9 @@ public void GzJsonSerializer_List() result.Should().BeEquivalentTo(items); } -#endregion newtonsoft json with GZ serializer + #endregion newtonsoft json with GZ serializer -#region data contract serializer common + #region data contract serializer common [Fact] public void DataContractSerializer_RespectSerializerSettings() @@ -526,9 +519,9 @@ public void DataContractSerializer_Binary_RespectSerializerSettings() cache.Configuration.SerializerTypeArguments.Length.Should().Be(1); } -#endregion data contract serializer common + #endregion data contract serializer common -#region data contract serializer + #region data contract serializer [Theory] [InlineData(true)] @@ -651,15 +644,17 @@ public void DataContractSerializer_List() result.Should().BeEquivalentTo(items); } +#if NET8_0_OR_GREATER [Fact] public void DataContractSerializer_FullAddGet() { FullAddGetWithSerializer(Serializer.DataContract); } +#endif -#endregion data contract serializer + #endregion data contract serializer -#region data contract serializer binary + #region data contract serializer binary [Theory] [InlineData(true)] @@ -782,15 +777,17 @@ public void DataContractBinarySerializer_List() result.Should().BeEquivalentTo(items); } +#if NET8_0_OR_GREATER [Fact] public void DataContractBinarySerializer_FullAddGet() { FullAddGetWithSerializer(Serializer.DataContractBinary); } +#endif -#endregion data contract serializer binary + #endregion data contract serializer binary -#region data contract serializer json + #region data contract serializer json [Theory] [InlineData(true)] @@ -928,15 +925,17 @@ public void DataContractJsonSerializer_List() result.Should().BeEquivalentTo(items); } +#if NET8_0_OR_GREATER [Fact] public void DataContractJsonSerializer_FullAddGet() { FullAddGetWithSerializer(Serializer.DataContractJson); } +#endif -#endregion data contract serializer json + #endregion data contract serializer json -#region data contract serializer gz json + #region data contract serializer gz json [Theory] [InlineData(true)] @@ -1074,15 +1073,17 @@ public void DataContractGzJsonSerializer_List() result.Should().BeEquivalentTo(items); } +#if NET8_0_OR_GREATER [Fact] public void DataContractGzJsonSerializer_FullAddGet() { FullAddGetWithSerializer(Serializer.DataContractGzJson); } +#endif -#endregion data contract serializer gz json + #endregion data contract serializer gz json -#region protobuf serializer + #region protobuf serializer [Theory] [InlineData(true)] @@ -1236,6 +1237,7 @@ public void ProtoBufSerializer_List() result.Should().BeEquivalentTo(items); } +#if NET8_0_OR_GREATER [Fact] public void ProtoBufSerializer_FullAddGet() { @@ -1256,10 +1258,11 @@ public void ProtoBufSerializer_FullAddGet() cache.Get(key).Should().BeEquivalentTo(pocco); } } +#endif -#endregion protobuf serializer + #endregion protobuf serializer -#region Bond binary serializer + #region Bond binary serializer [Theory] [InlineData(true)] @@ -1396,6 +1399,7 @@ public void BondBinarySerializer_CacheItemWithDerivedPocco() pocco.Should().BeEquivalentTo(item.Value); } +#if NET8_0_OR_GREATER [Fact] [Trait("category", "Redis")] public void BondBinarySerializer_FullAddGet() @@ -1417,8 +1421,9 @@ public void BondBinarySerializer_FullAddGet() cache.Get(key).Should().BeEquivalentTo(pocco); } } +#endif -#endregion Bond binary serializer + #endregion Bond binary serializer [Theory] [ClassData(typeof(TestCacheManagers))] @@ -1440,6 +1445,7 @@ public void Serializer_FullAddGet(T cache) } } +#if NET8_0_OR_GREATER private void FullAddGetWithSerializer(Serializer serializer) { using (var cache = TestManagers.CreateRedisCache(serializer: serializer)) @@ -1459,6 +1465,7 @@ private void FullAddGetWithSerializer(Serializer serializer) cache.Get(key).Should().BeEquivalentTo(pocco); } } +#endif private static class DataGenerator { diff --git a/test/CacheManager.Tests/TestCacheManagers.cs b/test/CacheManager.Tests/TestCacheManagers.cs index 70f8edc8..c9f2dfe9 100644 --- a/test/CacheManager.Tests/TestCacheManagers.cs +++ b/test/CacheManager.Tests/TestCacheManagers.cs @@ -21,7 +21,7 @@ public IEnumerator GetEnumerator() #endif yield return new object[] { TestManagers.WithManyDictionaryHandles }; yield return new object[] { TestManagers.WithOneDicCacheHandle }; -#if REDISENABLED +#if NET8_0_OR_GREATER yield return new object[] { TestManagers.WithRedisCacheDataContract }; yield return new object[] { TestManagers.WithRedisCacheDataContractBinary }; @@ -92,6 +92,7 @@ public static ICacheManager WithManyDictionaryHandles .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromSeconds(1000)) .Build()); +#if NET8_0_OR_GREATER public static ICacheManager WithRedisCacheBondBinary { get @@ -245,6 +246,7 @@ public static ICacheManager WithDicAndRedisCacheNoLua return CreateRedisAndDicCacheWithBackplane(database: _databaseCount, sharedRedisConfig: false, channelName: Guid.NewGuid().ToString(), useLua: false); } } +#endif #if !MSBUILD @@ -291,6 +293,7 @@ public static ICacheManager WithTwoNamedMemoryCaches .EnableStatistics() .Build()); +#if NET8_0_OR_GREATER public static ICacheManager CreateRedisAndDicCacheWithBackplane(int database = 0, bool sharedRedisConfig = true, string channelName = null, Serializer serializer = Serializer.Proto, bool useLua = true) { if (database > NumDatabases) @@ -313,7 +316,7 @@ public static ICacheManager CreateRedisAndDicCacheWithBackplane(int data { config .WithAllowAdmin() - .WithDatabase(database) + //.WithDatabase(database) .WithEndpoint(RedisHost, RedisPort); if (!useLua) @@ -391,7 +394,7 @@ public static ICacheManager CreateRedisCache(int database = 0, bool shar .WithRedisConfiguration(redisKey, config => { config - .WithDatabase(database) + //.WithDatabase(database) .WithEndpoint(RedisHost, RedisPort); if (!useLua) @@ -423,7 +426,7 @@ public static ICacheManager CreateRedisCache(int database = 0, bool shared .WithRedisConfiguration(redisKey, config => { config - .WithDatabase(database) + //.WithDatabase(database) .WithEndpoint(RedisHost, RedisPort); }) .WithRedisBackplane(redisKey) @@ -433,6 +436,7 @@ public static ICacheManager CreateRedisCache(int database = 0, bool shared return cache; } +#endif private static string NewKey() => Guid.NewGuid().ToString(); } diff --git a/test/CacheManager.Tests/ThreadRandomReadWriteTestBase.cs b/test/CacheManager.Tests/ThreadRandomReadWriteTestBase.cs index b8b67dd1..641188bb 100644 --- a/test/CacheManager.Tests/ThreadRandomReadWriteTestBase.cs +++ b/test/CacheManager.Tests/ThreadRandomReadWriteTestBase.cs @@ -10,7 +10,7 @@ namespace CacheManager.Tests { [ExcludeFromCodeCoverage] - public class ThreadRandomReadWriteTestBase + public class ThreadRandomReadWriteTestBase : IClassFixture { [Theory] [Trait("category", "Unreliable")] @@ -78,4 +78,4 @@ await ThreadTestHelper.RunAsync( } } } -} \ No newline at end of file +} diff --git a/test/CacheManager.Tests/app.config b/test/CacheManager.Tests/app.config index e4bf9568..d1b34ca6 100644 --- a/test/CacheManager.Tests/app.config +++ b/test/CacheManager.Tests/app.config @@ -10,11 +10,11 @@ - + - + diff --git a/test/CacheManager.Tests/testhost.dll.config b/test/CacheManager.Tests/testhost.dll.config index 2ec19a76..0e7a3317 100644 --- a/test/CacheManager.Tests/testhost.dll.config +++ b/test/CacheManager.Tests/testhost.dll.config @@ -14,11 +14,11 @@ - + - + diff --git a/test/CacheManager.Tests/testhost.x86.dll.config b/test/CacheManager.Tests/testhost.x86.dll.config index 2ec19a76..0e7a3317 100644 --- a/test/CacheManager.Tests/testhost.x86.dll.config +++ b/test/CacheManager.Tests/testhost.x86.dll.config @@ -14,11 +14,11 @@ - + - + diff --git a/tools/common.props b/tools/common.props index 6ad2ffd5..2099bf24 100644 --- a/tools/common.props +++ b/tools/common.props @@ -2,7 +2,7 @@ - Copyright (c) 2024 Michael Conrad + Copyright (c) 2025 Michael Conrad MichaConrad CacheManager.NET diff --git a/tools/memcached-amd64/RunMemcachd.bat b/tools/memcached-amd64/RunMemcachd.bat deleted file mode 100644 index cb32bdc8..00000000 --- a/tools/memcached-amd64/RunMemcachd.bat +++ /dev/null @@ -1,2 +0,0 @@ -:: requires linux subsystem for windows -bash run_memcached.sh \ No newline at end of file diff --git a/tools/memcached-amd64/StopMemcached.bat b/tools/memcached-amd64/StopMemcached.bat deleted file mode 100644 index 77f33278..00000000 --- a/tools/memcached-amd64/StopMemcached.bat +++ /dev/null @@ -1,2 +0,0 @@ -:: requires linux subsystem for windows -bash stop_memcached.sh \ No newline at end of file diff --git a/tools/memcached-amd64/run_memcached.sh b/tools/memcached-amd64/run_memcached.sh deleted file mode 100644 index 57487981..00000000 --- a/tools/memcached-amd64/run_memcached.sh +++ /dev/null @@ -1,14 +0,0 @@ -exists=$(whereis memcached | grep -c "bin/memcached") -if [[ $exists == 0 ]]; then - echo "installing memcached..." - sudo apt-get install memcached -y -fi - -status=$(service memcached status | grep -c "is running") -if [[ $status == 0 ]]; then - sudo service memcached start -else - echo "Memcached already running!" -fi - -service memcached status \ No newline at end of file diff --git a/tools/memcached-amd64/stop_memcached.sh b/tools/memcached-amd64/stop_memcached.sh deleted file mode 100644 index 78c54eb0..00000000 --- a/tools/memcached-amd64/stop_memcached.sh +++ /dev/null @@ -1,6 +0,0 @@ -sudo service memcached stop - -status=$(service memcached status | grep -c "is running") -if [[ $status == 0 ]]; then - echo "Service stopped" -fi \ No newline at end of file diff --git a/tools/redis/Cluster/7000/nodes.conf b/tools/redis/Cluster/7000/nodes.conf deleted file mode 100644 index 62ecbe30..00000000 --- a/tools/redis/Cluster/7000/nodes.conf +++ /dev/null @@ -1,7 +0,0 @@ -8160376d2096679aa466417c8cc3dd498a2bdd55 127.0.0.1:7005 slave c2deb32666652c94499cedc01f4a5849f1f03873 0 1489011302227 6 connected -d3b964e757e3f3f7b5ecb46b199f60313b95049d 127.0.0.1:7004 slave 76fc6991abd39a80e72b96362256220294454ce1 0 1489011301718 5 connected -86ea72e0b7e81e4e28595df1f920c23151e32ff5 127.0.0.1:7003 slave c6629041f2bc1c7740ce8567431ee975a7059a05 0 1489011303765 4 connected -c2deb32666652c94499cedc01f4a5849f1f03873 127.0.0.1:7002 master - 0 1489011303245 3 connected 10923-16383 -c6629041f2bc1c7740ce8567431ee975a7059a05 127.0.0.1:7000 myself,master - 0 0 1 connected 0-5460 -76fc6991abd39a80e72b96362256220294454ce1 127.0.0.1:7001 master - 0 1489011303765 2 connected 5461-10922 -vars currentEpoch 6 lastVoteEpoch 0 diff --git a/tools/redis/Cluster/7000/redis.conf b/tools/redis/Cluster/7000/redis.conf deleted file mode 100644 index 56465554..00000000 --- a/tools/redis/Cluster/7000/redis.conf +++ /dev/null @@ -1,6 +0,0 @@ -port 7000 -cluster-enabled yes -cluster-config-file nodes.conf -cluster-node-timeout 5000 -slave-read-only yes -cluster-require-full-coverage no \ No newline at end of file diff --git a/tools/redis/Cluster/7001/nodes.conf b/tools/redis/Cluster/7001/nodes.conf deleted file mode 100644 index c73e6746..00000000 --- a/tools/redis/Cluster/7001/nodes.conf +++ /dev/null @@ -1,7 +0,0 @@ -8160376d2096679aa466417c8cc3dd498a2bdd55 127.0.0.1:7005 slave c2deb32666652c94499cedc01f4a5849f1f03873 0 1489011303775 6 connected -d3b964e757e3f3f7b5ecb46b199f60313b95049d 127.0.0.1:7004 slave 76fc6991abd39a80e72b96362256220294454ce1 0 1489011303250 5 connected -c2deb32666652c94499cedc01f4a5849f1f03873 127.0.0.1:7002 master - 0 1489011302232 3 connected 10923-16383 -c6629041f2bc1c7740ce8567431ee975a7059a05 127.0.0.1:7000 master - 0 1489011302739 1 connected 0-5460 -86ea72e0b7e81e4e28595df1f920c23151e32ff5 127.0.0.1:7003 slave c6629041f2bc1c7740ce8567431ee975a7059a05 0 1489011301926 4 connected -76fc6991abd39a80e72b96362256220294454ce1 127.0.0.1:7001 myself,master - 0 0 2 connected 5461-10922 -vars currentEpoch 6 lastVoteEpoch 0 diff --git a/tools/redis/Cluster/7001/redis.conf b/tools/redis/Cluster/7001/redis.conf deleted file mode 100644 index d0ec1469..00000000 --- a/tools/redis/Cluster/7001/redis.conf +++ /dev/null @@ -1,6 +0,0 @@ -port 7001 -cluster-enabled yes -cluster-config-file nodes.conf -cluster-node-timeout 5000 -slave-read-only yes -cluster-require-full-coverage no \ No newline at end of file diff --git a/tools/redis/Cluster/7002/nodes.conf b/tools/redis/Cluster/7002/nodes.conf deleted file mode 100644 index f9647c9c..00000000 --- a/tools/redis/Cluster/7002/nodes.conf +++ /dev/null @@ -1,7 +0,0 @@ -8160376d2096679aa466417c8cc3dd498a2bdd55 127.0.0.1:7005 slave c2deb32666652c94499cedc01f4a5849f1f03873 0 1489011304295 6 connected -c6629041f2bc1c7740ce8567431ee975a7059a05 127.0.0.1:7000 master - 0 1489011302270 1 connected 0-5460 -d3b964e757e3f3f7b5ecb46b199f60313b95049d 127.0.0.1:7004 slave 76fc6991abd39a80e72b96362256220294454ce1 0 1489011304600 5 connected -76fc6991abd39a80e72b96362256220294454ce1 127.0.0.1:7001 master - 0 1489011303281 2 connected 5461-10922 -86ea72e0b7e81e4e28595df1f920c23151e32ff5 127.0.0.1:7003 slave c6629041f2bc1c7740ce8567431ee975a7059a05 0 1489011304397 4 connected -c2deb32666652c94499cedc01f4a5849f1f03873 127.0.0.1:7002 myself,master - 0 0 3 connected 10923-16383 -vars currentEpoch 6 lastVoteEpoch 0 diff --git a/tools/redis/Cluster/7002/redis.conf b/tools/redis/Cluster/7002/redis.conf deleted file mode 100644 index c923865d..00000000 --- a/tools/redis/Cluster/7002/redis.conf +++ /dev/null @@ -1,6 +0,0 @@ -port 7002 -cluster-enabled yes -cluster-config-file nodes.conf -cluster-node-timeout 5000 -slave-read-only yes -cluster-require-full-coverage no \ No newline at end of file diff --git a/tools/redis/Cluster/7003/nodes.conf b/tools/redis/Cluster/7003/nodes.conf deleted file mode 100644 index ac602249..00000000 --- a/tools/redis/Cluster/7003/nodes.conf +++ /dev/null @@ -1,7 +0,0 @@ -8160376d2096679aa466417c8cc3dd498a2bdd55 127.0.0.1:7005 slave c2deb32666652c94499cedc01f4a5849f1f03873 0 1489011304305 6 connected -86ea72e0b7e81e4e28595df1f920c23151e32ff5 127.0.0.1:7003 myself,slave c6629041f2bc1c7740ce8567431ee975a7059a05 0 0 4 connected -c6629041f2bc1c7740ce8567431ee975a7059a05 127.0.0.1:7000 master - 0 1489011303795 1 connected 0-5460 -d3b964e757e3f3f7b5ecb46b199f60313b95049d 127.0.0.1:7004 slave 76fc6991abd39a80e72b96362256220294454ce1 0 1489011304411 5 connected -c2deb32666652c94499cedc01f4a5849f1f03873 127.0.0.1:7002 master - 0 1489011302270 3 connected 10923-16383 -76fc6991abd39a80e72b96362256220294454ce1 127.0.0.1:7001 master - 0 1489011303281 2 connected 5461-10922 -vars currentEpoch 6 lastVoteEpoch 0 diff --git a/tools/redis/Cluster/7003/redis.conf b/tools/redis/Cluster/7003/redis.conf deleted file mode 100644 index 3d244fd9..00000000 --- a/tools/redis/Cluster/7003/redis.conf +++ /dev/null @@ -1,6 +0,0 @@ -port 7003 -cluster-enabled yes -cluster-config-file nodes.conf -cluster-node-timeout 5000 -slave-read-only yes -cluster-require-full-coverage no \ No newline at end of file diff --git a/tools/redis/Cluster/7004/nodes.conf b/tools/redis/Cluster/7004/nodes.conf deleted file mode 100644 index 5e2deee3..00000000 --- a/tools/redis/Cluster/7004/nodes.conf +++ /dev/null @@ -1,7 +0,0 @@ -c6629041f2bc1c7740ce8567431ee975a7059a05 127.0.0.1:7000 master - 0 1489011303281 1 connected 0-5460 -86ea72e0b7e81e4e28595df1f920c23151e32ff5 127.0.0.1:7003 slave c6629041f2bc1c7740ce8567431ee975a7059a05 0 1489011302270 4 connected -d3b964e757e3f3f7b5ecb46b199f60313b95049d 127.0.0.1:7004 myself,slave 76fc6991abd39a80e72b96362256220294454ce1 0 0 5 connected -76fc6991abd39a80e72b96362256220294454ce1 127.0.0.1:7001 master - 0 1489011304310 2 connected 5461-10922 -8160376d2096679aa466417c8cc3dd498a2bdd55 127.0.0.1:7005 slave c2deb32666652c94499cedc01f4a5849f1f03873 0 1489011302776 6 connected -c2deb32666652c94499cedc01f4a5849f1f03873 127.0.0.1:7002 master - 0 1489011302167 3 connected 10923-16383 -vars currentEpoch 6 lastVoteEpoch 0 diff --git a/tools/redis/Cluster/7004/redis.conf b/tools/redis/Cluster/7004/redis.conf deleted file mode 100644 index e5b3c2ae..00000000 --- a/tools/redis/Cluster/7004/redis.conf +++ /dev/null @@ -1,6 +0,0 @@ -port 7004 -cluster-enabled yes -cluster-config-file nodes.conf -cluster-node-timeout 5000 -slave-read-only yes -cluster-require-full-coverage no \ No newline at end of file diff --git a/tools/redis/Cluster/7005/nodes.conf b/tools/redis/Cluster/7005/nodes.conf deleted file mode 100644 index b866484a..00000000 --- a/tools/redis/Cluster/7005/nodes.conf +++ /dev/null @@ -1,7 +0,0 @@ -76fc6991abd39a80e72b96362256220294454ce1 127.0.0.1:7001 master - 0 1489011302270 2 connected 5461-10922 -c6629041f2bc1c7740ce8567431ee975a7059a05 127.0.0.1:7000 master - 0 1489011302776 1 connected 0-5460 -d3b964e757e3f3f7b5ecb46b199f60313b95049d 127.0.0.1:7004 slave 76fc6991abd39a80e72b96362256220294454ce1 0 1489011301966 5 connected -c2deb32666652c94499cedc01f4a5849f1f03873 127.0.0.1:7002 master - 0 1489011301966 3 connected 10923-16383 -86ea72e0b7e81e4e28595df1f920c23151e32ff5 127.0.0.1:7003 slave c6629041f2bc1c7740ce8567431ee975a7059a05 0 1489011303281 4 connected -8160376d2096679aa466417c8cc3dd498a2bdd55 127.0.0.1:7005 myself,slave c2deb32666652c94499cedc01f4a5849f1f03873 0 0 6 connected -vars currentEpoch 6 lastVoteEpoch 0 diff --git a/tools/redis/Cluster/7005/redis.conf b/tools/redis/Cluster/7005/redis.conf deleted file mode 100644 index 11e19c91..00000000 --- a/tools/redis/Cluster/7005/redis.conf +++ /dev/null @@ -1,6 +0,0 @@ -port 7005 -cluster-enabled yes -cluster-config-file nodes.conf -cluster-node-timeout 5000 -slave-read-only yes -cluster-require-full-coverage no \ No newline at end of file diff --git a/tools/redis/install-service.cmd b/tools/redis/install-service.cmd deleted file mode 100644 index 8057e2a4..00000000 --- a/tools/redis/install-service.cmd +++ /dev/null @@ -1,4 +0,0 @@ -cd /d %~dp0 -CALL install.cmd -@packages\Redis-64\tools\redis-server.exe --service-install %~dp0\master.conf -@packages\Redis-64\tools\redis-server.exe --service-start \ No newline at end of file diff --git a/tools/redis/install.cmd b/tools/redis/install.cmd deleted file mode 100644 index 8a6ca11e..00000000 --- a/tools/redis/install.cmd +++ /dev/null @@ -1,23 +0,0 @@ -@echo off -cd %~dp0 - -SETLOCAL -SET NUGET_VERSION=v6.10.1 -SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe - -IF EXIST %CACHED_NUGET% goto copynuget -echo Downloading latest version of NuGet.exe... -IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet -@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'" - -:copynuget -IF EXIST .nuget\nuget.exe goto restore -md .nuget -copy %CACHED_NUGET% .nuget\nuget.exe > nul - -:restore -IF EXIST packages\redis-64 goto run -.nuget\NuGet.exe install redis-64 -ExcludeVersion -o packages -nocache - - -:run diff --git a/tools/redis/master-debug.conf b/tools/redis/master-debug.conf deleted file mode 100644 index 3df03dca..00000000 --- a/tools/redis/master-debug.conf +++ /dev/null @@ -1,8 +0,0 @@ -port 6379 -dbfilename master.rdb -databases 100 -maxmemory 2gb -timeout 10 -loglevel debug -notify-keyspace-events AKE -appendonly no \ No newline at end of file diff --git a/tools/redis/master.conf b/tools/redis/master.conf deleted file mode 100644 index 90883428..00000000 --- a/tools/redis/master.conf +++ /dev/null @@ -1,14 +0,0 @@ -port 6379 -dbfilename master.rdb -databases 100 -maxmemory 250mb -maxclients 1000 -notify-keyspace-events AKE - - -#loglevel debug -#save 900 1 -#save 300 10 -#save 60 10000 - -appendonly no \ No newline at end of file diff --git a/tools/redis/redis-cli master.cmd b/tools/redis/redis-cli master.cmd deleted file mode 100644 index bb76f04a..00000000 --- a/tools/redis/redis-cli master.cmd +++ /dev/null @@ -1 +0,0 @@ -@packages\Redis-64\tools\redis-cli.exe -p 6379 diff --git a/tools/redis/redis-server cluster.cmd b/tools/redis/redis-server cluster.cmd deleted file mode 100644 index b5ab5ca0..00000000 --- a/tools/redis/redis-server cluster.cmd +++ /dev/null @@ -1,21 +0,0 @@ -@echo off -cd /d %~dp0 -CALL install.cmd -pushd Cluster\7000 -@start ..\..\packages\Redis-64\tools\redis-server.exe redis.conf -popd -pushd Cluster\7001 -@start ..\..\packages\Redis-64\tools\redis-server.exe redis.conf -popd -pushd Cluster\7002 -@start ..\..\packages\Redis-64\tools\redis-server.exe redis.conf -popd -pushd Cluster\7003 -@start ..\..\packages\Redis-64\tools\redis-server.exe redis.conf -popd -pushd Cluster\7004 -@start ..\..\packages\Redis-64\tools\redis-server.exe redis.conf -popd -pushd Cluster\7005 -@start ..\..\packages\Redis-64\tools\redis-server.exe redis.conf -popd \ No newline at end of file diff --git a/tools/redis/redis-server-full.cmd b/tools/redis/redis-server-full.cmd deleted file mode 100644 index 110d039a..00000000 --- a/tools/redis/redis-server-full.cmd +++ /dev/null @@ -1,7 +0,0 @@ -cd /d %~dp0 -CALL install.cmd -cmd /C start packages\Redis-64\tools\redis-server.exe master.conf -cmd /C start packages\Redis-64\tools\redis-server.exe slave.conf -cmd /C start packages\Redis-64\tools\redis-server.exe sentinel1.conf --sentinel -cmd /C start packages\Redis-64\tools\redis-server.exe sentinel2.conf --sentinel -cmd /C start packages\Redis-64\tools\redis-server.exe sentinel3.conf --sentinel diff --git a/tools/redis/redis-server-master-debug.cmd b/tools/redis/redis-server-master-debug.cmd deleted file mode 100644 index be908b94..00000000 --- a/tools/redis/redis-server-master-debug.cmd +++ /dev/null @@ -1 +0,0 @@ -@packages\Redis-64\tools\redis-server.exe master-debug.conf diff --git a/tools/redis/redis-server-master.cmd b/tools/redis/redis-server-master.cmd deleted file mode 100644 index b151bf65..00000000 --- a/tools/redis/redis-server-master.cmd +++ /dev/null @@ -1,3 +0,0 @@ -cd /d %~dp0 -CALL install.cmd -@packages\Redis-64\tools\redis-server.exe master.conf diff --git a/tools/redis/redis-server-sentinel.cmd b/tools/redis/redis-server-sentinel.cmd deleted file mode 100644 index 18223cc4..00000000 --- a/tools/redis/redis-server-sentinel.cmd +++ /dev/null @@ -1,5 +0,0 @@ -cd /d %~dp0 -CALL install.cmd -cmd /C start packages\Redis-64\tools\redis-server.exe sentinel1.conf --sentinel -cmd /C start packages\Redis-64\tools\redis-server.exe sentinel2.conf --sentinel -cmd /C start packages\Redis-64\tools\redis-server.exe sentinel3.conf --sentinel diff --git a/tools/redis/redis-server-slave.cmd b/tools/redis/redis-server-slave.cmd deleted file mode 100644 index 641de985..00000000 --- a/tools/redis/redis-server-slave.cmd +++ /dev/null @@ -1 +0,0 @@ -@packages\Redis-64\tools\redis-server.exe slave.conf diff --git a/tools/redis/sentinel1.conf b/tools/redis/sentinel1.conf deleted file mode 100644 index 6cf132e0..00000000 --- a/tools/redis/sentinel1.conf +++ /dev/null @@ -1,9 +0,0 @@ -port 26380 -sentinel monitor mymaster 127.0.0.1 6379 2 -sentinel down-after-milliseconds mymaster 1000 -sentinel failover-timeout mymaster 1800 - -sentinel monitor resque 192.168.1.3 6380 4 -sentinel down-after-milliseconds resque 1000 -sentinel failover-timeout resque 1800 -sentinel parallel-syncs resque 5 \ No newline at end of file diff --git a/tools/redis/sentinel2.conf b/tools/redis/sentinel2.conf deleted file mode 100644 index 7c33eef9..00000000 --- a/tools/redis/sentinel2.conf +++ /dev/null @@ -1,9 +0,0 @@ -port 26381 -sentinel monitor mymaster 127.0.0.1 6379 2 -sentinel down-after-milliseconds mymaster 1000 -sentinel failover-timeout mymaster 1800 - -sentinel monitor resque 192.168.1.3 6380 4 -sentinel down-after-milliseconds resque 1000 -sentinel failover-timeout resque 1800 -sentinel parallel-syncs resque 5 diff --git a/tools/redis/sentinel3.conf b/tools/redis/sentinel3.conf deleted file mode 100644 index e278be00..00000000 --- a/tools/redis/sentinel3.conf +++ /dev/null @@ -1,9 +0,0 @@ -port 26382 -sentinel monitor mymaster 127.0.0.1 6379 2 -sentinel down-after-milliseconds mymaster 1000 -sentinel failover-timeout mymaster 1800 - -sentinel monitor resque 192.168.1.3 6380 4 -sentinel down-after-milliseconds resque 1000 -sentinel failover-timeout resque 1800 -sentinel parallel-syncs resque 5 \ No newline at end of file diff --git a/tools/redis/slave.conf b/tools/redis/slave.conf deleted file mode 100644 index 315e175f..00000000 --- a/tools/redis/slave.conf +++ /dev/null @@ -1,6 +0,0 @@ -port 6380 -slaveof 127.0.0.1 6379 -dbfilename slave.rdb -databases 2000 -maxmemory 2gb -save 180 1000 \ No newline at end of file