예제 #1
0
 private void ConnectToHub()
 {
     try
     {
         hubClient = hubFactory.CreateConnection();
         hubClient.MessageArrived     += ClientInvokation;
         hubClient.OperationalChanged += ConnectedChanges;
         if (initCalled)
         {
             hubClient.Initialize();
         }
     }
     catch (Exception ex)
     {
         LogEnvironment.LogEvent($"Error connecting to hub: {ex.OutlineException()}", LogSeverity.Warning);
         throw;
     }
     finally
     {
         if (!hubClient.Operational && initCalled)
         {
             reconnector.Change(reconnectTimeout, reconnectTimeout);
         }
         else
         {
             reconnector.Change(Timeout.Infinite, Timeout.Infinite);
         }
     }
 }
예제 #2
0
        private void ConnectedChanges(object sender, EventArgs e)
        {
            if (hubClient != null && !hubClient.Operational)
            {
                try
                {
                    hubClient.MessageArrived -= ClientInvokation;
                    if (hubClient is not LocalServiceHubConsumer)
                    {
                        hubClient.OperationalChanged -= ConnectedChanges;
                    }

                    hubClient.Dispose();
                }
                catch (Exception ex)
                {
                    LogEnvironment.LogDebugEvent($"Un-Expected Disconnection Error: {ex.OutlineException()}", LogSeverity.Error);
                }
                finally
                {
                    hubClient = null;
                    reconnector.Change(reconnectTimeout, reconnectTimeout);
                }
            }
        }
예제 #3
0
 public override void Dispose()
 {
     base.Dispose();
     hubClient?.Dispose();
     hubClient = null;
     reconnector.Dispose();
 }
        private IDisposable Subscribe(object handler, MethodInfo method, IHubConnection connection)
        {
            var args        = method.GetParameters().Select(p => p.ParameterType).ToArray();
            var state       = new HandlerState(method, handler);
            var handlerFunc = HandlerForMethod(method);

            return(connection.On(method.Name, args, handlerFunc, state));
        }
        public static HubProxy <TClient> CreateProxy <TClient>(IHubConnection connection)
            where TClient : class
        {
            var interceptor = new SignalRInterceptor(connection);
            var client      = generator.CreateInterfaceProxyWithoutTarget <TClient>(interceptor);

            return(new HubProxy <TClient>(connection, client, new HandlerSubscriber()));
        }
예제 #6
0
 public HubController(
     IHubConnection hubConnection,
     IHubObservable hubObservable,
     IHubReconnector hubReconnector,
     IList <IHubObserver> hubObservers,
     string hubName)
 {
     _hubConnection  = hubConnection;
     _hubObservable  = hubObservable;
     _hubReconnector = hubReconnector;
     _hubObservers   = hubObservers.Where(o => o.HubName == hubName).ToList();
 }
        public IDisposable Subscribe(object handler, Type handlerType, IHubConnection connection)
        {
            var subs = new List <IDisposable>();

            foreach (var method in handlerType.GetMethods())
            {
                var sub = Subscribe(handler, method, connection);
                subs.Add(sub);
            }

            return(new BatchedDisposable(subs));
        }
