1
0
mirror of https://github.com/JKorf/CryptoExchange.Net synced 2025-06-09 00:46:19 +00:00

Fixed various resharper warning

This commit is contained in:
JKorf 2018-11-30 16:19:01 +01:00
parent 4c6218c8e3
commit 64a66d4206
17 changed files with 91 additions and 97 deletions

View File

@ -34,10 +34,10 @@ namespace CryptoExchange.Net.Authentication
protected string ByteToString(byte[] buff)
{
var sbinary = "";
var result = "";
foreach (var t in buff)
sbinary += t.ToString("X2"); /* hex format */
return sbinary;
result += t.ToString("X2"); /* hex format */
return result;
}
}
}

View File

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Security;
using System.Text;
namespace CryptoExchange.Net.Authentication
{
@ -13,7 +11,7 @@ namespace CryptoExchange.Net.Authentication
public SecureString Key { get; }
/// <summary>
/// The private key's passphrase
/// The private key's pass phrase
/// </summary>
public SecureString Passphrase { get; }
@ -36,7 +34,7 @@ namespace CryptoExchange.Net.Authentication
}
/// <summary>
/// Create a private key providing an encrypted key informations
/// Create a private key providing an encrypted key information
/// </summary>
/// <param name="key">The private key used for signing</param>
/// <param name="passphrase">The private key's passphrase</param>
@ -61,7 +59,7 @@ namespace CryptoExchange.Net.Authentication
}
/// <summary>
/// Create a private key providing an unencrypted key informations
/// Create a private key providing an unencrypted key information
/// </summary>
/// <param name="key">The private key used for signing</param>
public PrivateKey(SecureString key)
@ -72,7 +70,7 @@ namespace CryptoExchange.Net.Authentication
}
/// <summary>
/// Create a private key providing an encrypted key informations
/// Create a private key providing an encrypted key information
/// </summary>
/// <param name="key">The private key used for signing</param>
public PrivateKey(string key)

View File

@ -6,6 +6,7 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
@ -23,12 +24,13 @@ namespace CryptoExchange.Net
private static readonly JsonSerializer defaultSerializer = JsonSerializer.Create(new JsonSerializerSettings()
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
Culture = CultureInfo.InvariantCulture
});
public static int LastId { get => lastId; }
public static int LastId => lastId;
public BaseClient(ExchangeOptions options, AuthenticationProvider authenticationProvider)
protected BaseClient(ExchangeOptions options, AuthenticationProvider authenticationProvider)
{
log = new Log();
authProvider = authenticationProvider;
@ -39,7 +41,7 @@ namespace CryptoExchange.Net
/// Configure the client using the provided options
/// </summary>
/// <param name="exchangeOptions">Options</param>
protected virtual void Configure(ExchangeOptions exchangeOptions)
protected void Configure(ExchangeOptions exchangeOptions)
{
log.UpdateWriters(exchangeOptions.LogWriters);
log.Level = exchangeOptions.LogVerbosity;
@ -53,11 +55,11 @@ namespace CryptoExchange.Net
/// <summary>
/// Set the authentication provider
/// </summary>
/// <param name="authentictationProvider"></param>
protected void SetAuthenticationProvider(AuthenticationProvider authentictationProvider)
/// <param name="authenticationProvider"></param>
protected void SetAuthenticationProvider(AuthenticationProvider authenticationProvider)
{
log.Write(LogVerbosity.Debug, "Setting api credentials");
authProvider = authentictationProvider;
authProvider = authenticationProvider;
}
/// <summary>
@ -117,10 +119,9 @@ namespace CryptoExchange.Net
{
CheckObject(typeof(T), o);
}
else
else if (obj is JArray j)
{
var ary = (JArray)obj;
if (ary.HasValues && ary[0] is JObject jObject)
if (j.HasValues && j[0] is JObject jObject)
CheckObject(typeof(T).GetElementType(), jObject);
}
}
@ -134,19 +135,19 @@ namespace CryptoExchange.Net
}
catch (JsonReaderException jre)
{
var info = $"Deserialize JsonReaderException: {jre.Message}, Path: {jre.Path}, LineNumber: {jre.LineNumber}, LinePosition: {jre.LinePosition}. Received data: {obj.ToString()}";
var info = $"Deserialize JsonReaderException: {jre.Message}, Path: {jre.Path}, LineNumber: {jre.LineNumber}, LinePosition: {jre.LinePosition}. Received data: {obj}";
log.Write(LogVerbosity.Error, info);
return new CallResult<T>(default(T), new DeserializeError(info));
}
catch (JsonSerializationException jse)
{
var info = $"Deserialize JsonSerializationException: {jse.Message}. Received data: {obj.ToString()}";
var info = $"Deserialize JsonSerializationException: {jse.Message}. Received data: {obj}";
log.Write(LogVerbosity.Error, info);
return new CallResult<T>(default(T), new DeserializeError(info));
}
catch (Exception ex)
{
var info = $"Deserialize Unknown Exception: {ex.Message}. Received data: {obj.ToString()}";
var info = $"Deserialize Unknown Exception: {ex.Message}. Received data: {obj}";
log.Write(LogVerbosity.Error, info);
return new CallResult<T>(default(T), new DeserializeError(info));
}
@ -201,8 +202,8 @@ namespace CryptoExchange.Net
{
if (propType.IsArray && token.Value.HasValues && ((JArray)token.Value).Any() && ((JArray)token.Value)[0] is JObject)
CheckObject(propType.GetElementType(), (JObject)token.Value[0]);
else if (token.Value is JObject)
CheckObject(propType, (JObject)token.Value);
else if (token.Value is JObject o)
CheckObject(propType, o);
}
}

