Configure() public method

public Configure ( Action startup ) : void
startup Action
return void
        public async Task SendToGroupFromOutsideOfHub()
        {
            using (var host = new MemoryHost())
            {
                IHubContext<IBasicClient> hubContext = null;
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    app.MapSignalR(configuration);
                    hubContext = configuration.Resolver.Resolve<IConnectionManager>().GetHubContext<SendToSome, IBasicClient>();
                });

                var connection1 = new HubConnection("http://foo/");

                using (connection1)
                {
                    var wh1 = new AsyncManualResetEvent(initialState: false);

                    var hub1 = connection1.CreateHubProxy("SendToSome");

                    await connection1.Start(host);

                    hub1.On("send", wh1.Set);

                    hubContext.Groups.Add(connection1.ConnectionId, "Foo").Wait();
                    hubContext.Clients.Group("Foo").send();

                    Assert.True(await wh1.WaitAsync(TimeSpan.FromSeconds(10)));
                }
            }
        }
Example #2
0
        public void AuthenticatedAndAuthorizedUserCanInvokeMethodsInHubsAuthorizedSpecifyingUserAndRole()
        {
            using (var host = new MemoryHost())
            {
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    WithUser(app, new GenericPrincipal(new GenericIdentity("User"), new string[] { "Admin" }));
                    app.MapHubs("/signalr", configuration);
                });

                var connection = CreateHubConnection("http://foo/");

                var hub = connection.CreateHubProxy("UserAndRoleAuthHub");
                var wh = new ManualResetEvent(false);
                hub.On<string, string>("invoked", (id, time) =>
                {
                    Assert.NotNull(id);
                    wh.Set();
                });

                connection.Start(host).Wait();

                hub.InvokeWithTimeout("InvokedFromClient");

                Assert.True(wh.WaitOne(TimeSpan.FromSeconds(3)));
                connection.Stop();
            }
        }
Example #3
0
        public async Task AuthenticatedUserCanReceiveHubMessagesByDefault()
        {
            using (var host = new MemoryHost())
            {
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    WithUser(app, new GenericPrincipal(new GenericIdentity("test"), new string[] { }));
                    app.MapSignalR("/signalr", configuration);

                });

                var connection = CreateHubConnection("http://foo/");

                using (connection)
                {
                    var hub = connection.CreateHubProxy("NoAuthHub");
                    var wh = new ManualResetEvent(false);
                    hub.On<string, string, object>("joined", (id, time, authInfo) =>
                    {
                        Assert.NotNull(id);
                        wh.Set();
                    });

                    await connection.Start(host);

                    Assert.True(wh.WaitOne(TimeSpan.FromSeconds(3)));
                }
            }
        }
Example #4
0
        public static IDisposable StressGroups(int max = 100)
        {
            var host = new MemoryHost();
            host.Configure(app =>
            {
                var config = new HubConfiguration()
                {
                    Resolver = new DefaultDependencyResolver()
                };

                app.MapSignalR(config);

                var configuration = config.Resolver.Resolve<IConfigurationManager>();
                // The below effectively sets the heartbeat interval to five seconds.
                configuration.KeepAlive = TimeSpan.FromSeconds(10);
            });

            var countDown = new CountDownRange<int>(Enumerable.Range(0, max));
            var connection = new HubConnection("http://foo");
            var proxy = connection.CreateHubProxy("HubWithGroups");

            proxy.On<int>("Do", i =>
            {
                if (!countDown.Mark(i))
                {
                    Debugger.Break();
                }
            });

            try
            {
                connection.Start(new Client.Transports.LongPollingTransport(host)).Wait();

                proxy.Invoke("Join", "foo").Wait();

                for (int i = 0; i < max; i++)
                {
                    proxy.Invoke("Send", "foo", i).Wait();
                }

                proxy.Invoke("Leave", "foo").Wait();

                for (int i = max + 1; i < max + 50; i++)
                {
                    proxy.Invoke("Send", "foo", i).Wait();
                }

                if (!countDown.Wait(TimeSpan.FromSeconds(10)))
                {
                    Console.WriteLine("Didn't receive " + max + " messages. Got " + (max - countDown.Count) + " missed " + String.Join(",", countDown.Left.Select(i => i.ToString())));
                    Debugger.Break();
                }
            }
            finally
            {
                connection.Stop();
            }

            return host;
        }
            public void ConnectionsWithTheSameConnectionIdLongPollingCloseGracefully()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyGroupEchoConnection>("/echo", config);

                        config.Resolver.Register(typeof(IProtectedData), () => new EmptyProtectedData());
                    });

                    string id = Guid.NewGuid().ToString("d");

                    var tasks = new List<Task>();

                    for (int i = 0; i < 1000; i++)
                    {
                        tasks.Add(ProcessRequest(host, "longPolling", id));
                    }

                    ProcessRequest(host, "longPolling", id);

                    Task.WaitAll(tasks.ToArray());

                    Assert.True(tasks.All(t => !t.IsFaulted));
                }
            }
