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) protected string ByteToString(byte[] buff)
{ {
var sbinary = ""; var result = "";
foreach (var t in buff) foreach (var t in buff)
sbinary += t.ToString("X2"); /* hex format */ result += t.ToString("X2"); /* hex format */
return sbinary; return result;
} }
} }
} }

View File

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

View File

@ -6,6 +6,7 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
@ -23,12 +24,13 @@ namespace CryptoExchange.Net
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
}); });
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(); log = new Log();
authProvider = authenticationProvider; authProvider = authenticationProvider;
@ -39,7 +41,7 @@ namespace CryptoExchange.Net
/// Configure the client using the provided options /// Configure the client using the provided options
/// </summary> /// </summary>
/// <param name="exchangeOptions">Options</param> /// <param name="exchangeOptions">Options</param>
protected virtual void Configure(ExchangeOptions exchangeOptions) protected void Configure(ExchangeOptions exchangeOptions)
{ {
log.UpdateWriters(exchangeOptions.LogWriters); log.UpdateWriters(exchangeOptions.LogWriters);
log.Level = exchangeOptions.LogVerbosity; log.Level = exchangeOptions.LogVerbosity;
@ -53,11 +55,11 @@ namespace CryptoExchange.Net
/// <summary> /// <summary>
/// Set the authentication provider /// Set the authentication provider
/// </summary> /// </summary>
/// <param name="authentictationProvider"></param> /// <param name="authenticationProvider"></param>
protected void SetAuthenticationProvider(AuthenticationProvider authentictationProvider) protected void SetAuthenticationProvider(AuthenticationProvider authenticationProvider)
{ {
log.Write(LogVerbosity.Debug, "Setting api credentials"); log.Write(LogVerbosity.Debug, "Setting api credentials");
authProvider = authentictationProvider; authProvider = authenticationProvider;
} }
/// <summary> /// <summary>
@ -117,10 +119,9 @@ namespace CryptoExchange.Net
{ {
CheckObject(typeof(T), o); CheckObject(typeof(T), o);
} }
else else if (obj is JArray j)
{ {
var ary = (JArray)obj; if (j.HasValues && j[0] is JObject jObject)
if (ary.HasValues && ary[0] is JObject jObject)
CheckObject(typeof(T).GetElementType(), jObject); CheckObject(typeof(T).GetElementType(), jObject);
} }
} }
@ -134,19 +135,19 @@ namespace CryptoExchange.Net
} }
catch (JsonReaderException jre) 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); log.Write(LogVerbosity.Error, info);
return new CallResult<T>(default(T), new DeserializeError(info)); return new CallResult<T>(default(T), new DeserializeError(info));
} }
catch (JsonSerializationException jse) 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); log.Write(LogVerbosity.Error, info);
return new CallResult<T>(default(T), new DeserializeError(info)); return new CallResult<T>(default(T), new DeserializeError(info));
} }
catch (Exception ex) 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); log.Write(LogVerbosity.Error, info);
return new CallResult<T>(default(T), new DeserializeError(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) if (propType.IsArray && token.Value.HasValues && ((JArray)token.Value).Any() && ((JArray)token.Value)[0] is JObject)
CheckObject(propType.GetElementType(), (JObject)token.Value[0]); CheckObject(propType.GetElementType(), (JObject)token.Value[0]);
else if (token.Value is JObject) else if (token.Value is JObject o)
CheckObject(propType, (JObject)token.Value); CheckObject(propType, o);
} }
} }

View File

@ -41,12 +41,12 @@ namespace CryptoExchange.Net.Converters
var count = 0; var count = 0;
if (innerArray.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); property.SetValue(result, arrayResult);
} }
else if (innerArray[0].Type == JTokenType.Array) 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) foreach (var obj in innerArray)
{ {
var innerObj = Activator.CreateInstance(objType); var innerObj = Activator.CreateInstance(objType);
@ -57,7 +57,7 @@ namespace CryptoExchange.Net.Converters
} }
else 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); var innerObj = Activator.CreateInstance(objType);
arrayResult[0] = ParseObject(innerArray, innerObj, objType); arrayResult[0] = ParseObject(innerArray, innerObj, objType);
property.SetValue(result, arrayResult); property.SetValue(result, arrayResult);
@ -65,22 +65,15 @@ namespace CryptoExchange.Net.Converters
continue; continue;
} }
object value; var converterAttribute = (JsonConverterAttribute)property.GetCustomAttribute(typeof(JsonConverterAttribute)) ?? (JsonConverterAttribute)property.PropertyType.GetCustomAttribute(typeof(JsonConverterAttribute));
var converterAttribute = (JsonConverterAttribute)property.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 (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];
if (value != null && property.PropertyType.IsInstanceOfType(value)) if (value != null && property.PropertyType.IsInstanceOfType(value))
property.SetValue(result, value); property.SetValue(result, value);
else else
{ {
if (value is JToken) if (value is JToken token)
if (((JToken)value).Type == JTokenType.Null) if (token.Type == JTokenType.Null)
value = null; value = null;
if ((property.PropertyType == typeof(decimal) if ((property.PropertyType == typeof(decimal)
@ -123,10 +116,10 @@ namespace CryptoExchange.Net.Converters
last = arrayProp.Index; last = arrayProp.Index;
var converterAttribute = (JsonConverterAttribute)prop.GetCustomAttribute(typeof(JsonConverterAttribute)); 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))); writer.WriteRawValue(JsonConvert.SerializeObject(prop.GetValue(value), (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType)));
else if(!IsSimple(prop.PropertyType)) else if (!IsSimple(prop.PropertyType))
writer.WriteValue(JsonConvert.SerializeObject(prop.GetValue(value))); serializer.Serialize(writer, prop.GetValue(value));
else else
writer.WriteValue(prop.GetValue(value)); writer.WriteValue(prop.GetValue(value));
} }
@ -142,8 +135,8 @@ namespace CryptoExchange.Net.Converters
} }
return type.IsPrimitive return type.IsPrimitive
|| type.IsEnum || type.IsEnum
|| type.Equals(typeof(string)) || type == typeof(string)
|| type.Equals(typeof(decimal)); || 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) public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{ {
if (reader.Value.GetType() == typeof(double)) if (reader.Value is double d)
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds((double)reader.Value); return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(d);
var t = double.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture); var t = double.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture);
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(t); 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; return null;
DateTime value; DateTime value;
if (reader.Value is string) if (reader.Value is string s)
value = (DateTime)JsonConvert.DeserializeObject((string)reader.Value); value = (DateTime)JsonConvert.DeserializeObject(s);
else else
value = (DateTime) reader.Value; value = (DateTime) reader.Value;

