예제 #1
0
        public async Task ClientCanUseJwtBearerTokenForAuthenticationWhenRedirected(HttpTransportType transportType)
        {
            using (StartVerifiableLog(out var loggerFactory, $"{nameof(ClientCanUseJwtBearerTokenForAuthenticationWhenRedirected)}_{transportType}"))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithLoggerFactory(loggerFactory)
                                    .WithUrl(ServerFixture.Url + "/redirect", transportType)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var message = await hubConnection.InvokeAsync <string>(nameof(TestHub.Echo), "Hello, World!").OrTimeout();

                    Assert.Equal("Hello, World!", message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #2
0
        private async Task ServerClosesConnectionWithErrorIfHubCannotBeCreated(TransportType transportType)
        {
            using (StartLog(out var loggerFactory, testName: $"ConnectionCanSendAndReceiveMessages_{transportType.ToString()}"))
            {
                _serverFixture.SetTestLoggerFactory(loggerFactory);

                var logger = loggerFactory.CreateLogger <EndToEndTests>();

                var url = _serverFixture.Url + "/uncreatable";

                var connection = new HubConnectionBuilder()
                                 .WithUrl(new Uri(url))
                                 .WithTransport(transportType)
                                 .WithLoggerFactory(loggerFactory)
                                 .Build();
                try
                {
                    var closeTcs = new TaskCompletionSource <object>();
                    connection.Closed += e =>
                    {
                        if (e != null)
                        {
                            closeTcs.SetException(e);
                        }
                        else
                        {
                            closeTcs.SetResult(null);
                        }
                    };

                    logger.LogInformation("Starting connection to {url}", url);

                    try
                    {
                        await connection.StartAsync().OrTimeout();
                    }
                    catch (OperationCanceledException)
                    {
                        // Due to a race, this can fail with OperationCanceledException in the SendAsync
                        // call that HubConnection does to send the negotiate message.
                        // This has only been happening on AppVeyor, likely due to a slower CI machine
                        // The closed event will still fire with the exception we care about.
                    }

                    await closeTcs.Task.OrTimeout();
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Test threw {exceptionType}: {message}", ex.GetType(), ex.Message);
                    throw;
                }
                finally
                {
                    logger.LogInformation("Disposing Connection");
                    await connection.DisposeAsync().OrTimeout();

                    logger.LogInformation("Disposed Connection");
                }
            }
        }
예제 #3
0
        public async Task CheckFixedMessage(IHubProtocol protocol, TransportType transportType, string path)
        {
            using (StartLog(out var loggerFactory))
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl(_serverFixture.Url + path)
                                 .WithTransport(transportType)
                                 .WithLoggerFactory(loggerFactory)
                                 .WithHubProtocol(protocol)
                                 .Build();

                try
                {
                    await connection.StartAsync().OrTimeout();

                    var result = await connection.InvokeAsync <string>("HelloWorld").OrTimeout();

                    Assert.Equal("Hello World!", result);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test");
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #4
0
        public async Task <Kernel> ConnectKernelAsync(KernelInfo kernelInfo)
        {
            // QUESTION: (ConnectKernelAsync) tests?
            var hubConnection = new HubConnectionBuilder()
                                .WithUrl(HubUrl)
                                .Build();

            await hubConnection.StartAsync();

            await hubConnection.SendAsync("connect");

            var receiver    = new KernelCommandAndEventSignalRHubConnectionReceiver(hubConnection);
            var sender      = new KernelCommandAndEventSignalRHubConnectionSender(hubConnection);
            var proxyKernel = new ProxyKernel(kernelInfo.LocalName, receiver, sender);

            var _ = proxyKernel.StartAsync();

            proxyKernel.RegisterForDisposal(receiver);
            proxyKernel.RegisterForDisposal(async() =>
            {
                await hubConnection.DisposeAsync();
            });

            return(proxyKernel);
        }
예제 #5
0
        static async Task Main(string[] args)
        {
            const string backendUrl = "https://iotdemofunction.azurewebsites.net/api/";
            //const string backendUrl = "http://localhost:7071/api/";

            // Connect to SignalR Service
            var connect = new HubConnectionBuilder()
                          .WithUrl(backendUrl)
                          .Build();

            // Attach Message handler
            connect.On <string>("measurement", (messageString) =>
            {
                var message = JsonConvert.DeserializeObject <Measurement>(messageString);
                System.Console.WriteLine("Message Received: " + messageString);
            });

            // Start Monitoring
            await connect.StartAsync();

            // User input handling

            System.Console.WriteLine("...");
            System.Console.ReadLine();
            await connect.DisposeAsync();
        }
        public ActionResult ShowTelemetry([FromBody] Telemetry telemetry)
        {
            try
            {
                #if DEBUG
                var connection = new HubConnectionBuilder()
                                 .WithUrl("https://localhost:44303/chat")
                                 //.WithTransport(Microsoft.AspNetCore.Sockets.TransportType.LongPolling)
                                 //.WithConsoleLogger()
                                 .Build();
                #else
                var connection = new HubConnectionBuilder()
                                 .WithUrl("http://signalrapplication.azurewebsites.net/chat")
                                 .WithConsoleLogger()
                                 .Build();
                #endif
                connection.StartAsync().Wait();
                var text = telemetry == null || string.IsNullOrEmpty(telemetry.text)
                                          ? "***"
                                          : telemetry.text;
                connection.SendAsync("Send", text).Wait(); // InvokeAsync("Send", text)

                connection.DisposeAsync().Wait();
                return(Json("Success"));
            }
            catch (Exception ex)
            {
                return(Json($"Exception {ex.Message}"));
            }
        }
예제 #7
0
        async void Send_Vote(string vote, int seatno, string azureID)
        {
            HubConnection connection;

            try
            {
                string domainName = HttpContext.Request.Host.Value;
                string scheme     = HttpContext.Request.Scheme;
                string hub        = _configuration.GetValue <string>("HubString");
                hub = hub.StartsWith("/") ? hub.Remove(0, 1) : hub;

                string hubPath = $"{scheme}://{domainName}/{hub}";
                connection = new HubConnectionBuilder()
                             .WithUrl(hubPath)
                             .Build();

                await connection.StartAsync();

                await connection.InvokeAsync("Vote", vote, seatno);

                await connection.DisposeAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError("{0}- Member- {1} in seat {2} voted {3}", DateTime.Now, azureID, seatno, vote);
                _logger.LogError(ex.ToString());
            }
        }
예제 #8
0
        public async Task NegotiationSkipsServerSentEventsWhenUsingBinaryProtocol()
        {
            using (StartLog(out var loggerFactory))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/default-nowebsockets")
                                    .WithHubProtocol(new MessagePackHubProtocol())
                                    .WithLoggerFactory(loggerFactory)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var transport = await hubConnection.InvokeAsync <TransportType>(nameof(TestHub.GetActiveTransportName)).OrTimeout();

                    Assert.Equal(TransportType.LongPolling, transport);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #9
0
        public async Task ClientCanSendHeaders(TransportType transportType)
        {
            using (StartLog(out var loggerFactory, $"{nameof(ClientCanSendHeaders)}_{transportType}"))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/default")
                                    .WithTransport(transportType)
                                    .WithLoggerFactory(loggerFactory)
                                    .WithHeader("X-test", "42")
                                    .WithHeader("X-42", "test")
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var headerValues = await hubConnection.InvokeAsync <string[]>(nameof(TestHub.GetHeaderValues), new object[] { new[] { "X-test", "X-42" } }).OrTimeout();

                    Assert.Equal(new[] { "42", "test" }, headerValues);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #10
0
        public async Task CheckFixedMessage(string protocolName, TransportType transportType, string path)
        {
            var protocol = HubProtocols[protocolName];

            using (StartLog(out var loggerFactory, $"{nameof(CheckFixedMessage)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}"))
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl(_serverFixture.Url + path)
                                 .WithTransport(transportType)
                                 .WithLoggerFactory(loggerFactory)
                                 .WithHubProtocol(protocol)
                                 .Build();

                try
                {
                    await connection.StartAsync().OrTimeout();

                    var result = await connection.InvokeAsync <string>(nameof(TestHub.HelloWorld)).OrTimeout();

                    Assert.Equal("Hello World!", result);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await connection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #11
0
        public async Task ClientCanUseJwtBearerTokenForAuthentication(TransportType transportType)
        {
            using (StartLog(out var loggerFactory, $"{nameof(ClientCanUseJwtBearerTokenForAuthentication)}_{transportType}"))
            {
                var httpResponse = await new HttpClient().GetAsync(_serverFixture.Url + "/generateJwtToken");
                httpResponse.EnsureSuccessStatusCode();
                var token = await httpResponse.Content.ReadAsStringAsync();

                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/authorizedhub")
                                    .WithTransport(transportType)
                                    .WithLoggerFactory(loggerFactory)
                                    .WithAccessToken(() => token)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var message = await hubConnection.InvokeAsync <string>(nameof(TestHub.Echo), "Hello, World!").OrTimeout();

                    Assert.Equal("Hello, World!", message);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            HubConnection conn = new HubConnectionBuilder()
                                 .WithUrl("http://localhost:5000/QuoteHub")
                                 .WithConsoleLogger()
                                 .Build();

            conn.StartAsync().ContinueWith(t => {
                if (t.IsFaulted)
                {
                    Console.WriteLine(t.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Connected to Hub");
                }
            }).Wait();

            conn.On <string>("GetQuote", param => {
                Console.WriteLine(param);
            });

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
            conn.DisposeAsync().ContinueWith(t => {
                if (t.IsFaulted)
                {
                    Console.WriteLine(t.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Disconnected");
                }
            });
        }
예제 #13
0
        private static async Task ConnectSingle()
        {
            try
            {
                var connection = new HubConnectionBuilder()
                                 .WithUrl(_signalrArgs.Url)
                                 .WithConsoleLogger(LogLevel.Error)
                                 .Build();

                connection.On <string>("SendOne", SingleMessageReceive);
                connection.On <string>("SendGroup", GroupMessageReceive);
                connection.On <string>("BroadcastInvoke", m =>
                {
                    connection.InvokeAsync("BroadcastRecevie", m);
                });
                var sendCts = new CancellationTokenSource();
                connection.Closed += (s) =>
                {
                    Interlocked.Increment(ref _disconectedCount);
                    sendCts.Cancel();
                    connection.DisposeAsync();
                };
                await connection.StartAsync();

                Interlocked.Increment(ref _conectedCount);
                // await LoadTest( connection);
            }
            catch (AggregateException aex) when(aex.InnerExceptions.All(e => e is OperationCanceledException))
            {
            }
            catch (OperationCanceledException)
            {
            }
        }
예제 #14
0
        public async Task ClientCanSendHeaders(HttpTransportType transportType)
        {
            using (StartServer <Startup>(out var server))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithLoggerFactory(LoggerFactory)
                                    .WithUrl(server.Url + "/default", transportType, options =>
                {
                    options.Headers["X-test"] = "42";
                    options.Headers["X-42"]   = "test";
                })
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var headerValues = await hubConnection.InvokeAsync <string[]>(nameof(TestHub.GetHeaderValues), new[] { "X-test", "X-42" }).OrTimeout();

                    Assert.Equal(new[] { "42", "test" }, headerValues);
                }
                catch (Exception ex)
                {
                    LoggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #15
0
        static async Task Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl("http://localhost:5000/chat")
                             .WithAutomaticReconnect()
                             .Build();

            connection.On <string, string>("ReceiveMessage", (user, message) => {
                Console.WriteLine($"{user}: {message}");
            });

            Console.Write("Enter username: "******"Connecting to chat server...");
            await connection.StartAsync();

            Console.WriteLine("Connected to chat server");

            while (true)
            {
                var message = Console.ReadLine();

                if (message.Equals("exit", StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }

                await connection.SendAsync("SendMessage", username, message);
            }

            await connection.DisposeAsync();
        }
예제 #16
0
        static async Task MainAsync(CancellationToken cancellationToken)
        {
            var hubConnection = new HubConnectionBuilder()
                                .WithUrl("http://localhost:5000/sentiment")
                                .Build();

            await hubConnection.StartAsync();

            var keywords = _searchGroups.Contains("|") ? string.Join(",", _searchGroups.Split('|')) : _searchGroups;
            var tweet    = new Tweet(_logger, cancellationToken);

            var datum = tweet.StreamStatuses(new TwitterConfig(_oauthToken, _oauthTokenSecret, _oauthCustomerKey, _oauthConsumerSecret, keywords, _searchGroups))
                        .Where(e => !string.IsNullOrWhiteSpace(e.Text))
                        .Select(t => Sentiment140.ComputeScore(t, _searchGroups, _mode)).Select(t =>
                                                                                                new Payload
            {
                CreatedAt      = t.CreatedAt,
                Topic          = t.Topic,
                SentimentScore = t.SentimentScore,
                Author         = t.UserName,
                Text           = t.Text,
                SendExtended   = _sendExtendedInformation
            });

            if (_removeAllUndefined)
            {
                datum = datum.Where(e => e.SentimentScore > -1);
            }

            var tweetObserver = new TweetObserver(_logger, hubConnection, cancellationToken);

            datum.Where(e => e.Topic != "No Match").ToObservable().Subscribe(tweetObserver);

            await hubConnection.DisposeAsync();
        }
예제 #17
0
        private async void UpdateWebPlaylist()
        {
            //TODO:
            // URL needs to come from config
            var connection = new HubConnectionBuilder()
                             .WithUrl($"{config.WebPlaylistUrl}")
                             .WithConsoleLogger()
                             .Build();

            await connection.StartAsync();

            using (var context = contextFactory.Create())
            {
                var requests = context.SongRequests
                               .Where(sr => !sr.Played)
                               .OrderRequests()
                               .Take(5)
                               .ToList()
                               .Select(this.FormatRequest)
                               .ToArray();

                await connection.InvokeAsync("Send", new[] { requests });
            }
            await connection.DisposeAsync();
        }
        public static async Task <int> ExecuteAsync()
        {
            var baseUrl = "http://localhost:4235/inventory";

            Console.WriteLine("Connecting to {0}", baseUrl);
            var connection = new HubConnectionBuilder()
                             .WithUrl(baseUrl)
                             .WithConsoleLogger()
                             .Build();

            try
            {
                await connection.StartAsync();

                Console.WriteLine("Connected to {0}", baseUrl);

                var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, a) =>
                {
                    a.Cancel = true;
                    Console.WriteLine("Stopping loops...");
                    cts.Cancel();
                };

                // Set up handler
                connection.On <List <dynamic> >("UpdateCatalog", data =>
                {
                    var products = data;
                    foreach (var item in products)
                    {
                        Console.WriteLine($"{item.name}: {item.quantity}");
                    }
                });

                while (!cts.Token.IsCancellationRequested)
                {
                    var product = await Task.Run(() => ReadProduct(), cts.Token);

                    var quanity = await Task.Run(() => ReadQuantity(), cts.Token);

                    if (product == null)
                    {
                        break;
                    }

                    await connection.InvokeAsync("RegisterProduct", product, quanity, cts.Token);
                }
            }
            catch (AggregateException aex) when(aex.InnerExceptions.All(e => e is OperationCanceledException))
            {
            }
            catch (OperationCanceledException)
            {
            }
            finally
            {
                await connection.DisposeAsync();
            }
            return(0);
        }
예제 #19
0
        static async Task SendInformationAsync(CancellationToken cToken)
        {
            var connBuilder = new HubConnectionBuilder()
                              .WithUrl("http://localhost:7001/healthSensor")
                              .Build();

            await connBuilder.StartAsync();

            Random rnd = new Random();
            int    randomHealthPoint = 0;

            while (!cToken.IsCancellationRequested)
            {
                await Task.Delay(1000, cToken);

                randomHealthPoint = rnd.Next(1, 25);
                var information = new HealthInformation()
                {
                    Name  = $"service_{randomHealthPoint}",
                    Level = randomHealthPoint
                };
                Console.WriteLine(information.ToString());
                await connBuilder.InvokeAsync("Broadcast", "HealthSensor", information, cToken);
            }

            await connBuilder.DisposeAsync();
        }
예제 #20
0
        public override async Task <Kernel> CreateKernelAsync(
            SignalRConnectionOptions options,
            KernelInvocationContext context)
        {
            var connection = new HubConnectionBuilder()
                             .WithUrl(options.HubUrl)
                             .Build();

            await connection.StartAsync();

            await connection.SendAsync("connect");

            var receiver    = new KernelCommandAndEventSignalRHubConnectionReceiver(connection);
            var sender      = new KernelCommandAndEventSignalRHubConnectionSender(connection);
            var proxyKernel = new ProxyKernel(options.KernelName, receiver, sender);

            var _ = proxyKernel.RunAsync();

            proxyKernel.RegisterForDisposal(receiver);
            proxyKernel.RegisterForDisposal(async() =>
            {
                await connection.DisposeAsync();
            });

            return(proxyKernel);
        }
예제 #21
0
파일: Program.cs 프로젝트: abartic/dataexch
        static void Main(string[] args)
        {
            //Set connection
            var connection = new HubConnectionBuilder()
                             //.WithUrl("https://localhost:5001/messages")
                             .WithUrl("https://dataexch.herokuapp.com/messages")
                             .Build();

            connection.StartAsync()
            .ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Connected");
                }
            }).Wait();

            connection.On("ReceiveMessage", (string message) =>
            {
                Console.WriteLine(message);
                SendNotification(message);
            });

            Console.Read();
            connection.DisposeAsync();
        }
예제 #22
0
        public async Task WebSocketOptionsAreApplied()
        {
            using (StartServer <Startup>(out var server))
            {
                // System.Net has a HttpTransportType type which means we need to fully-qualify this rather than 'use' the namespace
                var cookieJar = new System.Net.CookieContainer();
                cookieJar.Add(new System.Net.Cookie("Foo", "Bar", "/", new Uri(server.Url).Host));

                var hubConnection = new HubConnectionBuilder()
                                    .WithLoggerFactory(LoggerFactory)
                                    .WithUrl(server.Url + "/default", HttpTransportType.WebSockets, options =>
                {
                    options.WebSocketConfiguration = o => o.Cookies = cookieJar;
                })
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var cookieValue = await hubConnection.InvokeAsync <string>(nameof(TestHub.GetCookieValue), "Foo").OrTimeout();

                    Assert.Equal("Bar", cookieValue);
                }
                catch (Exception ex)
                {
                    LoggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #23
0
        public async Task WebSocketOptionsAreApplied()
        {
            using (StartLog(out var loggerFactory, $"{nameof(WebSocketOptionsAreApplied)}"))
            {
                // System.Net has a TransportType type which means we need to fully-qualify this rather than 'use' the namespace
                var cookieJar = new System.Net.CookieContainer();
                cookieJar.Add(new System.Net.Cookie("Foo", "Bar", "/", new Uri(_serverFixture.Url).Host));

                var hubConnection = new HubConnectionBuilder()
                                    .WithUrl(_serverFixture.Url + "/default")
                                    .WithTransport(TransportType.WebSockets)
                                    .WithLoggerFactory(loggerFactory)
                                    .WithWebSocketOptions(options => options.Cookies = cookieJar)
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var cookieValue = await hubConnection.InvokeAsync <string>(nameof(TestHub.GetCookieValue), new object[] { "Foo" }).OrTimeout();

                    Assert.Equal("Bar", cookieValue);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #24
0
        public async Task UserIdProviderCanAccessHttpContext()
        {
            using (StartVerifiableLog(out var loggerFactory))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithLoggerFactory(loggerFactory)
                                    .WithUrl(ServerFixture.Url + "/default", options =>
                {
                    options.Headers.Add(HeaderUserIdProvider.HeaderName, "SuperAdmin");
                })
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var userIdentifier = await hubConnection.InvokeAsync <string>(nameof(TestHub.GetUserIdentifier)).OrTimeout();

                    Assert.Equal("SuperAdmin", userIdentifier);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #25
0
        public async Task CheckHttpConnectionFeatures()
        {
            using (StartVerifiableLog(out var loggerFactory))
            {
                var hubConnection = new HubConnectionBuilder()
                                    .WithLoggerFactory(loggerFactory)
                                    .WithUrl(ServerFixture.Url + "/default")
                                    .Build();
                try
                {
                    await hubConnection.StartAsync().OrTimeout();

                    var features = await hubConnection.InvokeAsync <object[]>(nameof(TestHub.GetIHttpConnectionFeatureProperties)).OrTimeout();

                    var localPort  = (Int64)features[0];
                    var remotePort = (Int64)features[1];
                    var localIP    = (string)features[2];
                    var remoteIP   = (string)features[3];

                    Assert.True(localPort > 0L);
                    Assert.True(remotePort > 0L);
                    Assert.Equal("127.0.0.1", localIP);
                    Assert.Equal("127.0.0.1", remoteIP);
                }
                catch (Exception ex)
                {
                    loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName);
                    throw;
                }
                finally
                {
                    await hubConnection.DisposeAsync().OrTimeout();
                }
            }
        }
예제 #26
0
        static async Task Main(string[] args)
        {
            HubConnection connection = new HubConnectionBuilder()
                                       .WithUrl("http://localhost:5000/signalR/People")
                                       .WithAutomaticReconnect()
                                       .Build();

            connection.ServerTimeout = TimeSpan.FromSeconds(10);

            connection.Reconnecting += connectionId => {
                System.Console.WriteLine("Reconnecting");
                return(Task.CompletedTask);
            };
            connection.Closed += connectionId => {
                System.Console.WriteLine("Closed");
                return(Task.CompletedTask);
            };

            connection.On <Person>("Post", x => System.Console.WriteLine(JsonConvert.SerializeObject(x)));
            connection.On <string>("Delete", x => System.Console.WriteLine(x));
            //connection.On<string>("Pong", x => System.Console.WriteLine(x) );


            while (true)
            {
                System.Console.WriteLine("Connecting...");
                try {
                    await connection.StartAsync();

                    System.Console.WriteLine("Connected");
                    break;
                }
                catch {}
            }

            if (args.Any())
            {
                System.Console.WriteLine(args[0]);
                if (args[0] == "Add")
                {
                    await connection.SendAsync("JoinToAddGroup");
                }
                else if (args[0] == "Delete")
                {
                    await connection.SendAsync("JoinToDeleteGroup");
                }
            }

            await Task.Delay(5000);

            try {
                await connection.SendAsync("addperson", new Person { FirstName = "Ewa", LastName = "Ewowska" });
            }
            catch
            {
            }
            Console.ReadLine();
            await connection.DisposeAsync();
        }
예제 #27
0
        public static async Task <int> ExecuteAsync(string baseUrl)
        {
            baseUrl = string.IsNullOrEmpty(baseUrl) ? "http://localhost:53042/chat" : baseUrl;

            var loggerFactory = new LoggerFactory();
            var logger        = loggerFactory.CreateLogger <Program>();

            Console.WriteLine($"Connecting to {baseUrl}...");

            var connection = new HubConnectionBuilder()
                             .WithUrl(baseUrl)
                             .WithConsoleLogger()
                             .Build();

            //var connection = new HttpConnection(new Uri(baseUrl), loggerFactory);
            try
            {
                var cts = new CancellationTokenSource();
                connection.On <string>("Send", Connection_MessageReceived);
                connection.Closed += e =>
                {
                    return(Task.CompletedTask);
                };

                await connection.StartAsync();

                Console.WriteLine($"Connected to {baseUrl}");

                Console.CancelKeyPress += (sender, a) =>
                {
                    a.Cancel = true;
                    cts.Cancel();
                };

                while (!cts.Token.IsCancellationRequested)
                {
                    var line = await Task.Run(() => Console.ReadLine(), cts.Token);

                    if (line == null)
                    {
                        break;
                    }

                    await connection.SendAsync("Send", cts.Token, line);
                }
            }
            catch (AggregateException aex) when(aex.InnerExceptions.All(e => e is OperationCanceledException))
            {
            }
            catch (OperationCanceledException)
            {
            }
            finally
            {
                await connection.DisposeAsync();
            }
            return(0);
        }
        private async Task ServerClosesConnectionWithErrorIfHubCannotBeCreated(HttpTransportType transportType)
        {
            using (var server = await StartServer <Startup>())
            {
                var logger = LoggerFactory.CreateLogger <EndToEndTests>();

                var url        = server.Url + "/uncreatable";
                var connection = new HubConnectionBuilder()
                                 .WithLoggerFactory(LoggerFactory)
                                 .WithUrl(url, transportType)
                                 .Build();
                try
                {
                    var closeTcs = new TaskCompletionSource <object>();
                    connection.Closed += e =>
                    {
                        if (e != null)
                        {
                            closeTcs.SetException(e);
                        }
                        else
                        {
                            closeTcs.SetResult(null);
                        }
                        return(Task.CompletedTask);
                    };

                    logger.LogInformation("Starting connection to {url}", url);

                    try
                    {
                        await connection.StartAsync().OrTimeout();
                    }
                    catch (OperationCanceledException)
                    {
                        // Due to a race, this can fail with OperationCanceledException in the SendAsync
                        // call that HubConnection does to send the handshake message.
                        // This has only been happening on AppVeyor, likely due to a slower CI machine
                        // The closed event will still fire with the exception we care about.
                    }

                    await closeTcs.Task.OrTimeout();
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Test threw {exceptionType}: {message}", ex.GetType(), ex.Message);
                    throw;
                }
                finally
                {
                    logger.LogInformation("Disposing Connection");
                    await connection.DisposeAsync().OrTimeout();

                    logger.LogInformation("Disposed Connection");
                }
            }
        }
예제 #29
0
        static async Task running()
        {
            var connection = new HubConnectionBuilder().WithUrl("https://localhost:44357/chathub").Build();
            await connection.StartAsync();

            Console.WriteLine("client connection state:" + connection.State);
            await connection.StopAsync();

            await connection.DisposeAsync();
        }
예제 #30
0
        public async Task GetUpdateTodosAsync()
        {
            HubConnection hubConnection = new HubConnectionBuilder()
                                          .WithUrl("http://localhost:55849/TodosHub").Build();
            await hubConnection.StartAsync();

            await hubConnection.InvokeAsync("GetServerTodo");

            await hubConnection.DisposeAsync();
        }