Example #6
0
        public static IDisposable BrodcastFromServer()
        {
            var host = new MemoryHost();
            IHubContext context = null;

            host.Configure(app =>
            {
                var config = new HubConfiguration()
                {
                    Resolver = new DefaultDependencyResolver()
                };

                app.MapHubs(config);

                var configuration = config.Resolver.Resolve<IConfigurationManager>();
                // The below effectively sets the heartbeat interval to five seconds.
                configuration.KeepAlive = TimeSpan.FromSeconds(10);

                var connectionManager = config.Resolver.Resolve<IConnectionManager>();
                context = connectionManager.GetHubContext("EchoHub");
            });

            var cancellationTokenSource = new CancellationTokenSource();

            var thread = new Thread(() =>
            {
                while (!cancellationTokenSource.IsCancellationRequested)
                {
                    context.Clients.All.echo();
                }
            });

            thread.Start();

            var connection = new Client.Hubs.HubConnection("http://foo");
            var proxy = connection.CreateHubProxy("EchoHub");

            try
            {
                connection.Start(host).Wait();

                Thread.Sleep(1000);
            }
            finally
            {
                connection.Stop();
            }

            return new DisposableAction(() =>
            {
                cancellationTokenSource.Cancel();

                thread.Join();

                host.Dispose();
            });
        }
Example #7
0
        public static IDisposable Run(int connections, int senders, string payload, string transport)
        {
            var host = new MemoryHost();

            host.Configure(app =>
            {
                app.MapConnection<StressConnection>("/echo");
            });

            var countDown = new CountdownEvent(senders);
            var cancellationTokenSource = new CancellationTokenSource();

            for (int i = 0; i < connections; i++)
            {
                if (transport.Equals("longPolling", StringComparison.OrdinalIgnoreCase))
                {
                    ThreadPool.QueueUserWorkItem(state =>
                    {
                        string connectionId = state.ToString();
                        LongPollingLoop(host, connectionId);

                    }, i);
                }
                else
                {
                    string connectionId = i.ToString();
                    ProcessRequest(host, transport, connectionId);
                }
            }

            for (var i = 0; i < senders; i++)
            {
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    while (!cancellationTokenSource.IsCancellationRequested)
                    {
                        string connectionId = i.ToString();
                        ProcessSendRequest(host, transport, connectionId, payload);
                    }

                    countDown.Signal();
                });
            }

            return new DisposableAction(() =>
            {
                cancellationTokenSource.Cancel();

                // Wait for all senders to stop
                countDown.Wait(TimeSpan.FromMilliseconds(1000 * senders));

                host.Dispose();
            });
        }
Example #8
0
        public void NoReconnectsAfterFallback()
        {
            // There was a regression where the SSE transport would try to reconnect after it times out.
            // This test ensures that no longer happens.
            // #2180
            using (var host = new MemoryHost())
            {
                var myReconnect = new MyReconnect();

                host.Configure(app =>
                {
                    Func<AppFunc, AppFunc> middleware = (next) =>
                    {
                        return env =>
                        {
                            var request = new OwinRequest(env);
                            var response = new OwinResponse(env);

                            if (!request.Path.Value.Contains("negotiate") && !request.QueryString.Value.Contains("longPolling"))
                            {
                                response.Body = new MemoryStream();
                            }

                            return next(env);
                        };
                    };

                    app.Use(middleware);

                    var config = new ConnectionConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

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

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

                var connection = new Connection("http://foo/echo");

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

                    // Give SSE an opportunity to reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    Assert.Equal(connection.State, ConnectionState.Connected);
                    Assert.Equal(connection.Transport.Name, "longPolling");
                    Assert.Equal(0, myReconnect.Reconnects);
                }
            }
        }
Example #9
0
            public async Task InitMessageSentToFallbackTransports()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        Func<AppFunc, AppFunc> middleware = (next) =>
                        {
                            return env =>
                            {
                                var request = new OwinRequest(env);
                                var response = new OwinResponse(env);

                                if (!request.Path.Value.Contains("negotiate") && !request.QueryString.Value.Contains("longPolling"))
                                {
                                    response.Body = new MemoryStream();
                                }

                                return next(env);
                            };
                        };

                        app.Use(middleware);

                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyConnection>("/echo", config);
                    });

                    var connection = new Connection("http://foo/echo");

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

                        Assert.Equal(connection.State, ConnectionState.Connected);
                        Assert.Equal(connection.Transport.Name, "longPolling");
                    }
                }
            }
