From 4ec642ec201fd0b0dc8eee339ac7019dbb523f68 Mon Sep 17 00:00:00 2001 From: jericho Date: Sun, 15 Nov 2026 14:04:23 -0500 Subject: [PATCH 01/11] Add an extension method to conveniently download a file in a single line of code Resolves #135 --- Client/FluentClientExtensions.cs | 44 +++++++++++++++++++++++++++ Tests/Integration/IntegrationTests.cs | 27 +++++++++++++++- 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index 1a0900e..0509622 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -287,6 +287,50 @@ public static IRequest WithOptions(this IRequest request, bool? ignoreHttpErrors }); } + /// + /// Download a file from the specified resource and save it to the specified path, reporting progress if requested. + /// + /// The HTTP client. + /// The resource to download. + /// The path to save the downloaded file. + /// The buffer size to use when reading the response stream. + /// An optional progress reporter. + /// A cancellation token. + /// A task representing the asynchronous operation. + public static async Task DownloadFileAsync(this IClient client, string resource, string path, int bufferSize = 4096, IProgress? progress = null, CancellationToken cancellationToken = default) + { + // Dispatch the request and get the streaming response + var response = await client + .GetAsync(resource) + .WithOptions(completeWhen: HttpCompletionOption.ResponseHeadersRead) + .WithCancellationToken(cancellationToken) + .AsResponse(); + + // Attempt to determine the content length for progress reporting + long? contentLength = response.Message.Content.Headers.ContentLength.HasValue + ? response.Message.Content.Headers.ContentLength.Value + : null; + + using Stream responseStream = await response.Message.Content.ReadAsStreamAsync().ConfigureAwait(false); + using FileStream fileStream = File.Create(path, bufferSize); + + int bytesRead; + long totalBytesRead = 0L; + byte[] buffer = new byte[bufferSize]; + + // Read the response stream in chunks and write to the file, reporting progress if requested + while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) + { + await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); + totalBytesRead += bytesRead; + + if (contentLength.HasValue) + { + double progressPercentage = ((totalBytesRead * 1d) / (contentLength.Value * 1d)) * 100; + progress?.Report(progressPercentage); + } + } + } /********* ** Internal methods diff --git a/Tests/Integration/IntegrationTests.cs b/Tests/Integration/IntegrationTests.cs index cd12e11..dd241a7 100644 --- a/Tests/Integration/IntegrationTests.cs +++ b/Tests/Integration/IntegrationTests.cs @@ -1,7 +1,10 @@ using System; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq.Expressions; +using System.Net; + #if NET452 using System.Net; #endif @@ -71,6 +74,28 @@ public async Task StreamLargeFile() Assert.IsNotNull(result); } + [Test(Description = "The client can download a large file.")] + public async Task DownloadLargeFile() + { + // arrange + IClient client = this.ConstructClient("https://proof.ovh.net/"); + bool progressInvoked = false; + string resource = "files/1Mb.dat"; // this is the resource we want to download + string filePath = Path.Combine(Path.GetTempPath(), "1Mb.dat"); // this is the path where we want to save the downloaded file + int bufferSize = 4096; // this is the size of the buffer we will use to read the response stream + IProgress progress = new Progress(percent => + { + Debug.WriteLine($"Download progress: {percent}%"); + progressInvoked = true; + }); // this is the progress reporter that will be invoked during the download + + // act + await client.DownloadFileAsync(resource, filePath, bufferSize, progress); + + // assert + Assert.IsTrue(progressInvoked); + } + [Test(Description = "The client can fetch a resource from the English Wikipedia's API.")] public async Task EnglishWikipedia() { @@ -165,4 +190,4 @@ public static TObject AssertValue(this TObject obj, Expression< Assert.AreEqual(expected, actual.Compile().Invoke(obj), "Unexpected value for " + actual.Body); return obj; } -} \ No newline at end of file +} From c339cf688b3711376863e320f4e68772e184a371 Mon Sep 17 00:00:00 2001 From: jericho Date: Sun, 15 Nov 2026 14:34:19 -0500 Subject: [PATCH 02/11] Cleanup duplicate 'using' statement --- Tests/Integration/IntegrationTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Tests/Integration/IntegrationTests.cs b/Tests/Integration/IntegrationTests.cs index dd241a7..304e95e 100644 --- a/Tests/Integration/IntegrationTests.cs +++ b/Tests/Integration/IntegrationTests.cs @@ -3,7 +3,6 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq.Expressions; -using System.Net; #if NET452 using System.Net; From 21dd6140bb4f44d1e637c15b43bb363b46df3613 Mon Sep 17 00:00:00 2001 From: jericho Date: Sat, 21 Nov 2026 17:09:33 -0500 Subject: [PATCH 03/11] More terse syntax --- Client/FluentClientExtensions.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index 0509622..9d9a5e8 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -307,9 +307,7 @@ public static async Task DownloadFileAsync(this IClient client, string resource, .AsResponse(); // Attempt to determine the content length for progress reporting - long? contentLength = response.Message.Content.Headers.ContentLength.HasValue - ? response.Message.Content.Headers.ContentLength.Value - : null; + long? contentLength = response.Message.Content.Headers.ContentLength; using Stream responseStream = await response.Message.Content.ReadAsStreamAsync().ConfigureAwait(false); using FileStream fileStream = File.Create(path, bufferSize); From b9ce67b8f218558ade7632349eaa27da2b43571f Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 21 Nov 2026 18:22:58 -0500 Subject: [PATCH 04/11] Fix test download file not deleted (#135) --- Tests/Integration/IntegrationTests.cs | 36 +++++++++++++++------------ 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/Tests/Integration/IntegrationTests.cs b/Tests/Integration/IntegrationTests.cs index 304e95e..4240d77 100644 --- a/Tests/Integration/IntegrationTests.cs +++ b/Tests/Integration/IntegrationTests.cs @@ -76,23 +76,27 @@ public async Task StreamLargeFile() [Test(Description = "The client can download a large file.")] public async Task DownloadLargeFile() { - // arrange - IClient client = this.ConstructClient("https://proof.ovh.net/"); - bool progressInvoked = false; - string resource = "files/1Mb.dat"; // this is the resource we want to download - string filePath = Path.Combine(Path.GetTempPath(), "1Mb.dat"); // this is the path where we want to save the downloaded file - int bufferSize = 4096; // this is the size of the buffer we will use to read the response stream - IProgress progress = new Progress(percent => + string saveToPath = Path.Combine(Path.GetTempPath(), "1Mb.dat"); + try { - Debug.WriteLine($"Download progress: {percent}%"); - progressInvoked = true; - }); // this is the progress reporter that will be invoked during the download - - // act - await client.DownloadFileAsync(resource, filePath, bufferSize, progress); - - // assert - Assert.IsTrue(progressInvoked); + // arrange + IClient client = this.ConstructClient("https://proof.ovh.net/"); + + // act + bool progressInvoked = false; + await client.DownloadFileAsync("files/1Mb.dat", saveToPath, 4096, new Progress(percent => + { + Debug.WriteLine($"Download progress: {percent}%"); + progressInvoked = true; + })); + + // assert + Assert.IsTrue(progressInvoked); + } + finally + { + File.Delete(saveToPath); + } } [Test(Description = "The client can fetch a resource from the English Wikipedia's API.")] From 20fe247b1eccff8c52a0e77a227d3167c01506e6 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 21 Nov 2026 18:22:58 -0500 Subject: [PATCH 05/11] Fix running new integration test in .NET 4.5.2 (#135) --- Tests/Integration/IntegrationTests.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Tests/Integration/IntegrationTests.cs b/Tests/Integration/IntegrationTests.cs index 4240d77..13d1f5c 100644 --- a/Tests/Integration/IntegrationTests.cs +++ b/Tests/Integration/IntegrationTests.cs @@ -57,6 +57,15 @@ public class IntegrationTests /********* ** Unit tests *********/ + /// The setup code to before any tests in the fixture. + [OneTimeSetUp] + public void OneTimeSetUp() + { +#if NET452 + ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; +#endif + } + [Test(Description = "The client can stream a large file.")] public async Task StreamLargeFile() { @@ -102,10 +111,6 @@ public async Task DownloadLargeFile() [Test(Description = "The client can fetch a resource from the English Wikipedia's API.")] public async Task EnglishWikipedia() { -#if NET452 - ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; -#endif - // arrange IClient client = this.ConstructClient("https://en.wikipedia.org/"); @@ -122,10 +127,6 @@ public async Task EnglishWikipedia() [Test(Description = "The client can fetch a resource from the Chinese Wikipedia's API, including proper Unicode handling.")] public async Task ChineseWikipedia() { -#if NET452 - ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; -#endif - // arrange IClient client = this.ConstructClient("https://zh.wikipedia.org/"); From 2f5dc68f166045eaf6e73523e0dc54414bf8087d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 21 Nov 2026 18:22:58 -0500 Subject: [PATCH 06/11] Fix running new integration test in parallel (#135) --- Tests/Integration/IntegrationTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Integration/IntegrationTests.cs b/Tests/Integration/IntegrationTests.cs index 13d1f5c..3baac6d 100644 --- a/Tests/Integration/IntegrationTests.cs +++ b/Tests/Integration/IntegrationTests.cs @@ -85,7 +85,7 @@ public async Task StreamLargeFile() [Test(Description = "The client can download a large file.")] public async Task DownloadLargeFile() { - string saveToPath = Path.Combine(Path.GetTempPath(), "1Mb.dat"); + string saveToPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); try { // arrange From c22cb39f09eca386b21a74e213a6eeed327128da Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 21 Nov 2026 18:22:58 -0500 Subject: [PATCH 07/11] Fix potential deadlock in some older apps (#135) --- Client/FluentClientExtensions.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index 9d9a5e8..08b2a77 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -300,11 +300,12 @@ public static IRequest WithOptions(this IRequest request, bool? ignoreHttpErrors public static async Task DownloadFileAsync(this IClient client, string resource, string path, int bufferSize = 4096, IProgress? progress = null, CancellationToken cancellationToken = default) { // Dispatch the request and get the streaming response - var response = await client + IResponse response = await client .GetAsync(resource) .WithOptions(completeWhen: HttpCompletionOption.ResponseHeadersRead) .WithCancellationToken(cancellationToken) - .AsResponse(); + .AsResponse() + .ConfigureAwait(false); // Attempt to determine the content length for progress reporting long? contentLength = response.Message.Content.Headers.ContentLength; From ca6c84978ecf8731be728c9c79db8a0a344fb36d Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 21 Nov 2026 18:22:58 -0500 Subject: [PATCH 08/11] Fix edge cases with progress tracking (#135) This fixes a few edge cases: - downloads finishing without a guaranteed 100% progress update; - progress reporting invalid percentages (e.g. 250%) if the server provides an incorrect Content-Length; - progress never reported if the server provides no Content-Length; - a DivideByZeroException if the server provides a zero Content-Length. --- Client/FluentClientExtensions.cs | 26 +++++++++++++++++--------- Tests/Integration/IntegrationTests.cs | 11 +++++++---- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index 08b2a77..c5b83e3 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -287,16 +287,13 @@ public static IRequest WithOptions(this IRequest request, bool? ignoreHttpErrors }); } - /// - /// Download a file from the specified resource and save it to the specified path, reporting progress if requested. - /// + /// Download a resource to a file path, reporting incremental download progress if requested. /// The HTTP client. /// The resource to download. /// The path to save the downloaded file. /// The buffer size to use when reading the response stream. - /// An optional progress reporter. + /// An optional progress reporter, which receives incremental progress updates (from 0 to 100) as it downloads. /// A cancellation token. - /// A task representing the asynchronous operation. public static async Task DownloadFileAsync(this IClient client, string resource, string path, int bufferSize = 4096, IProgress? progress = null, CancellationToken cancellationToken = default) { // Dispatch the request and get the streaming response @@ -308,7 +305,7 @@ public static async Task DownloadFileAsync(this IClient client, string resource, .ConfigureAwait(false); // Attempt to determine the content length for progress reporting - long? contentLength = response.Message.Content.Headers.ContentLength; + long contentLength = response.Message.Content.Headers.ContentLength ?? 0; using Stream responseStream = await response.Message.Content.ReadAsStreamAsync().ConfigureAwait(false); using FileStream fileStream = File.Create(path, bufferSize); @@ -318,17 +315,28 @@ public static async Task DownloadFileAsync(this IClient client, string resource, byte[] buffer = new byte[bufferSize]; // Read the response stream in chunks and write to the file, reporting progress if requested + double lastReportedProgress = 0; while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) { await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); totalBytesRead += bytesRead; - if (contentLength.HasValue) + if (contentLength > 0) { - double progressPercentage = ((totalBytesRead * 1d) / (contentLength.Value * 1d)) * 100; - progress?.Report(progressPercentage); + double percentDownloaded = (totalBytesRead / (contentLength * 1d)) * 100; + if (percentDownloaded > 100) + percentDownloaded = 100; + + if (percentDownloaded > lastReportedProgress) + { + progress?.Report(percentDownloaded); + lastReportedProgress = percentDownloaded; + } } } + + if (lastReportedProgress < 100) + progress?.Report(100); } /********* diff --git a/Tests/Integration/IntegrationTests.cs b/Tests/Integration/IntegrationTests.cs index 3baac6d..bdb87d6 100644 --- a/Tests/Integration/IntegrationTests.cs +++ b/Tests/Integration/IntegrationTests.cs @@ -70,7 +70,7 @@ public void OneTimeSetUp() public async Task StreamLargeFile() { // arrange - IClient client = this.ConstructClient("https://proof.ovh.net/"); + using IClient client = this.ConstructClient("https://proof.ovh.net/"); // act Stream result = await client @@ -89,18 +89,21 @@ public async Task DownloadLargeFile() try { // arrange - IClient client = this.ConstructClient("https://proof.ovh.net/"); + using IClient client = this.ConstructClient("https://proof.ovh.net/"); // act bool progressInvoked = false; + double lastProgressReported = 0; await client.DownloadFileAsync("files/1Mb.dat", saveToPath, 4096, new Progress(percent => { Debug.WriteLine($"Download progress: {percent}%"); progressInvoked = true; + lastProgressReported = percent; })); // assert Assert.IsTrue(progressInvoked); + Assert.AreEqual(100, lastProgressReported); } finally { @@ -112,7 +115,7 @@ public async Task DownloadLargeFile() public async Task EnglishWikipedia() { // arrange - IClient client = this.ConstructClient("https://en.wikipedia.org/"); + using IClient client = this.ConstructClient("https://en.wikipedia.org/"); // act WikipediaMetadata response = await client @@ -128,7 +131,7 @@ public async Task EnglishWikipedia() public async Task ChineseWikipedia() { // arrange - IClient client = this.ConstructClient("https://zh.wikipedia.org/"); + using IClient client = this.ConstructClient("https://zh.wikipedia.org/"); // act WikipediaMetadata response = await client From be1e8a16d400450c1a7c6b08f34115902c675c46 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 21 Nov 2026 18:22:58 -0500 Subject: [PATCH 09/11] Use the `AsStream()` extension (#135) This applies our pre-existing fixes like #126 to the new code. --- Client/FluentClientExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index c5b83e3..b865ec1 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -307,7 +307,7 @@ public static async Task DownloadFileAsync(this IClient client, string resource, // Attempt to determine the content length for progress reporting long contentLength = response.Message.Content.Headers.ContentLength ?? 0; - using Stream responseStream = await response.Message.Content.ReadAsStreamAsync().ConfigureAwait(false); + using Stream responseStream = await response.AsStream().ConfigureAwait(false); using FileStream fileStream = File.Create(path, bufferSize); int bytesRead; From 4d867151cfa37cbb5f383b26e2e765bd2464dbee Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 21 Nov 2026 18:22:59 -0500 Subject: [PATCH 10/11] Throttle download progress reports (#135) We reported progress on every chunk read, but that could lead to a large number of callbacks when downloading a large file over a fast connection (e.g. thousands per second). The progress reports are now throttled to one per 250ms at most. --- Client/FluentClientExtensions.cs | 54 ++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index b865ec1..b5d964f 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -296,7 +296,7 @@ public static IRequest WithOptions(this IRequest request, bool? ignoreHttpErrors /// A cancellation token. public static async Task DownloadFileAsync(this IClient client, string resource, string path, int bufferSize = 4096, IProgress? progress = null, CancellationToken cancellationToken = default) { - // Dispatch the request and get the streaming response + // fetch response IResponse response = await client .GetAsync(resource) .WithOptions(completeWhen: HttpCompletionOption.ResponseHeadersRead) @@ -304,37 +304,57 @@ public static async Task DownloadFileAsync(this IClient client, string resource, .AsResponse() .ConfigureAwait(false); - // Attempt to determine the content length for progress reporting + // get content length if possible long contentLength = response.Message.Content.Headers.ContentLength ?? 0; + // init file using Stream responseStream = await response.AsStream().ConfigureAwait(false); using FileStream fileStream = File.Create(path, bufferSize); - int bytesRead; - long totalBytesRead = 0L; - byte[] buffer = new byte[bufferSize]; - - // Read the response stream in chunks and write to the file, reporting progress if requested + // stream file to disk double lastReportedProgress = 0; - while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) { - await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); - totalBytesRead += bytesRead; + int bytesRead; + long totalBytesRead = 0L; + byte[] buffer = new byte[bufferSize]; + + long lastTickReported = 0; + const long throttleMilliseconds = 250; - if (contentLength > 0) + while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) { - double percentDownloaded = (totalBytesRead / (contentLength * 1d)) * 100; - if (percentDownloaded > 100) - percentDownloaded = 100; + // stream next chunk + await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); + totalBytesRead += bytesRead; + + // get current tick + long tick = +#if NET5_0_OR_GREATER + Environment.TickCount64; +#else + Environment.TickCount; +#endif + if (tick < lastTickReported) + lastTickReported = tick; // workaround: `Environment.TickCount` eventually wraps around, which would stop any further progress updates - if (percentDownloaded > lastReportedProgress) + // notify progress tracker + if (contentLength > 0 && tick >= lastTickReported + throttleMilliseconds) { - progress?.Report(percentDownloaded); - lastReportedProgress = percentDownloaded; + double percentDownloaded = (totalBytesRead / (contentLength * 1d)) * 100; + if (percentDownloaded > 100) + percentDownloaded = 100; + + if (percentDownloaded > lastReportedProgress) + { + progress?.Report(percentDownloaded); + lastReportedProgress = percentDownloaded; + lastTickReported = tick; + } } } } + // send final progress update if (lastReportedProgress < 100) progress?.Report(100); } From e7af4f75b8399e3de2ba85cba29850e20d471176 Mon Sep 17 00:00:00 2001 From: jericho Date: Sun, 22 Nov 2026 11:04:36 -0500 Subject: [PATCH 11/11] Optimisation for .NET 5 or greater https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1835 --- Client/FluentClientExtensions.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Client/FluentClientExtensions.cs b/Client/FluentClientExtensions.cs index b5d964f..9c01ca8 100644 --- a/Client/FluentClientExtensions.cs +++ b/Client/FluentClientExtensions.cs @@ -316,15 +316,24 @@ public static async Task DownloadFileAsync(this IClient client, string resource, { int bytesRead; long totalBytesRead = 0L; - byte[] buffer = new byte[bufferSize]; long lastTickReported = 0; const long throttleMilliseconds = 250; +#if NET5_0_OR_GREATER + Memory buffer = new byte[bufferSize]; + while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) +#else + byte[] buffer = new byte[bufferSize]; while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) +#endif { // stream next chunk +#if NET5_0_OR_GREATER + await fileStream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); +#else await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); +#endif totalBytesRead += bytesRead; // get current tick