• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

f2calv / CasCap.Common / 13300409113

13 Feb 2025 04:26AM UTC coverage: 0.334% (-0.03%) from 0.362%
13300409113

push

github

web-flow
F2calv/2025 02 updates (#215)

* logging

* tidy

* consolidate and rework IPAFValue and related objects + midpoint calc

* lots more tidynig

* fixed one more PAF test with Array2DConverter

* nuget

* big IGI tidy-up, still loads more to do

* PostAsync to HttpMessageRequest/Response

* nuget updates

* tidy SendAsync and fix tests

* nuget updates

* lint fixes

* tidy

0 of 336 branches covered (0.0%)

Branch coverage included in aggregate %.

0 of 79 new or added lines in 5 files covered. (0.0%)

4 existing lines in 3 files now uncovered.

3 of 561 relevant lines covered (0.53%)

0.01 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/CasCap.Common.Net/Services/Base/HttpClientBase.cs
1
namespace CasCap.Services;
2

3
public abstract class HttpClientBase
4
{
5
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
6
    protected ILogger _logger;
7
    protected HttpClient _client;
8
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
9

10
    protected virtual async Task<(TResult? result, TError? error)> PostJsonAsync<TResult, TError>(string requestUri, object? req = null, TimeSpan? timeout = null, List<(string name, string value)>? headers = null, string mediaType = "application/json")
11
        where TResult : class
12
        where TError : class
13
    {
14
        var res = await PostJson<TResult, TError>(requestUri, req, timeout, headers, mediaType);
×
15
        return (res.result, res.error);
×
16
    }
×
17

18
    protected virtual async Task<(TResult? result, TError? error, HttpStatusCode statusCode, HttpResponseHeaders responseHeaders)> PostJson<TResult, TError>(string requestUri, object? req = null, TimeSpan? timeout = null, List<(string name, string value)>? additionalHeaders = null, string mediaType = "application/json")
19
        where TResult : class
20
        where TError : class
21
    {
22
        (TResult? result, TError? error, HttpStatusCode httpStatusCode, HttpResponseHeaders responseHeaders) tpl;
23
        var url = requestUri.StartsWith("http") ? requestUri : $"{_client.BaseAddress}{requestUri}";//allows us to override base url
×
24
        //_logger.LogDebug("{className} {httpMethod}\t{url}", nameof(HttpClientBase), HttpMethod.Post, url);
25
        var json = req!.ToJson();
×
26
        using (var request = new HttpRequestMessage(HttpMethod.Post, url))//needs full url as a string as System.Uri can't cope with a colon
×
27
        {
28
            request.Content = new StringContent(json, Encoding.UTF8, mediaType);
×
NEW
29
            request.Headers.AddOrOverwrite(additionalHeaders);
×
30
            using var response = await _client.SendAsync(request).ConfigureAwait(false);//need to create a new .NET Standard extension method to handle GetCT(timeout)
×
31
            tpl = await HandleResult<TResult, TError>(response);
×
32
        }
×
33
        return tpl;
×
34
    }
×
35

36
    protected virtual async Task<(TResult? result, TError? error)> PostBytesAsync<TResult, TError>(string requestUri, byte[] bytes, TimeSpan? timeout = null, List<(string name, string value)>? headers = null, string mediaType = "application/octet-stream")
37
        where TResult : class
38
        where TError : class
39
    {
40
        var res = await PostBytes<TResult, TError>(requestUri, bytes, timeout, headers, mediaType);
×
41
        return (res.result, res.error);
×
42
    }
×
43

44
    protected virtual async Task<(TResult? result, TError? error, HttpStatusCode httpStatusCode, HttpResponseHeaders responseHeaders)> PostBytes<TResult, TError>(string requestUri, byte[] bytes, TimeSpan? timeout = null, List<(string name, string value)>? additionalHeaders = null, string mediaType = "application/octet-stream")
45
        where TResult : class
46
        where TError : class
47
    {
48
        (TResult? result, TError? error, HttpStatusCode httpStatusCode, HttpResponseHeaders responseHeaders) tpl;
49
        var url = requestUri.StartsWith("http") ? requestUri : $"{_client.BaseAddress}{requestUri}";//allows us to override base url
×
50
        //_logger.LogDebug("{className} {httpMethod}\t{url}", nameof(HttpClientBase), HttpMethod.Post, url);
51
        using (var request = new HttpRequestMessage(HttpMethod.Post, url))
×
52
        {
53
            request.Content = new ByteArrayContent(bytes);
×
54
            request.Content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
×
55
            //request.Headers.Add("Content-Type", mediaType);
NEW
56
            request.Headers.AddOrOverwrite(additionalHeaders);
×
57
            using var response = await _client.SendAsync(request).ConfigureAwait(false);
×
58
            tpl = await HandleResult<TResult, TError>(response);
×
59
        }
×
60
        return tpl;
×
61
    }
×
62

63
    protected virtual async Task<(TResult? result, TError? error)> GetAsync<TResult, TError>(string requestUri, TimeSpan? timeout = null, List<(string name, string value)>? headers = null)
64
        where TResult : class
65
        where TError : class
66
    {
67
        var res = await Get<TResult, TError>(requestUri, timeout, headers);
×
68
        return (res.result, res.error);
×
69
    }
×
70

71
    protected virtual async Task<(TResult? result, TError? error, HttpStatusCode httpStatusCode, HttpResponseHeaders responseHeaders)> Get<TResult, TError>(string requestUri, TimeSpan? timeout = null, List<(string name, string value)>? headers = null)
72
        where TResult : class
73
        where TError : class
74
    {
75
        var url = requestUri.StartsWith("http") ? requestUri : $"{_client.BaseAddress}{requestUri}";//allows us to override base url
×
76
        //_logger.LogDebug("{className} {httpMethod}\t{url}", nameof(HttpClientBase), HttpMethod.Post, url);
77
        //todo: add in headers?
78
        using var response = await _client.GetAsync(url, HttpCompletionOption.ResponseContentRead, GetCT(timeout)).ConfigureAwait(false);
×
79
        return await HandleResult<TResult, TError>(response);
×
80
    }
×
81

82
    private async Task<(TResult? result, TError? error, HttpStatusCode httpStatusCode, HttpResponseHeaders responseHeaders)> HandleResult<TResult, TError>(HttpResponseMessage response)
83
        where TResult : class
84
        where TError : class
85
    {
86
        (TResult? result, TError? error, HttpStatusCode httpStatusCode, HttpResponseHeaders responseHeaders) tpl;
87
        tpl.httpStatusCode = response.StatusCode;
×
88
        tpl.responseHeaders = response.Headers;
×
89
        if (response.IsSuccessStatusCode)
×
90
        {
91
            if (typeof(TResult).Equals(typeof(string)))
×
92
                tpl.result = (TResult)(object)await response.Content.ReadAsStringAsync().ConfigureAwait(false);
×
93
            else if (typeof(TResult).Equals(typeof(byte[])))
×
94
                tpl.result = (TResult)(object)await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
×
95
            else
96
                tpl.result = (await response.Content.ReadAsStringAsync().ConfigureAwait(false)).FromJson<TResult>();
×
97
            tpl.error = default;
×
98
        }
99
        else
100
        {
101
            if (typeof(TError).Equals(typeof(string)))
×
102
                tpl.error = (TError)(object)await response.Content.ReadAsStringAsync().ConfigureAwait(false);
×
103
            else if (typeof(TError).Equals(typeof(byte[])))
×
104
                tpl.error = (TError)(object)await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
×
105
            else
106
                tpl.error = (await response.Content.ReadAsStringAsync().ConfigureAwait(false)).FromJson<TError>();
×
107
            _logger.LogError("{className} StatusCode={StatusCode}, RequestUri={RequestUri}", nameof(HttpClientBase), response.StatusCode, response.RequestMessage?.RequestUri);
×
108
            //var err = $"requestUri= fail";
109
            //if (response.RequestMessage.Content.)
110
            //if (req is not null) err += $"{json}";
111
            //throw new Exception(err);
112
            tpl.result = default;
×
113
        }
114
        return tpl;
×
115
    }
×
116

117
    //https://stackoverflow.com/questions/46874693/re-using-httpclient-but-with-a-different-timeout-setting-per-request
118
    private static CancellationToken GetCT(TimeSpan? timeout = null)
119
    {
120
        var cts = new CancellationTokenSource();
×
121
        cts.CancelAfter(timeout ?? TimeSpan.FromSeconds(90));
×
122
        return cts.Token;
×
123
    }
124
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc