Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions QuickChart/QuickChart.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System.Text;
using System.Text.Json;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace QuickChart
{
Expand Down Expand Up @@ -51,7 +53,7 @@ public Chart(string scheme = null, string host = null, int? port = null)
}
else
{
if(scheme == "http")
if (scheme == "http")
{
Port = 80;
}
Expand Down Expand Up @@ -178,6 +180,52 @@ public byte[] ToByteArray()
return response.Content.ReadAsByteArrayAsync().Result;
}

public async Task<byte[]> 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());
Expand All @@ -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; }
Expand Down