From be1500919d00e9205a45e787a0b4715e1ec17d35 Mon Sep 17 00:00:00 2001 From: "Mark.Dingley" Date: Tue, 8 Sep 2026 09:50:27 +0100 Subject: [PATCH] Adds ToByteArrayAsync with cancellation support --- QuickChart/QuickChart.cs | 52 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/QuickChart/QuickChart.cs b/QuickChart/QuickChart.cs index 01d16e6..bf95a45 100644 --- a/QuickChart/QuickChart.cs +++ b/QuickChart/QuickChart.cs @@ -3,6 +3,8 @@ using System.Text; using System.Text.Json; using System.IO; +using System.Threading; +using System.Threading.Tasks; namespace QuickChart { @@ -51,7 +53,7 @@ public Chart(string scheme = null, string host = null, int? port = null) } else { - if(scheme == "http") + if (scheme == "http") { Port = 80; } @@ -178,6 +180,52 @@ public byte[] ToByteArray() return response.Content.ReadAsByteArrayAsync().Result; } + public async Task ToByteArrayAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (Config == null) + { + throw new NullReferenceException("You must set Config on the QuickChart object before generating a URL"); + } + + var options = new JsonSerializerOptions() + { + IgnoreNullValues = true, + }; + + var json = JsonSerializer.Serialize(new + { + width = Width, + height = Height, + backgroundColor = BackgroundColor, + devicePixelRatio = DevicePixelRatio, + format = Format, + chart = Config, + }, options); + + var url = $"{Scheme}://{Host}:{Port}/chart"; + + using (var content = new StringContent(json, Encoding.UTF8, "application/json")) + { + var response = await Client.PostAsync(url, content, cancellationToken).ConfigureAwait(false); + + if (!response.IsSuccessStatusCode) + { + throw new ApiException("Unsuccessful response from API", response); + } + + using (response) + { + cancellationToken.ThrowIfCancellationRequested(); + + return await response.Content + .ReadAsByteArrayAsync() + .ConfigureAwait(false); + } + } + } + public void ToFile(string filePath) { File.WriteAllBytes(filePath, this.ToByteArray()); @@ -186,7 +234,7 @@ public void ToFile(string filePath) public class ApiException : Exception { - public ApiException(string message, HttpResponseMessage response) : base(message) + public ApiException(string message, HttpResponseMessage response) : base(message) => this.Response = response; public HttpResponseMessage Response { get; private set; }