Example #10
0
        public void DisconnectFiresForHubsWhenConnectionGoesAway()
        {
            using (var host = new MemoryHost())
            {
                var dr = new DefaultDependencyResolver();
                var configuration = dr.Resolve<IConfigurationManager>();

                var connectWh = new ManualResetEventSlim();
                var disconnectWh = new ManualResetEventSlim();
                host.Configure(app =>
                {
                    var config = new HubConfiguration
                    {
                        Resolver = dr
                    };

                    app.MapHubs("/signalr", config);

                    configuration.DisconnectTimeout = TimeSpan.Zero;
                    configuration.HeartbeatInterval = TimeSpan.FromSeconds(5);
                    dr.Register(typeof(MyHub), () => new MyHub(connectWh, disconnectWh));
                });

                var connection = new Client.Hubs.HubConnection("http://foo/");

                connection.CreateHubProxy("MyHub");

                // Maximum wait time for disconnect to fire (3 heart beat intervals)
                var disconnectWait = TimeSpan.FromTicks(configuration.HeartbeatInterval.Ticks * 3);

                connection.Start(host).Wait();

                Assert.True(connectWh.Wait(TimeSpan.FromSeconds(10)), "Connect never fired");

                connection.Stop();

                Assert.True(disconnectWh.Wait(disconnectWait), "Disconnect never fired");
            }
        }
Example #11
0
            public async Task ConnectionCanStartWithAuthenicatedUserAndQueryString()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        Func<AppFunc, AppFunc> middleware = (next) =>
                        {
                            return env =>
                            {
                                if (((string)env["owin.RequestQueryString"]).IndexOf("access_token") == -1)
                                {
                                    return next(env);
                                }

                                var user = new CustomPrincipal
                                {
                                    Name = "Bob",
                                    IsAuthenticated = true,
                                    Roles = new[] { "User" }
                                };

                                env["server.User"] = user;

                                return next(env);
                            };
                        };

                        app.Use(middleware);

                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyAuthenticatedConnection>("/authenticatedConnection", config);

                    });

                    var connection = new Connection("http://foo/authenticatedConnection", "access_token=1234");

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

                        Assert.Equal(connection.State, ConnectionState.Connected);
                    }
                }
            }
Example #12
0
            public async Task PrefixMatchingIsNotGreedyExactMatch()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyConnection>("/echo", config);
                        app.MapSignalR<MyConnection2>("/echo2", config);
                    });

                    var tcs = new TaskCompletionSource<string>();
                    var mre = new AsyncManualResetEvent();
                    var connection = new Connection("http://foo/echo");

                    using (connection)
                    {
                        connection.Received += data =>
                        {
                            tcs.TrySetResult(data);
                            mre.Set();
                        };

                        await connection.Start(host);
                        var ignore = connection.Send("");

                        Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10)));
                        Assert.Equal("MyConnection", tcs.Task.Result);
                    }
                }
            }
Example #13
0
            public async Task ConnectionErrorCapturesExceptionsThrownWhenReceivingResponseFromSend()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<TransportResponse>("/transport-response", config);
                    });

                    var transports = new List<IClientTransport>()
                    {
                        new ServerSentEventsTransport(host),
                        new LongPollingTransport(host)
                    };

                    foreach (var transport in transports)
                    {
                        Debug.WriteLine("Transport: {0}", (object)transport.Name);

                        var wh = new AsyncManualResetEvent();
                        Exception thrown = new InvalidOperationException(),
                                  caught = null;

                        var connection = new Connection("http://foo/transport-response");

                        using (connection)
                        {
                            connection.Received += data =>
                            {
                                throw thrown;
                            };

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

                            await connection.Start(transport);
                            var ignore = connection.Send("");

                            Assert.True(await wh.WaitAsync(TimeSpan.FromSeconds(5)));
                            Assert.Equal(thrown, caught);
                        }
                    }
                }
            }