예제 #8
0
        private void TryReconnect(object state)
        {
            if (Monitor.TryEnter(reconnLock))
            {
                try
                {
                    if (hubClient != null && !hubClient.Operational)
                    {
                        try
                        {
                            hubClient.MessageArrived -= ClientInvokation;
                            if (hubClient is not LocalServiceHubConsumer)
                            {
                                hubClient.OperationalChanged -= ConnectedChanges;
                            }

                            hubClient.Dispose();
                        }
                        catch (Exception ex)
                        {
                            LogEnvironment.LogDebugEvent($"Un-Expected Disconnection Error: {ex.OutlineException()}", LogSeverity.Error);
                        }
                        finally
                        {
                            hubClient = null;
                        }
                    }
                    if (hubClient == null)
                    {
                        try
                        {
                            ConnectToHub();
                        }
                        catch (Exception ex)
                        {
                            LogEnvironment.LogEvent($"Error when connecting to hub: {ex.OutlineException()}", LogSeverity.Warning);
                        }
                    }
                    else
                    {
                        reconnector.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(reconnLock);
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Re-Initializes the client connection
        /// </summary>
        private void ReConnectClient()
        {
            connection = connector.CreateConnection();
            if (useEvents)
            {
                connection.MessageArrived     += ProcessMessage;
                connection.OperationalChanged += ConnectivityChanged;
            }

            if (initCalled)
            {
                connection.Initialize();
                connected = connection.Operational;
            }
        }
예제 #10
0
        /// <summary>
        /// Processes connectivity-changes of the underlaying client
        /// </summary>
        /// <param name="sender">the grpc-client that experienced a connectivity-change</param>
        /// <param name="e">empty arguments</param>
        private void ConnectivityChanged(object sender, EventArgs e)
        {
            connected = connection?.Operational ?? false;
            if (connection != null && !connection.Operational)
            {
                if (useEvents)
                {
                    connection.MessageArrived     -= ProcessMessage;
                    connection.OperationalChanged -= ConnectivityChanged;
                }

                connection.Dispose();
                connection = null;
            }
        }
예제 #11
0
        /// <summary>
        /// Tests the connection to the given target-proxy object
        /// </summary>
        /// <returns>a value indicating whether the connection is OK</returns>
        protected override bool Test()
        {
            if (connected || !initCalled)
            {
                if (!connection.Initialized)
                {
                    try
                    {
                        connection.Initialize();
                        if (isBidirectional != IsBidirectional)
                        {
                            throw new Exception("Failed to Register return-channel. Check permissions on server.");
                        }
                    }
                    finally
                    {
                        initCalled = true;
                    }
                }

                if (!connection.Operational)
                {
                    ConnectivityChanged(null, null);
                    return(connected = false);
                }

                return(connected = connection.DiscoverService(targetService));
            }
            else
            {
                try
                {
                    ReConnectClient();
                    //return Test();
                }
                catch
                {
                    connection?.Dispose();
                    connection = null;
                    connected  = false;
                }
            }

            return(false);
        }
예제 #12
0
        private bool WaitForConnection()
        {
            lock (connectionLock)
            {
                if (connection == null)
                {
                    connection = ConnectionFactory.Create(socketAddress);
                    if (apiProxy != null)
                    {
                        connection.SetProxy(apiProxy.Host, apiProxy.Port);
                    }

                    proxy = connection.CreateHubProxy(HubName);

                    connection.Closed         += SocketClosed;
                    connection.Error          += SocketError;
                    connection.ConnectionSlow += SocketSlow;
                    connection.StateChanged   += SocketStateChange;
                    connection.UserAgent       = UserAgent;

                    proxy.Subscribe(MarketDeltaEvent).Received   += SocketMessageMarketDeltas;
                    proxy.Subscribe(ExchangeStateEvent).Received += SocketMessageExchangeState;
                }

                // If failed, try to get CloudFlare bypass
                log.Write(LogVerbosity.Warning, "Getting CloudFlare cookies");
                var sw = Stopwatch.StartNew();
                var cookieContainer = CloudFlareAuthenticator.GetCloudFlareCookies(cloudFlareAuthenticationAddress, UserAgent, cloudFlareRetries).ConfigureAwait(false).GetAwaiter().GetResult();
                sw.Stop();

                log.Write(LogVerbosity.Debug, $"CloudFlare cookie retrieving done in {sw.ElapsedMilliseconds}ms");
                if (cookieContainer == null)
                {
                    log.Write(LogVerbosity.Error, "CloudFlareAuthenticator didn't give us the cookies, trying to start without");
                }
                else
                {
                    connection.Cookies = cookieContainer;
                }

                // Try connecting
                return(TryStart().ConfigureAwait(false).GetAwaiter().GetResult());
            }
        }
예제 #13
0
        public MessageClient(IServiceHubProvider serviceHub, string targetService, bool useEvents)
        {
            if (!useEvents)
            {
                connection = new LocalServiceHubConsumer(null, serviceHub, targetService, null);
            }
            else
            {
                connection      = new LocalServiceHubConsumer($"{Guid.NewGuid()}", serviceHub, targetService, null);
                isBidirectional = true;
            }

            this.targetService = targetService;
            this.useEvents     = useEvents;
            if (useEvents)
            {
                connection.MessageArrived += ProcessMessage;
            }

            connected = true;
        }
예제 #14
0
 public ObservableBase(IHubConnection connection, IStringDeserializer deserializer, string eventName)
 {
     this.Connection        = connection;
     this.DefaultSerializer = deserializer;
     this.EventName         = eventName;
 }
예제 #15
0
 public StringSerializedObservable(IHubConnection connection, IStringDeserializer deserializer, string eventName)
     : base(connection, deserializer, eventName)
 {
 }
예제 #16
0
 public CustomSerializedObservable(IHubConnection connection, string eventName, IStringDeserializer dataDeserializer, IStringDeserializer metaDeserializer)
     : base(connection, dataDeserializer, eventName)
 {
     this.MetaDeserializer = metaDeserializer;
 }
예제 #17
0
 public DisconnectedObservable(IHubConnection connection)
 {
     this.Connection = connection;
 }
예제 #18
0
 public bool TryRemove(string connectionId, out IHubConnection connection)
 {
     return(_connections.TryRemove(connectionId, out connection));
 }
예제 #19
0
 public void StopObserveForReconnection(IHubConnection hubConnection)
 {
     _hubConnection = null;
     hubConnection.ConnectionStatusChanged -= OnHubConnectionChanged;
 }
예제 #20
0
 public HubProxy(IHubConnection connection, string hubName)
 {
     _connection = connection;
     _hubName    = hubName;
 }
예제 #21
0
 public IscoolHub(IHubConnection hubConnection) : base(hubConnection, HubName)
 {
 }
예제 #22
0
        private bool WaitForConnection()
        {
            lock (connectionLock)
            {
                if (connection == null)
                {
                    connection = ConnectionFactory.Create(log, baseAddress);
                    if (apiProxy != null)
                    {
                        connection.SetProxy(apiProxy.Host, apiProxy.Port);
                    }

                    proxy = connection.CreateHubProxy(HubName);

                    proxy.On(MarketEvent, (data) => SocketMessageExchangeState(data));
                    proxy.On(SummaryEvent, (data) => SocketMessageMarketSummaries(data));
                    proxy.On(SummaryLiteEvent, (data) => SocketMessageMarketSummariesLite(data));
                    proxy.On(BalanceEvent, (data) => SocketMessageBalance(data));
                    proxy.On(OrderEvent, (data) => SocketMessageOrder(data));

                    connection.Closed         += SocketClosed;
                    connection.Error          += SocketError;
                    connection.ConnectionSlow += SocketSlow;
                    connection.StateChanged   += SocketStateChange;
                }

                // Try connecting
                var connectResult = TryStart().ConfigureAwait(false).GetAwaiter().GetResult();

                if (!connectResult)
                {
                    return(connectResult);
                }

                // Resubscribe the subscriptions
                List <BittrexRegistration> registrationsCopy;
                lock (registrationLock)
                    registrationsCopy = registrations.ToList();

                if (registrationsCopy.Count > 0)
                {
                    log.Write(LogVerbosity.Info, $"Resubscribing {registrationsCopy.Count} subscriptions");
                }

                bool failedResubscribe = false;
                foreach (var registration in registrationsCopy)
                {
                    if (registration is BittrexMarketSummariesRegistration)
                    {
                        var resubSuccess = InvokeProxy <bool>(SummaryDeltaSub).ConfigureAwait(false).GetAwaiter().GetResult();
                        if (!resubSuccess.Success)
                        {
                            log.Write(LogVerbosity.Warning, "Failed to resubscribe summary delta: " + resubSuccess.Error);
                            failedResubscribe = true;
                            break;
                        }
                    }
                    else if (registration is BittrexExchangeStateRegistration)
                    {
                        var resubSuccess = InvokeProxy <bool>(ExchangeDeltaSub, ((BittrexExchangeStateRegistration)registration).MarketName).ConfigureAwait(false).GetAwaiter().GetResult();
                        if (!resubSuccess.Success)
                        {
                            log.Write(LogVerbosity.Warning, "Failed to resubscribe exchange delta: " + resubSuccess.Error);
                            failedResubscribe = true;
                            break;
                        }
                    }
                    else if (registration is BittrexMarketSummariesLiteRegistration)
                    {
                        var resubSuccess = InvokeProxy <bool>(SummaryLiteDeltaSub).ConfigureAwait(false).GetAwaiter().GetResult();
                        if (!resubSuccess.Success)
                        {
                            log.Write(LogVerbosity.Warning, "Failed to resubscribe summary lite delta: " + resubSuccess.Error);
                            failedResubscribe = true;
                            break;
                        }
                    }
                    else if (registration is BittrexBalanceUpdateRegistration || registration is BittrexOrderUpdateRegistration)
                    {
                        if (!authenticated)
                        {
                            var authResult = Authenticate().ConfigureAwait(false).GetAwaiter().GetResult();
                            if (!authResult.Success)
                            {
                                log.Write(LogVerbosity.Warning, "Failed to re-authenticate: " + authResult.Error);
                                failedResubscribe = true;
                                break;
                            }
                        }
                    }
                }

                if (failedResubscribe)
                {
                    log.Write(LogVerbosity.Warning, "Failed to resubscribe all running subscriptions -> Reconnect and try again");
                    connection.Stop(TimeSpan.FromSeconds(1));
                    return(false);
                }

                return(connectResult);
            }
        }
예제 #23
0
 public HubProxy(IHubConnection connection, THubClient client, IHandlerSubscriber subscriber)
 {
     this.connection = connection;
     this.subscriber = subscriber;
     Client          = client;
 }
예제 #24
0
 public TcpClientHub(IHubConnection hubConnection)
 {
     _hubConnection = hubConnection;
 }
 public SignalRInterceptorTests()
 {
     connection  = Substitute.For <IHubConnection>();
     interceptor = new SignalRInterceptor(connection);
     proxy       = generator.CreateInterfaceProxyWithoutTarget <IServerClient>(interceptor);
 }
예제 #26
0
 public GenericHub(IHubConnection hubConnection, string hubName)
 {
     _hubConnection = hubConnection;
     _hubName       = hubName;
 }
예제 #27
0
 public void StartObserveForReconnection(IHubConnection hubConnection)
 {
     _hubConnection = hubConnection;
     hubConnection.ConnectionStatusChanged += OnHubConnectionChanged;
 }
예제 #28
0
 public void Add(IHubConnection connection)
 {
     _connections.TryAdd(connection.ConnectionId, connection);
 }
예제 #29
0
 public ConnectionEventArgs(IHubConnection connection)
 {
     Connection = connection ?? throw new ArgumentNullException(nameof(connection));
 }
예제 #30
0
 public bool TryGet(string connectionId, out IHubConnection connection)
 {
     return(_connections.TryGetValue(connectionId, out connection));
 }