Пример #1
0
        public async Task ReconnectionSuccesfulTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new AsyncManualResetEvent(false);
                host.Initialize(keepAlive: null, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                if (transportType == TransportType.LongPolling)
                {
                    ((Client.Transports.LongPollingTransport)host.Transport).ReconnectDelay = TimeSpan.Zero;
                }

                using (connection)
                {
                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2));

                    connection.Reconnected += () =>
                    {
                        mre.Set();
                    };

                    await connection.Start(host.Transport);

                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10)));

                    // Clean-up
                    mre.Dispose();
                }
            }
        }
Пример #2
0
 public AmqpProviderBase(
     IOptionsMonitor <AmqpOptions> options,
     MessageBusType messageBusType)
 {
     _messageBusType = messageBusType;
     _options        = options;
 }
Пример #3
0
        private IMessageBusProvider GetProviderFromConfig(MessageBusType messageBusType)
        {
            var configurationKey = messageBusType == MessageBusType.Queue ?
                                   _queueConfigSection : _pubsubConfigSection;

            var configuration = _serviceProvider.GetService <IConfiguration>();

            var messageBusTypeText = messageBusType == MessageBusType.Queue ? "Queue" : "Pub/Sub";

            if (configuration == null)
            {
                throw new ProviderNotFoundException($"MessageBus - Provider for {messageBusTypeText} must present at {configurationKey}.");
            }

            var providerTypeName = configuration[configurationKey];

            if (string.IsNullOrEmpty(providerTypeName))
            {
                throw new ProviderNotFoundException($"MessageBus - Provider for {messageBusTypeText} must present at {configurationKey}.");
            }

            var type = Type.GetType(providerTypeName);

            return(_serviceProvider.GetService(type) as IMessageBusProvider);
        }
Пример #4
0
        protected void UseMessageBus(MessageBusType type, IDependencyResolver resolver, ScaleoutConfiguration configuration = null, int streams = 1)
        {
            switch (type)
            {
            case MessageBusType.Default:
                break;

            case MessageBusType.Fake:
                var bus = new FakeScaleoutBus(resolver, streams);
                resolver.Register(typeof(IMessageBus), () => bus);
                break;

            case MessageBusType.SqlServer:
                break;

            case MessageBusType.ServiceBus:
                break;

            case MessageBusType.Redis:
                break;

            default:
                break;
            }
        }
Пример #5
0
        public async Task CanInvokeMethodsAndReceiveMessagesFromValidTypedHub(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                using (var connection = CreateHubConnection(host))
                {
                    var hub = connection.CreateHubProxy("ValidTypedHub");
                    var echoTcs = new TaskCompletionSource<string>();
                    var pingWh = new ManualResetEventSlim();

                    hub.On<string>("Echo", message => echoTcs.TrySetResult(message));
                    hub.On("Ping", pingWh.Set);

                    await connection.Start(host.TransportFactory());

                    hub.InvokeWithTimeout("Echo", "arbitrary message");
                    Assert.True(echoTcs.Task.Wait(TimeSpan.FromSeconds(10)));
                    Assert.Equal("arbitrary message", echoTcs.Task.Result);

                    hub.InvokeWithTimeout("Ping");
                    Assert.True(pingWh.Wait(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #6
0
        public void ReconnectionSuccesfulTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new ManualResetEventSlim(false);
                host.Initialize(keepAlive: null, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                using (connection)
                {
                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2));

                    connection.Reconnected += () =>
                    {
                        mre.Set();
                    };

                    connection.Start(host.Transport).Wait();

                    // Assert
                    Assert.True(mre.Wait(TimeSpan.FromSeconds(10)));

                    // Clean-up
                    mre.Dispose();
                }
            }
        }
Пример #7
0
        protected void UseMessageBus(MessageBusType type, IDependencyResolver resolver, int streams = 1)
        {
            IMessageBus bus = null;

            switch (type)
            {
            case MessageBusType.Default:
                break;

            case MessageBusType.Fake:
            case MessageBusType.FakeMultiStream:
                bus = new FakeScaleoutBus(resolver, streams);
                break;

            case MessageBusType.SqlServer:
                break;

            case MessageBusType.ServiceBus:
                break;

            case MessageBusType.Redis:
                break;

            default:
                break;
            }

            if (bus != null)
            {
                resolver.Register(typeof(IMessageBus), () => bus);
            }
        }
Пример #8
0
        public async Task TransportTimesOutIfNoInitMessage(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            var mre = new AsyncManualResetEvent();

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(transportConnectTimeout: 1, messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host, "/no-init");

                IHubProxy proxy = hubConnection.CreateHubProxy("DelayedOnConnectedHub");

                using (hubConnection)
                {
                    try
                    {
                        await hubConnection.Start(host.Transport);
                    }
                    catch
                    {
                        mre.Set();
                    }

                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #9
0
        public void Initialize(int?keepAlive,
                               int?connectionTimeout,
                               int?disconnectTimeout,
                               int?transportConnectTimeout,
                               int?maxIncomingWebSocketMessageSize,
                               bool enableAutoRejoiningGroups,
                               MessageBusType type = MessageBusType.Default)
        {
            if (type != MessageBusType.Default)
            {
                throw new NotImplementedException();
            }

            // Use a configuration file to specify values
            string content = String.Format(_webConfigTemplate.Value,
                                           keepAlive,
                                           connectionTimeout,
                                           disconnectTimeout,
                                           transportConnectTimeout,
                                           maxIncomingWebSocketMessageSize,
                                           enableAutoRejoiningGroups,
                                           _logFileName);

            File.WriteAllText(_webConfigPath, content);

            Url = _siteManager.GetSiteUrl(ExtraData);
        }
Пример #10
0
            public void ReconnectDoesntFireAfterTimeOut(TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = new MemoryHost())
                {
                    var conn = new MyReconnect();
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        UseMessageBus(messageBusType, config.Resolver);

                        app.MapSignalR <MyReconnect>("/endpoint", config);
                        var configuration = config.Resolver.Resolve <IConfigurationManager>();
                        configuration.DisconnectTimeout = TimeSpan.FromSeconds(6);
                        configuration.ConnectionTimeout = TimeSpan.FromSeconds(2);
                        configuration.KeepAlive         = null;

                        config.Resolver.Register(typeof(MyReconnect), () => conn);
                    });

                    var connection = new Client.Connection("http://foo/endpoint");
                    var transport  = CreateTransport(transportType, host);
                    connection.Start(transport).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(0, conn.Reconnects);
                }
            }