View File

@ -41,12 +41,12 @@ namespace CryptoExchange.Net.Converters
var count = 0;
if (innerArray.Count == 0)
{
var arrayResult = (IList)Activator.CreateInstance(property.PropertyType, new object[] { 0 });
var arrayResult = (IList)Activator.CreateInstance(property.PropertyType, new [] { 0 });
property.SetValue(result, arrayResult);
}
else if (innerArray[0].Type == JTokenType.Array)
{
var arrayResult = (IList)Activator.CreateInstance(property.PropertyType, new object[] { innerArray.Count() });
var arrayResult = (IList)Activator.CreateInstance(property.PropertyType, new [] { innerArray.Count });
foreach (var obj in innerArray)
{
var innerObj = Activator.CreateInstance(objType);
@ -57,7 +57,7 @@ namespace CryptoExchange.Net.Converters
}
else
{
var arrayResult = (IList)Activator.CreateInstance(property.PropertyType, new object[] { 1 });
var arrayResult = (IList)Activator.CreateInstance(property.PropertyType, new [] { 1 });
var innerObj = Activator.CreateInstance(objType);
arrayResult[0] = ParseObject(innerArray, innerObj, objType);
property.SetValue(result, arrayResult);
@ -65,22 +65,15 @@ namespace CryptoExchange.Net.Converters
continue;
}
object value;
var converterAttribute = (JsonConverterAttribute)property.GetCustomAttribute(typeof(JsonConverterAttribute));
if (converterAttribute == null)
converterAttribute = (JsonConverterAttribute)property.PropertyType.GetCustomAttribute(typeof(JsonConverterAttribute));
if (converterAttribute != null)
value = arr[attribute.Index].ToObject(property.PropertyType, new JsonSerializer() { Converters = { (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType) } });
else
value = arr[attribute.Index];
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];
if (value != null && property.PropertyType.IsInstanceOfType(value))
property.SetValue(result, value);
else
{
if (value is JToken)
if (((JToken)value).Type == JTokenType.Null)
if (value is JToken token)
if (token.Type == JTokenType.Null)
value = null;
if ((property.PropertyType == typeof(decimal)
@ -123,10 +116,10 @@ namespace CryptoExchange.Net.Converters
last = arrayProp.Index;
var converterAttribute = (JsonConverterAttribute)prop.GetCustomAttribute(typeof(JsonConverterAttribute));
if(converterAttribute != null)
if (converterAttribute != null)
writer.WriteRawValue(JsonConvert.SerializeObject(prop.GetValue(value), (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType)));
else if(!IsSimple(prop.PropertyType))
writer.WriteValue(JsonConvert.SerializeObject(prop.GetValue(value)));
else if (!IsSimple(prop.PropertyType))
serializer.Serialize(writer, prop.GetValue(value));
else
writer.WriteValue(prop.GetValue(value));
}
@ -142,8 +135,8 @@ namespace CryptoExchange.Net.Converters
}
return type.IsPrimitive
|| type.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal));
|| type == typeof(string)
|| type == typeof(decimal);
}
}

