From 181be6c17e7bbca957626fdead7621d6307d3413 Mon Sep 17 00:00:00 2001 From: JKorf Date: Thu, 6 Dec 2018 10:53:01 +0100 Subject: [PATCH] Some resharper fixes --- .../Authentication/AuthenticationProvider.cs | 3 +- .../Authentication/PrivateKey.cs | 2 +- CryptoExchange.Net/BaseClient.cs | 20 +++++------ .../Converters/ArrayConverter.cs | 8 ++--- .../Converters/BaseConverter.cs | 2 +- .../Converters/TimestampConverter.cs | 2 +- .../Converters/TimestampSecondsConverter.cs | 2 +- CryptoExchange.Net/ExtensionMethods.cs | 6 ++-- .../Interfaces/IExchangeClient.cs | 11 ------- CryptoExchange.Net/Logging/Log.cs | 2 +- .../Objects/ByteOrderComparer.cs | 10 +++--- CryptoExchange.Net/Objects/ExchangeOptions.cs | 2 +- CryptoExchange.Net/RestClient.cs | 33 ++++++++----------- CryptoExchange.Net/SocketClient.cs | 6 ++-- CryptoExchange.Net/Sockets/BaseSocket.cs | 16 +++------ CryptoExchange.Net/Sockets/SocketEvent.cs | 2 +- 16 files changed, 51 insertions(+), 76 deletions(-) delete mode 100644 CryptoExchange.Net/Interfaces/IExchangeClient.cs diff --git a/CryptoExchange.Net/Authentication/AuthenticationProvider.cs b/CryptoExchange.Net/Authentication/AuthenticationProvider.cs index 8d1af74..deb4e9b 100644 --- a/CryptoExchange.Net/Authentication/AuthenticationProvider.cs +++ b/CryptoExchange.Net/Authentication/AuthenticationProvider.cs @@ -1,5 +1,4 @@ -using CryptoExchange.Net.Interfaces; -using System.Collections.Generic; +using System.Collections.Generic; namespace CryptoExchange.Net.Authentication { diff --git a/CryptoExchange.Net/Authentication/PrivateKey.cs b/CryptoExchange.Net/Authentication/PrivateKey.cs index c421c36..62c20b1 100644 --- a/CryptoExchange.Net/Authentication/PrivateKey.cs +++ b/CryptoExchange.Net/Authentication/PrivateKey.cs @@ -21,7 +21,7 @@ namespace CryptoExchange.Net.Authentication public bool IsEncrypted { get; } /// - /// Create a private key providing an encrypted key informations + /// Create a private key providing an encrypted key information /// /// The private key used for signing /// The private key's passphrase diff --git a/CryptoExchange.Net/BaseClient.cs b/CryptoExchange.Net/BaseClient.cs index 6ceadef..6fa01d9 100644 --- a/CryptoExchange.Net/BaseClient.cs +++ b/CryptoExchange.Net/BaseClient.cs @@ -14,7 +14,7 @@ namespace CryptoExchange.Net { public abstract class BaseClient: IDisposable { - public string BaseAddress; + public string BaseAddress { get; private set; } protected Log log; protected ApiProxy apiProxy; protected AuthenticationProvider authProvider; @@ -22,7 +22,7 @@ namespace CryptoExchange.Net protected static int lastId; protected static object idLock = new object(); - private static readonly JsonSerializer defaultSerializer = JsonSerializer.Create(new JsonSerializerSettings() + private static readonly JsonSerializer defaultSerializer = JsonSerializer.Create(new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc, Culture = CultureInfo.InvariantCulture @@ -104,9 +104,7 @@ namespace CryptoExchange.Net protected CallResult Deserialize(string data, bool checkObject = true, JsonSerializer serializer = null) { var tokenResult = ValidateJson(data); - if(!tokenResult.Success) - return new CallResult(default(T), tokenResult.Error); - return Deserialize(tokenResult.Data, checkObject, serializer); + return !tokenResult.Success ? new CallResult(default(T), tokenResult.Error) : Deserialize(tokenResult.Data, checkObject, serializer); } /// @@ -181,7 +179,7 @@ namespace CryptoExchange.Net return; } - bool isDif = false; + var isDif = false; var properties = new List(); var props = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy); foreach (var prop in props) @@ -198,7 +196,7 @@ namespace CryptoExchange.Net var d = properties.FirstOrDefault(p => p == token.Key); if (d == null) { - d = properties.SingleOrDefault(p => p.ToLower() == token.Key.ToLower()); + d = properties.SingleOrDefault(p => string.Equals(p, token.Key, StringComparison.CurrentCultureIgnoreCase)); if (d == null && !(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))) { log.Write(LogVerbosity.Warning, $"Local object doesn't have property `{token.Key}` expected in type `{type.Name}`"); @@ -236,14 +234,14 @@ namespace CryptoExchange.Net log.Write(LogVerbosity.Debug, "Returned data: " + obj); } - private PropertyInfo GetProperty(string name, PropertyInfo[] props) + private static PropertyInfo GetProperty(string name, IEnumerable props) { foreach (var prop in props) { var attr = prop.GetCustomAttributes(typeof(JsonPropertyAttribute), false).FirstOrDefault(); if (attr == null) { - if (prop.Name.ToLower() == name.ToLower()) + if (String.Equals(prop.Name, name, StringComparison.CurrentCultureIgnoreCase)) return prop; } else @@ -255,7 +253,7 @@ namespace CryptoExchange.Net return null; } - private bool IsSimple(Type type) + private static bool IsSimple(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { @@ -291,7 +289,7 @@ namespace CryptoExchange.Net { foreach (var value in values) { - int index = path.IndexOf("{}", StringComparison.Ordinal); + var index = path.IndexOf("{}", StringComparison.Ordinal); if (index >= 0) { path = path.Remove(index, 2); diff --git a/CryptoExchange.Net/Converters/ArrayConverter.cs b/CryptoExchange.Net/Converters/ArrayConverter.cs index ed494b8..e4b777c 100644 --- a/CryptoExchange.Net/Converters/ArrayConverter.cs +++ b/CryptoExchange.Net/Converters/ArrayConverter.cs @@ -22,7 +22,7 @@ namespace CryptoExchange.Net.Converters return ParseObject(arr, result, objectType); } - private object ParseObject(JArray arr, object result, Type objectType) + private static object ParseObject(JArray arr, object result, Type objectType) { foreach (var property in objectType.GetProperties()) { @@ -66,7 +66,7 @@ namespace CryptoExchange.Net.Converters } var converterAttribute = (JsonConverterAttribute)property.GetCustomAttribute(typeof(JsonConverterAttribute)) ?? (JsonConverterAttribute)property.PropertyType.GetCustomAttribute(typeof(JsonConverterAttribute)); - var value = converterAttribute != null ? arr[attribute.Index].ToObject(property.PropertyType, new JsonSerializer() { Converters = { (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType) } }) : arr[attribute.Index]; + var value = converterAttribute != null ? arr[attribute.Index].ToObject(property.PropertyType, new JsonSerializer { Converters = { (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType) } }) : arr[attribute.Index]; if (value != null && property.PropertyType.IsInstanceOfType(value)) property.SetValue(result, value); @@ -98,7 +98,7 @@ namespace CryptoExchange.Net.Converters var props = value.GetType().GetProperties(); var ordered = props.OrderBy(p => p.GetCustomAttribute()?.Index); - int last = -1; + var last = -1; foreach (var prop in ordered) { var arrayProp = prop.GetCustomAttribute(); @@ -126,7 +126,7 @@ namespace CryptoExchange.Net.Converters writer.WriteEndArray(); } - private bool IsSimple(Type type) + private static bool IsSimple(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { diff --git a/CryptoExchange.Net/Converters/BaseConverter.cs b/CryptoExchange.Net/Converters/BaseConverter.cs index 449eb83..0fa912c 100644 --- a/CryptoExchange.Net/Converters/BaseConverter.cs +++ b/CryptoExchange.Net/Converters/BaseConverter.cs @@ -33,7 +33,7 @@ namespace CryptoExchange.Net.Converters if (Mapping.ContainsValue(value)) return Mapping.Single(m => m.Value == value).Key; - var lowerResult = Mapping.SingleOrDefault(m => m.Value.ToLower() == value.ToLower()); + var lowerResult = Mapping.SingleOrDefault(m => string.Equals(m.Value, value, StringComparison.CurrentCultureIgnoreCase)); if (!lowerResult.Equals(default(KeyValuePair))) return lowerResult.Key; diff --git a/CryptoExchange.Net/Converters/TimestampConverter.cs b/CryptoExchange.Net/Converters/TimestampConverter.cs index 3004ef7..aefed15 100644 --- a/CryptoExchange.Net/Converters/TimestampConverter.cs +++ b/CryptoExchange.Net/Converters/TimestampConverter.cs @@ -21,7 +21,7 @@ namespace CryptoExchange.Net.Converters public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteValue((long)Math.Round((((DateTime)value) - new DateTime(1970, 1, 1)).TotalMilliseconds)); + writer.WriteValue((long)Math.Round(((DateTime)value - new DateTime(1970, 1, 1)).TotalMilliseconds)); } } } diff --git a/CryptoExchange.Net/Converters/TimestampSecondsConverter.cs b/CryptoExchange.Net/Converters/TimestampSecondsConverter.cs index be51550..21f660c 100644 --- a/CryptoExchange.Net/Converters/TimestampSecondsConverter.cs +++ b/CryptoExchange.Net/Converters/TimestampSecondsConverter.cs @@ -22,7 +22,7 @@ namespace CryptoExchange.Net.Converters public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteValue((long)Math.Round((((DateTime)value) - new DateTime(1970, 1, 1)).TotalSeconds)); + writer.WriteValue((long)Math.Round(((DateTime)value - new DateTime(1970, 1, 1)).TotalSeconds)); } } } diff --git a/CryptoExchange.Net/ExtensionMethods.cs b/CryptoExchange.Net/ExtensionMethods.cs index 3b407f3..e27bf35 100644 --- a/CryptoExchange.Net/ExtensionMethods.cs +++ b/CryptoExchange.Net/ExtensionMethods.cs @@ -61,9 +61,9 @@ namespace CryptoExchange.Net lock (source) { string result; - int length = source.Length; - IntPtr pointer = IntPtr.Zero; - char[] chars = new char[length]; + var length = source.Length; + var pointer = IntPtr.Zero; + var chars = new char[length]; try { diff --git a/CryptoExchange.Net/Interfaces/IExchangeClient.cs b/CryptoExchange.Net/Interfaces/IExchangeClient.cs deleted file mode 100644 index e6dc273..0000000 --- a/CryptoExchange.Net/Interfaces/IExchangeClient.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CryptoExchange.Net.RateLimiter; - -namespace CryptoExchange.Net.Interfaces -{ - public interface IExchangeClient - { - IRequestFactory RequestFactory { get; set; } - void AddRateLimiter(IRateLimiter limiter); - void RemoveRateLimiters(); - } -} diff --git a/CryptoExchange.Net/Logging/Log.cs b/CryptoExchange.Net/Logging/Log.cs index 3fb7b3b..e090c30 100644 --- a/CryptoExchange.Net/Logging/Log.cs +++ b/CryptoExchange.Net/Logging/Log.cs @@ -27,7 +27,7 @@ namespace CryptoExchange.Net.Logging if ((int)logType < (int)Level) return; - string logMessage = $"{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff} | {logType} | {message}"; + var logMessage = $"{DateTime.Now:yyyy/MM/dd HH:mm:ss:fff} | {logType} | {message}"; foreach (var writer in writers.ToList()) { try diff --git a/CryptoExchange.Net/Objects/ByteOrderComparer.cs b/CryptoExchange.Net/Objects/ByteOrderComparer.cs index 4506ef9..25f026d 100644 --- a/CryptoExchange.Net/Objects/ByteOrderComparer.cs +++ b/CryptoExchange.Net/Objects/ByteOrderComparer.cs @@ -17,17 +17,17 @@ namespace CryptoExchange.Net.Objects // Both arrays are non-null. Find the shorter // of the two lengths. - int bytesToCompare = Math.Min(x.Length, y.Length); + var bytesToCompare = Math.Min(x.Length, y.Length); // Compare the bytes. - for (int index = 0; index < bytesToCompare; ++index) + for (var index = 0; index < bytesToCompare; ++index) { // The x and y bytes. - byte xByte = x[index]; - byte yByte = y[index]; + var xByte = x[index]; + var yByte = y[index]; // Compare result. - int compareResult = Comparer.Default.Compare(xByte, yByte); + var compareResult = Comparer.Default.Compare(xByte, yByte); // If not the same, then return the result of the // comparison of the bytes, as they were the same diff --git a/CryptoExchange.Net/Objects/ExchangeOptions.cs b/CryptoExchange.Net/Objects/ExchangeOptions.cs index e5498a5..7d3e526 100644 --- a/CryptoExchange.Net/Objects/ExchangeOptions.cs +++ b/CryptoExchange.Net/Objects/ExchangeOptions.cs @@ -36,7 +36,7 @@ namespace CryptoExchange.Net.Objects /// /// The log writers /// - public List LogWriters { get; set; } = new List() { new DebugTextWriter() }; + public List LogWriters { get; set; } = new List { new DebugTextWriter() }; } public class ClientOptions: ExchangeOptions diff --git a/CryptoExchange.Net/RestClient.cs b/CryptoExchange.Net/RestClient.cs index 79f97b4..f32ca2d 100644 --- a/CryptoExchange.Net/RestClient.cs +++ b/CryptoExchange.Net/RestClient.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; @@ -13,6 +12,7 @@ using CryptoExchange.Net.Authentication; using CryptoExchange.Net.Interfaces; using CryptoExchange.Net.Logging; using CryptoExchange.Net.Objects; +using CryptoExchange.Net.RateLimiter; using CryptoExchange.Net.Requests; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -93,17 +93,15 @@ namespace CryptoExchange.Net } catch(PingException e) { - if(e.InnerException != null) - { - if (e.InnerException is SocketException exception) - return new CallResult(0, new CantConnectError() { Message = "Ping failed: " + exception.SocketErrorCode }); - return new CallResult(0, new CantConnectError() { Message = "Ping failed: " + e.InnerException.Message }); - } - return new CallResult(0, new CantConnectError() { Message = "Ping failed: " + e.Message }); + if (e.InnerException == null) + return new CallResult(0, new CantConnectError() {Message = "Ping failed: " + e.Message}); + + if (e.InnerException is SocketException exception) + return new CallResult(0, new CantConnectError() { Message = "Ping failed: " + exception.SocketErrorCode }); + return new CallResult(0, new CantConnectError() { Message = "Ping failed: " + e.InnerException.Message }); } - if (reply.Status == IPStatus.Success) - return new CallResult(reply.RoundtripTime, null); - return new CallResult(0, new CantConnectError() { Message = "Ping failed: " + reply.Status }); + + return reply.Status == IPStatus.Success ? new CallResult(reply.RoundtripTime, null) : new CallResult(0, new CantConnectError() { Message = "Ping failed: " + reply.Status }); } /// @@ -157,7 +155,7 @@ namespace CryptoExchange.Net paramString = paramString.Trim(','); } - log.Write(LogVerbosity.Debug, $"Sending {method}{(signed ? " signed" : "")} request to {request.Uri} {(paramString ?? "")}"); + log.Write(LogVerbosity.Debug, $"Sending {method}{(signed ? " signed" : "")} request to {request.Uri} {paramString ?? ""}"); var result = await ExecuteRequest(request).ConfigureAwait(false); if(!result.Success) return new CallResult(null, result.Error); @@ -199,7 +197,7 @@ namespace CryptoExchange.Net if(authProvider != null) parameters = authProvider.AddAuthenticationToParameters(uriString, method, parameters, signed); - if((method == Constants.GetMethod || method == Constants.DeleteMethod || (postParametersPosition == PostParameters.InUri)) && parameters?.Any() == true) + if((method == Constants.GetMethod || method == Constants.DeleteMethod || postParametersPosition == PostParameters.InUri) && parameters?.Any() == true) uriString += "?" + parameters.CreateParamString(true); var request = RequestFactory.Create(uriString); @@ -253,10 +251,10 @@ namespace CryptoExchange.Net } else if(requestBodyFormat == RequestBodyFormat.FormData) { - NameValueCollection formData = HttpUtility.ParseQueryString(String.Empty); + var formData = HttpUtility.ParseQueryString(String.Empty); foreach (var kvp in parameters.OrderBy(p => p.Key)) formData.Add(kvp.Key, kvp.Value.ToString()); - string stringData = formData.ToString(); + var stringData = formData.ToString(); WriteParamBody(request, stringData); } } @@ -296,10 +294,7 @@ namespace CryptoExchange.Net response.Close(); var jsonResult = ValidateJson(returnedData); - if (!jsonResult.Success) - return new CallResult(null, jsonResult.Error); - - return new CallResult(null, ParseErrorResponse(jsonResult.Data)); + return !jsonResult.Success ? new CallResult(null, jsonResult.Error) : new CallResult(null, ParseErrorResponse(jsonResult.Data)); } catch (Exception) { diff --git a/CryptoExchange.Net/SocketClient.cs b/CryptoExchange.Net/SocketClient.cs index a40c67c..baee42c 100644 --- a/CryptoExchange.Net/SocketClient.cs +++ b/CryptoExchange.Net/SocketClient.cs @@ -84,7 +84,7 @@ namespace CryptoExchange.Net SocketOnClose(socket); }; - socket.OnError += (e) => + socket.OnError += e => { log.Write(LogVerbosity.Info, $"Socket {socket.Id} error: " + e.ToString()); SocketError(socket, e); @@ -248,7 +248,9 @@ namespace CryptoExchange.Net /// public virtual async Task UnsubscribeAll() { - log.Write(LogVerbosity.Debug, $"Closing all {sockets.Count} subscriptions"); + lock (sockets) + log.Write(LogVerbosity.Debug, $"Closing all {sockets.Count} subscriptions"); + await Task.Run(() => { var tasks = new List(); diff --git a/CryptoExchange.Net/Sockets/BaseSocket.cs b/CryptoExchange.Net/Sockets/BaseSocket.cs index fbb809c..0764948 100644 --- a/CryptoExchange.Net/Sockets/BaseSocket.cs +++ b/CryptoExchange.Net/Sockets/BaseSocket.cs @@ -55,15 +55,7 @@ namespace CryptoExchange.Net.Sockets set => socket.AutoSendPingInterval = (int) Math.Round(value.TotalSeconds); } - public WebSocketState SocketState - { - get - { - if (socket == null) - return WebSocketState.None; - return socket.State; - } - } + public WebSocketState SocketState => socket?.State ?? WebSocketState.None; public BaseSocket(Log log, string url):this(log, url, new Dictionary(), new Dictionary()) { @@ -151,7 +143,7 @@ namespace CryptoExchange.Net.Sockets var waitLock = new object(); log?.Write(LogVerbosity.Debug, $"Socket {Id} closing"); - ManualResetEvent evnt = new ManualResetEvent(false); + var evnt = new ManualResetEvent(false); var handler = new EventHandler((o, a) => { lock(waitLock) @@ -200,7 +192,7 @@ namespace CryptoExchange.Net.Sockets { log?.Write(LogVerbosity.Debug, $"Socket {Id} connecting"); var waitLock = new object(); - ManualResetEvent evnt = new ManualResetEvent(false); + var evnt = new ManualResetEvent(false); var handler = new EventHandler((o, a) => { lock (waitLock) @@ -266,7 +258,7 @@ namespace CryptoExchange.Net.Sockets } } - private int NextStreamId() + private static int NextStreamId() { lock (streamIdLock) { diff --git a/CryptoExchange.Net/Sockets/SocketEvent.cs b/CryptoExchange.Net/Sockets/SocketEvent.cs index 186a3d9..672ac40 100644 --- a/CryptoExchange.Net/Sockets/SocketEvent.cs +++ b/CryptoExchange.Net/Sockets/SocketEvent.cs @@ -9,7 +9,7 @@ namespace CryptoExchange.Net.Sockets public string WaitingId { get; set; } private CallResult result; - private ManualResetEvent setEvnt; + private readonly ManualResetEvent setEvnt; public SocketEvent(string name) {