Пример #11
0
        protected void UseMessageBus(MessageBusType type, IDependencyResolver resolver, int streams = 1)
        {
            IMessageBus bus = null;

            switch (type)
            {
                case MessageBusType.Default:
                    break;
                case MessageBusType.Fake:
                case MessageBusType.FakeMultiStream:
                    bus = new FakeScaleoutBus(resolver, streams);
                    break;
                case MessageBusType.SqlServer:
                    break;
                case MessageBusType.ServiceBus:
                    break;
                case MessageBusType.Redis:
                    break;
                default:
                    break;
            }

            if (bus != null)
            {
                resolver.Register(typeof(IMessageBus), () => bus);
            }
        }
Пример #12
0
        public void ReconnectExceedingReconnectWindowDisconnectsWithFastBeatInterval(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            // Test cannot be async because if we do host.ShutDown() after an await the connection stops.

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(keepAlive: 9, messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    SetReconnectDelay(host.Transport, TimeSpan.FromSeconds(15));

                    connection.Start(host.Transport).Wait();                    

                    // Without this the connection start and reconnect can race with eachother resulting in a deadlock.
                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    // Set reconnect window to zero so the second we attempt to reconnect we can ensure that the reconnect window is verified.
                    ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(0);

                    host.Shutdown();

                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Пример #13
0
        public void EndToEndTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy     proxy         = hubConnection.CreateHubProxy("ChatHub");

                using (hubConnection)
                {
                    var wh = new ManualResetEvent(false);

                    proxy.On("addMessage", data =>
                    {
                        Assert.Equal("hello", data);
                        wh.Set();
                    });

                    hubConnection.Start(host.Transport).Wait();

                    proxy.InvokeWithTimeout("Send", "hello");

                    Assert.True(wh.WaitOne(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #14
0
        public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    connection.Start(host.Transport).Wait();

                    // The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect.
                    ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1);

                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Пример #15
0
        public async Task SuccessiveTimeoutTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                var mre = new AsyncManualResetEvent(false);
                host.Initialize(keepAlive: 5, messageBusType: messageBusType);
                var connection = CreateConnection(host, "/my-reconnect");

                using (connection)
                {
                    connection.Reconnected += () =>
                    {
                        mre.Set();
                    };

                    await connection.Start(host.Transport);

                    ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromMilliseconds(300));

                    // Assert that Reconnected is called
                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(15)));

                    // Assert that Reconnected is called again
                    mre.Reset();
                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(15)));

                    // Clean-up
                    mre.Dispose();
                }
            }
        }
Пример #16
0
        public void Initialize(int? keepAlive,
                               int? connectionTimeout,
                               int? disconnectTimeout,
                               int? transportConnectTimeout,
                               bool enableAutoRejoiningGroups,
                               MessageBusType type = MessageBusType.Default)
        {
            if (type != MessageBusType.Default)
            {
                throw new NotImplementedException();
            }

            // Use a configuration file to specify values
            string content = String.Format(_webConfigTemplate.Value,
                                           keepAlive,
                                           connectionTimeout,
                                           disconnectTimeout,
                                           transportConnectTimeout,
                                           enableAutoRejoiningGroups,
                                           _logFileName);

            File.WriteAllText(_webConfigPath, content);

            Url = _siteManager.GetSiteUrl(ExtraData);
        }
Пример #17
0
        public IPublisher GetPublisher(string topic, MessageBusType messageBusType = MessageBusType.Queue)
        {
            var provider           = GetProvider(messageBusType);
            var messageBusTypeText = messageBusType == MessageBusType.Queue ? "Queue" : "Pub/Sub";

            StaticLog.Information($"MessageBus - Publisher provider created: {messageBusTypeText} - {provider.GetType().Name}");
            return(provider.GetPublisher(topic));
        }
