JsonClient.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Text;
  9. using InABox.Core;
  10. using RestSharp;
  11. //using InABox.Logging;
  12. namespace InABox.Clients
  13. {
  14. public class CompressedResponse
  15. {
  16. public CompressedResponse()
  17. {
  18. Headers = new Dictionary<string, string>();
  19. Options = new Dictionary<string, string>();
  20. }
  21. public string ContentType { get; set; }
  22. public Dictionary<string, string> Headers { get; set; }
  23. public int Status { get; set; }
  24. public string StatusCode { get; set; }
  25. public string Response { get; set; }
  26. public Dictionary<string, string> Options { get; set; }
  27. }
  28. public class JsonClient<TEntity> : RemoteClient<TEntity> where TEntity : Entity, new()
  29. {
  30. private readonly bool _compression = true;
  31. public JsonClient(string url, int port, bool useSimpleEncryption, bool compression) : base(url, port, useSimpleEncryption)
  32. {
  33. _compression = compression;
  34. }
  35. public JsonClient(string url, int port, bool useSimpleEncryption) : this(url, port, useSimpleEncryption, true)
  36. {
  37. }
  38. public JsonClient(string url, int port) : this(url, port, false, true)
  39. {
  40. }
  41. //private static void CheckSecuritySettings()
  42. //{
  43. // Boolean platformSupportsTls12 = false;
  44. // foreach (SecurityProtocolType protocol in Enum.GetValues(typeof(SecurityProtocolType)))
  45. // platformSupportsTls12 = platformSupportsTls12 || (protocol.GetHashCode() == 3072);
  46. // if (!ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072) && platformSupportsTls12)
  47. // ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
  48. // if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Ssl3))
  49. // System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
  50. //}
  51. protected override TResponse SendRequest<TRequest, TResponse>(TRequest request, string Action, bool includeEntity = true)
  52. {
  53. //DateTime now = DateTime.Now;
  54. //Log(" * {0}{1}() Starting..", Action, typeof(TEntity).Name);
  55. //Stopwatch sw = new Stopwatch();
  56. //sw.Start();
  57. //CheckSecuritySettings();
  58. var result = default(TResponse);
  59. long length = 0;
  60. if (string.IsNullOrEmpty(URL))
  61. {
  62. result = (TResponse)Activator.CreateInstance(typeof(TResponse));
  63. result.Status = StatusCode.BadServer;
  64. result.Messages.Add("Server URL not set!");
  65. return result;
  66. }
  67. //sw.Restart();
  68. var json = Serialization.Serialize(request);
  69. //Log(" * {0}{1}() Serializing data took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, json.Length);
  70. //sw.Restart();
  71. var uri = new Uri(string.Format("{0}:{1}", URL, Port));
  72. var cli = new RestClient(uri);
  73. var cmd = string.Format(
  74. "{0}{1}?format=json{2}",
  75. Action,
  76. includeEntity ? typeof(TEntity).Name : "",
  77. ""
  78. );
  79. var req = new RestRequest(cmd, Method.POST)
  80. {
  81. Timeout = Timeout.Milliseconds
  82. };
  83. //Log(" * {0}{1}() Creating Uri, Client and RestRequest took {2}ms", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds);
  84. //sw.Restart();
  85. req.AdvancedResponseWriter = (stream, response) =>
  86. {
  87. //Log(" * {0}{1}() Response from Server took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
  88. //length = response.ContentLength;
  89. //sw.Restart();
  90. //var str = new StreamReader(stream);//.ReadToEnd();
  91. try
  92. {
  93. result = Serialization.Deserialize<TResponse>(stream, true);
  94. }
  95. catch (Exception e)
  96. {
  97. Logger.Send(LogType.Information, "", $"Error deserializing response: {e.Message}");
  98. }
  99. //Log(" * {0}{1}() Deserializing Stream took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
  100. };
  101. //result = new TResponse();
  102. req.AddOrUpdateParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
  103. req.RequestFormat = DataFormat.Json;
  104. try
  105. {
  106. //sw.Restart();
  107. var res = cli.Execute(req);
  108. //Log(" * {0}{1}() returns {2} bytes in {3}ms", Action, typeof(TEntity).Name, res.ContentLength, sw.ElapsedMilliseconds);
  109. if (result == null)
  110. {
  111. if (res.ErrorException == null)
  112. {
  113. if (res.StatusCode != HttpStatusCode.OK)
  114. throw new Exception(String.Format("HTTP Request returns {0} {1}" + (int)res.StatusCode, CoreUtils.SplitCamelCase(res.StatusCode.ToString())));
  115. try
  116. {
  117. var data = "";
  118. if (_compression)
  119. {
  120. //sw.Restart();
  121. var comp = Serialization.Deserialize<CompressedResponse>(res.Content, true);
  122. var bytes = Convert.FromBase64String(comp.Response);
  123. var ms = new MemoryStream(bytes);
  124. using (var resultDeCompressedStream = new MemoryStream())
  125. {
  126. using (var decompressionStream = new DeflateStream(ms, CompressionMode.Decompress))
  127. {
  128. decompressionStream.CopyTo(resultDeCompressedStream);
  129. data = Encoding.UTF8.GetString(resultDeCompressedStream.ToArray(), 0,
  130. Convert.ToInt32(resultDeCompressedStream.Length));
  131. }
  132. }
  133. //Log(" * {0}{1}() Decompressing {2} -> {3} ({4:F2}%) bytes took {5}ms", Action, typeof(TEntity).Name, res.ContentLength, data.Length, ((double)data.Length *100.0F / (double)res.ContentLength), sw.ElapsedMilliseconds);
  134. }
  135. else
  136. {
  137. data = res.Content;
  138. }
  139. //sw.Restart();
  140. result = Serialization.Deserialize<TResponse>(data, true);
  141. //Log(" * {0}{1}() Deserializing data took {2}ms", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds);
  142. //sw.Stop();
  143. }
  144. catch (Exception eDeserialize)
  145. {
  146. throw new Exception(string.Format("Unable to deserialize response!\n\n{0}\n\n{1}", eDeserialize.Message, res.Content));
  147. }
  148. }
  149. else
  150. {
  151. // Connectivity
  152. result = new TResponse();
  153. result.Status = StatusCode.BadServer;
  154. result.Messages.Add(res.ErrorMessage);
  155. }
  156. }
  157. }
  158. catch (Exception err)
  159. {
  160. result = new TResponse();
  161. result.Status = StatusCode.BadServer;
  162. result.Messages.Add(err.Message);
  163. if (err.InnerException != null)
  164. result.Messages.Add("- " + err.InnerException.Message);
  165. }
  166. req = null;
  167. cli = null;
  168. //double elapsed = (DateTime.Now - now).TotalMilliseconds;
  169. //Log(" * {0}{1}() completed in {2:F0}ms", Action, typeof(TEntity).Name, elapsed);
  170. return result;
  171. }
  172. // SupportedTypes() function fallback for if the server is running on ServiceStack
  173. private void SupportedTypesOld(RestClient cli, List<string> result)
  174. {
  175. var req = new RestRequest("/operations/metadata?format=csv", Method.GET) { Timeout = 20000 };
  176. try
  177. {
  178. var res = cli.Execute(req);
  179. if (res.ErrorException == null)
  180. {
  181. var lines = res.Content.Split('\n').Skip(1);
  182. foreach (var line in lines)
  183. {
  184. var fields = line.Split(',');
  185. var svc = fields[2];
  186. if (!result.Contains(svc)) result.Add(svc);
  187. //if (svc.Equals("Comal_Classes_Login"))
  188. // result.Add("InABox_Core_Login");
  189. }
  190. }
  191. }
  192. catch (Exception e)
  193. {
  194. }
  195. req = null;
  196. cli = null;
  197. }
  198. // This code is duplicated in InABox.Clients.Remote.MsgPack
  199. // This should stay as-is, and work to remove RestSharp from MsgPack Client
  200. public override IEnumerable<string> SupportedTypes()
  201. {
  202. var result = new List<string>();
  203. var uri = new Uri(string.Format("{0}:{1}", URL, Port));
  204. var cli = new RestClient(uri);
  205. var req = new RestRequest("/classes", Method.GET) { Timeout = 20000 };
  206. try
  207. {
  208. var res = cli.Execute(req);
  209. if (res.StatusCode != HttpStatusCode.OK)
  210. {
  211. SupportedTypesOld(cli, result);
  212. }
  213. else if (res.ErrorException == null)
  214. {
  215. var list = res.Content.Trim('[', ']').Split(',');
  216. foreach (var operation in list)
  217. {
  218. var trimmed = operation.Trim('"');
  219. if (!result.Contains(trimmed)) result.Add(trimmed);
  220. //if (svc.Equals("Comal_Classes_Login"))
  221. // result.Add("InABox_Core_Login");
  222. }
  223. }
  224. }
  225. catch (Exception e)
  226. {
  227. }
  228. req = null;
  229. cli = null;
  230. return result.ToArray();
  231. }
  232. public override DatabaseInfo Info()
  233. {
  234. var uri = new Uri(string.Format("{0}:{1}", URL, Port));
  235. var cli = new RestClient(uri);
  236. var req = new RestRequest("/info", Method.GET) { Timeout = 20000 };
  237. try
  238. {
  239. var res = cli.Execute(req);
  240. if (res.StatusCode != HttpStatusCode.OK)
  241. {
  242. return new DatabaseInfo();
  243. }
  244. else if (res.ErrorException == null)
  245. {
  246. var info = Core.Serialization.Deserialize<InfoResponse>(res.Content);
  247. return info.Info;
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. return new DatabaseInfo();
  253. }
  254. return new DatabaseInfo();
  255. }
  256. }
  257. }