-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtility.cs
More file actions
69 lines (61 loc) · 2.3 KB
/
Utility.cs
File metadata and controls
69 lines (61 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Net.Mime;
using System.Text;
using Newtonsoft.Json;
using Serilog;
using SolarUseOptimiser.Models.Huawei;
namespace SolarUseOptimiser
{
public static class Utility
{
public static StringContent GetStringContent(string json)
{
return new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
}
public static StringContent GetStringContent(object obj, Formatting formatOption = Formatting.None)
{
string json = JsonConvert.SerializeObject(obj, formatOption);
Log.Logger.Debug("JSON Request Content: '{0}'", json);
return GetStringContent(json);
}
public static string GetJsonResponse(HttpResponseMessage message, CancellationToken cancellationToken)
{
return message.Content.ReadAsStringAsync(cancellationToken).GetAwaiter().GetResult();
}
public static bool WasSuccessMessage<T>(HttpResponseMessage message, out string json, out T response, CancellationToken cancellationToken) where T : BaseResponse
{
json = string.Empty;
response = null;
if (message != null)
{
try
{
json = GetJsonResponse(message, cancellationToken);
Log.Logger.Debug("JSON Response Content: '{0}'", json);
response = JsonConvert.DeserializeObject<T>(json);
if (response != null)
{
return response.success;
}
}
catch (Exception ex)
{
Log.Logger.Warning(ex, "Failed to get a valid response from the service. JSON: '{0}'", json);
return false;
}
}
return false;
}
public static string GetUrl(string baseUri, string methodUri)
{
if (methodUri.StartsWith("/"))
{
methodUri = methodUri.TrimStart('/');
}
if (baseUri.EndsWith("/"))
{
baseUri = baseUri.TrimEnd('/');
}
return string.Format("{0}/{1}", baseUri, methodUri);
}
}
}