View File

@ -13,8 +13,8 @@ namespace CryptoExchange.Net.Converters
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value.GetType() == typeof(double))
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds((double)reader.Value);
if (reader.Value is double d)
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(d);
var t = double.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture);
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(t);

View File

@ -16,8 +16,8 @@ namespace CryptoExchange.Net.Converters
return null;
DateTime value;
if (reader.Value is string)
value = (DateTime)JsonConvert.DeserializeObject((string)reader.Value);
if (reader.Value is string s)
value = (DateTime)JsonConvert.DeserializeObject(s);
else
value = (DateTime) reader.Value;

View File

@ -1,6 +1,6 @@
using CryptoExchange.Net.Objects;
namespace CryptoExchange.Net.RateLimiter
namespace CryptoExchange.Net.Interfaces
{
public interface IRateLimiter
{

View File

@ -9,18 +9,8 @@ namespace CryptoExchange.Net.Logging
public class Log
{
private List<TextWriter> writers;
private LogVerbosity level = LogVerbosity.Info;
public LogVerbosity Level
{
get => level;
set
{
if (level != value)
level = value;
}
}
public LogVerbosity Level { get; set; } = LogVerbosity.Info;
public Log()
{

View File

@ -2,8 +2,8 @@
using System.Collections.Generic;
using System.IO;
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Logging;
using CryptoExchange.Net.RateLimiter;
namespace CryptoExchange.Net.Objects
{
@ -42,7 +42,7 @@ namespace CryptoExchange.Net.Objects
public class ClientOptions: ExchangeOptions
{
/// <summary>
/// List of ratelimiters to use
/// List of rate limiters to use
/// </summary>
public List<IRateLimiter> RateLimiters { get; set; } = new List<IRateLimiter>();

View File

@ -1,4 +1,5 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
using System.Diagnostics;

View File

@ -1,4 +1,5 @@
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Objects;
using System;
using System.Collections.Generic;
using System.Diagnostics;

View File

@ -92,8 +92,8 @@ namespace CryptoExchange.Net
{
if(e.InnerException != null)
{
if (e.InnerException is SocketException)
return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + ((SocketException)e.InnerException).SocketErrorCode });
if (e.InnerException is SocketException exception)
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 });
@ -115,7 +115,7 @@ namespace CryptoExchange.Net
/// <returns></returns>
protected virtual async Task<CallResult<T>> ExecuteRequest<T>(Uri uri, string method = Constants.GetMethod, Dictionary<string, object> parameters = null, bool signed = false, bool checkResult = true) where T : class
{
log.Write(LogVerbosity.Debug, $"Creating request for " + uri);
log.Write(LogVerbosity.Debug, "Creating request for " + uri);
if (signed && authProvider == null)
{
log.Write(LogVerbosity.Warning, $"Request {uri.AbsolutePath} failed because no ApiCredentials were provided");
@ -203,7 +203,7 @@ namespace CryptoExchange.Net
}
/// <summary>
/// Writes the string data of the paramters to the request body stream
/// Writes the string data of the parameters to the request body stream
/// </summary>
/// <param name="request"></param>
/// <param name="stringData"></param>
@ -292,7 +292,7 @@ namespace CryptoExchange.Net
}
catch (Exception e)
{
log.Write(LogVerbosity.Error, $"Unkown error occured: {e.GetType()}, {e.Message}, {e.StackTrace}");
log.Write(LogVerbosity.Error, $"Unknown error occured: {e.GetType()}, {e.Message}, {e.StackTrace}");
return new CallResult<string>(null, new UnknownError(e.Message + ", data: " + returnedData));
}
}

View File

@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using CryptoExchange.Net.Authentication;
@ -52,7 +52,7 @@ namespace CryptoExchange.Net
}
/// <summary>
/// Set a function to interprete the data, used when the data is received as bytes instead of a string
/// Set a function to interpret the data, used when the data is received as bytes instead of a string
/// </summary>
/// <param name="handler"></param>
protected void SetDataInterpreter(Func<byte[], string> handler)
@ -83,13 +83,11 @@ namespace CryptoExchange.Net
};
socket.OnError += (e) =>
{
log.Write(LogVerbosity.Warning, $"Socket {socket.Id} error: " + e.ToString());
log.Write(LogVerbosity.Info, $"Socket {socket.Id} error: " + e.ToString());
SocketError(socket, e);
};
socket.OnOpen += () =>
{
SocketOpened(socket);
};
socket.OnOpen += () => SocketOpened(socket);
socket.OnClose += () => SocketClosed(socket);
return socket;
}
@ -141,16 +139,21 @@ namespace CryptoExchange.Net
string currentHandlerName = null;
try
{
var sw = Stopwatch.StartNew();
foreach (var handler in subscription.MessageHandlers)
{
currentHandlerName = handler.Key;
if (handler.Value(subscription, JToken.Parse(data)))
return;
break;
}
sw.Stop();
if (sw.ElapsedMilliseconds > 500)
log.Write(LogVerbosity.Warning, $"Socket {subscription.Socket.Id} message processing slow ({sw.ElapsedMilliseconds}ms), consider offloading data handling to another thread. " +
"Data from this socket may arrive late or not at all if message processing is continuously slow.");
}
catch(Exception ex)
{
log.Write(LogVerbosity.Error, $"Exception during message processing\r\nProcessor: {currentHandlerName}\r\nException: {ex}\r\nData: {data}");
log.Write(LogVerbosity.Error, $"Socket {subscription.Socket.Id} Exception during message processing\r\nProcessor: {currentHandlerName}\r\nException: {ex}\r\nData: {data}");
}
}
@ -186,7 +189,6 @@ namespace CryptoExchange.Net
socket.Close().Wait(); // Close so we end up reconnecting again
else
log.Write(LogVerbosity.Info, $"Socket {socket.Id} successfully resubscribed");
return;
});
}
else