Example #14
0
            public async Task ConnectionUsesClientSetTransportConnectTimeout()
            {
                TimeSpan defaultTransportConnectTimeout = TimeSpan.Zero;
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        defaultTransportConnectTimeout = config.Resolver.Resolve<IConfigurationManager>().TransportConnectTimeout;

                        app.MapSignalR<MyConnection>("/echo", config);
                    });

                    var tcs = new TaskCompletionSource<string>();
                    var connection = new Connection("http://foo/echo");
                    var newTimeout = TimeSpan.FromSeconds(4);

                    using (connection)
                    {
                        Assert.Equal(((IConnection)connection).TotalTransportConnectTimeout, TimeSpan.Zero);
                        connection.TransportConnectTimeout = newTimeout;
                        await connection.Start(host);
                        Assert.Equal(((IConnection)connection).TotalTransportConnectTimeout - defaultTransportConnectTimeout, newTimeout);
                    }
                }
            }
Example #15
0
        public static IDisposable RunConnectDisconnect(int connections)
        {
            var host = new MemoryHost();

            host.Configure(app =>
            {
                var config = new HubConfiguration()
                {
                    Resolver = new DefaultDependencyResolver()
                };
                app.MapHubs(config);
            });

            for (int i = 0; i < connections; i++)
            {
                var connection = new Client.Hubs.HubConnection("http://foo");
                var proxy = connection.CreateHubProxy("EchoHub");
                var wh = new ManualResetEventSlim(false);

                proxy.On("echo", _ => wh.Set());

                try
                {
                    connection.Start(host).Wait();

                    proxy.Invoke("Echo", "foo").Wait();

                    if (!wh.Wait(TimeSpan.FromSeconds(10)))
                    {
                        Debugger.Break();
                    }
                }
                finally
                {
                    connection.Stop();
                }
            }

            return host;
        }
Example #16
0
        public async Task UnauthenticatedUserCannotInvokeMethodsInIncomingAuthorizedHubs()
        {
            using (var host = new MemoryHost())
            {
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    WithUser(app, new GenericPrincipal(new GenericIdentity(""), new string[] { "User", "NotAdmin" }));
                    app.MapSignalR("/signalr", configuration);
                });

                var connection = CreateHubConnection("http://foo/");

                using (connection)
                {
                    var hub = connection.CreateHubProxy("IncomingAuthHub");
                    var wh = new ManualResetEvent(false);
                    hub.On<string, string>("invoked", (id, time) =>
                    {
                        Assert.NotNull(id);
                        wh.Set();
                    });

                    await connection.Start(host);

                    Assert.Throws<AggregateException>(() => hub.InvokeWithTimeout("InvokedFromClient"));

                    Assert.False(wh.WaitOne(TimeSpan.FromSeconds(3)));
                }
            }
        }
Example #17
0
 public void Restart()
 {
     lock (_lockobj)
     {
         Dispose();
         _server = new MemoryHost();
         // Ensure that all servers have the same instance name so tokens can be successfully unprotected
         _server.InstanceName = "ServerRestarter";
         _server.Configure(_startup);
     }
 }
Example #18
0
            public void ConnectionErrorCapturesExceptionsThrownWhenReceivingResponseFromSend()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        app.MapConnection<TransportResponse>("/transport-response");
                    });

                    var transports = new List<IClientTransport>()
                    {
                        new ServerSentEventsTransport(host),
                        new LongPollingTransport(host)
                    };

                    foreach (var transport in transports)
                    {
                        Debug.WriteLine("Transport: {0}", (object)transport.Name);

                        var wh = new ManualResetEventSlim();
                        Exception thrown = new Exception(),
                                  caught = null;

                        var connection = new Connection("http://foo/transport-response");

                        connection.Received += data =>
                        {
                            throw thrown;
                        };

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

                        connection.Start(transport).Wait();
                        connection.Send("");

                        Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
                        Assert.IsType(typeof(AggregateException), caught);
                        Assert.Equal(thrown, caught.InnerException);
                    }
                }
            }
Example #19
0
        public static IDisposable ManyUniqueGroups(int concurrency)
        {
            var host = new MemoryHost();
            var threads = new List<Thread>();
            var cancellationTokenSource = new CancellationTokenSource();

            host.Configure(app =>
            {
                var config = new HubConfiguration()
                {
                    Resolver = new DefaultDependencyResolver()
                };
                app.MapHubs(config);
            });

            for (int i = 0; i < concurrency; i++)
            {
                var thread = new Thread(_ =>
                {
                    while (!cancellationTokenSource.IsCancellationRequested)
                    {
                        RunOne(host);
                    }
                });

                threads.Add(thread);
                thread.Start();
            }

            return new DisposableAction(() =>
            {
                cancellationTokenSource.Cancel();

                threads.ForEach(t => t.Join());

                host.Dispose();
            });
        }
