Browse Source

CLIENT - upgrade RestSharp to V11, added static client as per best practice

Nick-PRSDigital@bitbucket.org 2 years ago
parent
commit
08f1a0a93a

+ 1 - 1
InABox.Client.Remote.Json/InABox.Client.Remote.Json.csproj

@@ -9,7 +9,7 @@
 
     <ItemGroup>
         <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
-        <PackageReference Include="RestSharp" Version="106.15.0" />
+        <PackageReference Include="RestSharp" Version="110.2.0" />
     </ItemGroup>
 
     <ItemGroup>

+ 2 - 2
InABox.Mobile/Shared/MobileUtils.cs

@@ -112,9 +112,9 @@ namespace InABox.Mobile
 
         private static void PingAndSetClient()
         {
-            var result = JsonClient<User>.Ping(App.DBSettings.URLs, out DatabaseInfo info);
+            var result = RestClient<User>.Ping(App.DBSettings.URLs, out DatabaseInfo info);
 
-            ClientFactory.SetClientType(typeof(JsonClient<>), "TimeBench", MobileUtils.AppVersion.InstalledVersionNumber + App.DeviceString, result, true);
+            ClientFactory.SetClientType(typeof(RestClient<>), InABox.Core.Platform.Mobile, MobileUtils.AppVersion.InstalledVersionNumber + App.DeviceString, result, true);
         }
 
         private static Tuple<string[], string> GetArray()

+ 4 - 4
inabox.client.rest/InABox.Client.Rest/HttpJsonClient.cs