View File

@ -21,7 +21,6 @@ namespace CryptoExchange.Net.Sockets
protected WebSocket socket;
protected Log log;
protected object socketLock = new object();
protected DateTime? lostTime = null;
protected readonly List<Action<Exception>> errorHandlers = new List<Action<Exception>>();
protected readonly List<Action> openHandlers = new List<Action>();
@ -214,16 +213,10 @@ namespace CryptoExchange.Net.Sockets
return connected;
}).ConfigureAwait(false);
}
public virtual void SetEnabledSslProtocols(SslProtocols protocols)
{
socket.Security.EnabledSslProtocols = protocols;
}
public virtual void SetProxy(string host, int port)
{
IPAddress address;
socket.Proxy = IPAddress.TryParse(host, out address)
socket.Proxy = IPAddress.TryParse(host, out var address)
? new HttpConnectProxy(new IPEndPoint(address, port))
: new HttpConnectProxy(new DnsEndPoint(host, port));
}

View File

@ -6,7 +6,7 @@ namespace CryptoExchange.Net.Sockets
public class SocketEvent
{
public string Name { get; set; }
public int WaitingId { get; set; }
public string WaitingId { get; set; }
private CallResult<bool> result;
private ManualResetEvent setEvnt;
@ -18,11 +18,11 @@ namespace CryptoExchange.Net.Sockets
result = new CallResult<bool>(false, new UnknownError("No response received"));
}
public void Set(bool result, Error error)
internal void Set(bool result, Error error)
{
this.result = new CallResult<bool>(result, error);
setEvnt.Set();
WaitingId = -1;
WaitingId = null;
}
public CallResult<bool> Wait(int timeout = 5000)

