AbstractConnection.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Abstractions;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using BO.AppServer.Metadata.Dto;
  11. using Quadarax.Foundation.Core.Data.Interface;
  12. using Quadarax.Foundation.Core.Data.Interface.Entity;
  13. using Quadarax.Foundation.Core.Data.Interface.Entity.Dto;
  14. using Quadarax.Foundation.Core.Json;
  15. using Quadarax.Foundation.Core.Logging;
  16. using Quadarax.Foundation.Core.Object;
  17. using Quadarax.Foundation.Core.Value.Extensions;
  18. namespace BO.Connector
  19. {
  20. public abstract class AbstractConnection : DisposableObject
  21. {
  22. #region *** Private fields ***
  23. private HttpClient _client;
  24. private Uri _uriApiBase;
  25. private ILogHandler _log;
  26. private TimeSpan _timeout;
  27. private string _ticket;
  28. private Binder _binder;
  29. private bool _isDumpContentEnabled;
  30. protected abstract string ApiName { get; }
  31. protected bool IsOpen => !string.IsNullOrEmpty(_ticket);
  32. protected string Ticket => _ticket;
  33. #endregion
  34. #region *** Constructors ***
  35. protected AbstractConnection(Uri uriApiBase, TimeSpan timeout, ILogHandler log = null, bool isDumpContentEnabled = false)
  36. {
  37. _uriApiBase = uriApiBase ?? throw new ArgumentNullException(nameof(uriApiBase));
  38. _uriApiBase = new Uri(_uriApiBase.AbsoluteUri + ApiName + "/");
  39. _log = log;
  40. _timeout = timeout;
  41. _binder = new Binder(new FileSystem());
  42. _binder.SerializerOptions.IgnoreReadOnlyProperties = true;
  43. _binder.SerializerOptions.IgnoreNullValues = true;
  44. _isDumpContentEnabled = isDumpContentEnabled;
  45. }
  46. #endregion
  47. #region *** Public Operations ***
  48. public void Open(string userName, string userPassword, string magicKey)
  49. {
  50. Log(LogSeverityEnum.Trace, $"Opening Connector '{ApiName}' open with magicKey='{magicKey}'");
  51. _client = CreateClient();
  52. InitTicket(magicKey);
  53. Login(userName, userPassword);
  54. OnOpening();
  55. Log(LogSeverityEnum.Debug, $"Connector '{ApiName}' open for user '{userName}' with timeout setting {_timeout}.");
  56. }
  57. public void Close()
  58. {
  59. _client?.CancelPendingRequests();
  60. _client?.Dispose();
  61. _client = null;
  62. _ticket = string.Empty;
  63. Log(LogSeverityEnum.Debug, $"Connector '{ApiName}' closed.");
  64. }
  65. public bool Ping(out TimeSpan duration, out string status)
  66. {
  67. CheckIsOpen();
  68. var start = DateTime.Now;
  69. var ping = Task.Run(() =>CallRequestAsync<ResultValueDto<PingDto>>($"{_ticket}/ping", RestCallTypeEnum.Get, null, null, true));
  70. ping.Wait();
  71. duration = DateTime.Now - start;
  72. if (ping.Result == null)
  73. {
  74. status = string.Empty;
  75. return false;
  76. }
  77. status = ping.Result.Value.Status;
  78. return ping.Result.IsSuccess;
  79. }
  80. #endregion
  81. #region *** Virtuals & Overrides ***
  82. protected override void OnDisposing()
  83. {
  84. _client?.Dispose();
  85. }
  86. #endregion
  87. #region *** Private Operations ***
  88. protected void CheckIsOpen()
  89. {
  90. if (!IsOpen)
  91. throw new InvalidOperationException(
  92. "Connector is not open to call specific operation. Call Open() first.");
  93. }
  94. protected void Log(LogSeverityEnum type, string message, Exception e = null)
  95. {
  96. _log?.Log(type, message, e);
  97. }
  98. protected void InitTicket(string magicKey)
  99. {
  100. var result = Task.Run(() => CallRequestAsync<ResultValueDto<AuthDto>>($"{magicKey}/auth", RestCallTypeEnum.Get));;
  101. result.Wait();
  102. if (!result.Result.IsSuccess)
  103. throw result.Result.ToAggregateException();
  104. _ticket = result.Result.Value.Ticket;
  105. }
  106. protected void Login(string userName, string userPassword)
  107. {
  108. var headerAtts = new Dictionary<string, string>();
  109. headerAtts.Add("userName",userName);
  110. headerAtts.Add("userPassword",userPassword);
  111. var result = Task.Run(() => CallRequestAsync<ResultValueDto<UserRDto>>($"{_ticket}/login", RestCallTypeEnum.Post, new ResultPlain(), headerAtts));
  112. result.Wait();
  113. if (!result.Result.IsSuccess)
  114. throw result.Result.ToAggregateException();
  115. Log(LogSeverityEnum.Info,$"User '{result.Result.Value.Name}' is logged in.");
  116. }
  117. protected IDictionary<string, string> GetPagingHeaderAttributes(PagingDto paging, IDictionary<string,string> source = null)
  118. {
  119. if (paging == null || paging.IsDisabled)
  120. return null;//paging = new PagingDto();
  121. if (source == null)
  122. source = new Dictionary<string, string>();
  123. source.Add(new KeyValuePair<string, string>("page", paging.Page.ToString()));
  124. source.Add(new KeyValuePair<string, string>("pageSize", paging.PageSize.ToString()));
  125. return source;
  126. }
  127. protected IDictionary<string, string> GetApiPasswordHeaderAttributes(string apiKeyPassword, IDictionary<string,string> source = null)
  128. {
  129. if (source == null)
  130. source = new Dictionary<string, string>();
  131. source.Add(new KeyValuePair<string, string>("apiKeyPassword", apiKeyPassword));
  132. return source;
  133. }
  134. protected IDictionary<string, string> GetUserContextHeaderAttributes(string userNameContext, IDictionary<string,string> source = null)
  135. {
  136. if (source == null)
  137. source = new Dictionary<string, string>();
  138. source.Add(new KeyValuePair<string, string>("context", userNameContext));
  139. return source;
  140. }
  141. protected async Task<Stream> CallGetStreamAsync(string relativeUrlApiCall,
  142. IDictionary<string, string> headerAttributes = null, bool silent = false)
  143. {
  144. Log(LogSeverityEnum.Trace, $"Calling REST API GET STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall}");
  145. if (headerAttributes != null)
  146. {
  147. foreach (var key in headerAttributes.Keys)
  148. {
  149. _client.DefaultRequestHeaders.Remove(key);
  150. _client.DefaultRequestHeaders.Add(key,headerAttributes[key]);
  151. }
  152. }
  153. return await _client.GetStreamAsync(relativeUrlApiCall);
  154. }
  155. protected async Task<TResult> CallPostStreamMultipartAsync<TResult>(string relativeUrlApiCall,
  156. string fileName,Stream stream,string streamMimeType, IDictionary<string, string> headerAttributes = null, bool silent = false)
  157. where TResult : ResultDto
  158. {
  159. Log(LogSeverityEnum.Trace, $"Calling REST API POST-MULTI-STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall}");
  160. var boundary = Guid.NewGuid().ToString();
  161. var mpc = new MultipartFormDataContent(boundary);
  162. mpc.Headers.Remove("Content-Type");
  163. mpc.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
  164. var stc = new StreamContent(stream);
  165. stc.Headers.ContentType = new MediaTypeHeaderValue(streamMimeType);
  166. mpc.Add(stc, "content", fileName);
  167. using (var rq = new HttpRequestMessage())
  168. {
  169. rq.Content = mpc;
  170. rq.Method = new System.Net.Http.HttpMethod("POST");
  171. rq.RequestUri = new Uri(_uriApiBase.AbsoluteUri + relativeUrlApiCall);
  172. rq.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));
  173. if (headerAttributes != null)
  174. foreach (var key in headerAttributes.Keys)
  175. rq.Headers.Add(key, headerAttributes[key]);
  176. var start = DateTime.Now;
  177. var resp = await _client.SendAsync(rq);
  178. //var resp = await cli.PostAsync(relativeUrlApiCall, rqdMulti);
  179. Log(LogSeverityEnum.Trace,
  180. $"REST API POST-MULTI-STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall} done @ {(DateTime.Now - start).ToReadableString()}");
  181. if (!resp.IsSuccessStatusCode)
  182. {
  183. var message =
  184. $"Calling REST API POST-MULTI-STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall} ends with result code '{resp.StatusCode}'";
  185. Log(LogSeverityEnum.Warn, message);
  186. throw new Exception(message);
  187. }
  188. var content = await resp.Content.ReadAsStringAsync();
  189. if (_isDumpContentEnabled)
  190. Log(LogSeverityEnum.Trace, content);
  191. var result = (TResult)_binder.LoadFromString(content, typeof(TResult));
  192. if (result.IsSuccess) return result;
  193. if (silent) return result;
  194. // handle errors
  195. var excps = new List<Exception>();
  196. foreach (var err in result.Errors)
  197. {
  198. var exc = new Exception($"[{err.Code}] {err.Message}");
  199. exc.Data.Add("Code", err.Code);
  200. excps.Add(exc);
  201. }
  202. throw new AggregateException(excps);
  203. }
  204. }
  205. protected async Task<TResult> CallRequestAsync<TResult>(string relativeUrlApiCall,RestCallTypeEnum method, IDto data = null,IDictionary<string,string> headerAttributes = null, bool silent = false)
  206. where TResult : ResultDto
  207. {
  208. if (data == null)
  209. if(method != RestCallTypeEnum.Get && method != RestCallTypeEnum.GetStream && method != RestCallTypeEnum.Delete)
  210. throw new ArgumentNullException(nameof(data), $"For REST API method '{method}' data must be specified!");
  211. Log(LogSeverityEnum.Trace, $"Calling REST API {method} {_uriApiBase.AbsoluteUri + relativeUrlApiCall}");
  212. var start = DateTime.Now;
  213. HttpResponseMessage resp = null;
  214. SetDefaultClientHeaders(_client);
  215. HttpContentHeaders reqHeaders = null;
  216. switch (method)
  217. {
  218. case RestCallTypeEnum.Get:
  219. if (headerAttributes != null)
  220. {
  221. foreach (var key in headerAttributes.Keys)
  222. {
  223. _client.DefaultRequestHeaders.Remove(key);
  224. _client.DefaultRequestHeaders.Add(key,headerAttributes[key]);
  225. }
  226. }
  227. resp = await _client.GetAsync(relativeUrlApiCall);
  228. break;
  229. case RestCallTypeEnum.Post:
  230. var req = new StringContent(_binder.SaveToString(data));
  231. reqHeaders = req.Headers;
  232. if (headerAttributes!=null)
  233. foreach (var key in headerAttributes.Keys)
  234. {
  235. //if (req.Headers.Contains(key))
  236. req.Headers.Remove(key);
  237. req.Headers.Add(key, headerAttributes[key]);
  238. }
  239. req.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  240. resp = await _client.PostAsync(relativeUrlApiCall, req);
  241. break;
  242. case RestCallTypeEnum.Put:
  243. req = new StringContent(_binder.SaveToString(data));
  244. reqHeaders = req.Headers;
  245. if (headerAttributes!=null)
  246. foreach (var key in headerAttributes.Keys)
  247. {
  248. // if (req.Headers.Contains(key))
  249. req.Headers.Remove(key);
  250. req.Headers.Add(key, headerAttributes[key]);
  251. }
  252. req.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  253. resp = await _client.PutAsync(relativeUrlApiCall, req);
  254. break;
  255. case RestCallTypeEnum.Delete:
  256. resp = await _client.DeleteAsync(relativeUrlApiCall);
  257. break;
  258. default:
  259. throw new NotSupportedException($"{method} REST API operation is not implemented.");
  260. }
  261. // may remove paging headers after call
  262. /*
  263. if (headerAttributes != null)
  264. foreach (var key in headerAttributes.Keys)
  265. _client.DefaultRequestHeaders.Remove(key);
  266. */
  267. Log(LogSeverityEnum.Trace, $"REST API {method} {_uriApiBase.AbsoluteUri + relativeUrlApiCall} done @ {(DateTime.Now - start).ToReadableString()}");
  268. if (!resp.IsSuccessStatusCode)
  269. {
  270. var message = $"Calling REST API {method} {_uriApiBase.AbsoluteUri + relativeUrlApiCall} ends with result code '{resp.StatusCode}'";
  271. Log(LogSeverityEnum.Warn, message);
  272. throw new Exception(message);
  273. }
  274. var content = await resp.Content.ReadAsStringAsync();
  275. if (_isDumpContentEnabled)
  276. {
  277. Log(LogSeverityEnum.Trace, DumpHttpClient(method,relativeUrlApiCall, _client, reqHeaders));
  278. Log(LogSeverityEnum.Trace, content);
  279. }
  280. var result = (TResult)_binder.LoadFromString(content, typeof(TResult));
  281. if (result.IsSuccess) return result;
  282. // No data exception pass result
  283. if (!result.IsSuccess && result.Errors.Any(x => x.Code == 1099)) return result;
  284. if (silent) return result;
  285. // handle errors
  286. var excps = new List<Exception>();
  287. foreach (var err in result.Errors)
  288. {
  289. var exc = new Exception($"[{err.Code}] {err.Message}");
  290. exc.Data.Add("Code", err.Code);
  291. excps.Add(exc);
  292. }
  293. throw new AggregateException(excps);
  294. }
  295. protected virtual void OnOpening()
  296. {
  297. }
  298. private HttpClient CreateClient()
  299. {
  300. var client = new HttpClient();
  301. client.BaseAddress = new Uri(_uriApiBase, ApiName);
  302. client.Timeout = _timeout;
  303. SetDefaultClientHeaders(client);
  304. return client;
  305. }
  306. private void SetDefaultClientHeaders(HttpClient client)
  307. {
  308. client.DefaultRequestHeaders.Clear();
  309. client.DefaultRequestHeaders.Add("User-Agent", "BO.Connector." + ApiName);
  310. // Add an Accept header for JSON format.
  311. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  312. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/mixed"));
  313. //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
  314. }
  315. private string DumpHttpClient(RestCallTypeEnum method, string relativeUrl, HttpClient client, HttpContentHeaders headers)
  316. {
  317. var sb = new StringBuilder();
  318. sb.Append($"RQ {method.ToString().ToUpper()} to url '{_client.BaseAddress + relativeUrl}':").AppendLine();
  319. sb.Append($"rq version: {_client.DefaultRequestVersion}").AppendLine();
  320. sb.Append($"rq timeout: {_client.Timeout.ToReadableString()}").AppendLine();
  321. sb.Append("Headers:").AppendLine();
  322. foreach (var header in _client.DefaultRequestHeaders)
  323. sb.Append(header.Key).Append(" : ").Append(string.Join(",", header.Value)).AppendLine();
  324. sb.Append(DumpHttpHeaders(headers));
  325. return sb.ToString();
  326. }
  327. private string DumpHttpHeaders(HttpContentHeaders headers)
  328. {
  329. var sb = new StringBuilder();
  330. sb.Append("Headers:").AppendLine();
  331. if (headers != null)
  332. {
  333. foreach (var header in headers)
  334. sb.Append(header.Key).Append(" : ").Append(string.Join(",", header.Value)).AppendLine();
  335. }
  336. return sb.ToString();
  337. }
  338. #endregion
  339. }
  340. }