@@ -71,7 +71,7 @@ namespace InABox.Client.Remote.Json
 
         public bool Ping(string endPoint)
         {
-            var req = new RestRequest(endPoint, Method.GET)
+            var req = new RestRequest(endPoint, Method.Get)
             {
                 Timeout = 10 * 1000
             };
@@ -100,7 +100,7 @@ namespace InABox.Client.Remote.Json
 
         public bool TryGetRequest<T>(string command, out T result, [NotNullWhen(false)] out string? error)
         {
-            var req = new RestRequest(command, Method.GET)
+            var req = new RestRequest(command, Method.Get)
             {
                 Timeout = 60 * 1000
             };
@@ -120,11 +120,11 @@ namespace InABox.Client.Remote.Json
         {
             var json = Serialization.Serialize(request);
 
-            var req = new RestRequest(command, Method.POST)
+            var req = new RestRequest(command, Method.Post)
             {
                 Timeout = 60 * 1000
             };
-            req.AddOrUpdateParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
+            req.AddOrUpdateParameter("application/json", json, ParameterType.RequestBody);
             req.RequestFormat = DataFormat.Json;
             return SendRequest<T>(req);
         }

+ 3 - 3
inabox.client.rest/InABox.Client.Rest/InABox.Client.Rest.csproj

@@ -1,8 +1,8 @@
 <Project Sdk="Microsoft.NET.Sdk">
 
     <PropertyGroup>
-        <TargetFramework>net6.0</TargetFramework>
-        <ImplicitUsings>enable</ImplicitUsings>
+        <TargetFramework>netstandard2.1</TargetFramework>
+        <ImplicitUsings>disable</ImplicitUsings>
         <Nullable>enable</Nullable>
     </PropertyGroup>
 
@@ -13,7 +13,7 @@
     </ItemGroup>
 
     <ItemGroup>
-      <PackageReference Include="RestSharp" Version="106.15.0" />
+      <PackageReference Include="RestSharp" Version="110.2.0" />
     </ItemGroup>
 
 </Project>

+ 58 - 31
inabox.client.rest/InABox.Client.Rest/RestClient.cs

@@ -1,8 +1,17 @@
 using System.IO.Compression;
 using System.Net;
+using System.Net.Security;
 using InABox.Core;
 using InABox.WebSocket.Shared;
 using RestSharp;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+
 
 namespace InABox.Clients
 {
@@ -12,6 +21,7 @@ namespace InABox.Clients
         private string _server;
         private bool _compression;
         private BinarySerializationSettings _binarysettings;
+        private static RestClient cli = null;
         
         public RestClient(string server, bool simpleencryption, bool compression, BinarySerializationSettings binarySerializationSettings)
         {
@@ -24,11 +34,28 @@ namespace InABox.Clients
             
         }
 
-        public RestClient(string server, bool simpleencryption, bool compression) : this(server, simpleencryption, compression, BinarySerializationSettings.Latest)
+        public static class StaticRestClients
+        {
+            public static Dictionary<string, RestClient> Clients = new Dictionary<string, RestClient>();
+
+            public static void SetClient(string url)
+            {
+                var uri = new Uri(url);
+                if (Clients.ContainsKey(url))
+                    cli = Clients[url];
+                else
+                {
+                    cli = new RestClient(uri);
+                    Clients.Add(url, cli);
+                }
+            }
+        }
+
+        public RestClient(string server, bool simpleencryption, bool compression) : this(server, simpleencryption, false, BinarySerializationSettings.Latest)
         {
         }
         
-        public RestClient(string server, bool simpleencryption) : this(server, simpleencryption, true)
+        public RestClient(string server, bool simpleencryption) : this(server, simpleencryption, false)
         {
         }
 
@@ -170,8 +197,9 @@ namespace InABox.Clients
                 return result;
             }
 
-            var uri = new Uri(url);
-            var cli = new RestClient(uri);
+            if (cli == null)
+                StaticRestClients.SetClient(url);
+
             var cmd = string.Format(
                 "{0}{1}?format={2}&responseFormat={3}&serializationVersion={4}", 
                 Action, 
@@ -180,35 +208,35 @@ namespace InABox.Clients
                 responseFormat,
                 _binarysettings.Version
             );
-            var req = new RestRequest(cmd, Method.POST)
+            var req = new RestRequest(cmd, Method.Post)
             {
                 Timeout = Timeout.Milliseconds,
             };
             //Log("  * {0}{1}() Creating Uri, Client and RestRequest took {2}ms", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds);
             //sw.Restart();
 
-            req.AdvancedResponseWriter = (stream, response) =>
-            {
-                //Log("  * {0}{1}() Response from Server took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
-                //length = response.ContentLength;
-                //sw.Restart();
-                try
-                {
-                    if (responseFormat == SerializationFormat.Binary && typeof(TResponse).HasInterface<ISerializeBinary>())
-                    {
-                        result = (TResponse)Serialization.ReadBinary(typeof(TResponse), stream, _binarysettings);
-                    }
-                    else
-                    {
-                        result = Serialization.Deserialize<TResponse>(stream, true);
-                    }
-                }
-                catch (Exception e)
-                {
-                    Logger.Send(LogType.Information, "", $"Error deserializing response: {e.Message}");
-                }
-                //Log("  * {0}{1}() Deserializing Stream took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
-            };
+            //req.AdvancedResponseWriter = (stream, response) =>
+            //{
+            //    //Log("  * {0}{1}() Response from Server took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
+            //    //length = response.ContentLength;
+            //    //sw.Restart();
+            //    try
+            //    {
+            //        if (responseFormat == SerializationFormat.Binary && typeof(TResponse).HasInterface<ISerializeBinary>())
+            //        {
+            //            result = (TResponse)Serialization.ReadBinary(typeof(TResponse), stream, _binarysettings);
+            //        }
+            //        else
+            //        {
+            //            result = Serialization.Deserialize<TResponse>(stream, true);
+            //        }
+            //    }
+            //    catch (Exception e)
+            //    {
+            //        Logger.Send(LogType.Information, "", $"Error deserializing response: {e.Message}");
+            //    }
+            //    //Log("  * {0}{1}() Deserializing Stream took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
+            //};
 
             if(requestFormat == SerializationFormat.Binary && request is ISerializeBinary binary)
             {
@@ -221,7 +249,7 @@ namespace InABox.Clients
             {
                 var json = Serialization.Serialize(request);
 
-                req.AddOrUpdateParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
+                req.AddOrUpdateParameter("application/json", json, ParameterType.RequestBody);
                 req.RequestFormat = DataFormat.Json;
             }
             try
@@ -293,7 +321,6 @@ namespace InABox.Clients
             }
 
             req = null;
-            cli = null;
             //double elapsed = (DateTime.Now - now).TotalMilliseconds;
             //Log("  * {0}{1}() completed in {2:F0}ms", Action, typeof(TEntity).Name, elapsed);
             return result;
@@ -541,7 +568,7 @@ namespace InABox.Clients
         protected override bool DoPing()
         {
             var cli = new RestClient(new Uri(RestClientCache.URL(_server)));
-            var req = new RestRequest("/info", Method.GET) { Timeout = 20000 };
+            var req = new RestRequest("/info", Method.Get) { Timeout = 20000 };
 
             try
             {
@@ -566,7 +593,7 @@ namespace InABox.Clients
             
             var uri = new Uri(url);
             var cli = new RestClient(uri);
-            var req = new RestRequest("/classes", Method.GET) { Timeout = 20000 };
+            var req = new RestRequest("/classes", Method.Get) { Timeout = 20000 };
 
             try
             {

+ 8 - 1
inabox.client.rest/InABox.Client.Rest/RestClientCache.cs

@@ -1,5 +1,12 @@
 using System.Net;
 using RestSharp;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
 
 namespace InABox.Clients
 {
@@ -33,7 +40,7 @@ namespace InABox.Clients
             var uri = new Uri($"http://{host}");
             string schema = https ? "https" : "http";
             var url = $"{schema}://{uri.Host}:{uri.Port}";
-            var req = new RestRequest("/info", Method.GET) { Timeout = 20000 };
+            var req = new RestRequest("/info", Method.Get) { Timeout = 20000 };
             var res = new RestClient(new Uri(url)).Execute(req);
             if ((res.StatusCode != HttpStatusCode.OK) || (res.ErrorException != null))
                 return false;

+ 7 - 0
inabox.client.rest/InABox.Client.Rest/SocketClientCache.cs

@@ -1,4 +1,11 @@
 using InABox.Client.WebSocket;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
 
 namespace InABox.Clients
 {