View File

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

View File

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

View File

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

View File

@ -92,8 +92,8 @@ namespace CryptoExchange.Net
{ {
if(e.InnerException != null) if(e.InnerException != null)
{ {
if (e.InnerException is SocketException) if (e.InnerException is SocketException exception)
return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + ((SocketException)e.InnerException).SocketErrorCode }); 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.InnerException.Message });
} }
return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + e.Message }); return new CallResult<long>(0, new CantConnectError() { Message = "Ping failed: " + e.Message });
@ -115,7 +115,7 @@ namespace CryptoExchange.Net
/// <returns></returns> /// <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 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) if (signed && authProvider == null)
{ {
log.Write(LogVerbosity.Warning, $"Request {uri.AbsolutePath} failed because no ApiCredentials were provided"); log.Write(LogVerbosity.Warning, $"Request {uri.AbsolutePath} failed because no ApiCredentials were provided");
@ -203,7 +203,7 @@ namespace CryptoExchange.Net
} }
/// <summary> /// <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> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="stringData"></param> /// <param name="stringData"></param>
@ -292,7 +292,7 @@ namespace CryptoExchange.Net
} }
catch (Exception e) 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)); return new CallResult<string>(null, new UnknownError(e.Message + ", data: " + returnedData));
} }
} }

View File

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Security.Authentication;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using CryptoExchange.Net.Authentication; using CryptoExchange.Net.Authentication;
@ -52,7 +52,7 @@ namespace CryptoExchange.Net
} }
/// <summary> /// <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> /// </summary>
/// <param name="handler"></param> /// <param name="handler"></param>
protected void SetDataInterpreter(Func<byte[], string> handler) protected void SetDataInterpreter(Func<byte[], string> handler)
@ -83,13 +83,11 @@ namespace CryptoExchange.Net
}; };
socket.OnError += (e) => 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); SocketError(socket, e);
}; };
socket.OnOpen += () => socket.OnOpen += () => SocketOpened(socket);
{ socket.OnClose += () => SocketClosed(socket);
SocketOpened(socket);
};
return socket; return socket;
} }
@ -141,16 +139,21 @@ namespace CryptoExchange.Net
string currentHandlerName = null; string currentHandlerName = null;
try try
{ {
var sw = Stopwatch.StartNew();
foreach (var handler in subscription.MessageHandlers) foreach (var handler in subscription.MessageHandlers)
{ {
currentHandlerName = handler.Key; currentHandlerName = handler.Key;
if (handler.Value(subscription, JToken.Parse(data))) 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) 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 socket.Close().Wait(); // Close so we end up reconnecting again
else else
log.Write(LogVerbosity.Info, $"Socket {socket.Id} successfully resubscribed"); log.Write(LogVerbosity.Info, $"Socket {socket.Id} successfully resubscribed");
return;
}); });
} }
else else

View File

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

View File

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

View File

@ -25,7 +25,7 @@ namespace CryptoExchange.Net.Sockets
public SocketType Type { get; set; } public SocketType Type { get; set; }
private bool lostTriggered; private bool lostTriggered;
private List<SocketEvent> waitingForEvents; private readonly List<SocketEvent> waitingForEvents;
public SocketSubscription(IWebsocket socket) public SocketSubscription(IWebsocket socket)
@ -55,7 +55,7 @@ namespace CryptoExchange.Net.Sockets
if (lostTriggered) if (lostTriggered)
{ {
lostTriggered = false; 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)); 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); var waitingEvent = waitingForEvents.SingleOrDefault(e => e.Name == name);
if (waitingEvent != null) 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); var waitingEvent = waitingForEvents.SingleOrDefault(e => e.WaitingId == id);
if (waitingEvent != null) if (waitingEvent != null)
@ -90,6 +90,13 @@ namespace CryptoExchange.Net.Sockets
return waitingForEvents.SingleOrDefault(w => w.Name == name); 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) public Task<CallResult<bool>> WaitForEvent(string name, int timeout)
{ {
var evnt = Events.Single(e => e.Name == name); var evnt = Events.Single(e => e.Name == name);
@ -97,7 +104,12 @@ namespace CryptoExchange.Net.Sockets
return Task.Run(() => evnt.Wait(timeout)); 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); var evnt = Events.Single(e => e.Name == name);
evnt.WaitingId = id; evnt.WaitingId = id;

View File

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