Example #20
0
            public void PrefixMatchingIsNotGreedyNotStartingWithSlashes()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        app.MapConnection<MyConnection>("echo");
                        app.MapConnection<MyConnection2>("echo2");
                    });

                    var tcs = new TaskCompletionSource<string>();
                    var connection = new Connection("http://foo/echo2");

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

                    connection.Start(host).Wait();
                    connection.Send("");

                    Assert.Equal("MyConnection2", tcs.Task.Result);
                }
            }
Example #21
0
        public async Task AuthenticatedUserCanInvokeMethodsWhenAuthenticationRequiredGlobally()
        {
            using (var host = new MemoryHost())
            {
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    configuration.Resolver.Resolve<IHubPipeline>().RequireAuthentication();

                    WithUser(app, new GenericPrincipal(new GenericIdentity("test"), new string[] { }));
                    app.MapSignalR("/signalr", configuration);
                });

                var connection = CreateHubConnection("http://foo/");

                using (connection)
                {
                    var hub = connection.CreateHubProxy("NoAuthHub");
                    var wh = new ManualResetEvent(false);
                    hub.On<string, string>("invoked", (id, time) =>
                    {
                        Assert.NotNull(id);
                        wh.Set();
                    });

                    await connection.Start(host);

                    hub.InvokeWithTimeout("InvokedFromClient");

                    Assert.True(wh.WaitOne(TimeSpan.FromSeconds(3)));
                }
            }
        }
Example #22
0
        public void UnauthenticatedUserCannotInvokeMethodsWhenAuthenticationRequiredGlobally()
        {
            using (var host = new MemoryHost())
            {
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    configuration.Resolver.Resolve<IHubPipeline>().RequireAuthentication();

                    WithUser(app, new GenericPrincipal(new GenericIdentity(""), new string[] { }));
                    app.MapSignalR("/signalr", configuration);
                });

                var connection = CreateHubConnection("http://foo/");

                using (connection)
                {
                    var hub = connection.CreateHubProxy("NoAuthHub");
                    var wh = new ManualResetEvent(false);
                    hub.On<string, string>("invoked", (id, time) =>
                    {
                        Assert.NotNull(id);
                        wh.Set();
                    });

                    Assert.Throws<AggregateException>(() => connection.Start(host).Wait());
                }
            }
        }
            public void ReconnectFiresAfterTimeOut(TransportType transportType)
            {
                using (var host = new MemoryHost())
                {
                    var conn = new MyReconnect();
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapConnection<MyReconnect>("/endpoint", config);
                        var configuration = config.Resolver.Resolve<IConfigurationManager>();
                        configuration.KeepAlive = 0;
                        configuration.ConnectionTimeout = TimeSpan.FromSeconds(5);
                        configuration.HeartbeatInterval = TimeSpan.FromSeconds(5);

                        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(15));

                    connection.Stop();

                    Assert.InRange(conn.Reconnects, 1, 4);
                }
            }
            public void ConnectionsWithTheSameConnectionIdSSECloseGracefully()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };
                        app.MapConnection<MyGroupEchoConnection>("/echo", config);
                    });

                    string id = Guid.NewGuid().ToString("d");

                    var tasks = new List<Task>();

                    for (int i = 0; i < 1000; i++)
                    {
                        tasks.Add(ProcessRequest(host, "serverSentEvents", id));
                    }

                    ProcessRequest(host, "serverSentEvents", id);

                    Task.WaitAll(tasks.ToArray());

                    Assert.True(tasks.All(t => !t.IsFaulted));
                }
            }