Пример #18
0
 public void Initialize(int?keepAlive                  = -1,
                        int?connectionTimeout          = 110,
                        int?disconnectTimeout          = 30,
                        int?transportConnectTimeout    = 5,
                        bool enableAutoRejoiningGroups = false,
                        MessageBusType type            = MessageBusType.Default)
 {
     // nothing to initialize since it is external!
 }
Пример #19
0
 public void Initialize(int? keepAlive = -1,
                        int? connectionTimeout = 110,                               
                        int? disconnectTimeout = 30,
                        int? transportConnectTimeout = 5,
                        bool enableAutoRejoiningGroups = false,
                        MessageBusType type = MessageBusType.Default)
 {
     // nothing to initialize since it is external! 
 }
Пример #20
0
 public void Unsubscribe(MessageBusType type, Action <Message> handler)
 {
     if (listeners.ContainsKey(type))
     {
         if (listeners[type] != null)
         {
             listeners[type].Remove(handler);
         }
     }
 }
Пример #21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="busType">消息总线的实现方式</param>
 /// <param name="connectionInfo"></param>
 /// <param name="receiveDic"></param>
 public MessageBusClient(
     MessageBusType busType,
     ConnectionInfo connectionInfo,
     Dictionary <string, Action <IReceiveEndpointConfigurator> > receiveDic = null)
 {
     BusType        = busType;
     ConnectionInfo = connectionInfo;
     _receiveDic    = receiveDic ?? new Dictionary <string, Action <IReceiveEndpointConfigurator> >(0);
     _sendEndpoints = new ConcurrentDictionary <string, ISendEndpoint>();
 }
Пример #22
0
        public async Task ReconnectFiresAfterHostShutdown(TransportType transportType, MessageBusType messageBusType)
        {
            var serverRestarts = 0;
            var serverReconnects = 0;

            var host = new ServerRestarter(app =>
            {
                var config = new ConnectionConfiguration
                {
                    Resolver = new DefaultDependencyResolver()
                };

                UseMessageBus(messageBusType, config.Resolver);

                app.MapSignalR<MyReconnect>("/endpoint", config);

                serverRestarts++;
                serverReconnects = 0;
                config.Resolver.Register(typeof(MyReconnect), () => new MyReconnect(() => serverReconnects++));
            });

            using (host)
            {
                using (var connection = CreateConnection("http://foo/endpoint"))
                {
                    var transport = CreateTransport(transportType, host);
                    var pollEvent = new AsyncManualResetEvent();
                    var reconnectedEvent = new AsyncManualResetEvent();

                    host.OnPoll = () =>
                    {
                        pollEvent.Set();
                    };

                    connection.Reconnected += () =>
                    {
                        reconnectedEvent.Set();
                    };

                    await connection.Start(transport);

                    // Wait for the /poll before restarting the server
                    Assert.True(await pollEvent.WaitAsync(TimeSpan.FromSeconds(15)), "Timed out waiting for poll request");

                    host.Restart();

                    Assert.True(await reconnectedEvent.WaitAsync(TimeSpan.FromSeconds(15)), "Timed out waiting for client side reconnect");

                    Assert.Equal(2, serverRestarts);
                    Assert.Equal(1, serverReconnects);
                }
            }
        }
Пример #23
0
        public void ReconnectFiresAfterHostShutdown(TransportType transportType, MessageBusType messageBusType)
        {
            var persistentConnections = new List <MyReconnect>();
            var host = new ServerRestarter(app =>
            {
                var config = new ConnectionConfiguration
                {
                    Resolver = new DefaultDependencyResolver()
                };

                UseMessageBus(messageBusType, config.Resolver);

                app.MapSignalR <MyReconnect>("/endpoint", config);

                var conn = new MyReconnect();
                config.Resolver.Register(typeof(MyReconnect), () => conn);
                persistentConnections.Add(conn);
            });

            using (host)
            {
                using (var connection = CreateConnection("http://foo/endpoint"))
                {
                    var transport        = CreateTransport(transportType, host);
                    var pollEvent        = new ManualResetEventSlim();
                    var reconnectedEvent = new ManualResetEventSlim();

                    host.OnPoll = () =>
                    {
                        pollEvent.Set();
                    };

                    connection.Reconnected += () =>
                    {
                        reconnectedEvent.Set();
                    };

                    connection.Start(transport).Wait();

                    // Wait for the /poll before restarting the server
                    Assert.True(pollEvent.Wait(TimeSpan.FromSeconds(15)), "Timed out waiting for poll request");

                    host.Restart();

                    Assert.True(reconnectedEvent.Wait(TimeSpan.FromSeconds(15)), "Timed out waiting for client side reconnect");

                    Assert.Equal(2, persistentConnections.Count);
                    Assert.Equal(1, persistentConnections[1].Reconnects);
                }
            }
        }
