JsonClient.cs 12 KB

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