Skip to content

Commit

Permalink
Update to .NET 8
Browse files Browse the repository at this point in the history
Update the samples to .NET 8 and use some C# 12 syntax.
  • Loading branch information
martincostello committed Nov 18, 2023
1 parent 4803620 commit 6e2c357
Show file tree
Hide file tree
Showing 17 changed files with 54 additions and 72 deletions.
1 change: 0 additions & 1 deletion PollyDemos/Demo06_WaitAndRetryNestingCircuitBreaker.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Diagnostics;
using Polly.CircuitBreaker;

using PollyDemos.Helpers;
using PollyDemos.OutputHelpers;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Diagnostics;
using Polly.Timeout;

using PollyDemos.Helpers;
using PollyDemos.OutputHelpers;

Expand Down
4 changes: 2 additions & 2 deletions PollyDemos/Demo10_SharedConcurrencyLimiter.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Concurrent;

using PollyDemos.Helpers;
using PollyDemos.OutputHelpers;

Expand Down Expand Up @@ -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
{
Expand Down
1 change: 0 additions & 1 deletion PollyDemos/Demo11_MultipleConcurrencyLimiters.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Concurrent;

using PollyDemos.Helpers;
using PollyDemos.OutputHelpers;

Expand Down
1 change: 1 addition & 0 deletions PollyDemos/Demo16_EntityFramework-WithRetryNTimes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<DemoProgress> progress)
Expand Down
18 changes: 1 addition & 17 deletions PollyDemos/EntityFramework/PollyExecutionStrategy.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Polly;

namespace PollyDemos.EntityFramework;


/// <summary>
/// Represents a class that implements the <see cref="IExecutionStrategy"/> interface using Polly for resilience and transient-fault handling.
/// </summary>
public class PollyExecutionStrategy : IExecutionStrategy
public class PollyExecutionStrategy(ExecutionStrategyDependencies dependencies, ResiliencePipeline resiliencePipeline) : IExecutionStrategy
{
private readonly ExecutionStrategyDependencies dependencies;
private readonly ResiliencePipeline resiliencePipeline;

/// <summary>
/// Initializes a new instance of the <see cref="PollyExecutionStrategy"/> class with the specified dependencies and resilience pipeline.
/// </summary>
/// <param name="dependencies">The dependencies required by the execution strategy.</param>
/// <param name="resiliencePipeline">The resilience pipeline used by the execution strategy.</param>
public PollyExecutionStrategy(ExecutionStrategyDependencies dependencies, ResiliencePipeline resiliencePipeline)
{
this.dependencies = dependencies;
this.resiliencePipeline = resiliencePipeline;
}

/// <summary>
/// Gets a value indicating whether the execution strategy should retry on failure.
/// </summary>
Expand Down
10 changes: 4 additions & 6 deletions PollyDemos/EntityFramework/PollyExecutionStrategyFactory.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using Polly;
using Polly.Timeout;

namespace PollyDemos.EntityFramework;
Expand All @@ -11,7 +10,7 @@ namespace PollyDemos.EntityFramework;
public class PollyExecutionStrategyFactory : IExecutionStrategyFactory
{
private readonly ExecutionStrategyDependencies dependencies;
private readonly ResiliencePipeline resiliencePipeline;
private readonly ResiliencePipeline pipeline;

/// <summary>
/// Initializes a new instance of the <see cref="PollyExecutionStrategyFactory"/> class.
Expand All @@ -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<Exception>(ex => ex is InvalidOperationException
or TimeoutRejectedException)
ShouldHandle = new PredicateBuilder().Handle<Exception>(ex => ex is InvalidOperationException or TimeoutRejectedException)
})
.AddTimeout(TimeSpan.FromSeconds(1))
.ConfigureTelemetry(loggerFactory)
Expand All @@ -37,5 +35,5 @@ public PollyExecutionStrategyFactory(ExecutionStrategyDependencies dependencies,
/// <summary>
/// Creates a new instance of the <see cref="PollyExecutionStrategy"/> class.
/// </summary>
public IExecutionStrategy Create() => new PollyExecutionStrategy(dependencies, resiliencePipeline);
public IExecutionStrategy Create() => new PollyExecutionStrategy(dependencies, pipeline);
}
2 changes: 1 addition & 1 deletion PollyDemos/EntityFramework/TodoDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IExecutionStrategyFactory, PollyExecutionStrategyFactory>();
optionsBuilder.UseInMemoryDatabase("data");
Expand Down
19 changes: 10 additions & 9 deletions PollyDemos/PollyDemos.csproj
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<ProjectType>Library</ProjectType>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
<NoWarn>$(NoWarn);SA1123;SA1515;CA2000;CA2007;CA1303;IDE0021;IDE0017;IDE0060;CS1998;CA1064;S3257;IDE0028;CA1031;CA1848</NoWarn>
<OutputType>Library</OutputType>
<ProjectType>Library</ProjectType>
<RootNamespace>PollyDemos</RootNamespace>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Polly.Core" Version="8.2.0" />
<PackageReference Include="Polly.RateLimiting" Version="8.2.0" />
<PackageReference Include="Polly.Extensions" Version="8.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.14" />
<PackageReference Include="Polly.RateLimiting" Version="8.2.0" />
</ItemGroup>
<ItemGroup>
<Using Include="Polly" />
</ItemGroup>
</Project>
12 changes: 8 additions & 4 deletions PollyTestClientConsole/Menu/ConsoleMenu.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
namespace PollyTestClientConsole.Menu;