Пример #24
0
        public void ReconnectFiresAfterHostShutdown(TransportType transportType, MessageBusType messageBusType)
        {
            var persistentConnections = new List<MyReconnect>();
            var host = new ServerRestarter(app =>
            {
                var config = new ConnectionConfiguration
                {
                    Resolver = new DefaultDependencyResolver()
                };

                UseMessageBus(messageBusType, config.Resolver);

                app.MapSignalR<MyReconnect>("/endpoint", config);

                var conn = new MyReconnect();
                config.Resolver.Register(typeof(MyReconnect), () => conn);
                persistentConnections.Add(conn);
            });

            using (host)
            {
                using (var connection = CreateConnection("http://foo/endpoint"))
                {
                    var transport = CreateTransport(transportType, host);
                    var pollEvent = new ManualResetEventSlim();
                    var reconnectedEvent = new ManualResetEventSlim();

                    host.OnPoll = () =>
                    {
                        pollEvent.Set();
                    };

                    connection.Reconnected += () =>
                    {
                        reconnectedEvent.Set();
                    };

                    connection.Start(transport).Wait();

                    // Wait for the /poll before restarting the server
                    Assert.True(pollEvent.Wait(TimeSpan.FromSeconds(15)), "Timed out waiting for poll request");

                    host.Restart();

                    Assert.True(reconnectedEvent.Wait(TimeSpan.FromSeconds(15)), "Timed out waiting for client side reconnect");

                    Assert.Equal(2, persistentConnections.Count);
                    Assert.Equal(1, persistentConnections[1].Reconnects);
                }
            }
        }
Пример #25
0
        public override void Initialize(int?keepAlive                  = -1,
                                        int?connectionTimeout          = 110,
                                        int?disconnectTimeout          = 30,
                                        int?transportConnectTimeout    = 5,
                                        bool enableAutoRejoiningGroups = false,
                                        MessageBusType messageBusType  = MessageBusType.Default)
        {
            base.Initialize(keepAlive, connectionTimeout, disconnectTimeout, transportConnectTimeout, enableAutoRejoiningGroups, messageBusType);

            _host.Configure(app =>
            {
                Initializer.ConfigureRoutes(app, Resolver);
            });
        }
Пример #26
0
        public override void Initialize(int? keepAlive = -1,
                                        int? connectionTimeout = 110,
                                        int? disconnectTimeout = 30,
                                        int? transportConnectTimeout = 5,
                                        bool enableAutoRejoiningGroups = false,
                                        MessageBusType messageBusType = MessageBusType.Default)
        {
            base.Initialize(keepAlive, connectionTimeout, disconnectTimeout, transportConnectTimeout, enableAutoRejoiningGroups, messageBusType);

            _host.Configure(app =>
            {
                Initializer.ConfigureRoutes(app, Resolver);
            });
        }
Пример #27
0
        public void Subscribe(MessageBusType type, Action <Message> handler)
        {
            if (listeners.ContainsKey(type))
            {
                if (listeners[type] == null)
                {
                    listeners[type] = new List <Action <Message> >(20);
                }
            }
            else
            {
                listeners.Add(type, new List <Action <Message> >(20));
            }

            //print("Added handler for message " + type);
            listeners[type].Add(handler);
        }
Пример #28
0
        private IMessageBusProvider GetProvider(MessageBusType messageBusType)
        {
            try
            {
                var provider = GetProviderFromDi(messageBusType);
                if (provider != null)
                {
                    return(provider);
                }

                return(GetProviderFromConfig(messageBusType));
            }
            catch (Exception ex)
            {
                StaticLog.Warning($"An error has occurred while trying to retrieve provider for Message Bus: {ex.Message}");
                return(GetProviderFromConfig(messageBusType));
            }
        }
Пример #29
0
        /// <summary>
        /// Gets a message bus type based on the specified string <paramref name="value"/>.
        /// </summary>
        /// <param name="value">The value to convert to an message bus type (i.e., name, value or unique description).</param>
        /// <param name="result">The message bus type.</param>
        public static Boolean TryGetMessageBusType(String value, out MessageBusType result)
        {
            Int32  parsedValue;
            Object boxedValue = Int32.TryParse(value, out parsedValue) ? parsedValue : (Object)value;

            if (value.IsNullOrWhiteSpace())
            {
                result = MessageBusType.MicrosoftMessageQueuing;
                return(true);
            }

            if (Enum.IsDefined(typeof(MessageBusType), boxedValue))
            {
                result = (MessageBusType)Enum.ToObject(typeof(MessageBusType), boxedValue);
                return(true);
            }

            return(KnownMessageBusTypes.TryGetValue(value, out result));
        }
Пример #30
0
        public async Task HubProgressThrowsInvalidOperationExceptionIfAttemptToReportProgressAfterMethodReturn(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy proxy = hubConnection.CreateHubProxy("progress");
                
                proxy.On<bool>("sendProgressAfterMethodReturnResult", result => Assert.True(result));

                using (hubConnection)
                {
                    await hubConnection.Start(host.Transport);

                    await proxy.Invoke<int>("SendProgressAfterMethodReturn", _ => { });
                }
            }
        }
