AbstractConnection.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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> GetOverwriteHeaderAttributes(bool overwrite, IDictionary<string,string> source = null)
  135. {
  136. if (source == null)
  137. source = new Dictionary<string, string>();
  138. source.Add(new KeyValuePair<string, string>("overwrite", overwrite.ToString()));
  139. return source;
  140. }
  141. protected IDictionary<string, string> GetForceHeaderAttributes(bool force, IDictionary<string,string> source = null)
  142. {
  143. if (source == null)
  144. source = new Dictionary<string, string>();
  145. source.Add(new KeyValuePair<string, string>("force", force.ToString()));
  146. return source;
  147. }
  148. protected IDictionary<string, string> GetUserContextHeaderAttributes(string userNameContext, IDictionary<string,string> source = null)
  149. {
  150. if (source == null)
  151. source = new Dictionary<string, string>();
  152. source.Add(new KeyValuePair<string, string>("context", userNameContext));
  153. return source;
  154. }
  155. protected async Task<Stream> CallGetStreamAsync(string relativeUrlApiCall,
  156. IDictionary<string, string> headerAttributes = null, bool silent = false)
  157. {
  158. Log(LogSeverityEnum.Trace, $"Calling REST API GET STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall}");
  159. if (headerAttributes != null)
  160. {
  161. foreach (var key in headerAttributes.Keys)
  162. {
  163. _client.DefaultRequestHeaders.Remove(key);
  164. _client.DefaultRequestHeaders.Add(key, headerAttributes[key]);
  165. }
  166. }
  167. return await _client.GetStreamAsync(relativeUrlApiCall);
  168. }
  169. protected async Task<TResult> CallPostStreamMultipartAsync<TResult>(string relativeUrlApiCall,
  170. string fileName,Stream stream,string streamMimeType, IDictionary<string, string> headerAttributes = null, bool silent = false)
  171. where TResult : ResultDto
  172. {
  173. Log(LogSeverityEnum.Trace, $"Calling REST API POST-MULTI-STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall}");
  174. var boundary = Guid.NewGuid().ToString();
  175. var mpc = new MultipartFormDataContent(boundary);
  176. mpc.Headers.Remove("Content-Type");
  177. mpc.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
  178. var stc = new StreamContent(stream);
  179. stc.Headers.ContentType = new MediaTypeHeaderValue(streamMimeType);
  180. mpc.Add(stc, "content", fileName);
  181. using (var rq = new HttpRequestMessage())
  182. {
  183. rq.Content = mpc;
  184. rq.Method = new System.Net.Http.HttpMethod("POST");
  185. rq.RequestUri = new Uri(_uriApiBase.AbsoluteUri + relativeUrlApiCall);
  186. rq.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));
  187. if (headerAttributes != null)
  188. foreach (var key in headerAttributes.Keys)
  189. rq.Headers.Add(key, headerAttributes[key]);
  190. var start = DateTime.Now;
  191. var resp = await _client.SendAsync(rq);
  192. //var resp = await cli.PostAsync(relativeUrlApiCall, rqdMulti);
  193. Log(LogSeverityEnum.Trace,
  194. $"REST API POST-MULTI-STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall} done @ {(DateTime.Now - start).ToReadableString()}");
  195. if (!resp.IsSuccessStatusCode)
  196. {
  197. var message =
  198. $"Calling REST API POST-MULTI-STREAM {_uriApiBase.AbsoluteUri + relativeUrlApiCall} ends with result code '{resp.StatusCode}'";
  199. Log(LogSeverityEnum.Warn, message);
  200. throw new Exception(message);
  201. }
  202. var content = await resp.Content.ReadAsStringAsync();
  203. if (_isDumpContentEnabled)
  204. Log(LogSeverityEnum.Trace, content);
  205. var result = (TResult)_binder.LoadFromString(content, typeof(TResult));
  206. if (result.IsSuccess) return result;
  207. if (silent) return result;
  208. // handle errors
  209. var excps = new List<Exception>();
  210. foreach (var err in result.Errors)
  211. {
  212. var exc = new Exception($"[{err.Code}] {err.Message}");
  213. exc.Data.Add("Code", err.Code);
  214. excps.Add(exc);
  215. }
  216. throw new AggregateException(excps);
  217. }
  218. }
  219. protected async Task<TResult> CallRequestAsync<TResult>(string relativeUrlApiCall,RestCallTypeEnum method, IDto data = null,IDictionary<string,string> headerAttributes = null, bool silent = false)
  220. where TResult : ResultDto
  221. {
  222. if (data == null)
  223. if(method != RestCallTypeEnum.Get && method != RestCallTypeEnum.GetStream && method != RestCallTypeEnum.Delete)
  224. throw new ArgumentNullException(nameof(data), $"For REST API method '{method}' data must be specified!");
  225. Log(LogSeverityEnum.Trace, $"Calling REST API {method} {_uriApiBase.AbsoluteUri + relativeUrlApiCall}");
  226. var start = DateTime.Now;
  227. HttpResponseMessage resp = null;
  228. SetDefaultClientHeaders(_client);
  229. HttpContentHeaders reqHeaders = null;
  230. switch (method)
  231. {
  232. case RestCallTypeEnum.Get:
  233. if (headerAttributes != null)
  234. {
  235. foreach (var key in headerAttributes.Keys)
  236. {
  237. _client.DefaultRequestHeaders.Remove(key);
  238. _client.DefaultRequestHeaders.Add(key,headerAttributes[key]);
  239. }
  240. }
  241. resp = await _client.GetAsync(relativeUrlApiCall);
  242. break;
  243. case RestCallTypeEnum.Post:
  244. var req = new StringContent(_binder.SaveToString(data));
  245. reqHeaders = req.Headers;
  246. if (headerAttributes!=null)
  247. foreach (var key in headerAttributes.Keys)
  248. {
  249. //if (req.Headers.Contains(key))
  250. req.Headers.Remove(key);
  251. req.Headers.Add(key, headerAttributes[key]);
  252. }
  253. req.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  254. resp = await _client.PostAsync(relativeUrlApiCall, req);
  255. break;
  256. case RestCallTypeEnum.Put:
  257. req = new StringContent(_binder.SaveToString(data));
  258. reqHeaders = req.Headers;
  259. if (headerAttributes!=null)
  260. foreach (var key in headerAttributes.Keys)
  261. {
  262. // if (req.Headers.Contains(key))
  263. req.Headers.Remove(key);
  264. req.Headers.Add(key, headerAttributes[key]);
  265. }
  266. req.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  267. resp = await _client.PutAsync(relativeUrlApiCall, req);
  268. break;
  269. case RestCallTypeEnum.Delete:
  270. using (var delRq = new HttpRequestMessage(HttpMethod.Delete, relativeUrlApiCall))
  271. {
  272. if (headerAttributes != null)
  273. foreach (var key in headerAttributes.Keys)
  274. {
  275. delRq.Headers.Remove(key);
  276. delRq.Headers.Add(key, headerAttributes[key]);
  277. }
  278. resp = await _client.SendAsync(delRq);
  279. }
  280. break;
  281. default:
  282. throw new NotSupportedException($"{method} REST API operation is not implemented.");
  283. }
  284. // may remove paging headers after call
  285. /*
  286. if (headerAttributes != null)
  287. foreach (var key in headerAttributes.Keys)
  288. _client.DefaultRequestHeaders.Remove(key);
  289. */
  290. Log(LogSeverityEnum.Trace, $"REST API {method} {_uriApiBase.AbsoluteUri + relativeUrlApiCall} done @ {(DateTime.Now - start).ToReadableString()}");
  291. if (!resp.IsSuccessStatusCode)
  292. {
  293. var message = $"Calling REST API {method} {_uriApiBase.AbsoluteUri + relativeUrlApiCall} ends with result code '{resp.StatusCode}'";
  294. Log(LogSeverityEnum.Warn, message);
  295. throw new Exception(message);
  296. }
  297. var content = await resp.Content.ReadAsStringAsync();
  298. if (_isDumpContentEnabled)
  299. {
  300. Log(LogSeverityEnum.Trace, DumpHttpClient(method,relativeUrlApiCall, _client, reqHeaders));
  301. Log(LogSeverityEnum.Trace, content);
  302. }
  303. var result = (TResult)_binder.LoadFromString(content, typeof(TResult));
  304. if (result.IsSuccess) return result;
  305. // No data exception pass result
  306. if (!result.IsSuccess && result.Errors.Any(x => x.Code == 1099)) return result;
  307. if (silent) return result;
  308. // handle errors
  309. var excps = new List<Exception>();
  310. foreach (var err in result.Errors)
  311. {
  312. var exc = new Exception($"[{err.Code}] {err.Message}");
  313. exc.Data.Add("Code", err.Code);
  314. excps.Add(exc);
  315. }
  316. throw new AggregateException(excps);
  317. }
  318. protected virtual void OnOpening()
  319. {
  320. }
  321. private HttpClient CreateClient()
  322. {
  323. var client = new HttpClient();
  324. client.BaseAddress = new Uri(_uriApiBase, ApiName);
  325. client.Timeout = _timeout;
  326. SetDefaultClientHeaders(client);
  327. return client;
  328. }
  329. private void SetDefaultClientHeaders(HttpClient client)
  330. {
  331. client.DefaultRequestHeaders.Clear();
  332. client.DefaultRequestHeaders.Add("User-Agent", "BO.Connector." + ApiName);
  333. // Add an Accept header for JSON format.
  334. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  335. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/mixed"));
  336. //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
  337. }
  338. private string DumpHttpClient(RestCallTypeEnum method, string relativeUrl, HttpClient client, HttpContentHeaders headers)
  339. {
  340. var sb = new StringBuilder();
  341. sb.Append($"RQ {method.ToString().ToUpper()} to url '{_client.BaseAddress + relativeUrl}':").AppendLine();
  342. sb.Append($"rq version: {_client.DefaultRequestVersion}").AppendLine();
  343. sb.Append($"rq timeout: {_client.Timeout.ToReadableString()}").AppendLine();
  344. sb.Append("Headers:").AppendLine();
  345. foreach (var header in _client.DefaultRequestHeaders)
  346. sb.Append(header.Key).Append(" : ").Append(string.Join(",", header.Value)).AppendLine();
  347. sb.Append(DumpHttpHeaders(headers));
  348. return sb.ToString();
  349. }
  350. private string DumpHttpHeaders(HttpContentHeaders headers)
  351. {
  352. var sb = new StringBuilder();
  353. sb.Append("Headers:").AppendLine();
  354. if (headers != null)
  355. {
  356. foreach (var header in headers)
  357. sb.Append(header.Key).Append(" : ").Append(string.Join(",", header.Value)).AppendLine();
  358. }
  359. return sb.ToString();
  360. }
  361. #endregion
  362. }
  363. }