public static class ConsoleMenu
{
static readonly List<string> PollyAsciiArt = new()
{
private static readonly List<string> PollyAsciiArt =
[
" ",
" ",
" .,,,*******, ",
Expand Down Expand Up @@ -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<ConsoleMenuItem> items)
Expand Down Expand Up @@ -82,6 +85,7 @@ public static void Run(List<ConsoleMenuItem> items)
private static void WriteMenu(List<ConsoleMenuItem> items, ConsoleMenuItem selectedItem)
{
Console.Clear();

foreach (var item in items)
{
Console.Write(item == selectedItem ? "> " : " ");
Expand Down
1 change: 1 addition & 0 deletions PollyTestClientConsole/Menu/ConsoleMenuItem.cs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
namespace PollyTestClientConsole.Menu;

public record ConsoleMenuItem(string Name, Action Handler);
6 changes: 3 additions & 3 deletions PollyTestClientConsole/PollyTestClientConsole.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<OutputType>Exe</OutputType>
<RootNamespace>PollyTestClientConsole</RootNamespace>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\PollyDemos\PollyDemos.csproj" />
Expand Down
24 changes: 12 additions & 12 deletions PollyTestClientConsole/Program.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
using PollyDemos;
using PollyDemos.Helpers;
using PollyDemos.OutputHelpers;

using PollyTestClientConsole;
using PollyTestClientConsole.Menu;

Statistic[] statistics = Array.Empty<Statistic>();
Statistic[] statistics = [];
Progress<DemoProgress> 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 <summary> at top of each demo class, for explanation.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
List<ConsoleMenuItem> menu = new()
{
List<ConsoleMenuItem> menu =
[
new("00 - No strategy",
InvokeDemo<Demo00_NoStrategy>),
new("01 - Retry N times",
Expand Down Expand Up @@ -58,12 +59,11 @@
InvokeDemo<Demo16_EntityFramework_WithRetryNTimes>),

new("-=Exit=-", () => Environment.Exit(0))
};
];

ConsoleMenu.PrintSplashScreen();
ConsoleMenu.Run(menu);


void InvokeDemo<T>() where T : DemoBase, new()
{
using var cancellationSource = new CancellationTokenSource();
Expand All @@ -88,7 +88,7 @@ void PrintStatisticsThenClear()
WriteLineInColor($"{stat.Description.PadRight(longestDescription)}: {stat.Value}", stat.Color.ToConsoleColor());
}

statistics = Array.Empty<Statistic>();
statistics = [];
}

void WriteLineInColor(string message, ConsoleColor color)
Expand Down
4 changes: 2 additions & 2 deletions PollyTestClientWpf/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public partial class MainWindow : Window

private readonly object lockObject = new();

private Statistic[] closingStatistics = Array.Empty<Statistic>();
private Statistic[] closingStatistics = [];

private const int MaxStatisticsToShow = 9;
private const string StatisticBoxPrefix = "Statistic";
Expand Down Expand Up @@ -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)
Expand Down
16 changes: 6 additions & 10 deletions PollyTestClientWpf/PollyTestClientWpf.csproj
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<TargetFramework>net7.0-windows</TargetFramework>
<OutputType>WinExe</OutputType>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<UseWPF>true</UseWPF>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<None Remove="Polly-Logo.png" />
<ProjectReference Include="..\PollyDemos\PollyDemos.csproj" />
</ItemGroup>
<ItemGroup>
<AppDesigner Include="Properties\" />
</ItemGroup>
<ItemGroup>
<None Remove="Polly-Logo.png" />
<Content Include="Polly-Logo.png" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PollyDemos\PollyDemos.csproj" />
</ItemGroup>
</Project>
4 changes: 2 additions & 2 deletions PollyTestWebApi/PollyTestWebApi.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
</Project>
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "7.0.401",
"version": "8.0.100",
"allowPrerelease": false,
"rollForward": "latestMajor"
}
Expand Down

0 comments on commit 6e2c357

Please sign in to comment.