Пример #31
0
        /// <summary>
        /// Gets a message bus type based on the specified string <paramref name="value"/>.
        /// </summary>
        /// <param name="value">The value to convert to an message bus type (i.e., name, value or unique description).</param>
        /// <param name="result">The message bus type.</param>
        public static Boolean TryGetMessageBusType(String value, out MessageBusType result)
        {
            Int32 parsedValue;
            Object boxedValue = Int32.TryParse(value, out parsedValue) ? parsedValue : (Object)value;

            if (value.IsNullOrWhiteSpace())
            {
                result = MessageBusType.MicrosoftMessageQueuing;
                return true;
            }

            if (Enum.IsDefined(typeof(MessageBusType), boxedValue))
            {
                result = (MessageBusType)Enum.ToObject(typeof(MessageBusType), boxedValue);
                return true;
            }

            return KnownMessageBusTypes.TryGetValue(value, out result);
        }
Пример #32
0
        public override void Initialize(int? keepAlive = -1,
                                        int? connectionTimeout = 110,
                                        int? disconnectTimeout = 30,
                                        int? transportConnectTimeout = 5,
                                        int? maxIncomingWebSocketMessageSize = 64 * 1024,
                                        bool enableAutoRejoiningGroups = false,
                                        MessageBusType messageBusType = MessageBusType.Default)
        {
            base.Initialize(keepAlive,
                            connectionTimeout,
                            disconnectTimeout,
                            transportConnectTimeout,
                            maxIncomingWebSocketMessageSize,
                            enableAutoRejoiningGroups,
                            messageBusType);

            _server = WebApp.Start(Url, app =>
            {
                Initializer.ConfigureRoutes(app, Resolver);
            });
        }
Пример #33
0
        public override void Initialize(int?keepAlive                       = -1,
                                        int?connectionTimeout               = 110,
                                        int?disconnectTimeout               = 30,
                                        int?transportConnectTimeout         = 5,
                                        int?maxIncomingWebSocketMessageSize = 64 * 1024,
                                        bool enableAutoRejoiningGroups      = false,
                                        MessageBusType messageBusType       = MessageBusType.Default)
        {
            base.Initialize(keepAlive,
                            connectionTimeout,
                            disconnectTimeout,
                            transportConnectTimeout,
                            maxIncomingWebSocketMessageSize,
                            enableAutoRejoiningGroups,
                            messageBusType);

            _server = WebApp.Start(Url, app =>
            {
                Initializer.ConfigureRoutes(app, Resolver);
            });
        }
Пример #34
0
        public async Task HubProgressIsReportedSuccessfully(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy proxy = hubConnection.CreateHubProxy("progress");
                var progressUpdates = new List<int>();
                var jobName = "test";

                using (hubConnection)
                {    
                    await hubConnection.Start(host.Transport);

                    var result = await proxy.Invoke<string, int>("DoLongRunningJob", progress => progressUpdates.Add(progress), jobName);

                    Assert.Equal(new[] { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }, progressUpdates);
                    Assert.Equal(String.Format("{0} done!", jobName), result);
                }
            }
        }
Пример #35
0
        public void ReadingState(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection connection = CreateHubConnection(host);

                using (connection)
                {
                    var hub = connection.CreateHubProxy("demo");

                    hub["name"] = "test";

                    connection.Start(host.Transport).Wait();

                    var result = hub.InvokeWithTimeout<string>("ReadStateValue");

                    Assert.Equal("test", result);
                }
            }
        }