Example #25
0
        public async Task ContextGroupAddCompletesSuccessfully()
        {
            // https://github.com/SignalR/SignalR/issues/3337
            // Each node shares the same bus but are independent servers
            var counters = new Infrastructure.PerformanceCounterManager();
            var configurationManager = new DefaultConfigurationManager();

            using (EnableDisposableTracing())
            using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000))
            using (var memoryHost = new MemoryHost())
            {
                memoryHost.Configure(app =>
                {
                    var resolver = new DefaultDependencyResolver();
                    resolver.Register(typeof(IMessageBus), () => bus);
                    app.MapSignalR(new HubConfiguration { Resolver = resolver });
                });

                using (var connection = new HubConnection("http://goo/"))
                {
                    var proxy = connection.CreateHubProxy("FarmGroupHub");

                    const string group = "group";
                    const string message = "message";

                    var mre = new AsyncManualResetEvent();
                    proxy.On<string>("message", m =>
                    {
                        if (m == message)
                        {
                            mre.Set();
                        }
                    });

                    await connection.Start(memoryHost);

                    // Add the connection to a group via an IHubContext on a "second" server.
                    var secondResolver = new DefaultDependencyResolver();
                    secondResolver.Register(typeof(IMessageBus), () => bus);
                    var secondConnectionManager = secondResolver.Resolve<IConnectionManager>();
                    var secondHubContext = secondConnectionManager.GetHubContext<FarmGroupHub>();
                    await secondHubContext.Groups.Add(connection.ConnectionId, group);
                    await proxy.Invoke("SendToGroup", group, message);

                    Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(5)));
                }
            }
        }
Example #26
0
        public void UnauthorizedUserCannotInvokeMethodsInHubsAuthorizedSpecifyingUserAndRole()
        {
            using (var host = new MemoryHost())
            {
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    WithUser(app, new GenericPrincipal(new GenericIdentity("test"), new string[] { "User", "Admin" }));
                    app.MapSignalR("/signalr", configuration);
                });

                var connection = CreateHubConnection("http://foo/");

                using (connection)
                {
                    var hub = connection.CreateHubProxy("UserAndRoleAuthHub");
                    var wh = new ManualResetEvent(false);
                    hub.On<string, string>("invoked", (id, time) =>
                    {
                        Assert.NotNull(id);
                        wh.Set();
                    });

                    Assert.Throws<AggregateException>(() => connection.Start(host).Wait());
                }
            }
        }
            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);
                }
            }
Example #28
0
        public static IDisposable Connect_Broadcast5msg_AndDisconnect(int concurrency)
        {
            var host = new MemoryHost();
            var threads = new List<Thread>();
            var cancellationTokenSource = new CancellationTokenSource();

            host.Configure(app =>
            {
                var config = new ConnectionConfiguration
                {
                    Resolver = new DefaultDependencyResolver()
                };
                app.MapConnection<RawConnection>("/Raw-connection", config);
            });

            for (int i = 0; i < concurrency; i++)
            {
                var thread = new Thread(_ =>
                {
                    while (!cancellationTokenSource.IsCancellationRequested)
                    {
                        BroadcastFive(host);
                    }
                });

                threads.Add(thread);
                thread.Start();
            }

            return new DisposableAction(() =>
            {
                cancellationTokenSource.Cancel();

                threads.ForEach(t => t.Join());

                host.Dispose();
            });
        }
            public void SendToClientFromOutsideOfConnection()
            {
                using (var host = new MemoryHost())
                {
                    IPersistentConnectionContext connectionContext = null;
                    host.Configure(app =>
                    {
                        var configuration = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<BroadcastConnection>("/echo", configuration);
                        connectionContext = configuration.Resolver.Resolve<IConnectionManager>().GetConnectionContext<BroadcastConnection>();
                    });

                    var connection1 = new Client.Connection("http://foo/echo");

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

                        connection1.Start(host).Wait();

                        connection1.Received += data =>
                        {
                            Assert.Equal("yay", data);
                            wh1.Set();
                        };

                        connectionContext.Connection.Send(connection1.ConnectionId, "yay");

                        Assert.True(wh1.Wait(TimeSpan.FromSeconds(10)));
                    }
                }
            }
Example #30
0
        public void UnauthorizedUserCannotReceiveHubMessagesFromHubsAuthorizedWithRoles()
        {
            using (var host = new MemoryHost())
            {
                host.Configure(app =>
                {
                    var configuration = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    WithUser(app, new GenericPrincipal(new GenericIdentity("test"), new string[] { "User", "NotAdmin" }));
                    app.MapSignalR("/signalr", configuration);
                });

                var connection = CreateHubConnection("http://foo/");

                using (connection)
                {
                    var hub = connection.CreateHubProxy("AdminAuthHub");
                    var wh = new ManualResetEvent(false);
                    hub.On<string, string, object>("joined", (id, time, authInfo) =>
                    {
                        Assert.NotNull(id);
                        wh.Set();
                    });

                    Assert.Throws<AggregateException>(() => connection.Start(host).Wait());
                }
            }
        }