View File

@ -25,7 +25,7 @@ namespace CryptoExchange.Net.Sockets
public SocketType Type { get; set; }
private bool lostTriggered;
private List<SocketEvent> waitingForEvents;
private readonly List<SocketEvent> waitingForEvents;
public SocketSubscription(IWebsocket socket)
@ -55,7 +55,7 @@ namespace CryptoExchange.Net.Sockets
if (lostTriggered)
{
lostTriggered = false;
ConnectionRestored?.Invoke(DateTime.UtcNow - Socket.DisconnectTime.Value);
ConnectionRestored?.Invoke(Socket.DisconnectTime.HasValue ? DateTime.UtcNow - Socket.DisconnectTime.Value: TimeSpan.FromSeconds(0));
}
};
}
@ -65,7 +65,7 @@ namespace CryptoExchange.Net.Sockets
Events.Add(new SocketEvent(name));
}
public void SetEvent(string name, bool success, Error error)
public void SetEventByName(string name, bool success, Error error)
{
var waitingEvent = waitingForEvents.SingleOrDefault(e => e.Name == name);
if (waitingEvent != null)
@ -75,7 +75,7 @@ namespace CryptoExchange.Net.Sockets
}
}
public void SetEvent(int id, bool success, Error error)
public void SetEventById(string id, bool success, Error error)
{
var waitingEvent = waitingForEvents.SingleOrDefault(e => e.WaitingId == id);
if (waitingEvent != null)
@ -90,6 +90,13 @@ namespace CryptoExchange.Net.Sockets
return waitingForEvents.SingleOrDefault(w => w.Name == name);
}
public Task<CallResult<bool>> WaitForEvent(string name, TimeSpan timeout)
{
return WaitForEvent(name, (int)Math.Round(timeout.TotalMilliseconds, 0));
}
public Task<CallResult<bool>> WaitForEvent(string name, int timeout)
{
var evnt = Events.Single(e => e.Name == name);
@ -97,7 +104,12 @@ namespace CryptoExchange.Net.Sockets
return Task.Run(() => evnt.Wait(timeout));
}
public Task<CallResult<bool>> WaitForEvent(string name, int id, int timeout)
public Task<CallResult<bool>> WaitForEvent(string name, string id, TimeSpan timeout)
{
return WaitForEvent(name, id, (int)Math.Round(timeout.TotalMilliseconds, 0));
}
public Task<CallResult<bool>> WaitForEvent(string name, string id, int timeout)
{
var evnt = Events.Single(e => e.Name == name);
evnt.WaitingId = id;

View File

@ -5,7 +5,7 @@ namespace CryptoExchange.Net.Sockets
{
public class UpdateSubscription
{
private SocketSubscription subscription;
private readonly SocketSubscription subscription;
/// <summary>
/// Event when the connection is lost
@ -25,6 +25,9 @@ namespace CryptoExchange.Net.Sockets
remove => subscription.ConnectionRestored -= value;
}
/// <summary>
/// The id of the socket
/// </summary>
public int Id => subscription.Socket.Id;
public UpdateSubscription(SocketSubscription sub)