Пример #36
0
        public void TransportTimesOutIfNoInitMessage(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            var mre = new ManualResetEventSlim();

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(transportConnectTimeout: 1, messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy proxy = hubConnection.CreateHubProxy("DelayedOnConnectedHub");

                using (hubConnection)
                {
                    hubConnection.Start(host.Transport).Catch(ex =>
                    {
                        mre.Set();
                    });

                    Assert.True(mre.Wait(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #37
0
        public void ReadingComplexState(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var hub = connection.CreateHubProxy("demo");

                    hub["state"] = JToken.FromObject(new
                    {
                        Name = "David",
                        Address = new
                        {
                            Street = "St"
                        }
                    });

                    connection.Start(host.Transport).Wait();

                    var result = hub.InvokeWithTimeout<dynamic>("ReadAnyState");
                    dynamic state2 = hub["state2"];
                    dynamic addy = hub["addy"];

                    Assert.NotNull(result);
                    Assert.NotNull(state2);
                    Assert.NotNull(addy);
                    Assert.Equal("David", (string)result.Name);
                    Assert.Equal("St", (string)result.Address.Street);
                    Assert.Equal("David", (string)state2.Name);
                    Assert.Equal("St", (string)state2.Address.Street);
                    Assert.Equal("St", (string)addy.Street);
                }
            }
        }
Пример #38
0
        public async Task CannotInvokeMethodsAndReceiveMessagesFromInvalidTypedHub(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                using (var connection = CreateHubConnection(host))
                {
                    var hub = connection.CreateHubProxy("InvalidTypedHub");
                    var tcs = new TaskCompletionSource<string>();

                    await connection.Start(host.TransportFactory());

                    var ex = Assert.Throws<AggregateException>(() => hub.InvokeWithTimeout("Echo", "arbitrary message"));
                    Assert.Equal(1, ex.InnerExceptions.Count);
                    Assert.IsType<InvalidOperationException>(ex.InnerExceptions[0]);

                    ex = Assert.Throws<AggregateException>(() => hub.InvokeWithTimeout("Ping"));
                    Assert.Equal(1, ex.InnerExceptions.Count);
                    Assert.IsType<InvalidOperationException>(ex.InnerExceptions[0]);
                }
            }
        }
Пример #39
0
        public void TransportCanJoinGroupInOnConnected(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy     proxy         = hubConnection.CreateHubProxy("GroupJoiningHub");
                int           pingCount     = 0;

                using (hubConnection)
                {
                    var wh = new ManualResetEvent(false);

                    proxy.On("ping", () =>
                    {
                        if (++pingCount == 2)
                        {
                            wh.Set();
                        }

                        Assert.True(pingCount <= 2);
                    });

                    hubConnection.Start(host.Transport).Wait();

                    proxy.Invoke("PingGroup").Catch();

                    Assert.True(wh.WaitOne(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #40
0
        public void TransportsBufferMessagesCorrectly(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection   = CreateHubConnection(host);
                IHubProxy     proxy           = hubConnection.CreateHubProxy("OnConnectedBufferHub");
                var           bufferCountdown = new OrderedCountDownRange <int>(new[] { 0, 1 });
                int           bufferMeCalls   = 0;

                using (hubConnection)
                {
                    var wh = new ManualResetEvent(false);

                    proxy.On("pong", () =>
                    {
                        Assert.Equal(2, bufferMeCalls);

                        wh.Set();
                    });

                    proxy.On <int>("bufferMe", (val) =>
                    {
                        // Ensure correct ordering of the buffered messages
                        Assert.True(bufferCountdown.Expect(val));
                        bufferMeCalls++;
                        Assert.Equal(hubConnection.State, ConnectionState.Connected);
                    });

                    hubConnection.Start(host.Transport).Wait();

                    Assert.Equal(2, bufferMeCalls);

                    proxy.Invoke("Ping").Catch();

                    Assert.True(wh.WaitOne(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #41
0
            public void ReceivePreserializedJson(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/preserialize");
                    var tcs = new TaskCompletionSource<string>();

                    connection.Received += json =>
                    {
                        tcs.TrySetResult(json);
                    };

                    using (connection)
                    {
                        connection.Start(host.Transport).Wait();

                        connection.SendWithTimeout(new { preserialized = true });

                        Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(5)));
                        var json = JObject.Parse(tcs.Task.Result);
                        Assert.True((bool)json["preserialized"]);
                    }
                }
            }
Пример #42
0
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.IISExpress, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.Websockets, MessageBusType.Default)]
        public async Task ConnectionDisposeTriggersStop(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);
                var connection = CreateConnection(host, "/signalr");

                using (connection)
                {
                    await connection.Start(host.Transport);

                    Assert.Equal(connection.State, Client.ConnectionState.Connected);
                }

                Assert.Equal(connection.State, Client.ConnectionState.Disconnected);
            }
        }
Пример #43
0
        public void ConnectionFailsStartOnMultipleTransportTimeouts(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            var mre = new ManualResetEventSlim();

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(transportConnectTimeout: 1, messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy     proxy         = hubConnection.CreateHubProxy("DelayedOnConnectedHub");

                using (hubConnection)
                {
                    hubConnection.Start(host.Transport).Catch(ex =>
                    {
                        mre.Set();
                    });

                    var transport = hubConnection.Transport;

                    // Should take 1-2s per transport timeout
                    Assert.True(mre.Wait(TimeSpan.FromSeconds(15)));
                    Assert.True(String.IsNullOrEmpty(transport.Name));
                }
            }
        }
Пример #44
0
        public void RequestHeadersSetCorrectly(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);

                using (hubConnection)
                {
                    IHubProxy proxy = hubConnection.CreateHubProxy("ExamineHeadersHub");
                    var       tcs   = new TaskCompletionSource <object>();

                    proxy.On("sendHeader", headers =>
                    {
                        Assert.Equal("test-header", (string)headers.testHeader);
                        if (transportType != TransportType.Websockets)
                        {
                            Assert.Equal("referer", (string)headers.refererHeader);
                        }
                        tcs.TrySetResult(null);
                    });

                    hubConnection.Error += e => tcs.TrySetException(e);

                    hubConnection.Headers.Add("test-header", "test-header");
                    if (transportType != TransportType.Websockets)
                    {
                        hubConnection.Headers.Add(System.Net.HttpRequestHeader.Referer.ToString(), "referer");
                    }

                    hubConnection.Start(host.Transport).Wait();
                    proxy.Invoke("Send").Catch();

                    Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #45
0
        public void UnableToCreateHubThrowsError(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);

                using (hubConnection)
                {
                    IHubProxy proxy = hubConnection.CreateHubProxy("MyHub2");

                    hubConnection.Start(host.Transport).Wait();
                    var ex = Assert.Throws <AggregateException>(() => proxy.InvokeWithTimeout("Send", "hello"));
                }
            }
        }
Пример #46
0
            public void SendCanBeCalledAfterStateChangedEvent(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/multisend");
                    var results = new List<string>();
                    connection.Received += data =>
                    {
                        results.Add(data);
                    };

                    connection.StateChanged += stateChange =>
                    {
                        if (stateChange.NewState == Client.ConnectionState.Connected)
                        {
                            connection.SendWithTimeout("");
                        }
                    };

                    connection.Start(host.Transport).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Debug.WriteLine(String.Join(", ", results));

                    Assert.Equal(4, results.Count);
                }
            }
Пример #47
0
            public void SendRaisesOnReceivedFromAllEvents(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/multisend");
                    var results = new List<string>();
                    connection.Received += data =>
                    {
                        results.Add(data);
                    };

                    connection.Start(host.Transport).Wait();
                    connection.SendWithTimeout("");

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Debug.WriteLine(String.Join(", ", results));

                    Assert.Equal(4, results.Count);
                    Assert.Equal("OnConnectedAsync1", results[0]);
                    Assert.Equal("OnConnectedAsync2", results[1]);
                    Assert.Equal("OnReceivedAsync1", results[2]);
                    Assert.Equal("OnReceivedAsync2", results[3]);
                }
            }
