From 6e2c3578450fd3582afe3b75288edfe7915367ac Mon Sep 17 00:00:00 2001 From: martincostello Date: Sat, 18 Nov 2023 16:42:25 +0000 Subject: [PATCH] Update to .NET 8 Update the samples to .NET 8 and use some C# 12 syntax. --- ...emo06_WaitAndRetryNestingCircuitBreaker.cs | 1 - ..._Pipeline-Fallback-Timeout-WaitAndRetry.cs | 1 - PollyDemos/Demo10_SharedConcurrencyLimiter.cs | 4 ++-- .../Demo11_MultipleConcurrencyLimiters.cs | 1 - .../Demo16_EntityFramework-WithRetryNTimes.cs | 1 + .../EntityFramework/PollyExecutionStrategy.cs | 18 +------------- .../PollyExecutionStrategyFactory.cs | 10 ++++---- PollyDemos/EntityFramework/TodoDbContext.cs | 2 +- PollyDemos/PollyDemos.csproj | 19 ++++++++------- PollyTestClientConsole/Menu/ConsoleMenu.cs | 12 ++++++---- .../Menu/ConsoleMenuItem.cs | 1 + .../PollyTestClientConsole.csproj | 6 ++--- PollyTestClientConsole/Program.cs | 24 +++++++++---------- PollyTestClientWpf/MainWindow.xaml.cs | 4 ++-- PollyTestClientWpf/PollyTestClientWpf.csproj | 16 +++++-------- PollyTestWebApi/PollyTestWebApi.csproj | 4 ++-- global.json | 2 +- 17 files changed, 54 insertions(+), 72 deletions(-) diff --git a/PollyDemos/Demo06_WaitAndRetryNestingCircuitBreaker.cs b/PollyDemos/Demo06_WaitAndRetryNestingCircuitBreaker.cs index 6a56291..c04c455 100644 --- a/PollyDemos/Demo06_WaitAndRetryNestingCircuitBreaker.cs +++ b/PollyDemos/Demo06_WaitAndRetryNestingCircuitBreaker.cs @@ -1,6 +1,5 @@ using System.Diagnostics; using Polly.CircuitBreaker; - using PollyDemos.Helpers; using PollyDemos.OutputHelpers; diff --git a/PollyDemos/Demo09_Pipeline-Fallback-Timeout-WaitAndRetry.cs b/PollyDemos/Demo09_Pipeline-Fallback-Timeout-WaitAndRetry.cs index 1826969..7f51f45 100644 --- a/PollyDemos/Demo09_Pipeline-Fallback-Timeout-WaitAndRetry.cs +++ b/PollyDemos/Demo09_Pipeline-Fallback-Timeout-WaitAndRetry.cs @@ -1,6 +1,5 @@ using System.Diagnostics; using Polly.Timeout; - using PollyDemos.Helpers; using PollyDemos.OutputHelpers; diff --git a/PollyDemos/Demo10_SharedConcurrencyLimiter.cs b/PollyDemos/Demo10_SharedConcurrencyLimiter.cs index 896304f..8769531 100644 --- a/PollyDemos/Demo10_SharedConcurrencyLimiter.cs +++ b/PollyDemos/Demo10_SharedConcurrencyLimiter.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; - using PollyDemos.Helpers; using PollyDemos.OutputHelpers; @@ -98,9 +97,10 @@ public override async Task ExecuteAsync(CancellationToken externalCancellationTo // Cancel any unstarted and running tasks. internalCancellationTokenSource.Cancel(); + try { - Task.WaitAll(tasks.ToArray()); + Task.WaitAll([.. tasks]); } catch { diff --git a/PollyDemos/Demo11_MultipleConcurrencyLimiters.cs b/PollyDemos/Demo11_MultipleConcurrencyLimiters.cs index abddf8a..4f21ca9 100644 --- a/PollyDemos/Demo11_MultipleConcurrencyLimiters.cs +++ b/PollyDemos/Demo11_MultipleConcurrencyLimiters.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; - using PollyDemos.Helpers; using PollyDemos.OutputHelpers; diff --git a/PollyDemos/Demo16_EntityFramework-WithRetryNTimes.cs b/PollyDemos/Demo16_EntityFramework-WithRetryNTimes.cs index 801d5e1..33a2c57 100644 --- a/PollyDemos/Demo16_EntityFramework-WithRetryNTimes.cs +++ b/PollyDemos/Demo16_EntityFramework-WithRetryNTimes.cs @@ -30,6 +30,7 @@ public class Demo16_EntityFramework_WithRetryNTimes : DemoBase { public override string Description => "This demo demonstrates using a Retry resilience pipeline with Entity Framework Core."; + public int ItemsAddedToDatabase = 0; public override async Task ExecuteAsync(CancellationToken cancellationToken, IProgress progress) diff --git a/PollyDemos/EntityFramework/PollyExecutionStrategy.cs b/PollyDemos/EntityFramework/PollyExecutionStrategy.cs index 6a6dafb..f4ca0f1 100644 --- a/PollyDemos/EntityFramework/PollyExecutionStrategy.cs +++ b/PollyDemos/EntityFramework/PollyExecutionStrategy.cs @@ -1,29 +1,13 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; -using Polly; namespace PollyDemos.EntityFramework; - /// /// Represents a class that implements the interface using Polly for resilience and transient-fault handling. /// -public class PollyExecutionStrategy : IExecutionStrategy +public class PollyExecutionStrategy(ExecutionStrategyDependencies dependencies, ResiliencePipeline resiliencePipeline) : IExecutionStrategy { - private readonly ExecutionStrategyDependencies dependencies; - private readonly ResiliencePipeline resiliencePipeline; - - /// - /// Initializes a new instance of the class with the specified dependencies and resilience pipeline. - /// - /// The dependencies required by the execution strategy. - /// The resilience pipeline used by the execution strategy. - public PollyExecutionStrategy(ExecutionStrategyDependencies dependencies, ResiliencePipeline resiliencePipeline) - { - this.dependencies = dependencies; - this.resiliencePipeline = resiliencePipeline; - } - /// /// Gets a value indicating whether the execution strategy should retry on failure. /// diff --git a/PollyDemos/EntityFramework/PollyExecutionStrategyFactory.cs b/PollyDemos/EntityFramework/PollyExecutionStrategyFactory.cs index cad8409..fe7ef6a 100644 --- a/PollyDemos/EntityFramework/PollyExecutionStrategyFactory.cs +++ b/PollyDemos/EntityFramework/PollyExecutionStrategyFactory.cs @@ -1,6 +1,5 @@ using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; -using Polly; using Polly.Timeout; namespace PollyDemos.EntityFramework; @@ -11,7 +10,7 @@ namespace PollyDemos.EntityFramework; public class PollyExecutionStrategyFactory : IExecutionStrategyFactory { private readonly ExecutionStrategyDependencies dependencies; - private readonly ResiliencePipeline resiliencePipeline; + private readonly ResiliencePipeline pipeline; /// /// Initializes a new instance of the class. @@ -21,13 +20,12 @@ public class PollyExecutionStrategyFactory : IExecutionStrategyFactory public PollyExecutionStrategyFactory(ExecutionStrategyDependencies dependencies, ILoggerFactory loggerFactory) { this.dependencies = dependencies; - resiliencePipeline = new ResiliencePipelineBuilder() + pipeline = new ResiliencePipelineBuilder() .AddRetry(new() { BackoffType = DelayBackoffType.Constant, MaxRetryAttempts = 3, - ShouldHandle = new PredicateBuilder().Handle(ex => ex is InvalidOperationException - or TimeoutRejectedException) + ShouldHandle = new PredicateBuilder().Handle(ex => ex is InvalidOperationException or TimeoutRejectedException) }) .AddTimeout(TimeSpan.FromSeconds(1)) .ConfigureTelemetry(loggerFactory) @@ -37,5 +35,5 @@ public PollyExecutionStrategyFactory(ExecutionStrategyDependencies dependencies, /// /// Creates a new instance of the class. /// - public IExecutionStrategy Create() => new PollyExecutionStrategy(dependencies, resiliencePipeline); + public IExecutionStrategy Create() => new PollyExecutionStrategy(dependencies, pipeline); } diff --git a/PollyDemos/EntityFramework/TodoDbContext.cs b/PollyDemos/EntityFramework/TodoDbContext.cs index 1f40ac9..ecd7102 100644 --- a/PollyDemos/EntityFramework/TodoDbContext.cs +++ b/PollyDemos/EntityFramework/TodoDbContext.cs @@ -22,8 +22,8 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // Create a logger factory and add a console logger. var loggerFactory = LoggerFactory.Create(factory => factory.AddConsole()); - optionsBuilder.UseLoggerFactory(loggerFactory); + // Replace the default execution strategy factory with our own Polly-based implementation. optionsBuilder.ReplaceService(); optionsBuilder.UseInMemoryDatabase("data"); diff --git a/PollyDemos/PollyDemos.csproj b/PollyDemos/PollyDemos.csproj index b7e6f59..740c913 100644 --- a/PollyDemos/PollyDemos.csproj +++ b/PollyDemos/PollyDemos.csproj @@ -1,22 +1,23 @@ - Library - net7.0 - enable - enable - Library false + enable false + enable $(NoWarn);SA1123;SA1515;CA2000;CA2007;CA1303;IDE0021;IDE0017;IDE0060;CS1998;CA1064;S3257;IDE0028;CA1031;CA1848 + Library + Library PollyDemos + net8.0 - - + + - - + + + diff --git a/PollyTestClientConsole/Menu/ConsoleMenu.cs b/PollyTestClientConsole/Menu/ConsoleMenu.cs index 08923b0..fb28f7a 100644 --- a/PollyTestClientConsole/Menu/ConsoleMenu.cs +++ b/PollyTestClientConsole/Menu/ConsoleMenu.cs @@ -1,8 +1,9 @@ namespace PollyTestClientConsole.Menu; + public static class ConsoleMenu { - static readonly List PollyAsciiArt = new() - { + private static readonly List PollyAsciiArt = + [ " ", " ", " .,,,*******, ", @@ -35,17 +36,19 @@ public static class ConsoleMenu " .%%%% *(((((((( %%%%%%%%%%%********* ", " %%%%%%%%%%%********* ", " ", - }; + ]; public static void PrintSplashScreen() { Console.Clear(); Console.WriteLine("Welcome to Polly Demos!"); + foreach(var line in PollyAsciiArt) { Console.WriteLine(line); } - Thread.Sleep(2_500); + + Thread.Sleep(TimeSpan.FromSeconds(2.5)); } public static void Run(List items) @@ -82,6 +85,7 @@ public static void Run(List items) private static void WriteMenu(List items, ConsoleMenuItem selectedItem) { Console.Clear(); + foreach (var item in items) { Console.Write(item == selectedItem ? "> " : " "); diff --git a/PollyTestClientConsole/Menu/ConsoleMenuItem.cs b/PollyTestClientConsole/Menu/ConsoleMenuItem.cs index ecc0b3c..16bbd7d 100644 --- a/PollyTestClientConsole/Menu/ConsoleMenuItem.cs +++ b/PollyTestClientConsole/Menu/ConsoleMenuItem.cs @@ -1,2 +1,3 @@ namespace PollyTestClientConsole.Menu; + public record ConsoleMenuItem(string Name, Action Handler); diff --git a/PollyTestClientConsole/PollyTestClientConsole.csproj b/PollyTestClientConsole/PollyTestClientConsole.csproj index e95d5e5..d8ccd63 100644 --- a/PollyTestClientConsole/PollyTestClientConsole.csproj +++ b/PollyTestClientConsole/PollyTestClientConsole.csproj @@ -1,11 +1,11 @@  - Exe - net7.0 + false enable enable - false + Exe PollyTestClientConsole + net8.0 diff --git a/PollyTestClientConsole/Program.cs b/PollyTestClientConsole/Program.cs index 7d8d677..83077cf 100644 --- a/PollyTestClientConsole/Program.cs +++ b/PollyTestClientConsole/Program.cs @@ -1,27 +1,28 @@ using PollyDemos; using PollyDemos.Helpers; using PollyDemos.OutputHelpers; - using PollyTestClientConsole; using PollyTestClientConsole.Menu; -Statistic[] statistics = Array.Empty(); +Statistic[] statistics = []; Progress progress = new(); + progress.ProgressChanged += (_, args) => { -foreach (var message in args.Messages) -{ - WriteLineInColor(message.Message, message.Color.ToConsoleColor()); -} -statistics = args.Statistics; + foreach (var message in args.Messages) + { + WriteLineInColor(message.Message, message.Color.ToConsoleColor()); + } + + statistics = args.Statistics; }; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Walk through the demos in order, to discover features. // See at top of each demo class, for explanation. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -List menu = new() -{ +List menu = +[ new("00 - No strategy", InvokeDemo), new("01 - Retry N times", @@ -58,12 +59,11 @@ InvokeDemo), new("-=Exit=-", () => Environment.Exit(0)) -}; +]; ConsoleMenu.PrintSplashScreen(); ConsoleMenu.Run(menu); - void InvokeDemo() where T : DemoBase, new() { using var cancellationSource = new CancellationTokenSource(); @@ -88,7 +88,7 @@ void PrintStatisticsThenClear() WriteLineInColor($"{stat.Description.PadRight(longestDescription)}: {stat.Value}", stat.Color.ToConsoleColor()); } - statistics = Array.Empty(); + statistics = []; } void WriteLineInColor(string message, ConsoleColor color) diff --git a/PollyTestClientWpf/MainWindow.xaml.cs b/PollyTestClientWpf/MainWindow.xaml.cs index 2fb8b38..daa95fc 100644 --- a/PollyTestClientWpf/MainWindow.xaml.cs +++ b/PollyTestClientWpf/MainWindow.xaml.cs @@ -17,7 +17,7 @@ public partial class MainWindow : Window private readonly object lockObject = new(); - private Statistic[] closingStatistics = Array.Empty(); + private Statistic[] closingStatistics = []; private const int MaxStatisticsToShow = 9; private const string StatisticBoxPrefix = "Statistic"; @@ -162,7 +162,7 @@ private void StopButton_Click(object sender, RoutedEventArgs args) return; } - if (closingStatistics.Any()) + if (closingStatistics.Length != 0) { int longestDescription = closingStatistics.Max(s => s.Description.Length); foreach (Statistic stat in closingStatistics) diff --git a/PollyTestClientWpf/PollyTestClientWpf.csproj b/PollyTestClientWpf/PollyTestClientWpf.csproj index 4421efa..601b975 100644 --- a/PollyTestClientWpf/PollyTestClientWpf.csproj +++ b/PollyTestClientWpf/PollyTestClientWpf.csproj @@ -1,26 +1,22 @@ true - net7.0-windows - WinExe + false enable enable - false - true - - + WinExe + net8.0-windows true + true - + + - - - diff --git a/PollyTestWebApi/PollyTestWebApi.csproj b/PollyTestWebApi/PollyTestWebApi.csproj index e4d879d..96051f4 100644 --- a/PollyTestWebApi/PollyTestWebApi.csproj +++ b/PollyTestWebApi/PollyTestWebApi.csproj @@ -1,7 +1,7 @@ - net7.0 - enable enable + enable + net8.0 diff --git a/global.json b/global.json index 01254dd..33d26e5 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "7.0.401", + "version": "8.0.100", "allowPrerelease": false, "rollForward": "latestMajor" }