diff --git a/CryptoExchange.Net/Attributes/MapAttribute.cs b/CryptoExchange.Net/Attributes/MapAttribute.cs index 1cdc145..f824ea4 100644 --- a/CryptoExchange.Net/Attributes/MapAttribute.cs +++ b/CryptoExchange.Net/Attributes/MapAttribute.cs @@ -5,6 +5,7 @@ namespace CryptoExchange.Net.Attributes /// /// Map a enum entry to string values /// + [AttributeUsage(AttributeTargets.Field)] public class MapAttribute : Attribute { /// diff --git a/CryptoExchange.Net/Authentication/AuthenticationProvider.cs b/CryptoExchange.Net/Authentication/AuthenticationProvider.cs index c2ca2e4..6920e98 100644 --- a/CryptoExchange.Net/Authentication/AuthenticationProvider.cs +++ b/CryptoExchange.Net/Authentication/AuthenticationProvider.cs @@ -459,10 +459,10 @@ namespace CryptoExchange.Net.Authentication /// /// /// - protected string GetSerializedBody(IMessageSerializer serializer, IDictionary parameters) + protected static string GetSerializedBody(IMessageSerializer serializer, IDictionary parameters) { - if (parameters.Count == 1 && parameters.ContainsKey(Constants.BodyPlaceHolderKey)) - return serializer.Serialize(parameters[Constants.BodyPlaceHolderKey]); + if (parameters.Count == 1 && parameters.TryGetValue(Constants.BodyPlaceHolderKey, out object? value)) + return serializer.Serialize(value); else return serializer.Serialize(parameters); } diff --git a/CryptoExchange.Net/Clients/BaseApiClient.cs b/CryptoExchange.Net/Clients/BaseApiClient.cs index b827b6f..50b03c4 100644 --- a/CryptoExchange.Net/Clients/BaseApiClient.cs +++ b/CryptoExchange.Net/Clients/BaseApiClient.cs @@ -55,7 +55,7 @@ namespace CryptoExchange.Net.Clients /// ctor /// /// Logger - /// Should data from this client include the orginal data in the call result + /// Should data from this client include the original data in the call result /// Base address for this API client /// Api credentials /// Client options diff --git a/CryptoExchange.Net/Clients/BaseClient.cs b/CryptoExchange.Net/Clients/BaseClient.cs index 0916c31..842c77c 100644 --- a/CryptoExchange.Net/Clients/BaseClient.cs +++ b/CryptoExchange.Net/Clients/BaseClient.cs @@ -49,7 +49,7 @@ namespace CryptoExchange.Net.Clients /// protected internal ILogger _logger; - private object _versionLock = new object(); + private readonly object _versionLock = new object(); private Version _exchangeVersion; /// diff --git a/CryptoExchange.Net/Clients/BaseSocketClient.cs b/CryptoExchange.Net/Clients/BaseSocketClient.cs index 01258b8..e376a41 100644 --- a/CryptoExchange.Net/Clients/BaseSocketClient.cs +++ b/CryptoExchange.Net/Clients/BaseSocketClient.cs @@ -93,6 +93,7 @@ namespace CryptoExchange.Net.Clients { tasks.Add(client.ReconnectAsync()); } + await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false); } @@ -106,6 +107,7 @@ namespace CryptoExchange.Net.Clients { result.AppendLine(client.GetSubscriptionsState()); } + return result.ToString(); } @@ -120,6 +122,7 @@ namespace CryptoExchange.Net.Clients { result.Add(client.GetState()); } + return result; } } diff --git a/CryptoExchange.Net/Clients/CryptoBaseClient.cs b/CryptoExchange.Net/Clients/CryptoBaseClient.cs index e577721..c781a66 100644 --- a/CryptoExchange.Net/Clients/CryptoBaseClient.cs +++ b/CryptoExchange.Net/Clients/CryptoBaseClient.cs @@ -9,7 +9,7 @@ namespace CryptoExchange.Net.Clients /// public class CryptoBaseClient : IDisposable { - private Dictionary _serviceCache = new Dictionary(); + private readonly Dictionary _serviceCache = new Dictionary(); /// /// Service provider diff --git a/CryptoExchange.Net/Clients/RestApiClient.cs b/CryptoExchange.Net/Clients/RestApiClient.cs index 2770226..5125138 100644 --- a/CryptoExchange.Net/Clients/RestApiClient.cs +++ b/CryptoExchange.Net/Clients/RestApiClient.cs @@ -89,7 +89,7 @@ namespace CryptoExchange.Net.Clients /// /// Memory cache /// - private static MemoryCache _cache = new MemoryCache(); + private readonly static MemoryCache _cache = new MemoryCache(); /// /// ctor @@ -826,7 +826,7 @@ namespace CryptoExchange.Net.Clients if (parameterPosition == HttpMethodParameterPosition.InUri) { foreach (var parameter in parameters) - uri = uri.AddQueryParmeter(parameter.Key, parameter.Value.ToString()!); + uri = uri.AddQueryParameter(parameter.Key, parameter.Value.ToString()!); } var headers = new Dictionary(); diff --git a/CryptoExchange.Net/Clients/SocketApiClient.cs b/CryptoExchange.Net/Clients/SocketApiClient.cs index 1adcba6..6d17d6f 100644 --- a/CryptoExchange.Net/Clients/SocketApiClient.cs +++ b/CryptoExchange.Net/Clients/SocketApiClient.cs @@ -82,7 +82,7 @@ namespace CryptoExchange.Net.Clients { get { - if (!socketConnections.Any()) + if (socketConnections.IsEmpty) return 0; return socketConnections.Sum(s => s.Value.IncomingKbps); @@ -97,7 +97,7 @@ namespace CryptoExchange.Net.Clients { get { - if (!socketConnections.Any()) + if (socketConnections.IsEmpty) return 0; return socketConnections.Sum(s => s.Value.UserSubscriptionCount); @@ -510,7 +510,7 @@ namespace CryptoExchange.Net.Clients if (connection != null) { - if (connection.UserSubscriptionCount < ClientOptions.SocketSubscriptionsCombineTarget || socketConnections.Count >= (ApiOptions.MaxSocketConnections ?? ClientOptions.MaxSocketConnections) && socketConnections.All(s => s.Value.UserSubscriptionCount >= ClientOptions.SocketSubscriptionsCombineTarget)) + if (connection.UserSubscriptionCount < ClientOptions.SocketSubscriptionsCombineTarget || (socketConnections.Count >= (ApiOptions.MaxSocketConnections ?? ClientOptions.MaxSocketConnections) && socketConnections.All(s => s.Value.UserSubscriptionCount >= ClientOptions.SocketSubscriptionsCombineTarget))) // Use existing socket if it has less than target connections OR it has the least connections and we can't make new return new CallResult(connection); } @@ -598,7 +598,7 @@ namespace CryptoExchange.Net.Clients KeepAliveInterval = KeepAliveInterval, ReconnectInterval = ClientOptions.ReconnectInterval, RateLimiter = ClientOptions.RateLimiterEnabled ? RateLimiter : null, - RateLimitingBehaviour = ClientOptions.RateLimitingBehaviour, + RateLimitingBehavior = ClientOptions.RateLimitingBehaviour, Proxy = ClientOptions.Proxy, Timeout = ApiOptions.SocketNoDataTimeout ?? ClientOptions.SocketNoDataTimeout }; @@ -718,7 +718,7 @@ namespace CryptoExchange.Net.Clients base.SetOptions(options); if ((!previousProxyIsSet && options.Proxy == null) - || !socketConnections.Any()) + || socketConnections.IsEmpty) { return; } diff --git a/CryptoExchange.Net/Converters/MessageParsing/MessageNode.cs b/CryptoExchange.Net/Converters/MessageParsing/MessageNode.cs index 2a9782e..b20eb1b 100644 --- a/CryptoExchange.Net/Converters/MessageParsing/MessageNode.cs +++ b/CryptoExchange.Net/Converters/MessageParsing/MessageNode.cs @@ -3,7 +3,7 @@ /// /// Node accessor /// - public struct NodeAccessor + public readonly struct NodeAccessor { /// /// Index diff --git a/CryptoExchange.Net/Converters/MessageParsing/MessagePath.cs b/CryptoExchange.Net/Converters/MessageParsing/MessagePath.cs index 601c692..54588ed 100644 --- a/CryptoExchange.Net/Converters/MessageParsing/MessagePath.cs +++ b/CryptoExchange.Net/Converters/MessageParsing/MessagePath.cs @@ -6,9 +6,9 @@ namespace CryptoExchange.Net.Converters.MessageParsing /// /// Message access definition /// - public struct MessagePath : IEnumerable + public readonly struct MessagePath : IEnumerable { - private List _path; + private readonly List _path; internal void Add(NodeAccessor node) { diff --git a/CryptoExchange.Net/Converters/SystemTextJson/SystemTextJsonMessageAccessor.cs b/CryptoExchange.Net/Converters/SystemTextJson/SystemTextJsonMessageAccessor.cs index d7969db..45c8a86 100644 --- a/CryptoExchange.Net/Converters/SystemTextJson/SystemTextJsonMessageAccessor.cs +++ b/CryptoExchange.Net/Converters/SystemTextJson/SystemTextJsonMessageAccessor.cs @@ -20,8 +20,8 @@ namespace CryptoExchange.Net.Converters.SystemTextJson /// protected JsonDocument? _document; - private static JsonSerializerOptions _serializerOptions = SerializerOptions.WithConverters; - private JsonSerializerOptions? _customSerializerOptions; + private static readonly JsonSerializerOptions _serializerOptions = SerializerOptions.WithConverters; + private readonly JsonSerializerOptions? _customSerializerOptions; /// public bool IsJson { get; set; } @@ -148,6 +148,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson return value.Value.Deserialize(_customSerializerOptions ?? _serializerOptions); } catch { } + return default; } @@ -359,7 +360,7 @@ namespace CryptoExchange.Net.Converters.SystemTextJson /// public override string GetOriginalString() => - // Netstandard 2.0 doesn't support GetString from a ReadonlySpan, so use ToArray there instead + // NetStandard 2.0 doesn't support GetString from a ReadonlySpan, so use ToArray there instead #if NETSTANDARD2_0 Encoding.UTF8.GetString(_bytes.ToArray()); #else diff --git a/CryptoExchange.Net/ExchangeHelpers.cs b/CryptoExchange.Net/ExchangeHelpers.cs index 66b04eb..95411ff 100644 --- a/CryptoExchange.Net/ExchangeHelpers.cs +++ b/CryptoExchange.Net/ExchangeHelpers.cs @@ -160,7 +160,7 @@ namespace CryptoExchange.Net } /// - /// Generate a new unique id. The id is staticly stored so it is guarenteed to be unique + /// Generate a new unique id. The id is statically stored so it is guaranteed to be unique /// /// public static int NextId() => Interlocked.Increment(ref _lastId); diff --git a/CryptoExchange.Net/ExtensionMethods.cs b/CryptoExchange.Net/ExtensionMethods.cs index 41b4473..4f72a1d 100644 --- a/CryptoExchange.Net/ExtensionMethods.cs +++ b/CryptoExchange.Net/ExtensionMethods.cs @@ -111,6 +111,7 @@ namespace CryptoExchange.Net formData.Add(kvp.Key, string.Format(CultureInfo.InvariantCulture, "{0}", kvp.Value)); } } + return formData.ToString()!; } @@ -286,6 +287,7 @@ namespace CryptoExchange.Net httpValueCollection.Add(parameter.Key, parameter.Value.ToString()); } } + uriBuilder.Query = httpValueCollection.ToString(); return uriBuilder.Uri; } @@ -333,6 +335,7 @@ namespace CryptoExchange.Net httpValueCollection.Add(parameter.Key, parameter.Value.ToString()); } } + uriBuilder.Query = httpValueCollection.ToString(); return uriBuilder.Uri; } @@ -344,7 +347,7 @@ namespace CryptoExchange.Net /// /// /// - public static Uri AddQueryParmeter(this Uri uri, string name, string value) + public static Uri AddQueryParameter(this Uri uri, string name, string value) { var httpValueCollection = HttpUtility.ParseQueryString(uri.Query); diff --git a/CryptoExchange.Net/Interfaces/ISocketApiClient.cs b/CryptoExchange.Net/Interfaces/ISocketApiClient.cs index 4c95c4b..fdc49bd 100644 --- a/CryptoExchange.Net/Interfaces/ISocketApiClient.cs +++ b/CryptoExchange.Net/Interfaces/ISocketApiClient.cs @@ -19,7 +19,7 @@ namespace CryptoExchange.Net.Interfaces /// int CurrentSubscriptions { get; } /// - /// Incoming data kpbs + /// Incoming data Kbps /// double IncomingKbps { get; } /// diff --git a/CryptoExchange.Net/Interfaces/ISymbolOrderBook.cs b/CryptoExchange.Net/Interfaces/ISymbolOrderBook.cs index 120ad7e..baf9df3 100644 --- a/CryptoExchange.Net/Interfaces/ISymbolOrderBook.cs +++ b/CryptoExchange.Net/Interfaces/ISymbolOrderBook.cs @@ -105,7 +105,7 @@ namespace CryptoExchange.Net.Interfaces Task StopAsync(); /// - /// Get the average price that a market order would fill at at the current order book state. This is no guarentee that an order of that quantity would actually be filled + /// Get the average price that a market order would fill at at the current order book state. This is no guarantee that an order of that quantity would actually be filled /// at that price since between this calculation and the order placement the book might have changed. /// /// The quantity in base asset to fill @@ -115,7 +115,7 @@ namespace CryptoExchange.Net.Interfaces /// /// Get the amount of base asset which can be traded with the quote quantity when placing a market order at at the current order book state. - /// This is no guarentee that an order of that quantity would actually be fill the quantity returned by this since between this calculation and the order placement the book might have changed. + /// This is no guarantee that an order of that quantity would actually be fill the quantity returned by this since between this calculation and the order placement the book might have changed. /// /// The quantity in quote asset looking to trade /// The type diff --git a/CryptoExchange.Net/Interfaces/IWebsocket.cs b/CryptoExchange.Net/Interfaces/IWebsocket.cs index 721688d..31bae16 100644 --- a/CryptoExchange.Net/Interfaces/IWebsocket.cs +++ b/CryptoExchange.Net/Interfaces/IWebsocket.cs @@ -47,7 +47,7 @@ namespace CryptoExchange.Net.Interfaces /// event Func OnReconnected; /// - /// Get reconntion url + /// Get reconnection url /// Func>? GetReconnectionUrl { get; set; } diff --git a/CryptoExchange.Net/LibraryHelpers.cs b/CryptoExchange.Net/LibraryHelpers.cs index c13993d..f96fdc3 100644 --- a/CryptoExchange.Net/LibraryHelpers.cs +++ b/CryptoExchange.Net/LibraryHelpers.cs @@ -10,9 +10,9 @@ namespace CryptoExchange.Net public static class LibraryHelpers { /// - /// Client order id seperator + /// Client order id separator /// - public const string ClientOrderIdSeperator = "JK"; + public const string ClientOrderIdSeparator = "JK"; /// /// Apply broker id to a client order id @@ -20,25 +20,25 @@ namespace CryptoExchange.Net /// /// /// - /// + /// /// - public static string ApplyBrokerId(string? clientOrderId, string brokerId, int maxLength, bool allowValueAdjustement) + public static string ApplyBrokerId(string? clientOrderId, string brokerId, int maxLength, bool allowValueAdjustment) { - var reservedLength = brokerId.Length + ClientOrderIdSeperator.Length; + var reservedLength = brokerId.Length + ClientOrderIdSeparator.Length; if ((clientOrderId?.Length + reservedLength) > maxLength) return clientOrderId!; if (!string.IsNullOrEmpty(clientOrderId)) { - if (allowValueAdjustement) - clientOrderId = brokerId + ClientOrderIdSeperator + clientOrderId; + if (allowValueAdjustment) + clientOrderId = brokerId + ClientOrderIdSeparator + clientOrderId; return clientOrderId!; } else { - clientOrderId = ExchangeHelpers.AppendRandomString(brokerId + ClientOrderIdSeperator, maxLength); + clientOrderId = ExchangeHelpers.AppendRandomString(brokerId + ClientOrderIdSeparator, maxLength); } return clientOrderId; diff --git a/CryptoExchange.Net/Logging/Extensions/CryptoExchangeWebSocketClientLoggingExtension.cs b/CryptoExchange.Net/Logging/Extensions/CryptoExchangeWebSocketClientLoggingExtension.cs index 79b4f23..758cb5b 100644 --- a/CryptoExchange.Net/Logging/Extensions/CryptoExchangeWebSocketClientLoggingExtension.cs +++ b/CryptoExchange.Net/Logging/Extensions/CryptoExchangeWebSocketClientLoggingExtension.cs @@ -33,7 +33,7 @@ namespace CryptoExchange.Net.Logging.Extensions private static readonly Action _receiveLoopStoppedWithException; private static readonly Action _receiveLoopFinished; private static readonly Action _startingTaskForNoDataReceivedCheck; - private static readonly Action _noDataReceiveTimoutReconnect; + private static readonly Action _noDataReceiveTimeoutReconnect; private static readonly Action _socketProcessingStateChanged; private static readonly Action _socketPingTimeout; @@ -169,7 +169,7 @@ namespace CryptoExchange.Net.Logging.Extensions new EventId(1026, "StartingTaskForNoDataReceivedCheck"), "[Sckt {SocketId}] starting task checking for no data received for {Timeout}"); - _noDataReceiveTimoutReconnect = LoggerMessage.Define( + _noDataReceiveTimeoutReconnect = LoggerMessage.Define( LogLevel.Warning, new EventId(1027, "NoDataReceiveTimeoutReconnect"), "[Sckt {SocketId}] no data received for {Timeout}, reconnecting socket"); @@ -356,7 +356,7 @@ namespace CryptoExchange.Net.Logging.Extensions public static void SocketNoDataReceiveTimoutReconnect( this ILogger logger, int socketId, TimeSpan? timeSpan) { - _noDataReceiveTimoutReconnect(logger, socketId, timeSpan, null); + _noDataReceiveTimeoutReconnect(logger, socketId, timeSpan, null); } public static void SocketProcessingStateChanged( diff --git a/CryptoExchange.Net/Logging/Extensions/RestApiClientLoggingExtensions.cs b/CryptoExchange.Net/Logging/Extensions/RestApiClientLoggingExtensions.cs index 59e9625..a71285b 100644 --- a/CryptoExchange.Net/Logging/Extensions/RestApiClientLoggingExtensions.cs +++ b/CryptoExchange.Net/Logging/Extensions/RestApiClientLoggingExtensions.cs @@ -22,7 +22,6 @@ namespace CryptoExchange.Net.Logging.Extensions private static readonly Action _restApiCacheHit; private static readonly Action _restApiCacheNotHit; - static RestApiClientLoggingExtensions() { _restApiErrorReceived = LoggerMessage.Define( @@ -37,7 +36,7 @@ namespace CryptoExchange.Net.Logging.Extensions _restApiFailedToSyncTime = LoggerMessage.Define( LogLevel.Debug, - new EventId(4002, "RestApifailedToSyncTime"), + new EventId(4002, "RestApiFailedToSyncTime"), "[Req {RequestId}] Failed to sync time, aborting request: {ErrorMessage}"); _restApiNoApiCredentials = LoggerMessage.Define( diff --git a/CryptoExchange.Net/Logging/Extensions/SocketConnectionLoggingExtension.cs b/CryptoExchange.Net/Logging/Extensions/SocketConnectionLoggingExtension.cs index 1eb7146..d4c3725 100644 --- a/CryptoExchange.Net/Logging/Extensions/SocketConnectionLoggingExtension.cs +++ b/CryptoExchange.Net/Logging/Extensions/SocketConnectionLoggingExtension.cs @@ -10,7 +10,7 @@ namespace CryptoExchange.Net.Logging.Extensions private static readonly Action _activityPaused; private static readonly Action _socketStatusChanged; private static readonly Action _failedReconnectProcessing; - private static readonly Action _unkownExceptionWhileProcessingReconnection; + private static readonly Action _unknownExceptionWhileProcessingReconnection; private static readonly Action _webSocketErrorCodeAndDetails; private static readonly Action _webSocketError; private static readonly Action _messageSentNotPending; @@ -28,7 +28,7 @@ namespace CryptoExchange.Net.Logging.Extensions private static readonly Action _closingNoMoreSubscriptions; private static readonly Action _addingNewSubscription; private static readonly Action _nothingToResubscribeCloseConnection; - private static readonly Action _failedAuthenticationDisconnectAndRecoonect; + private static readonly Action _failedAuthenticationDisconnectAndReconnect; private static readonly Action _authenticationSucceeded; private static readonly Action _failedRequestRevitalization; private static readonly Action _allSubscriptionResubscribed; @@ -55,15 +55,15 @@ namespace CryptoExchange.Net.Logging.Extensions new EventId(2002, "FailedReconnectProcessing"), "[Sckt {SocketId}] failed reconnect processing: {ErrorMessage}, reconnecting again"); - _unkownExceptionWhileProcessingReconnection = LoggerMessage.Define( + _unknownExceptionWhileProcessingReconnection = LoggerMessage.Define( LogLevel.Warning, - new EventId(2003, "UnkownExceptionWhileProcessingReconnection"), + new EventId(2003, "UnknownExceptionWhileProcessingReconnection"), "[Sckt {SocketId}] Unknown exception while processing reconnection, reconnecting again"); _webSocketErrorCodeAndDetails = LoggerMessage.Define( LogLevel.Warning, new EventId(2004, "WebSocketErrorCode"), - "[Sckt {SocketId}] error: Websocket error code {WebSocketErrorCdoe}, details: {Details}"); + "[Sckt {SocketId}] error: Websocket error code {WebSocketErrorCode}, details: {Details}"); _webSocketError = LoggerMessage.Define( LogLevel.Warning, @@ -145,7 +145,7 @@ namespace CryptoExchange.Net.Logging.Extensions new EventId(2020, "NothingToResubscribe"), "[Sckt {SocketId}] nothing to resubscribe, closing connection"); - _failedAuthenticationDisconnectAndRecoonect = LoggerMessage.Define( + _failedAuthenticationDisconnectAndReconnect = LoggerMessage.Define( LogLevel.Warning, new EventId(2021, "FailedAuthentication"), "[Sckt {SocketId}] authentication failed on reconnected socket. Disconnecting and reconnecting"); @@ -206,9 +206,9 @@ namespace CryptoExchange.Net.Logging.Extensions _failedReconnectProcessing(logger, socketId, error, null); } - public static void UnkownExceptionWhileProcessingReconnection(this ILogger logger, int socketId, Exception e) + public static void UnknownExceptionWhileProcessingReconnection(this ILogger logger, int socketId, Exception e) { - _unkownExceptionWhileProcessingReconnection(logger, socketId, e); + _unknownExceptionWhileProcessingReconnection(logger, socketId, e); } public static void WebSocketErrorCodeAndDetails(this ILogger logger, int socketId, WebSocketError error, string? details, Exception e) @@ -285,7 +285,7 @@ namespace CryptoExchange.Net.Logging.Extensions } public static void FailedAuthenticationDisconnectAndRecoonect(this ILogger logger, int socketId) { - _failedAuthenticationDisconnectAndRecoonect(logger, socketId, null); + _failedAuthenticationDisconnectAndReconnect(logger, socketId, null); } public static void AuthenticationSucceeded(this ILogger logger, int socketId) { diff --git a/CryptoExchange.Net/Logging/Extensions/SymbolOrderBookLoggingExtensions.cs b/CryptoExchange.Net/Logging/Extensions/SymbolOrderBookLoggingExtensions.cs index e49ea44..464859c 100644 --- a/CryptoExchange.Net/Logging/Extensions/SymbolOrderBookLoggingExtensions.cs +++ b/CryptoExchange.Net/Logging/Extensions/SymbolOrderBookLoggingExtensions.cs @@ -62,7 +62,6 @@ namespace CryptoExchange.Net.Logging.Extensions new EventId(5005, "OrderBookStopping"), "{Api} order book {Symbol} stopping"); - _orderBookStopped = LoggerMessage.Define( LogLevel.Trace, new EventId(5006, "OrderBookStopped"), diff --git a/CryptoExchange.Net/Logging/Extensions/TrackerLoggingExtensions.cs b/CryptoExchange.Net/Logging/Extensions/TrackerLoggingExtensions.cs index 514db43..1090a8b 100644 --- a/CryptoExchange.Net/Logging/Extensions/TrackerLoggingExtensions.cs +++ b/CryptoExchange.Net/Logging/Extensions/TrackerLoggingExtensions.cs @@ -97,7 +97,6 @@ namespace CryptoExchange.Net.Logging.Extensions new EventId(6012, "KlineTrackerConnectionRestored"), "Kline tracker for {Symbol} successfully resynchronized"); - _tradeTrackerStatusChanged = LoggerMessage.Define( LogLevel.Debug, new EventId(6013, "KlineTrackerStatusChanged"), diff --git a/CryptoExchange.Net/Objects/CallResult.cs b/CryptoExchange.Net/Objects/CallResult.cs index 0cfa78d..6dbded1 100644 --- a/CryptoExchange.Net/Objects/CallResult.cs +++ b/CryptoExchange.Net/Objects/CallResult.cs @@ -89,7 +89,7 @@ namespace CryptoExchange.Net.Objects /// /// Create a new error result /// - /// The erro rto return + /// The error to return public CallResult(Error error) : this(default, null, error) { } /// diff --git a/CryptoExchange.Net/Objects/Enums.cs b/CryptoExchange.Net/Objects/Enums.cs index 27e8e35..179b3a0 100644 --- a/CryptoExchange.Net/Objects/Enums.cs +++ b/CryptoExchange.Net/Objects/Enums.cs @@ -1,4 +1,6 @@ -namespace CryptoExchange.Net.Objects +using CryptoExchange.Net.Attributes; + +namespace CryptoExchange.Net.Objects { /// /// What to do when a request would exceed the rate limit @@ -92,7 +94,7 @@ /// /// Disposed /// - Diposed + Disposed } /// @@ -215,7 +217,7 @@ /// FixedDelay, /// - /// Backof policy of 2^`reconnectAttempt`, where `reconnectAttempt` has a max value of 5 + /// Backoff policy of 2^`reconnectAttempt`, where `reconnectAttempt` has a max value of 5 /// ExponentialBackoff } diff --git a/CryptoExchange.Net/Objects/Options/RestExchangeOptions.cs b/CryptoExchange.Net/Objects/Options/RestExchangeOptions.cs index 25e4608..6235782 100644 --- a/CryptoExchange.Net/Objects/Options/RestExchangeOptions.cs +++ b/CryptoExchange.Net/Objects/Options/RestExchangeOptions.cs @@ -55,7 +55,7 @@ namespace CryptoExchange.Net.Objects.Options { /// /// Trade environment. Contains info about URL's to use to connect to the API. To swap environment select another environment for - /// the exhange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live` + /// the exchange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live` /// #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public TEnvironment Environment { get; set; } diff --git a/CryptoExchange.Net/Objects/RequestDefinition.cs b/CryptoExchange.Net/Objects/RequestDefinition.cs index e583ddd..3d78592 100644 --- a/CryptoExchange.Net/Objects/RequestDefinition.cs +++ b/CryptoExchange.Net/Objects/RequestDefinition.cs @@ -25,8 +25,7 @@ namespace CryptoExchange.Net.Objects /// public bool Authenticated { get; set; } - - // Formating + // Formatting /// /// The body format for this request diff --git a/CryptoExchange.Net/Objects/Sockets/UpdateSubscription.cs b/CryptoExchange.Net/Objects/Sockets/UpdateSubscription.cs index f75268b..e627c43 100644 --- a/CryptoExchange.Net/Objects/Sockets/UpdateSubscription.cs +++ b/CryptoExchange.Net/Objects/Sockets/UpdateSubscription.cs @@ -41,7 +41,7 @@ namespace CryptoExchange.Net.Objects.Sockets /// /// Event when the connection is restored. Timespan parameter indicates the time the socket has been offline for before reconnecting. - /// Note that when the executing code is suspended and resumed at a later period (for example, a laptop going to sleep) the disconnect time will be incorrect as the diconnect + /// Note that when the executing code is suspended and resumed at a later period (for example, a laptop going to sleep) the disconnect time will be incorrect as the disconnect /// will only be detected after resuming the code, so the initial disconnect time is lost. Use the timespan only for informational purposes. /// public event Action ConnectionRestored diff --git a/CryptoExchange.Net/Objects/Sockets/WebSocketParameters.cs b/CryptoExchange.Net/Objects/Sockets/WebSocketParameters.cs index fa66787..c401c0e 100644 --- a/CryptoExchange.Net/Objects/Sockets/WebSocketParameters.cs +++ b/CryptoExchange.Net/Objects/Sockets/WebSocketParameters.cs @@ -41,7 +41,7 @@ namespace CryptoExchange.Net.Objects.Sockets public ApiProxy? Proxy { get; set; } /// - /// The maximum time of no data received before considering the connection lost and closting/reconnecting the socket + /// The maximum time of no data received before considering the connection lost and closing/reconnecting the socket /// public TimeSpan? Timeout { get; set; } @@ -57,7 +57,7 @@ namespace CryptoExchange.Net.Objects.Sockets /// /// What to do when rate limit is reached /// - public RateLimitingBehaviour RateLimitingBehaviour { get; set; } + public RateLimitingBehaviour RateLimitingBehavior { get; set; } /// /// Encoding for sending/receiving data diff --git a/CryptoExchange.Net/Objects/TradeEnvironment.cs b/CryptoExchange.Net/Objects/TradeEnvironment.cs index 7689b31..3afadaa 100644 --- a/CryptoExchange.Net/Objects/TradeEnvironment.cs +++ b/CryptoExchange.Net/Objects/TradeEnvironment.cs @@ -17,7 +17,7 @@ /// /// Trade environment. Contains info about URL's to use to connect to the API. To swap environment select another environment for - /// the echange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live` + /// the exchange's environment list or create a custom environment using either `[Exchange]Environment.CreateCustom()` or `[Exchange]Environment.[Environment]`, for example `KucoinEnvironment.TestNet` or `BinanceEnvironment.Live` /// public class TradeEnvironment { diff --git a/CryptoExchange.Net/OrderBook/SymbolOrderBook.cs b/CryptoExchange.Net/OrderBook/SymbolOrderBook.cs index bcd72a0..124de93 100644 --- a/CryptoExchange.Net/OrderBook/SymbolOrderBook.cs +++ b/CryptoExchange.Net/OrderBook/SymbolOrderBook.cs @@ -74,8 +74,7 @@ namespace CryptoExchange.Net.OrderBook /// /// Whether levels should be strictly enforced. For example, when an order book has 25 levels and a new update comes in which pushes - /// the current level 25 ask out of the top 25, should the curent the level 26 entry be removed from the book or does the - /// server handle this + /// the current level 25 ask out of the top 25, should the level 26 entry be removed from the book or does the server handle this /// protected bool _strictLevels; @@ -250,6 +249,7 @@ namespace CryptoExchange.Net.OrderBook // Clear any previous messages while (_processQueue.TryDequeue(out _)) { } + _processBuffer.Clear(); _bookSet = false; @@ -407,7 +407,7 @@ namespace CryptoExchange.Net.OrderBook /// /// Set the initial data for the order book. Typically the snapshot which was requested from the Rest API, or the first snapshot - /// received from a socket subcription + /// received from a socket subscription /// /// The last update sequence number until which the snapshot is in sync /// List of asks @@ -618,6 +618,7 @@ namespace CryptoExchange.Net.OrderBook var bid = book.bids.Count() > i ? book.bids.ElementAt(i): null; stringBuilder.AppendLine($"[{ask?.Quantity.ToString(CultureInfo.InvariantCulture),14}] {ask?.Price.ToString(CultureInfo.InvariantCulture),14} | {bid?.Price.ToString(CultureInfo.InvariantCulture),-14} [{bid?.Quantity.ToString(CultureInfo.InvariantCulture),-14}]"); } + return stringBuilder.ToString(); } @@ -636,6 +637,7 @@ namespace CryptoExchange.Net.OrderBook _queueEvent.Set(); // Clear queue while (_processQueue.TryDequeue(out _)) { } + _processBuffer.Clear(); _bookSet = false; DoReset(); @@ -732,7 +734,7 @@ namespace CryptoExchange.Net.OrderBook var (prevBestBid, prevBestAsk) = BestOffers; ProcessRangeUpdates(item.StartUpdateId, item.EndUpdateId, item.Bids, item.Asks); - if (!_asks.Any() || !_bids.Any()) + if (_asks.Count == 0 || _bids.Count == 0) return; if (_asks.First().Key < _bids.First().Key) diff --git a/CryptoExchange.Net/RateLimiting/Guards/RateLimitGuard.cs b/CryptoExchange.Net/RateLimiting/Guards/RateLimitGuard.cs index 810fca7..a5d173d 100644 --- a/CryptoExchange.Net/RateLimiting/Guards/RateLimitGuard.cs +++ b/CryptoExchange.Net/RateLimiting/Guards/RateLimitGuard.cs @@ -32,9 +32,9 @@ namespace CryptoExchange.Net.RateLimiting.Guards private readonly IEnumerable _filters; private readonly Dictionary _trackers; - private RateLimitWindowType _windowType; - private double? _decayRate; - private int? _connectionWeight; + private readonly RateLimitWindowType _windowType; + private readonly double? _decayRate; + private readonly int? _connectionWeight; private readonly Func _keySelector; /// diff --git a/CryptoExchange.Net/RateLimiting/Trackers/DecayWindowTracker.cs b/CryptoExchange.Net/RateLimiting/Trackers/DecayWindowTracker.cs index 20ef53c..86b783b 100644 --- a/CryptoExchange.Net/RateLimiting/Trackers/DecayWindowTracker.cs +++ b/CryptoExchange.Net/RateLimiting/Trackers/DecayWindowTracker.cs @@ -38,7 +38,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers if (Current == 0) { throw new Exception("Request limit reached without any prior request. " + - $"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}"); + $"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}"); } // Determine the time to wait before this weight can be applied without going over the rate limit diff --git a/CryptoExchange.Net/RateLimiting/Trackers/FixedAfterStartWindowTracker.cs b/CryptoExchange.Net/RateLimiting/Trackers/FixedAfterStartWindowTracker.cs index cbca4e8..be0d713 100644 --- a/CryptoExchange.Net/RateLimiting/Trackers/FixedAfterStartWindowTracker.cs +++ b/CryptoExchange.Net/RateLimiting/Trackers/FixedAfterStartWindowTracker.cs @@ -45,7 +45,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers if (Current == 0) { throw new Exception("Request limit reached without any prior request. " + - $"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}"); + $"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}"); } // Determine the time to wait before this weight can be applied without going over the rate limit diff --git a/CryptoExchange.Net/RateLimiting/Trackers/FixedWindowTracker.cs b/CryptoExchange.Net/RateLimiting/Trackers/FixedWindowTracker.cs index 61ddcba..1481894 100644 --- a/CryptoExchange.Net/RateLimiting/Trackers/FixedWindowTracker.cs +++ b/CryptoExchange.Net/RateLimiting/Trackers/FixedWindowTracker.cs @@ -41,7 +41,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers if (Current == 0) { throw new Exception("Request limit reached without any prior request. " + - $"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}"); + $"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}"); } // Determine the time to wait before this weight can be applied without going over the rate limit diff --git a/CryptoExchange.Net/RateLimiting/Trackers/SlidingWindowTracker.cs b/CryptoExchange.Net/RateLimiting/Trackers/SlidingWindowTracker.cs index bb8446f..19f9abb 100644 --- a/CryptoExchange.Net/RateLimiting/Trackers/SlidingWindowTracker.cs +++ b/CryptoExchange.Net/RateLimiting/Trackers/SlidingWindowTracker.cs @@ -40,7 +40,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers if (Current == 0) { throw new Exception("Request limit reached without any prior request. " + - $"This request can never execute with the current rate limiter. Request weight: {weight}, Ratelimit: {Limit}"); + $"This request can never execute with the current rate limiter. Request weight: {weight}, RateLimit: {Limit}"); } // Determine the time to wait before this weight can be applied without going over the rate limit @@ -102,7 +102,7 @@ namespace CryptoExchange.Net.RateLimiting.Trackers } throw new Exception("Request not possible to execute with current rate limit guard. " + - $" Request weight: {requestWeight}, Ratelimit: {Limit}"); + $" Request weight: {requestWeight}, RateLimit: {Limit}"); } } } diff --git a/CryptoExchange.Net/SharedApis/Models/ExchangeParameters.cs b/CryptoExchange.Net/SharedApis/Models/ExchangeParameters.cs index f853f25..85f838b 100644 --- a/CryptoExchange.Net/SharedApis/Models/ExchangeParameters.cs +++ b/CryptoExchange.Net/SharedApis/Models/ExchangeParameters.cs @@ -10,7 +10,7 @@ namespace CryptoExchange.Net.SharedApis public class ExchangeParameters { private readonly List _parameters; - private static List _staticParameters = new List(); + private readonly static List _staticParameters = new List(); /// /// ctor diff --git a/CryptoExchange.Net/SharedApis/Models/ExchangeWebResult.cs b/CryptoExchange.Net/SharedApis/Models/ExchangeWebResult.cs index 6093e47..61908e4 100644 --- a/CryptoExchange.Net/SharedApis/Models/ExchangeWebResult.cs +++ b/CryptoExchange.Net/SharedApis/Models/ExchangeWebResult.cs @@ -132,7 +132,6 @@ namespace CryptoExchange.Net.SharedApis NextPageToken = nextPageToken; } - /// /// Copy the ExchangeWebResult to a new data type /// diff --git a/CryptoExchange.Net/Sockets/CryptoExchangeWebSocketClient.cs b/CryptoExchange.Net/Sockets/CryptoExchangeWebSocketClient.cs index b92639b..c0b3576 100644 --- a/CryptoExchange.Net/Sockets/CryptoExchangeWebSocketClient.cs +++ b/CryptoExchange.Net/Sockets/CryptoExchangeWebSocketClient.cs @@ -46,14 +46,14 @@ namespace CryptoExchange.Net.Sockets private bool _disposed; private ProcessState _processState; private DateTime _lastReconnectTime; - private string _baseAddress; + private readonly string _baseAddress; private int _reconnectAttempt; private const int _receiveBufferSize = 1048576; private const int _sendBufferSize = 4096; /// - /// Received messages, the size and the timstamp + /// Received messages, the size and the timestamp /// protected readonly List _receivedMessages; @@ -96,7 +96,7 @@ namespace CryptoExchange.Net.Sockets { UpdateReceivedMessages(); - if (!_receivedMessages.Any()) + if (_receivedMessages.Count == 0) return 0; return Math.Round(_receivedMessages.Sum(v => v.Bytes) / 1000d / 3d); @@ -219,7 +219,7 @@ namespace CryptoExchange.Net.Sockets if (Parameters.RateLimiter != null) { var definition = new RequestDefinition(Uri.AbsolutePath, HttpMethod.Get) { ConnectionId = Id }; - var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, Id, RateLimitItemType.Connection, definition, _baseAddress, null, 1, Parameters.RateLimitingBehaviour, _ctsSource.Token).ConfigureAwait(false); + var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, Id, RateLimitItemType.Connection, definition, _baseAddress, null, 1, Parameters.RateLimitingBehavior, _ctsSource.Token).ConfigureAwait(false); if (!limitResult) return new CallResult(new ClientRateLimitError("Connection limit reached")); } @@ -296,7 +296,7 @@ namespace CryptoExchange.Net.Sockets await (OnReconnecting?.Invoke() ?? Task.CompletedTask).ConfigureAwait(false); } - // Delay here to prevent very repid looping when a connection to the server is accepted and immediately disconnected + // Delay here to prevent very rapid looping when a connection to the server is accepted and immediately disconnected var initialDelay = GetReconnectDelay(); await Task.Delay(initialDelay).ConfigureAwait(false); @@ -491,7 +491,7 @@ namespace CryptoExchange.Net.Sockets { try { - if (!_sendBuffer.Any()) + if (_sendBuffer.IsEmpty) await _sendEvent.WaitAsync(ct: _ctsSource.Token).ConfigureAwait(false); } catch (OperationCanceledException) @@ -508,7 +508,7 @@ namespace CryptoExchange.Net.Sockets { try { - var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, data.Id, RateLimitItemType.Request, requestDefinition, _baseAddress, null, data.Weight, Parameters.RateLimitingBehaviour, _ctsSource.Token).ConfigureAwait(false); + var limitResult = await Parameters.RateLimiter.ProcessAsync(_logger, data.Id, RateLimitItemType.Request, requestDefinition, _baseAddress, null, data.Weight, Parameters.RateLimitingBehavior, _ctsSource.Token).ConfigureAwait(false); if (!limitResult) { await (OnRequestRateLimited?.Invoke(data.Id) ?? Task.CompletedTask).ConfigureAwait(false); @@ -589,9 +589,9 @@ namespace CryptoExchange.Net.Sockets } catch (OperationCanceledException ex) { - if (ex.InnerException?.InnerException?.Message.Equals("The WebSocket didn't recieve a Pong frame in response to a Ping frame within the configured KeepAliveTimeout.") == true) + if (ex.InnerException?.InnerException?.Message.Equals("The WebSocket didn't receive a Pong frame in response to a Ping frame within the configured KeepAliveTimeout.") == true) { - // Spefic case that the websocket connection got closed because of a ping frame timeout + // Specific case that the websocket connection got closed because of a ping frame timeout // Unfortunately doesn't seem to be a nicer way to catch _logger.SocketPingTimeout(Id); } @@ -679,11 +679,11 @@ namespace CryptoExchange.Net.Sockets if (multiPartMessage) { - // When the connection gets interupted we might not have received a full message + // When the connection gets interrupted we might not have received a full message if (receiveResult?.EndOfMessage == true) { _logger.SocketReassembledMessage(Id, multipartStream!.Length); - // Get the underlying buffer of the memorystream holding the written data and delimit it (GetBuffer return the full array, not only the written part) + // Get the underlying buffer of the memory stream holding the written data and delimit it (GetBuffer return the full array, not only the written part) await ProcessData(receiveResult.MessageType, new ReadOnlyMemory(multipartStream.GetBuffer(), 0, (int)multipartStream.Length)).ConfigureAwait(false); } else @@ -710,7 +710,7 @@ namespace CryptoExchange.Net.Sockets } /// - /// Proccess a stream message + /// Process a stream message /// /// /// @@ -742,6 +742,7 @@ namespace CryptoExchange.Net.Sockets _ = ReconnectAsync().ConfigureAwait(false); return; } + try { await Task.Delay(500, _ctsSource.Token).ConfigureAwait(false); diff --git a/CryptoExchange.Net/Sockets/SocketConnection.cs b/CryptoExchange.Net/Sockets/SocketConnection.cs index e844272..8e32437 100644 --- a/CryptoExchange.Net/Sockets/SocketConnection.cs +++ b/CryptoExchange.Net/Sockets/SocketConnection.cs @@ -143,7 +143,7 @@ namespace CryptoExchange.Net.Sockets public DateTime? DisconnectTime { get; set; } /// - /// Tag for identificaion + /// Tag for identification /// public string Tag { get; set; } @@ -214,7 +214,7 @@ namespace CryptoExchange.Net.Sockets private readonly IByteMessageAccessor _accessor; /// - /// The task that is sending periodic data on the websocket. Can be used for sending Ping messages every x seconds or similair. Not necesarry. + /// The task that is sending periodic data on the websocket. Can be used for sending Ping messages every x seconds or similar. Not necessary. /// protected Task? periodicTask; @@ -286,7 +286,7 @@ namespace CryptoExchange.Net.Sockets foreach (var query in _listeners.OfType().ToList()) { - query.Fail(new WebError("Connection interupted")); + query.Fail(new WebError("Connection interrupted")); _listeners.Remove(query); } } @@ -311,7 +311,7 @@ namespace CryptoExchange.Net.Sockets foreach (var query in _listeners.OfType().ToList()) { - query.Fail(new WebError("Connection interupted")); + query.Fail(new WebError("Connection interrupted")); _listeners.Remove(query); } } @@ -340,7 +340,7 @@ namespace CryptoExchange.Net.Sockets { foreach (var query in _listeners.OfType().ToList()) { - query.Fail(new WebError("Connection interupted")); + query.Fail(new WebError("Connection interrupted")); _listeners.Remove(query); } } @@ -369,7 +369,7 @@ namespace CryptoExchange.Net.Sockets } catch(Exception ex) { - _logger.UnkownExceptionWhileProcessingReconnection(SocketId, ex); + _logger.UnknownExceptionWhileProcessingReconnection(SocketId, ex); _ = _socket.ReconnectAsync().ConfigureAwait(false); } }); @@ -392,7 +392,7 @@ namespace CryptoExchange.Net.Sockets } /// - /// Handler for whenever a request is rate limited and rate limit behaviour is set to fail + /// Handler for whenever a request is rate limited and rate limit behavior is set to fail /// /// /// diff --git a/CryptoExchange.Net/Testing/Comparers/JsonNetComparer.cs b/CryptoExchange.Net/Testing/Comparers/JsonNetComparer.cs index 4d7b3ad..3893b33 100644 --- a/CryptoExchange.Net/Testing/Comparers/JsonNetComparer.cs +++ b/CryptoExchange.Net/Testing/Comparers/JsonNetComparer.cs @@ -172,7 +172,7 @@ namespace CryptoExchange.Net.Testing.Comparers throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {propValue}"); } - if (propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString())) || propValue.ToString() == "0") + if ((propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString()))) || propValue.ToString() == "0") return; if (propertyValue!.GetType().GetInterfaces().Contains(typeof(IDictionary))) diff --git a/CryptoExchange.Net/Testing/Comparers/SystemTextJsonComparer.cs b/CryptoExchange.Net/Testing/Comparers/SystemTextJsonComparer.cs index 50eb76b..3adbdb3 100644 --- a/CryptoExchange.Net/Testing/Comparers/SystemTextJsonComparer.cs +++ b/CryptoExchange.Net/Testing/Comparers/SystemTextJsonComparer.cs @@ -69,11 +69,11 @@ namespace CryptoExchange.Net.Testing.Comparers } else if (jsonObject!.Type == JTokenType.Array) { - var jObjs = (JArray)jsonObject; + var jArray = (JArray)jsonObject; if (resultData is IEnumerable list) { var enumerator = list.GetEnumerator(); - foreach (var jObj in jObjs) + foreach (var jObj in jArray) { if (!enumerator.MoveNext()) { @@ -123,7 +123,7 @@ namespace CryptoExchange.Net.Testing.Comparers { var resultProps = resultData.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast().SingleOrDefault())); int i = 0; - foreach (var item in jObjs.Children()) + foreach (var item in jArray.Children()) { var arrayProp = resultProps.Where(p => p.Item2 != null).SingleOrDefault(p => p.Item2!.Index == i).p; if (arrayProp != null) @@ -196,7 +196,7 @@ namespace CryptoExchange.Net.Testing.Comparers throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {propValue}"); } - if (propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString())) || propValue.ToString() == "0") + if ((propertyValue == default && (propValue.Type == JTokenType.Null || string.IsNullOrEmpty(propValue.ToString()))) || propValue.ToString() == "0") return; if (propertyValue!.GetType().GetInterfaces().Contains(typeof(IDictionary))) @@ -227,10 +227,10 @@ namespace CryptoExchange.Net.Testing.Comparers if (propValue.Type != JTokenType.Array) return; - var jObjs = (JArray)propValue; + var jArray = (JArray)propValue; var list = (IEnumerable)propertyValue; var enumerator = list.GetEnumerator(); - foreach (JToken jtoken in jObjs) + foreach (JToken jToken in jArray) { var moved = enumerator.MoveNext(); if (!moved) @@ -241,9 +241,9 @@ namespace CryptoExchange.Net.Testing.Comparers // Custom converter for the type, skip continue; - if (jtoken.Type == JTokenType.Object) + if (jToken.Type == JTokenType.Object) { - foreach (var subProp in ((JObject)jtoken).Properties()) + foreach (var subProp in ((JObject)jToken).Properties()) { if (ignoreProperties?.Contains(subProp.Name) == true) continue; @@ -251,7 +251,7 @@ namespace CryptoExchange.Net.Testing.Comparers CheckObject(method, subProp, enumerator.Current, ignoreProperties); } } - else if (jtoken.Type == JTokenType.Array) + else if (jToken.Type == JTokenType.Array) { var resultObj = enumerator.Current; var resultProps = resultObj.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast().SingleOrDefault())); @@ -262,7 +262,7 @@ namespace CryptoExchange.Net.Testing.Comparers continue; int i = 0; - foreach (var item in jtoken.Children()) + foreach (var item in jToken.Children()) { var arrayProp = resultProps.Where(p => p.Item2 != null).FirstOrDefault(p => p.Item2!.Index == i).p; if (arrayProp != null) @@ -274,10 +274,10 @@ namespace CryptoExchange.Net.Testing.Comparers else { var value = enumerator.Current; - if (value == default && ((JValue)jtoken).Type != JTokenType.Null) - throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {jtoken}"); + if (value == default && ((JValue)jToken).Type != JTokenType.Null) + throw new Exception($"{method}: Property `{propertyName}` has no value while input json `{propName}` has value {jToken}"); - CheckValues(method, propertyName!, propertyType, (JValue)jtoken, value!); + CheckValues(method, propertyName!, propertyType, (JValue)jToken, value!); } } } @@ -298,11 +298,11 @@ namespace CryptoExchange.Net.Testing.Comparers } else if (propValue.Type == JTokenType.Array) { - var jObjs = (JArray)propValue; + var jArray = (JArray)propValue; if (propertyValue is IEnumerable list) { var enumerator = list.GetEnumerator(); - foreach (var jObj in jObjs) + foreach (var jObj in jArray) { if (!enumerator.MoveNext()) { @@ -348,7 +348,7 @@ namespace CryptoExchange.Net.Testing.Comparers { var resultProps = propertyValue.GetType().GetProperties().Select(p => (p, p.GetCustomAttributes(typeof(ArrayPropertyAttribute), true).Cast().SingleOrDefault())); int i = 0; - foreach (var item in jObjs.Children()) + foreach (var item in jArray.Children()) { var arrayProp = resultProps.Where(p => p.Item2 != null).FirstOrDefault(p => p.Item2!.Index == i).p; if (arrayProp != null) diff --git a/CryptoExchange.Net/Testing/RestIntergrationTest.cs b/CryptoExchange.Net/Testing/RestIntegrationTest.cs similarity index 98% rename from CryptoExchange.Net/Testing/RestIntergrationTest.cs rename to CryptoExchange.Net/Testing/RestIntegrationTest.cs index bb2fe69..f045cee 100644 --- a/CryptoExchange.Net/Testing/RestIntergrationTest.cs +++ b/CryptoExchange.Net/Testing/RestIntegrationTest.cs @@ -11,7 +11,7 @@ namespace CryptoExchange.Net.Testing /// Base class for executing REST API integration tests /// /// Client type - public abstract class RestIntergrationTest + public abstract class RestIntegrationTest { /// /// Get a client instance diff --git a/CryptoExchange.Net/Testing/SocketSubscriptionValidator.cs b/CryptoExchange.Net/Testing/SocketSubscriptionValidator.cs index 5ce2771..87ca865 100644 --- a/CryptoExchange.Net/Testing/SocketSubscriptionValidator.cs +++ b/CryptoExchange.Net/Testing/SocketSubscriptionValidator.cs @@ -113,7 +113,6 @@ namespace CryptoExchange.Net.Testing if (lastMessage == null) throw new Exception($"{name} expected to {line} to be send to server but did not receive anything"); - var lastMessageJson = JToken.Parse(lastMessage); var expectedJson = JToken.Parse(line.Substring(2)); foreach(var item in expectedJson) @@ -133,7 +132,9 @@ namespace CryptoExchange.Net.Testing overrideValue = lastMessageJson[prop.Name]?.Value().ToString(); } else if (lastMessageJson[prop.Name]?.Value() != val.ToString() && ignoreProperties?.Contains(prop.Name) != true) + { throw new Exception($"{name} Expected {prop.Name} to be {val}, but was {lastMessageJson[prop.Name]?.Value()}"); + } } // TODO check objects and arrays diff --git a/CryptoExchange.Net/Trackers/Klines/IKlineTracker.cs b/CryptoExchange.Net/Trackers/Klines/IKlineTracker.cs index 63cc323..f304249 100644 --- a/CryptoExchange.Net/Trackers/Klines/IKlineTracker.cs +++ b/CryptoExchange.Net/Trackers/Klines/IKlineTracker.cs @@ -94,7 +94,7 @@ namespace CryptoExchange.Net.Trackers.Klines IEnumerable GetData(DateTime? fromTimestamp = null, DateTime? toTimestamp = null); /// - /// Get statitistics on the klines + /// Get statistics on the klines /// /// Start timestamp to get the data from, defaults to tracked data start time /// End timestamp to get the data until, defaults to current time diff --git a/CryptoExchange.Net/Trackers/Trades/ITradeTracker.cs b/CryptoExchange.Net/Trackers/Trades/ITradeTracker.cs index 589d5bd..713dee4 100644 --- a/CryptoExchange.Net/Trackers/Trades/ITradeTracker.cs +++ b/CryptoExchange.Net/Trackers/Trades/ITradeTracker.cs @@ -90,7 +90,7 @@ namespace CryptoExchange.Net.Trackers.Trades IEnumerable GetData(DateTime? fromTimestamp = null, DateTime? toTimestamp = null); /// - /// Get statitistics on the trades + /// Get statistics on the trades /// /// Start timestamp to get the data from, defaults to tracked data start time /// End timestamp to get the data until, defaults to current time diff --git a/CryptoExchange.Net/Trackers/Trades/TradeTracker.cs b/CryptoExchange.Net/Trackers/Trades/TradeTracker.cs index 05bc209..e92be50 100644 --- a/CryptoExchange.Net/Trackers/Trades/TradeTracker.cs +++ b/CryptoExchange.Net/Trackers/Trades/TradeTracker.cs @@ -163,7 +163,7 @@ namespace CryptoExchange.Net.Trackers.Trades Period = period; } - private TradesStats GetStats(IEnumerable trades) + private static TradesStats GetStats(IEnumerable trades) { if (!trades.Any()) return new TradesStats(); @@ -350,7 +350,7 @@ namespace CryptoExchange.Net.Trackers.Trades _data.Add(item); } - if (_data.Any()) + if (_data.Count != 0) _firstTimestamp = _data.Min(v => v.Timestamp); ApplyWindow(false); @@ -431,7 +431,6 @@ namespace CryptoExchange.Net.Trackers.Trades SetSyncStatus(); } - private void HandleConnectionLost() { _logger.TradeTrackerConnectionLost(SymbolName); diff --git a/CryptoExchange.Net/Trackers/Trades/TradesStats.cs b/CryptoExchange.Net/Trackers/Trades/TradesStats.cs index 2a0b241..74107ca 100644 --- a/CryptoExchange.Net/Trackers/Trades/TradesStats.cs +++ b/CryptoExchange.Net/Trackers/Trades/TradesStats.cs @@ -47,7 +47,7 @@ namespace CryptoExchange.Net.Trackers.Trades public bool Complete { get; set; } /// - /// Compare 2 stat snapshots to eachother + /// Compare 2 stat snapshots to each other /// public TradesCompare CompareTo(TradesStats otherStats) {