Пример #48
0
        public void TransportTimesOutIfNoInitMessage(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            var mre = new ManualResetEventSlim();

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(transportConnectTimeout: 1, messageBusType: messageBusType);

                HubConnection hubConnection = CreateHubConnection(host);
                IHubProxy     proxy         = hubConnection.CreateHubProxy("DelayedOnConnectedHub");

                using (hubConnection)
                {
                    hubConnection.Start(host.Transport).Catch(ex =>
                    {
                        mre.Set();
                    });

                    Assert.True(mre.Wait(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #49
0
            // [InlineData(HostType.IISExpress, TransportType.LongPolling)]
            public void ReconnectFiresAfterHostShutDown(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/my-reconnect");

                    using (connection)
                    {
                        connection.Start(host.Transport).Wait();

                        host.Shutdown();

                        Thread.Sleep(TimeSpan.FromSeconds(5));

                        Assert.Equal(Client.ConnectionState.Reconnecting, connection.State);
                    }
                }
            }
Пример #50
0
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.IISExpress, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.LongPolling, MessageBusType.Default)]
        public void ConnectionFunctionsCorrectlyAfterCallingStartMutlipleTimes(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);

                using (var connection = CreateConnection(host, "/echo"))
                {
                    var tcs = new TaskCompletionSource <object>();
                    connection.Received += _ => tcs.TrySetResult(null);

                    // We're purposely calling Start().Wait() twice here
                    connection.Start(host.TransportFactory()).Wait();
                    connection.Start(host.TransportFactory()).Wait();

                    connection.Send("test").Wait();

                    // Wait for message to be received
                    Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(10)));
                }
            }
        }
Пример #51
0
        public void ConnectionErrorCapturesExceptionsThrownInClientHubMethod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                var       wh     = new ManualResetEventSlim();
                Exception thrown = new Exception(),
                          caught = null;

                host.Initialize(messageBusType: messageBusType);

                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var proxy = connection.CreateHubProxy("ChatHub");

                    proxy.On <string>("addMessage", (message) =>
                    {
                        throw thrown;
                    });

                    connection.Error += e =>
                    {
                        caught = e;
                        wh.Set();
                    };

                    connection.Start(host.Transport).Wait();
                    proxy.Invoke("Send", "").Catch();

                    Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
                    Assert.Equal(thrown, caught);
                }
            }
        }
Пример #52
0
            public void ReconnectDoesntFireAfterTimeOut(TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = new MemoryHost())
                {
                    var conn = new MyReconnect();
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        UseMessageBus(messageBusType, config.Resolver);

                        app.MapSignalR<MyReconnect>("/endpoint", config);
                        var configuration = config.Resolver.Resolve<IConfigurationManager>();
                        configuration.DisconnectTimeout = TimeSpan.FromSeconds(6);
                        configuration.ConnectionTimeout = TimeSpan.FromSeconds(2);
                        configuration.KeepAlive = null;

                        config.Resolver.Register(typeof(MyReconnect), () => conn);
                    });

                    var connection = new Client.Connection("http://foo/endpoint");
                    var transport = CreateTransport(transportType, host);
                    connection.Start(transport).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(0, conn.Reconnects);
                }
            }
