1
0
mirror of https://github.com/JKorf/CryptoExchange.Net synced 2025-06-10 01:16:24 +00:00

Some resharper fixes

This commit is contained in:
JKorf 2018-12-06 10:53:01 +01:00
parent e5f712633e
commit 181be6c17e
16 changed files with 51 additions and 76 deletions

View File

@ -1,5 +1,4 @@
using CryptoExchange.Net.Interfaces; using System.Collections.Generic;
using System.Collections.Generic;
namespace CryptoExchange.Net.Authentication namespace CryptoExchange.Net.Authentication
{ {

View File

@ -21,7 +21,7 @@ namespace CryptoExchange.Net.Authentication
public bool IsEncrypted { get; } public bool IsEncrypted { get; }
/// <summary> /// <summary>
/// Create a private key providing an encrypted key informations /// Create a private key providing an encrypted key information
/// </summary> /// </summary>
/// <param name="key">The private key used for signing</param> /// <param name="key">The private key used for signing</param>
/// <param name="passphrase">The private key's passphrase</param> /// <param name="passphrase">The private key's passphrase</param>

View File

@ -14,7 +14,7 @@ namespace CryptoExchange.Net
{ {
public abstract class BaseClient: IDisposable public abstract class BaseClient: IDisposable
{ {
public string BaseAddress; public string BaseAddress { get; private set; }
protected Log log; protected Log log;
protected ApiProxy apiProxy; protected ApiProxy apiProxy;
protected AuthenticationProvider authProvider; protected AuthenticationProvider authProvider;
@ -22,7 +22,7 @@ namespace CryptoExchange.Net
protected static int lastId; protected static int lastId;
protected static object idLock = new object(); 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, DateTimeZoneHandling = DateTimeZoneHandling.Utc,
Culture = CultureInfo.InvariantCulture Culture = CultureInfo.InvariantCulture
@ -104,9 +104,7 @@ namespace CryptoExchange.Net
protected CallResult<T> Deserialize<T>(string data, bool checkObject = true, JsonSerializer serializer = null) protected CallResult<T> Deserialize<T>(string data, bool checkObject = true, JsonSerializer serializer = null)
{ {
var tokenResult = ValidateJson(data); var tokenResult = ValidateJson(data);
if(!tokenResult.Success) return !tokenResult.Success ? new CallResult<T>(default(T), tokenResult.Error) : Deserialize<T>(tokenResult.Data, checkObject, serializer);
return new CallResult<T>(default(T), tokenResult.Error);
return Deserialize<T>(tokenResult.Data, checkObject, serializer);
} }
/// <summary> /// <summary>
@ -181,7 +179,7 @@ namespace CryptoExchange.Net
return; return;
} }
bool isDif = false; var isDif = false;
var properties = new List<string>(); var properties = new List<string>();
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy); var props = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
foreach (var prop in props) foreach (var prop in props)
@ -198,7 +196,7 @@ namespace CryptoExchange.Net
var d = properties.FirstOrDefault(p => p == token.Key); var d = properties.FirstOrDefault(p => p == token.Key);
if (d == null) 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<,>))) 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}`"); 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); log.Write(LogVerbosity.Debug, "Returned data: " + obj);
} }
private PropertyInfo GetProperty(string name, PropertyInfo[] props) private static PropertyInfo GetProperty(string name, IEnumerable<PropertyInfo> props)
{ {
foreach (var prop in props) foreach (var prop in props)
{ {
var attr = prop.GetCustomAttributes(typeof(JsonPropertyAttribute), false).FirstOrDefault(); var attr = prop.GetCustomAttributes(typeof(JsonPropertyAttribute), false).FirstOrDefault();
if (attr == null) if (attr == null)
{ {
if (prop.Name.ToLower() == name.ToLower()) if (String.Equals(prop.Name, name, StringComparison.CurrentCultureIgnoreCase))
return prop; return prop;
} }
else else
@ -255,7 +253,7 @@ namespace CryptoExchange.Net
return null; return null;
} }
private bool IsSimple(Type type) private static bool IsSimple(Type type)
{ {
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{ {
@ -291,7 +289,7 @@ namespace CryptoExchange.Net
{ {
foreach (var value in values) foreach (var value in values)
{ {
int index = path.IndexOf("{}", StringComparison.Ordinal); var index = path.IndexOf("{}", StringComparison.Ordinal);
if (index >= 0) if (index >= 0)
{ {
path = path.Remove(index, 2); path = path.Remove(index, 2);

View File

@ -22,7 +22,7 @@ namespace CryptoExchange.Net.Converters
return ParseObject(arr, result, objectType); 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()) 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 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)) if (value != null && property.PropertyType.IsInstanceOfType(value))
property.SetValue(result, value); property.SetValue(result, value);
@ -98,7 +98,7 @@ namespace CryptoExchange.Net.Converters
var props = value.GetType().GetProperties(); var props = value.GetType().GetProperties();
var ordered = props.OrderBy(p => p.GetCustomAttribute<ArrayPropertyAttribute>()?.Index); var ordered = props.OrderBy(p => p.GetCustomAttribute<ArrayPropertyAttribute>()?.Index);
int last = -1; var last = -1;
foreach (var prop in ordered) foreach (var prop in ordered)
{ {
var arrayProp = prop.GetCustomAttribute<ArrayPropertyAttribute>(); var arrayProp = prop.GetCustomAttribute<ArrayPropertyAttribute>();
@ -126,7 +126,7 @@ namespace CryptoExchange.Net.Converters
writer.WriteEndArray(); writer.WriteEndArray();
} }
private bool IsSimple(Type type) private static bool IsSimple(Type type)
{ {
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{ {

View File

@ -33,7 +33,7 @@ namespace CryptoExchange.Net.Converters
if (Mapping.ContainsValue(value)) if (Mapping.ContainsValue(value))
return Mapping.Single(m => m.Value == value).Key; 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<T, string>))) if (!lowerResult.Equals(default(KeyValuePair<T, string>)))
return lowerResult.Key; return lowerResult.Key;

View File

@ -21,7 +21,7 @@ namespace CryptoExchange.Net.Converters
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 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));
} }
} }
} }

View File

@ -22,7 +22,7 @@ namespace CryptoExchange.Net.Converters
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 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));
} }
} }
} }

View File

@ -61,9 +61,9 @@ namespace CryptoExchange.Net
lock (source) lock (source)
{ {
string result; string result;
int length = source.Length; var length = source.Length;
IntPtr pointer = IntPtr.Zero; var pointer = IntPtr.Zero;
char[] chars = new char[length]; var chars = new char[length];
try try
{ {

View File

@ -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();
}
}

View File

@ -27,7 +27,7 @@ namespace CryptoExchange.Net.Logging
if ((int)logType < (int)Level) if ((int)logType < (int)Level)
return; 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()) foreach (var writer in writers.ToList())
{ {
try try

View File

@ -17,17 +17,17 @@ namespace CryptoExchange.Net.Objects
// Both arrays are non-null. Find the shorter // Both arrays are non-null. Find the shorter
// of the two lengths. // of the two lengths.
int bytesToCompare = Math.Min(x.Length, y.Length); var bytesToCompare = Math.Min(x.Length, y.Length);
// Compare the bytes. // Compare the bytes.
for (int index = 0; index < bytesToCompare; ++index) for (var index = 0; index < bytesToCompare; ++index)
{ {
// The x and y bytes. // The x and y bytes.
byte xByte = x[index]; var xByte = x[index];
byte yByte = y[index]; var yByte = y[index];
// Compare result. // Compare result.
int compareResult = Comparer<byte>.Default.Compare(xByte, yByte); var compareResult = Comparer<byte>.Default.Compare(xByte, yByte);
// If not the same, then return the result of the // If not the same, then return the result of the
// comparison of the bytes, as they were the same // comparison of the bytes, as they were the same

View File

@ -36,7 +36,7 @@ namespace CryptoExchange.Net.Objects
/// <summary> /// <summary>
/// The log writers /// The log writers
/// </summary> /// </summary>
public List<TextWriter> LogWriters { get; set; } = new List<TextWriter>() { new DebugTextWriter() }; public List<TextWriter> LogWriters { get; set; } = new List<TextWriter> { new DebugTextWriter() };
} }
public class ClientOptions: ExchangeOptions public class ClientOptions: ExchangeOptions

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
@ -13,6 +12,7 @@ using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Interfaces; using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Logging; using CryptoExchange.Net.Logging;
using CryptoExchange.Net.Objects; using CryptoExchange.Net.Objects;
using CryptoExchange.Net.RateLimiter;
using CryptoExchange.Net.Requests; using CryptoExchange.Net.Requests;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -93,17 +93,15 @@ namespace CryptoExchange.Net
} }
catch(PingException e) catch(PingException e)
{ {
if(e.InnerException != null) if (e.InnerException == null)
{ return new CallResult<long>(0, new CantConnectError() {Message = "Ping failed: " + e.Message});
if (e.InnerException is SocketException exception)
return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + exception.SocketErrorCode }); if (e.InnerException is SocketException exception)
return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + e.InnerException.Message }); return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + exception.SocketErrorCode });
} return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + e.InnerException.Message });
return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + e.Message });
} }
if (reply.Status == IPStatus.Success)
return new CallResult<long>(reply.RoundtripTime, null); return reply.Status == IPStatus.Success ? new CallResult<long>(reply.RoundtripTime, null) : new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + reply.Status });
return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + reply.Status });
} }
/// <summary> /// <summary>
@ -157,7 +155,7 @@ namespace CryptoExchange.Net
paramString = paramString.Trim(','); 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); var result = await ExecuteRequest(request).ConfigureAwait(false);
if(!result.Success) if(!result.Success)
return new CallResult<T>(null, result.Error); return new CallResult<T>(null, result.Error);
@ -199,7 +197,7 @@ namespace CryptoExchange.Net
if(authProvider != null) if(authProvider != null)
parameters = authProvider.AddAuthenticationToParameters(uriString, method, parameters, signed); 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); uriString += "?" + parameters.CreateParamString(true);
var request = RequestFactory.Create(uriString); var request = RequestFactory.Create(uriString);
@ -253,10 +251,10 @@ namespace CryptoExchange.Net
} }
else if(requestBodyFormat == RequestBodyFormat.FormData) 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)) foreach (var kvp in parameters.OrderBy(p => p.Key))
formData.Add(kvp.Key, kvp.Value.ToString()); formData.Add(kvp.Key, kvp.Value.ToString());
string stringData = formData.ToString(); var stringData = formData.ToString();
WriteParamBody(request, stringData); WriteParamBody(request, stringData);
} }
} }
@ -296,10 +294,7 @@ namespace CryptoExchange.Net
response.Close(); response.Close();
var jsonResult = ValidateJson(returnedData); var jsonResult = ValidateJson(returnedData);
if (!jsonResult.Success) return !jsonResult.Success ? new CallResult<string>(null, jsonResult.Error) : new CallResult<string>(null, ParseErrorResponse(jsonResult.Data));
return new CallResult<string>(null, jsonResult.Error);
return new CallResult<string>(null, ParseErrorResponse(jsonResult.Data));
} }
catch (Exception) catch (Exception)
{ {

View File

@ -84,7 +84,7 @@ namespace CryptoExchange.Net
SocketOnClose(socket); SocketOnClose(socket);
}; };
socket.OnError += (e) => socket.OnError += e =>
{ {
log.Write(LogVerbosity.Info, $"Socket {socket.Id} error: " + e.ToString()); log.Write(LogVerbosity.Info, $"Socket {socket.Id} error: " + e.ToString());
SocketError(socket, e); SocketError(socket, e);
@ -248,7 +248,9 @@ namespace CryptoExchange.Net
/// <returns></returns> /// <returns></returns>
public virtual async Task UnsubscribeAll() 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(() => await Task.Run(() =>
{ {
var tasks = new List<Task>(); var tasks = new List<Task>();

View File

@ -55,15 +55,7 @@ namespace CryptoExchange.Net.Sockets
set => socket.AutoSendPingInterval = (int) Math.Round(value.TotalSeconds); set => socket.AutoSendPingInterval = (int) Math.Round(value.TotalSeconds);
} }
public WebSocketState SocketState public WebSocketState SocketState => socket?.State ?? WebSocketState.None;
{
get
{
if (socket == null)
return WebSocketState.None;
return socket.State;
}
}
public BaseSocket(Log log, string url):this(log, url, new Dictionary<string, string>(), new Dictionary<string, string>()) public BaseSocket(Log log, string url):this(log, url, new Dictionary<string, string>(), new Dictionary<string, string>())
{ {
@ -151,7 +143,7 @@ namespace CryptoExchange.Net.Sockets
var waitLock = new object(); var waitLock = new object();
log?.Write(LogVerbosity.Debug, $"Socket {Id} closing"); log?.Write(LogVerbosity.Debug, $"Socket {Id} closing");
ManualResetEvent evnt = new ManualResetEvent(false); var evnt = new ManualResetEvent(false);
var handler = new EventHandler((o, a) => var handler = new EventHandler((o, a) =>
{ {
lock(waitLock) lock(waitLock)
@ -200,7 +192,7 @@ namespace CryptoExchange.Net.Sockets
{ {
log?.Write(LogVerbosity.Debug, $"Socket {Id} connecting"); log?.Write(LogVerbosity.Debug, $"Socket {Id} connecting");
var waitLock = new object(); var waitLock = new object();
ManualResetEvent evnt = new ManualResetEvent(false); var evnt = new ManualResetEvent(false);
var handler = new EventHandler((o, a) => var handler = new EventHandler((o, a) =>
{ {
lock (waitLock) lock (waitLock)
@ -266,7 +258,7 @@ namespace CryptoExchange.Net.Sockets
} }
} }
private int NextStreamId() private static int NextStreamId()
{ {
lock (streamIdLock) lock (streamIdLock)
{ {

View File

@ -9,7 +9,7 @@ namespace CryptoExchange.Net.Sockets
public string WaitingId { get; set; } public string WaitingId { get; set; }
private CallResult<bool> result; private CallResult<bool> result;
private ManualResetEvent setEvnt; private readonly ManualResetEvent setEvnt;
public SocketEvent(string name) public SocketEvent(string name)
{ {