private async Task DirectConnectionJoinGroup(string connectionString) { var serviceManager = new ServiceManagerBuilder().WithOptions(option => { option.ConnectionString = connectionString; option.ServiceTransportType = ServiceTransportType.Transient; }).Build(); var hubContext = await serviceManager.CreateHubContextAsync(SignalRConstants.DefaultRestHubName); await SignalRUtils.JoinGroupForConnection( _totalConnection, _groupCount, _connectionIndex, async (i, g) => { var userId = SignalRUtils.GenClientUserIdFromConnectionIndex(_connectionIndex[i]); try { await hubContext.UserGroups.AddToGroupAsync( userId, SignalRUtils.GroupName(_type, g)); _statisticsCollector.IncreaseJoinGroupSuccess(); } catch (Exception e) { _statisticsCollector.IncreaseJoinGroupFail(); Log.Error($"Fail to join group: {e.Message}"); } }); }
public async Task Call_NegotiateAsync_After_WithEndpoints(ServiceTransportType serviceTransportType) { var serviceManager = new ServiceManagerBuilder() .WithOptions(o => { o.ServiceTransportType = serviceTransportType; o.ServiceEndpoints = ServiceEndpoints; }) .BuildServiceManager(); var hubContext = await serviceManager.CreateHubContextAsync(Hub, default); for (var i = 0; i < 5; i++) { var randomEndpoint = ServiceEndpoints[StaticRandom.Next(0, Count)]; var negotiationResponse = await(hubContext as IInternalServiceHubContext) .WithEndpoints(new ServiceEndpoint[] { randomEndpoint }) .NegotiateAsync(); Assert.Equal(ClientEndpointUtils.GetExpectedClientEndpoint(Hub, null, randomEndpoint.Endpoint), negotiationResponse.Url); var tokenString = negotiationResponse.AccessToken; var token = JwtTokenHelper.JwtHandler.ReadJwtToken(tokenString); var expectedToken = JwtTokenHelper.GenerateJwtBearer( ClientEndpointUtils.GetExpectedClientEndpoint(Hub, null, randomEndpoint.Endpoint), ClaimsUtility.BuildJwtClaims(null, null, null), token.ValidTo, token.ValidFrom, token.ValidFrom, randomEndpoint.AccessKey); Assert.Equal(expectedToken, tokenString); } }
public async Task NegotiateAsync() { var serviceManager = new ServiceManagerBuilder().WithOptions(o => o.ConnectionString = FakeEndpointUtils.GetFakeConnectionString(1).Single()).BuildServiceManager(); var hubContext = await serviceManager.CreateHubContextAsync <IChatClient>("hubName", default); var myHub = new TestStronglyTypedHub(hubContext); var connectionInfo = await myHub.Negotiate("user"); Assert.NotNull(connectionInfo); }
public async Task InitAsync() { var serviceManager = new ServiceManagerBuilder().WithOptions(option => { option.ConnectionString = _connectionString; option.ServiceTransportType = _serviceTransportType; }).Build(); _hubContext = await serviceManager.CreateHubContextAsync(HubName, new LoggerFactory()); }
public async Task StartAsync(CancellationToken cancellationToken) { var serviceManager = new ServiceManagerBuilder().WithOptions(option => { option.ConnectionString = _config[ENV_SIGNALR]; }).Build(); _notificationHub = await serviceManager.CreateHubContextAsync(HubName); ConnectToQueue(); }
public async Task InitAsync() { var serviceManager = new ServiceManagerBuilder().WithOptions(option => { option.ConnectionString = _connectionString; option.ServiceTransportType = _serviceTransportType; }) //Uncomment the following line to get more logs //.WithLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole())) .BuildServiceManager(); _hubContext = await serviceManager.CreateHubContextAsync(HubName, default); }
private async Task DirectConnectionLeaveGroup(string connectionString) { var serviceManager = new ServiceManagerBuilder().WithOptions(option => { option.ConnectionString = connectionString; option.ServiceTransportType = ServiceTransportType.Transient; }).Build(); var hubContext = await serviceManager.CreateHubContextAsync(SignalRConstants.DefaultRestHubName); if (_connections.Count >= _groupCount) { for (var i = 0; i < _connections.Count; i++) { var userId = SignalRUtils.GenClientUserIdFromConnectionIndex(_connectionIndex[i]); try { await hubContext.UserGroups.RemoveFromGroupAsync(userId, SignalRUtils.GroupName(_type, _connectionIndex[i] % _groupCount)); _statisticsCollector.IncreaseLeaveGroupSuccess(); } catch (Exception e) { _statisticsCollector.IncreaseLeaveGroupFail(); Log.Error($"Fail to leave group: {e.Message}"); } } } else { for (var i = 0; i < _groupCount; i++) { var userId = SignalRUtils.GenClientUserIdFromConnectionIndex(i); try { await hubContext.UserGroups.RemoveFromGroupAsync( userId, SignalRUtils.GroupName(_type, i)); _statisticsCollector.IncreaseLeaveGroupSuccess(); } catch (Exception e) { _statisticsCollector.IncreaseLeaveGroupFail(); Log.Error($"Fail to leave group: {e.Message}"); } } } }
//[InlineData(ServiceTransportType.Transient)] Not implemented yet public async Task StrongTypedHubContextCheckEndpointHealthWithMultiEndpoints(ServiceTransportType serviceTransportType) { var serviceManager = new ServiceManagerBuilder() .WithOptions(o => { o.ServiceTransportType = serviceTransportType; o.ServiceEndpoints = FakeEndpointUtils.GetFakeEndpoint(2).ToArray(); }) .WithLoggerFactory(_loggerFactory) .BuildServiceManager(); var hubContext = await serviceManager.CreateHubContextAsync <IChat>("hubName", default); await Assert.ThrowsAsync <AzureSignalRNotConnectedException>(() => hubContext.NegotiateAsync().AsTask()); }
static Task <IServiceHubContext> CreateHubContextAsync() { var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build(); string signalRConnString = config.GetConnectionString("AzureSignalRConnectionString"); var serviceManager = new ServiceManagerBuilder() .WithOptions(option => { option.ConnectionString = signalRConnString; option.ServiceTransportType = ServiceTransportType.Persistent; }) .Build(); return(serviceManager.CreateHubContextAsync("testhub")); }
private static Task <IServiceHubContext> CreateHubContext() { string signalRConnString = Environment.GetEnvironmentVariable(Constants.AzureSignalRConnectionStringEnvironmentVariableName); var serviceManager = new ServiceManagerBuilder() .WithOptions(option => { option.ConnectionString = signalRConnString; // ServiceTransportType.Persistent would be more efficient, but it is not reliable (connection might be dropped and never reestablished) option.ServiceTransportType = ServiceTransportType.Transient; }) .Build(); return(serviceManager.CreateHubContextAsync(nameof(LetsGoOutHub))); }
public async Task StrongTypedHubContextNotCheckEndpointHealthWithSingleEndpoint(ServiceTransportType serviceTransportType) { var serviceManager = new ServiceManagerBuilder() .WithOptions(o => { o.ServiceTransportType = serviceTransportType; o.ConnectionString = FakeEndpointUtils.GetFakeConnectionString(1).First(); }) .WithLoggerFactory(_loggerFactory) .BuildServiceManager(); var hubContext = await serviceManager.CreateHubContextAsync <IChat>("hubName", default); var negotiateResponse = await hubContext.NegotiateAsync(); Assert.NotNull(negotiateResponse); }
static async Task Main(string[] args) { var serviceManager = new ServiceManagerBuilder() .WithOptions(option => { option.ConnectionString = ""; }) .Build(); Console.WriteLine("Press any key to connect"); Console.ReadKey(); var hubContext = await serviceManager.CreateHubContextAsync("TestHub").ConfigureAwait(false); await hubContext.Clients.Group("testGroup").SendAsync("Send", "Hello").ConfigureAwait(false); Console.ReadKey(); await hubContext.DisposeAsync(); }
private async Task MockConnectionTestAsync(ServiceTransportType serviceTransportType, Func <ServiceHubContext, Task> testAction, Action <Dictionary <HubServiceEndpoint, List <TestServiceConnection> > > assertAction) { using (StartLog(out var loggerFactory, LogLevel.Debug)) { var connectionFactory = new TestServiceConnectionFactory(); var serviceManager = new ServiceManagerBuilder() .WithOptions(o => { o.ServiceTransportType = serviceTransportType; o.ServiceEndpoints = ServiceEndpoints; }) .WithLoggerFactory(loggerFactory) .ConfigureServices(services => services.AddSingleton <IServiceConnectionFactory>(connectionFactory)) .BuildServiceManager(); var hubContext = await serviceManager.CreateHubContextAsync(Hub, default); await testAction.Invoke(hubContext); var createdConnections = connectionFactory.CreatedConnections.ToDictionary(p => p.Key, p => p.Value.Select(conn => conn as TestServiceConnection).ToList()); assertAction.Invoke(createdConnections); } }
internal async Task StopServiceHubContextTest() { using (StartVerifiableLog(out var loggerFactory, LogLevel.Debug, expectedErrors: context => context.EventId == new EventId(2, "EndpointOffline"))) { var serviceManager = new ServiceManagerBuilder() .WithOptions(o => { o.ConnectionString = TestConfiguration.Instance.ConnectionString; o.ConnectionCount = 1; o.ServiceTransportType = ServiceTransportType.Persistent; }) .Build(); var serviceHubContext = await serviceManager.CreateHubContextAsync("hub", loggerFactory); var connectionContainer = ((ServiceHubContext)serviceHubContext).ServiceProvider.GetRequiredService <IServiceConnectionContainer>(); await serviceHubContext.DisposeAsync(); await Task.Delay(500); Assert.Equal(ServiceConnectionStatus.Disconnected, connectionContainer.Status); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Replacing SignalR's userId provider with our custom services.AddTransient <IUserIdProvider, NickNameUserIdProvider>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); string signalRConnString = this.Configuration.GetValue <string>(Constants.AzureSignalRConnectionStringEnvironmentVariableName); signalRConnString = GetFromKeyVaultIfNeeded(signalRConnString); // Initializing SignalR with Azure SignalR Service connection string services .AddSignalR() .AddAzureSignalR(signalRConnString); // Also initializing and adding SignalR client var serviceManager = new ServiceManagerBuilder() .WithOptions(option => { option.ConnectionString = signalRConnString; // ServiceTransportType.Persistent would be more efficient, but it is not reliable (connection might be dropped and never reestablished) option.ServiceTransportType = ServiceTransportType.Transient; }) .Build(); // Adding the initialization Task to the container, not the IServiceHubContext itself. // That's OK, because the Task will only ran once (as guaranteed by the framework). services.AddSingleton(serviceManager.CreateHubContextAsync(nameof(LetsGoOutHub))); // Finally connecting to Redis string redisConnString = this.Configuration.GetValue <string>(Constants.RedisConnectionStringEnvironmentVariableName); redisConnString = GetFromKeyVaultIfNeeded(redisConnString); services.AddSingleton(ConnectionMultiplexer.Connect(redisConnString)); }