Пример #53
0
        public void RequestHeadersCanBeSetOnceConnected(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                // Arrange
                host.Initialize(messageBusType: messageBusType);
                HubConnection hubConnection = CreateHubConnection(host);
                var           mre           = new ManualResetEventSlim();

                using (hubConnection)
                {
                    IHubProxy proxy = hubConnection.CreateHubProxy("ExamineHeadersHub");

                    proxy.On("sendHeader", headers =>
                    {
                        Assert.Equal("test-header", (string)headers.testHeader);
                        mre.Set();
                    });

                    hubConnection.Start(host.Transport).Wait();

                    hubConnection.Headers.Add("test-header", "test-header");
                    proxy.Invoke("Send").Catch();
                    Assert.True(mre.Wait(TimeSpan.FromSeconds(5)));
                }
            }
        }
Пример #54
0
            // [InlineData(HostType.IISExpress, TransportType.Websockets)]
            public void GroupsReceiveMessages(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/groups");
                    var list = new List<string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.SendWithTimeout(new { type = 1, group = "test" });

                    // Sent a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "hello to group test" });

                    // Leave the group
                    connection.SendWithTimeout(new { type = 2, group = "test" });

                    for (int i = 0; i < 10; i++)
                    {
                        // Send a message
                        connection.SendWithTimeout(new { type = 3, group = "test", message = "goodbye to group test" });
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(1, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                }
            }
Пример #55
0
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.IISExpress, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.Websockets, MessageBusType.Default)]
        public void ReconnectExceedingReconnectWindowDisconnects(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            // Test cannot be async because if we do host.ShutDown() after an await the connection stops.

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var reconnectWh  = new ManualResetEventSlim();
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Reconnecting += () =>
                    {
                        ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromMilliseconds(500);
                        reconnectWh.Set();
                    };

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    connection.Start(host.Transport).Wait();

                    // Without this the connection start and reconnect can race with eachother resulting in a deadlock.
                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    host.Shutdown();

                    Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(15)), "Reconnect never fired");
                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Пример #56
0
            public void GroupsRejoinedWhenOnRejoiningGroupsOverridden(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: null,
                                    disconnectTimeout: 6,
                                    connectionTimeout: 2,
                                    messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/rejoin-groups");

                    var list = new List<string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.SendWithTimeout(new { type = 1, group = "test" });

                    // Sent a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "hello to group test" });

                    // Force Reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    // Send a message
                    connection.SendWithTimeout(new { type = 3, group = "test", message = "goodbye to group test" });

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(2, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                    Assert.Equal("goodbye to group test", list[1]);
                }
            }
Пример #57
0
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.IISExpress, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.Websockets, MessageBusType.Default)]
        public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    connection.Start(host.Transport).Wait();

                    // The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect.
                    ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1);

                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Пример #58
0
            public void SendToAllButCaller(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection1 = CreateConnection(host, "/filter");
                    var connection2 = CreateConnection(host, "/filter");

                    using (connection1)
                    using (connection2)
                    {
                        var wh1 = new ManualResetEventSlim(initialState: false);
                        var wh2 = new ManualResetEventSlim(initialState: false);

                        connection1.Received += data => wh1.Set();
                        connection2.Received += data => wh2.Set();

                        connection1.Start(host.TransportFactory()).Wait();
                        connection2.Start(host.TransportFactory()).Wait();

                        connection1.SendWithTimeout("test");

                        Assert.False(wh1.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));
                        Assert.True(wh2.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));
                    }
                }
            }
Пример #59
0
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.ServerSentEvents, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.Fake)]
        //[InlineData(HostType.Memory, TransportType.LongPolling, MessageBusType.FakeMultiStream)]
        //[InlineData(HostType.IISExpress, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.ServerSentEvents, MessageBusType.Default)]
        //[InlineData(HostType.IISExpress, TransportType.Websockets, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.LongPolling, MessageBusType.Default)]
        //[InlineData(HostType.HttpListener, TransportType.ServerSentEvents, MessageBusType.Default)]
        public void ReconnectExceedingReconnectWindowDisconnectsWithFastBeatInterval(HostType hostType, TransportType transportType, MessageBusType messageBusType)
        {
            // Test cannot be async because if we do host.ShutDown() after an await the connection stops.

            using (var host = CreateHost(hostType, transportType))
            {
                host.Initialize(keepAlive: 9, messageBusType: messageBusType);
                var connection = CreateHubConnection(host);

                using (connection)
                {
                    var disconnectWh = new ManualResetEventSlim();

                    connection.Closed += () =>
                    {
                        disconnectWh.Set();
                    };

                    SetReconnectDelay(host.Transport, TimeSpan.FromSeconds(15));

                    connection.Start(host.Transport).Wait();

                    // Without this the connection start and reconnect can race with eachother resulting in a deadlock.
                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    // Set reconnect window to zero so the second we attempt to reconnect we can ensure that the reconnect window is verified.
                    ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(0);

                    host.Shutdown();

                    Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
                }
            }
        }
Пример #60
0
            public void SendWithSyncErrorThrows(HostType hostType, TransportType transportType, MessageBusType messageBusType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(messageBusType: messageBusType);

                    var connection = CreateConnection(host, "/sync-error");

                    using (connection)
                    {
                        connection.Start(host.Transport).Wait();

                        Assert.Throws<AggregateException>(() => connection.SendWithTimeout("test"));
                    }
                }
            }