public MqttTransportSettings(TransportType transportType) { this.transportType = transportType; switch (transportType) { case TransportType.Mqtt_WebSocket_Only: case TransportType.Mqtt_Tcp_Only: this.transportType = transportType; break; case TransportType.Mqtt: throw new ArgumentOutOfRangeException(nameof(transportType), transportType, "Must specify Mqtt_WebSocket_Only or Mqtt_Tcp_Only"); default: throw new ArgumentOutOfRangeException(nameof(transportType), transportType, "Unsupported Transport Type {0}".FormatInvariant(transportType)); } this.CleanSession = DefaultCleanSession; this.ConnectArrivalTimeout = DefaultConnectArrivalTimeout; this.DeviceReceiveAckCanTimeout = DefaultDeviceReceiveAckCanTimeout; this.DeviceReceiveAckTimeout = DefaultDeviceReceiveAckTimeout; this.DupPropertyName = "mqtt-dup"; this.HasWill = DefaultHasWill; this.KeepAliveInSeconds = DefaultKeepAliveInSeconds; this.MaxOutboundRetransmissionEnforced = DefaultMaxOutboundRetransmissionEnforced; this.MaxPendingInboundMessages = DefaultMaxPendingInboundMessages; this.PublishToServerQoS = DefaultPublishToServerQoS; this.ReceivingQoS = DefaultReceivingQoS; this.QoSPropertyName = "mqtt-qos"; this.RetainPropertyName = "mqtt-retain"; this.WillMessage = null; this.DefaultReceiveTimeout = TimeSpan.FromSeconds(DefaultReceiveTimeoutInSeconds); }
public void ClientStopsReconnectingAfterDisconnectTimeout(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(keepAlive: 1, disconnectTimeout: 2); var connection = new Client.Hubs.HubConnection(host.Url); var reconnectWh = new ManualResetEventSlim(); var disconnectWh = new ManualResetEventSlim(); connection.Reconnecting += () => { reconnectWh.Set(); Assert.Equal(ConnectionState.Reconnecting, connection.State); }; connection.Closed += () => { disconnectWh.Set(); Assert.Equal(ConnectionState.Disconnected, connection.State); }; connection.Start(host.Transport).Wait(); host.Shutdown(); Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(5))); Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(5))); } }
public void AddingToMultipleGroups(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(); int max = 10; var countDown = new CountDownRange<int>(Enumerable.Range(0, max)); var connection = new Client.Hubs.HubConnection(host.Url); var proxy = connection.CreateHubProxy("MultGroupHub"); proxy.On<User>("onRoomJoin", user => { Assert.True(countDown.Mark(user.Index)); }); connection.Start(host.Transport).Wait(); for (int i = 0; i < max; i++) { var user = new User { Index = i, Name = "tester", Room = "test" + i }; proxy.InvokeWithTimeout("login", user); proxy.InvokeWithTimeout("joinRoom", user); } Assert.True(countDown.Wait(TimeSpan.FromSeconds(30)), "Didn't receive " + max + " messages. Got " + (max - countDown.Count) + " missed " + String.Join(",", countDown.Left.Select(i => i.ToString()))); connection.Stop(); } }
public async Task ReconnectionSuccesfulTest(HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { // Arrange var mre = new AsyncManualResetEvent(false); host.Initialize(keepAlive: null, messageBusType: messageBusType); var connection = CreateConnection(host, "/my-reconnect"); if (transportType == TransportType.LongPolling) { ((Client.Transports.LongPollingTransport)host.Transport).ReconnectDelay = TimeSpan.Zero; } using (connection) { ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2)); connection.Reconnected += () => { mre.Set(); }; await connection.Start(host.Transport); Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10))); // Clean-up mre.Dispose(); } } }
public void CancelledGenericTask(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(); var connection = new Client.Hubs.HubConnection(host.Url); var tcs = new TaskCompletionSource<object>(); var hub = connection.CreateHubProxy("demo"); connection.Start(host.Transport).Wait(); hub.Invoke("CancelledGenericTask").ContinueWith(tcs); try { tcs.Task.Wait(TimeSpan.FromSeconds(10)); Assert.True(false, "Didn't fault"); } catch (Exception) { } connection.Stop(); } }
public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(messageBusType: messageBusType); var connection = CreateHubConnection(host); using (connection) { var disconnectWh = new ManualResetEventSlim(); connection.Closed += () => { disconnectWh.Set(); }; connection.Start(host.Transport).Wait(); // The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect. ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1); Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired"); } } }
public void ReconnectExceedingReconnectWindowDisconnectsWithFastBeatInterval(HostType hostType, TransportType transportType, MessageBusType messageBusType) { // Test cannot be async because if we do host.ShutDown() after an await the connection stops. using (var host = CreateHost(hostType, transportType)) { host.Initialize(keepAlive: 9, messageBusType: messageBusType); var connection = CreateHubConnection(host); using (connection) { var disconnectWh = new ManualResetEventSlim(); connection.Closed += () => { disconnectWh.Set(); }; SetReconnectDelay(host.Transport, TimeSpan.FromSeconds(15)); connection.Start(host.Transport).Wait(); // Without this the connection start and reconnect can race with eachother resulting in a deadlock. Thread.Sleep(TimeSpan.FromSeconds(3)); // Set reconnect window to zero so the second we attempt to reconnect we can ensure that the reconnect window is verified. ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(0); host.Shutdown(); Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired"); } } }
bool IsUniqueType(TransportType type) { DataRow[] typeRows = ticketsDataSet.Type.Select("[ttype_name] ='" + type.Name.ToString() + "'"); if (typeRows.Length > 0) return false; return true; }
public async Task TransportTimesOutIfNoInitMessage(HostType hostType, TransportType transportType, MessageBusType messageBusType) { var mre = new AsyncManualResetEvent(); using (var host = CreateHost(hostType, transportType)) { host.Initialize(transportConnectTimeout: 1, messageBusType: messageBusType); HubConnection hubConnection = CreateHubConnection(host, "/no-init"); IHubProxy proxy = hubConnection.CreateHubProxy("DelayedOnConnectedHub"); using (hubConnection) { try { await hubConnection.Start(host.Transport); } catch { mre.Set(); } Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(10))); } } }
public void SuccessiveTimeoutTest(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { // Arrange var mre = new ManualResetEventSlim(false); host.Initialize(keepAlive: null); var connection = CreateConnection(host, "/my-reconnect"); ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2)); connection.Reconnected += () => { mre.Set(); }; connection.Start(host.Transport).Wait(); // Assert that Reconnected is called Assert.True(mre.Wait(TimeSpan.FromSeconds(10))); // Assert that Reconnected is called again mre.Reset(); Assert.True(mre.Wait(TimeSpan.FromSeconds(10))); // Clean-up mre.Dispose(); connection.Stop(); } }
public void ReconnectionSuccesfulTest(HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { // Arrange var mre = new ManualResetEventSlim(false); host.Initialize(keepAlive: null, messageBusType: messageBusType); var connection = CreateConnection(host, "/my-reconnect"); using (connection) { ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromSeconds(2)); connection.Reconnected += () => { mre.Set(); }; connection.Start(host.Transport).Wait(); // Assert Assert.True(mre.Wait(TimeSpan.FromSeconds(10))); // Clean-up mre.Dispose(); } } }
/// <summary> /// Construct a Kerberos test client for FAST /// </summary> /// <param name="domain">The realm part of the client's principal identifier. /// This argument cannot be null.</param> /// <param name="cName">The account to logon the remote machine. Either user account or computer account /// This argument cannot be null.</param> /// <param name="password">The password of the user. This argument cannot be null.</param> /// <param name="accountType">The type of the logon account. User or Computer</param> public KerberosFunctionalClient(string domain, string cName, string password, KerberosAccountType accountType, KerberosTicket armorTicket, EncryptionKey armorSessionKey, string kdcAddress, int kdcPort, TransportType transportType, KerberosConstValue.OidPkt omiPkt, ITestSite baseTestSite) : base(domain, cName, password, accountType, armorTicket, armorSessionKey, kdcAddress, kdcPort, transportType, omiPkt) { testSite = baseTestSite; if (accountType == KerberosAccountType.Device) { testSite.Log.Add(LogEntryKind.Debug, "Construct Kerberos client using computer account: {0}@{1}.", cName, domain); } else { testSite.Log.Add(LogEntryKind.Debug, "Construct Kerberos client using user account: {0}@{1}.", cName, domain); } EncryptionType[] encryptionTypes = new EncryptionType[] { EncryptionType.AES256_CTS_HMAC_SHA1_96, EncryptionType.AES128_CTS_HMAC_SHA1_96, EncryptionType.RC4_HMAC, EncryptionType.RC4_HMAC_EXP, EncryptionType.DES_CBC_CRC, EncryptionType.DES_CBC_MD5 }; KerbInt32[] etypes = new KerbInt32[encryptionTypes.Length]; for (int i = 0; i < encryptionTypes.Length; i++) { etypes[i] = new KerbInt32((int)encryptionTypes[i]); } Asn1SequenceOf<KerbInt32> etype = new Asn1SequenceOf<KerbInt32>(etypes); Context.SupportedEType = etype; Context.Pvno = KerberosConstValue.KERBEROSV5; }
public void ThrownWebExceptionShouldBeUnwrapped(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(); var connection = new Client.Connection(host.Url + "/ErrorsAreFun"); // Expecting 404 var aggEx = Assert.Throws<AggregateException>(() => connection.Start(host.Transport).Wait()); connection.Stop(); using (var ser = aggEx.GetError()) { if (hostType == HostType.IISExpress) { Assert.Equal(System.Net.HttpStatusCode.InternalServerError, ser.StatusCode); } else { Assert.Equal(System.Net.HttpStatusCode.NotFound, ser.StatusCode); } Assert.NotNull(ser.ResponseBody); Assert.NotNull(ser.Exception); } } }
/// <summary> /// Creates the input gateway. /// </summary> /// <param name="uri">The URI.</param> /// <param name="transportType">The supported transports.</param> /// <param name="numberOfParallelTasks">The number of parallel tasks.</param> /// <param name="maxReijections">The max reijections.</param> /// <returns></returns> public static RouterInputGateway CreateInputGateway(Uri uri, TransportType transportType, int numberOfParallelTasks, int maxReijections) { return new RouterInputGateway(EndPointFactory.CreateReceiverEndPoint(uri, transportType, numberOfParallelTasks), maxReijections) { Logger = LoggerManager.Instance }; }
TransportListener(IPEndPoint endPoint) { if (TD.TcpTransportListenerListeningStartIsEnabled()) { TD.TcpTransportListenerListeningStart(this.EventTraceActivity, GetRemoteEndpointAddressPort(endPoint)); } transportType = TransportType.Tcp; SocketSettings socketSettings = new SocketSettings(); IConnectionListener connectionListener = null; if (endPoint.Address.Equals(IPAddress.Broadcast)) { if (Socket.OSSupportsIPv4) { connectionListener = new SocketConnectionListener(new IPEndPoint(IPAddress.Any, endPoint.Port), socketSettings, true); demuxer = Go(connectionListener); } if (Socket.OSSupportsIPv6) { connectionListener = new SocketConnectionListener(new IPEndPoint(IPAddress.IPv6Any, endPoint.Port), socketSettings, true); demuxerV6 = Go(connectionListener); } } else { connectionListener = new SocketConnectionListener(endPoint, socketSettings, true); demuxer = Go(connectionListener); } if (TD.TcpTransportListenerListeningStopIsEnabled()) { TD.TcpTransportListenerListeningStop(this.EventTraceActivity); } }
public void ReconnectRequestPathEndsInReconnect(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { // Arrange var tcs = new TaskCompletionSource<bool>(); var receivedMessage = false; host.Initialize(keepAlive: null, connectionTimeout: 2, disconnectTimeout: 6); var connection = CreateConnection(host, "/examine-reconnect"); connection.Received += (reconnectEndsPath) => { if (!receivedMessage) { tcs.TrySetResult(reconnectEndsPath == "True"); receivedMessage = true; } }; connection.Start(host.Transport).Wait(); // Wait for reconnect Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(10))); Assert.True(tcs.Task.Result); // Clean-up connection.Stop(); } }
protected ITestHost CreateHost(HostType hostType, TransportType transportType) { ITestHost host = null; switch (hostType) { case HostType.IISExpress: host = new IISExpressTestHost(); host.TransportFactory = () => CreateTransport(transportType); host.Transport = host.TransportFactory(); break; case HostType.Memory: var mh = new MemoryHost(); host = new MemoryTestHost(mh); host.TransportFactory = () => CreateTransport(transportType, mh); host.Transport = host.TransportFactory(); break; case HostType.Owin: host = new OwinTestHost(); host.TransportFactory = () => CreateTransport(transportType); host.Transport = host.TransportFactory(); break; default: break; } return host; }
public void GroupsReceiveMessages(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(); var connection = CreateConnection(host, "/groups"); var list = new List<string>(); connection.Received += data => { list.Add(data); }; connection.Start(host.Transport).Wait(); // Join the group connection.SendWithTimeout(new { type = 1, group = "test" }); // Sent a message connection.SendWithTimeout(new { type = 3, group = "test", message = "hello to group test" }); // Leave the group connection.SendWithTimeout(new { type = 2, group = "test" }); // Send a message connection.SendWithTimeout(new { type = 3, group = "test", message = "goodbye to group test" }); Thread.Sleep(TimeSpan.FromSeconds(5)); connection.Stop(); Assert.Equal(1, list.Count); Assert.Equal("hello to group test", list[0]); } }
public async Task CanInvokeMethodsAndReceiveMessagesFromValidTypedHub(HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(messageBusType: messageBusType); using (var connection = CreateHubConnection(host)) { var hub = connection.CreateHubProxy("ValidTypedHub"); var echoTcs = new TaskCompletionSource<string>(); var pingWh = new ManualResetEventSlim(); hub.On<string>("Echo", message => echoTcs.TrySetResult(message)); hub.On("Ping", pingWh.Set); await connection.Start(host.TransportFactory()); hub.InvokeWithTimeout("Echo", "arbitrary message"); Assert.True(echoTcs.Task.Wait(TimeSpan.FromSeconds(10))); Assert.Equal("arbitrary message", echoTcs.Task.Result); hub.InvokeWithTimeout("Ping"); Assert.True(pingWh.Wait(TimeSpan.FromSeconds(10))); } } }
public void ConnectionErrorCapturesExceptionsThrownInClientHubMethod(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { var wh = new ManualResetEventSlim(); Exception thrown = new Exception(), caught = null; host.Initialize(); var connection = CreateHubConnection(host); var proxy = connection.CreateHubProxy("ChatHub"); proxy.On("addMessage", () => { throw thrown; }); connection.Error += e => { caught = e; wh.Set(); }; connection.Start(host.Transport).Wait(); proxy.Invoke("Send", ""); Assert.True(wh.Wait(TimeSpan.FromSeconds(5))); Assert.Equal(thrown, caught); } }
public void EndToEndTest(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(); HubConnection hubConnection = CreateHubConnection(host); IHubProxy proxy = hubConnection.CreateHubProxy("ChatHub"); var wh = new ManualResetEvent(false); proxy.On("addMessage", data => { Assert.Equal("hello", data); wh.Set(); }); hubConnection.Start(host.Transport).Wait(); proxy.InvokeWithTimeout("Send", "hello"); Assert.True(wh.WaitOne(TimeSpan.FromSeconds(10))); hubConnection.Stop(); } }
public IVoIPTransport CreateTransport(TransportType transportType, TransportConfig config) { var tpt = CreateTransport(transportType); using (((Initializable)tpt).InitializationScope()) if (config != null) tpt.SetConfig(config); return tpt; }
public async Task SuccessiveTimeoutTest(HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { // Arrange var mre = new AsyncManualResetEvent(false); host.Initialize(keepAlive: 5, messageBusType: messageBusType); var connection = CreateConnection(host, "/my-reconnect"); using (connection) { connection.Reconnected += () => { mre.Set(); }; await connection.Start(host.Transport); ((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromMilliseconds(300)); // Assert that Reconnected is called Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(15))); // Assert that Reconnected is called again mre.Reset(); Assert.True(await mre.WaitAsync(TimeSpan.FromSeconds(15))); // Clean-up mre.Dispose(); } } }
public ActionResult ImportTransportTypes() { String[] transportTypes = new[] { "Автобусы", "Троллейбусы", "Маршрутные такси" }; using (DataContext dataContext = new DataContext()) { foreach (String typeName in transportTypes) { TransportType type = new TransportType() { Name = typeName }; dataContext.TransportTypes.Add(type); dataContext.SaveChanges(); } } return this.Content("Transport types imported"); }
public void BasicAuthCredentialsFlow(TransportType transportType) { using (var host = new OwinTestHost()) { Debug.Listeners.Clear(); host.Start<BasicAuthApplication>(); HubConnection connection = CreateHubConnection(host); var hub = connection.CreateHubProxy("demo"); hub["name"] = "test"; connection.Credentials = new System.Net.NetworkCredential("user", "password"); connection.Start(CreateTransport(transportType)).Wait(); var result = hub.InvokeWithTimeout<string>("ReadStateValue"); Assert.Equal("test", result); connection.Stop(); } }
/// <summary> /// Create a Kpassword client instance /// </summary> /// <param name="kdcAddress">The IP address of the KDC.</param> /// <param name="kdcPort">The port of the KDC.</param> /// <param name="transportType">Whether the transport is TCP or UDP transport.</param> public KpasswdClient(string kdcAddress, int kdcPort, TransportType transportType) { this.Context = new KerberosContext(); this.kdcAddress = kdcAddress; this.kdcPort = kdcPort; this.transportType = transportType; }
bool IsUsedType(TransportType type) { DataRow[] typesUsedInTicketRows = ticketsDataSet.Ticket.Select("[ttype_id] ='" + type.ID.ToString() + "'"); if (typesUsedInTicketRows.Length > 0) return false; return true; }
public Transport(TransportType transportType, String assetName, int carSize, Texture2D graphic, Texture2D glowingGraphic, int value) : base(AssetType.Car, value, assetName) { TransportType = transportType; _currentGraphic = graphic; _glowingGraphic = glowingGraphic; CarSize = carSize; }
public ListenerSessionConnectionReader(IConnection connection, Action connectionDequeuedCallback, TransportType transportType, long streamPosition, int offset, int size, ConnectionClosedCallback closedCallback, ViaDecodedCallback viaDecodedCallback) : base(connection, connectionDequeuedCallback, transportType, offset, size, closedCallback, viaDecodedCallback) { this.decoder = new ServerSessionDecoder(streamPosition, ListenerConstants.MaxUriSize, ListenerConstants.SharedMaxContentTypeSize); }
public Location(string realName, string[] aliases, string latitude, string longtitude, TransportType type) { this.RealName = realName; this.Latitude = latitude; this.Longtitude = longtitude; this.aliases.AddRange(aliases); this.LocationType = type; }
public async Task ServerThrowsHubExceptionIfStreamingHubMethodCannotBeResolved(IHubProtocol hubProtocol, TransportType transportType, string hubPath) { using (StartLog(out var loggerFactory, $"{nameof(ServerThrowsHubExceptionIfStreamingHubMethodCannotBeResolved)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}")) { var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory); var connection = new HubConnection(httpConnection, hubProtocol, loggerFactory); try { await connection.StartAsync().OrTimeout(); var channel = await connection.StreamAsync <int>("!@#$%"); var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync().OrTimeout()); Assert.Equal("Unknown hub method '!@#$%'", ex.Message); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test"); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public async Task ServerThrowsHubExceptionOnStreamingHubMethodArgumentCountMismatch(IHubProtocol hubProtocol, TransportType transportType, string hubPath) { using (StartLog(out var loggerFactory, $"{nameof(ServerThrowsHubExceptionOnStreamingHubMethodArgumentCountMismatch)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}")) { loggerFactory.AddConsole(LogLevel.Trace); var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory); var connection = new HubConnection(httpConnection, hubProtocol, loggerFactory); try { await connection.StartAsync().OrTimeout(); var channel = await connection.StreamAsync <int>("Stream", 42, 42); var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync().OrTimeout()); Assert.Equal("Invocation provides 2 argument(s) but target expects 1.", ex.Message); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test"); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public TransportArrived(int time, int transportId, TransportType kind, Place destination, Cargo[] cargo) : base("ARRIVE", time, transportId, kind, null, destination, null, cargo) { }
public HttpConnection(Uri url, TransportType transportType, ILoggerFactory loggerFactory) : this(url, transportType, loggerFactory, httpOptions : null) { }
/// <summary> /// Create an DeviceClient from the specified connection string using the specified transport type /// </summary> /// <param name="connectionString">IoT Hub-Scope Connection string for the IoT hub (without DeviceId)</param> /// <param name="deviceId">Id of the device</param> /// <param name="transportType">The transportType used (Http1 or Amqp)</param> /// <returns>DeviceClient</returns> public static DeviceClient CreateFromConnectionString(string connectionString, string deviceId, TransportType transportType) { if (connectionString == null) { throw new ArgumentNullException("connectionString"); } if (deviceId == null) { throw new ArgumentNullException("deviceId"); } return(CreateFromConnectionString(connectionString + ";" + DeviceId + "=" + deviceId, transportType)); }
public static TransportHeader Parse(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Unable to parse null or empty Transport header value"); } LOG.Debug($"Attempting to parsing RTSP Transport header: {value}"); TransportType discoveredType = TransportType.Unknown; TransportHeader.Builder builder = TransportHeader.CreateBuilder(); string[] parts = value.Split(new char[] { ';' }); foreach (var part in parts) { string[] keyValue = part.Split(new char[] { '=' }, 2); switch (keyValue.Length) { case 1: { if (keyValue[0] == "RTP/AVP/TCP") { discoveredType = TransportType.RtspInterleaved; builder.Type(discoveredType); } else if (keyValue[0] == "unicast" && discoveredType != TransportType.RtspInterleaved) { builder.Type(TransportType.UdpUnicast); } else if (keyValue[0] == "multicast" && discoveredType != TransportType.RtspInterleaved) { builder.Type(TransportType.UdpMulticast); } else if ((keyValue[0] != "multicast") || parts[0] == "RTP/AVP") { builder.AddExtra(part); } } break; case 2: { if (keyValue[0] == "interleaved") { builder.InterleavedChannels(ParsePortPair(keyValue[1])); } else if (keyValue[0] == "server_port") { builder.ServerPorts(ParsePortPair(keyValue[1])); } else if (keyValue[0] == "client_port") { builder.ClientPorts(ParsePortPair(keyValue[1])); } else if (keyValue[0] == "port") { builder.MulticastPorts(ParsePortPair(keyValue[1])); } else if (keyValue[0] == "ttl") { builder.TTL(int.Parse(keyValue[1])); } else if (keyValue[0] == "destination") { builder.Destination(keyValue[1].Trim()); } else if (keyValue[0] == "source") { builder.Source(keyValue[1].Trim()); } else if (keyValue[0] == "ssrc") { builder.SSRC(keyValue[1].Trim()); } else { builder.AddExtra(part); } } break; default: { builder.AddExtra(part); break; } } } return(builder.Build()); }
public void ConnectionFunctionsCorrectlyAfterCallingStartMutlipleTimes(HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(messageBusType: messageBusType); using (var connection = CreateConnection(host, "/echo")) { var tcs = new TaskCompletionSource <object>(); connection.Received += _ => tcs.TrySetResult(null); // We're purposely calling Start().Wait() twice here connection.Start(host.TransportFactory()).Wait(); connection.Start(host.TransportFactory()).Wait(); connection.Send("test").Wait(); // Wait for message to be received Assert.True(tcs.Task.Wait(TimeSpan.FromSeconds(10))); } } }
/// <summary> /// gets realtime data from public transport in city vilnius of lithuania /// </summary> /// <param name="type">type of transport</param> /// <param name="line">linenum or null to get all</param> /// <param name="ret"></param> public static void GetVilniusTransportData(TransportType type, string line, List <VehicleData> ret) { ret.Clear(); //http://stops.lt/vilnius/gps.txt?1318577178193 //http://www.marsrutai.lt/vilnius/Vehicle_Map.aspx?trackID=34006&t=1318577231295 // http://www.troleibusai.lt/eismas/get_gps.php?allowed=true&more=1&bus=1&rand=0.5487859781558404 string url = string.Format(CultureInfo.InvariantCulture, "http://www.troleibusai.lt/eismas/get_gps.php?allowed=true&more=1&bus={0}&rand={1}", type == TransportType.Bus ? 2 : 1, r.NextDouble()); if (!string.IsNullOrEmpty(line)) { url += "&nr=" + line; } #if !PocketPC url += "&app=GMap.NET.Desktop"; #else url += "&app=GMap.NET.WindowsMobile"; #endif string xml = string.Empty; { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = GMapProvider.UserAgent; request.Timeout = GMapProvider.TimeoutMs; request.ReadWriteTimeout = GMapProvider.TimeoutMs * 6; request.Accept = "*/*"; request.KeepAlive = true; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader read = new StreamReader(responseStream, Encoding.UTF8)) { xml = read.ReadToEnd(); } } #if PocketPC request.Abort(); #endif response.Close(); } } // 54.690688; 25.2116; 1263522; 1; 48.152; 2011-10-14 14:41:29 if (!string.IsNullOrEmpty(xml)) { var items = xml.Split('&'); foreach (var it in items) { var sit = it.Split(';'); if (sit.Length == 8) { VehicleData d = new VehicleData(); { d.Id = int.Parse(sit[2]); d.Lat = double.Parse(sit[0], CultureInfo.InvariantCulture); d.Lng = double.Parse(sit[1], CultureInfo.InvariantCulture); d.Line = sit[3]; if (!string.IsNullOrEmpty(sit[4])) { d.Bearing = double.Parse(sit[4], CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(sit[5])) { d.Time = sit[5]; var t = DateTime.Parse(d.Time); if (DateTime.Now - t > TimeSpan.FromMinutes(5)) { continue; } d.Time = t.ToLongTimeString(); } d.TrackType = sit[6]; } //if(d.Id == 1262760) //if(d.Line == "13") { ret.Add(d); } } } } #region -- old -- //XmlDocument doc = new XmlDocument(); //{ // doc.LoadXml(xml); // XmlNodeList devices = doc.GetElementsByTagName("Device"); // foreach(XmlNode dev in devices) // { // VehicleData d = new VehicleData(); // d.Id = int.Parse(dev.Attributes["ID"].InnerText); // foreach(XmlElement elem in dev.ChildNodes) // { // // Debug.WriteLine(d.Id + "->" + elem.Name + ": " + elem.InnerText); // switch(elem.Name) // { // case "Lat": // { // d.Lat = double.Parse(elem.InnerText, CultureInfo.InvariantCulture); // } // break; // case "Lng": // { // d.Lng = double.Parse(elem.InnerText, CultureInfo.InvariantCulture); // } // break; // case "Bearing": // { // if(!string.IsNullOrEmpty(elem.InnerText)) // { // d.Bearing = double.Parse(elem.InnerText, CultureInfo.InvariantCulture); // } // } // break; // case "LineNum": // { // d.Line = elem.InnerText; // } // break; // case "AreaName": // { // d.AreaName = elem.InnerText; // } // break; // case "StreetName": // { // d.StreetName = elem.InnerText; // } // break; // case "TrackType": // { // d.TrackType = elem.InnerText; // } // break; // case "LastStop": // { // d.LastStop = elem.InnerText; // } // break; // case "Time": // { // d.Time = elem.InnerText; // } // break; // } // } // ret.Add(d); // } //} #endregion }
private async Task <bool> EnsureConnectionStateAsync(DefaultConnectionContext connection, HttpContext context, TransportType transportType, TransportType supportedTransports, ConnectionLogScope logScope, HttpSocketOptions options) { if ((supportedTransports & transportType) == 0) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = StatusCodes.Status404NotFound; Log.TransportNotSupported(_logger, transportType); await context.Response.WriteAsync($"{transportType} transport not supported by this end point type"); return(false); } // Set the IHttpConnectionFeature now that we can access it. connection.Features.Set(context.Features.Get <IHttpConnectionFeature>()); var transport = (TransportType?)connection.Metadata[ConnectionMetadataNames.Transport]; if (transport == null) { connection.Metadata[ConnectionMetadataNames.Transport] = transportType; } else if (transport != transportType) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = StatusCodes.Status400BadRequest; Log.CannotChangeTransport(_logger, transport.Value, transportType); await context.Response.WriteAsync("Cannot change transports mid-connection"); return(false); } // Configure transport-specific features. if (transportType == TransportType.LongPolling) { connection.Features.Set <IConnectionInherentKeepAliveFeature>(new ConnectionInherentKeepAliveFeature(options.LongPolling.PollTimeout)); } // Setup the connection state from the http context connection.User = context.User; connection.SetHttpContext(context); // this is the default setting which should be overwritten by transports that have different capabilities (e.g. SSE) connection.TransportCapabilities = TransferMode.Binary | TransferMode.Text; // Set the Connection ID on the logging scope so that logs from now on will have the // Connection ID metadata set. logScope.ConnectionId = connection.ConnectionId; return(true); }
public HttpConnection(Uri url, TransportType transportType) : this(url, transportType, loggerFactory : null) { }
public async Task StreamDoesNotStartIfTokenAlreadyCanceled(IHubProtocol protocol, TransportType transportType, string path) { using (StartLog(out var loggerFactory, $"{nameof(StreamDoesNotStartIfTokenAlreadyCanceled)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) { var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + path), transportType, loggerFactory); var connection = new HubConnection(httpConnection, protocol, loggerFactory); try { await connection.StartAsync().OrTimeout(); var cts = new CancellationTokenSource(); cts.Cancel(); var channel = await connection.StreamAsync <int>("Stream", 5, cts.Token).OrTimeout(); await Assert.ThrowsAnyAsync <OperationCanceledException>(() => channel.WaitToReadAsync().OrTimeout()); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test"); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public async Task ConnectionFailsToStartWithInvalidOldProtocol(string protocolVersion, HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(messageBusType: messageBusType); var connection = CreateConnection(host, "/signalr"); Boolean faulted = false; connection.Protocol = new Version(protocolVersion); using (connection) { try { await connection.Start(host.Transport); } catch { faulted = true; } Assert.True(faulted); } } }
public async Task InvokeNonExistantClientMethodFromServer(IHubProtocol protocol, TransportType transportType, string path) { using (StartLog(out var loggerFactory, $"{nameof(InvokeNonExistantClientMethodFromServer)}_{protocol.Name}_{transportType}_{path.TrimStart('/')}")) { var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + path), transportType, loggerFactory); var connection = new HubConnection(httpConnection, protocol, loggerFactory); var closeTcs = new TaskCompletionSource <object>(); connection.Closed += e => { if (e != null) { closeTcs.SetException(e); } else { closeTcs.SetResult(null); } }; try { await connection.StartAsync().OrTimeout(); await connection.InvokeAsync("CallHandlerThatDoesntExist").OrTimeout(); await connection.DisposeAsync().OrTimeout(); await closeTcs.Task.OrTimeout(); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} during test: {Message}", ex.GetType().Name, ex.Message); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public async Task ServerThrowsHubExceptionIfBuildingAsyncEnumeratorIsNotPossible(IHubProtocol hubProtocol, TransportType transportType, string hubPath) { using (StartLog(out var loggerFactory, $"{nameof(ServerThrowsHubExceptionIfBuildingAsyncEnumeratorIsNotPossible)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}")) { var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory); var connection = new HubConnection(httpConnection, hubProtocol, loggerFactory); try { await connection.StartAsync().OrTimeout(); var channel = await connection.StreamAsync <int>("StreamBroken").OrTimeout(); var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync()).OrTimeout(); Assert.Equal("The value returned by the streaming method 'StreamBroken' is null, does not implement the IObservable<> interface or is not a ReadableChannel<>.", ex.Message); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test"); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public async Task ConnectionCanSendAndReceiveMessages(TransportType transportType, TransferMode requestedTransferMode) { using (StartLog(out var loggerFactory, testName: $"ConnectionCanSendAndReceiveMessages_{transportType.ToString()}")) { var logger = loggerFactory.CreateLogger <EndToEndTests>(); const string message = "Major Key"; var url = _serverFixture.Url + "/echo"; var connection = new HttpConnection(new Uri(url), transportType, loggerFactory); connection.Features.Set <ITransferModeFeature>( new TransferModeFeature { TransferMode = requestedTransferMode }); try { var receiveTcs = new TaskCompletionSource <string>(); connection.OnReceived((data, state) => { logger.LogInformation("Received {length} byte message", data.Length); if (IsBase64Encoded(requestedTransferMode, connection)) { data = Convert.FromBase64String(Encoding.UTF8.GetString(data)); } var tcs = (TaskCompletionSource <string>)state; tcs.TrySetResult(Encoding.UTF8.GetString(data)); return(Task.CompletedTask); }, receiveTcs); logger.LogInformation("Starting connection to {url}", url); await connection.StartAsync().OrTimeout(); logger.LogInformation("Started connection to {url}", url); var bytes = Encoding.UTF8.GetBytes(message); // Need to encode binary payloads sent over text transports if (IsBase64Encoded(requestedTransferMode, connection)) { bytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(bytes)); } logger.LogInformation("Sending {length} byte message", bytes.Length); try { await connection.SendAsync(bytes).OrTimeout(); } catch (OperationCanceledException) { // Because the server and client are run in the same process there is a race where websocket.SendAsync // can send a message but before returning be suspended allowing the server to run the EchoEndpoint and // send a close frame which triggers a cancellation token on the client and cancels the websocket.SendAsync. // Our solution to this is to just catch OperationCanceledException from the sent message if the race happens // because we know the send went through, and its safe to check the response. } logger.LogInformation("Sent message", bytes.Length); logger.LogInformation("Receiving message"); Assert.Equal(message, await receiveTcs.Task.OrTimeout()); logger.LogInformation("Completed receive"); await connection.Closed.OrTimeout(); } catch (Exception ex) { logger.LogInformation(ex, "Test threw exception"); throw; } finally { logger.LogInformation("Disposing Connection"); await connection.DisposeAsync().OrTimeout(); logger.LogInformation("Disposed Connection"); } } }
public async Task ServerThrowsHubExceptionIfStreamMethodInvokedWithInvoke(IHubProtocol hubProtocol, TransportType transportType, string hubPath) { using (StartLog(out var loggerFactory, $"{nameof(ServerThrowsHubExceptionIfStreamMethodInvokedWithInvoke)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}")) { var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory); var connection = new HubConnection(httpConnection, hubProtocol, loggerFactory); try { await connection.StartAsync().OrTimeout(); var ex = await Assert.ThrowsAsync <HubException>(() => connection.InvokeAsync("Stream", 3)).OrTimeout(); Assert.Equal("The client attempted to invoke the streaming 'Stream' method in a non-streaming fashion.", ex.Message); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test"); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
/// <summary> /// Create DeviceClient from the specified connection string using the specified transport type /// (WinRT) Only Http transport is allowed /// </summary> /// <param name="connectionString">Connection string for the IoT hub (including DeviceId)</param> /// <param name="transportType">Specifies whether Amqp or Http transport is used</param> /// <returns>DeviceClient</returns> public static DeviceClient CreateFromConnectionString(string connectionString, TransportType transportType) { if (connectionString == null) { throw new ArgumentNullException("connectionString"); } var iotHubConnectionString = IotHubConnectionString.Parse(connectionString); if (transportType == TransportType.Http1) { return(new DeviceClient(new HttpDeviceClient(iotHubConnectionString))); } else { throw new NotImplementedException(); } throw new InvalidOperationException("Unsupported Transport Type " + transportType.ToString()); }
public async Task ServerThrowsHubExceptionOnStreamingHubMethodArgumentTypeMismatch(IHubProtocol hubProtocol, TransportType transportType, string hubPath) { using (StartLog(out var loggerFactory, $"{nameof(ServerThrowsHubExceptionOnStreamingHubMethodArgumentTypeMismatch)}_{hubProtocol.Name}_{transportType}_{hubPath.TrimStart('/')}")) { var httpConnection = new HttpConnection(new Uri(_serverFixture.Url + hubPath), transportType, loggerFactory); var connection = new HubConnection(httpConnection, hubProtocol, loggerFactory); try { await connection.StartAsync().OrTimeout(); var channel = await connection.StreamAsync <int>("Stream", "xyz"); var ex = await Assert.ThrowsAsync <HubException>(() => channel.ReadAllAsync().OrTimeout()); Assert.StartsWith("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex.Message); } catch (Exception ex) { loggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "Exception from test"); throw; } finally { await connection.DisposeAsync().OrTimeout(); } } }
public void SaveStateReward(string previousAgentState, string currentAgentState, double reward, TransportType previousAction) { var item = collection.Find(x => x.State == previousAgentState).FirstOrDefault(); if (item != null) { var allTransportTypes = item.AgentActions; var current = allTransportTypes.Find(x => x.Transport == previousAction.ToString()); current.AddReward(reward); var updateDef = Builders <MongoAgentStateInfo> .Update.Set(o => o.AgentActions, allTransportTypes); collection.UpdateOne(x => x.State == previousAgentState, updateDef); } else { collection.InsertOne( new MongoAgentStateInfo { State = previousAgentState, AgentActions = StorageHelpers.CreateFirstAgentActions(previousAction, reward) }); } }
public TransportDeparted(int time, int transportId, TransportType kind, Place location, Place destination, Cargo[] cargo) : base("DEPART", time, transportId, kind, location, destination, null, cargo) { }
/// <summary> /// Creates a ModuleClient instance in an IoT Edge deployment /// based on environment variables. /// </summary> /// <param name="transportType">Specifies whether Amqp or Http transport is used</param> /// <returns>ModuleClient instance</returns> public static Task <ModuleClient> CreateFromEnvironmentAsync(TransportType transportType) { return(CreateFromEnvironmentAsync(ClientFactory.GetTransportSettings(transportType))); }
private async Task StartAsyncInternal() { Log.HttpConnectionStarting(_logger); try { var connectUrl = Url; if (_requestedTransportType == TransportType.WebSockets) { Log.StartingTransport(_logger, _requestedTransportType, connectUrl); await StartTransport(connectUrl, _requestedTransportType); } else { var negotiationResponse = await GetNegotiationResponse(); // Connection is being disposed while start was in progress if (_connectionState == ConnectionState.Disposed) { Log.HttpConnectionClosed(_logger); return; } // This should only need to happen once _serverTransports = GetAvailableServerTransports(negotiationResponse); connectUrl = CreateConnectUrl(Url, negotiationResponse.ConnectionId); foreach (var transport in AllTransports) { try { if ((transport & _serverTransports & _requestedTransportType) != 0) { // The negotiation response gets cleared in the fallback scenario. if (negotiationResponse == null) { negotiationResponse = await GetNegotiationResponse(); connectUrl = CreateConnectUrl(Url, negotiationResponse.ConnectionId); } Log.StartingTransport(_logger, transport, connectUrl); await StartTransport(connectUrl, transport); break; } } catch (Exception) { // Try the next transport // Clear the negotiation response so we know to re-negotiate. negotiationResponse = null; } } } if (_transport == null) { throw new InvalidOperationException("Unable to connect to the server with any of the available transports."); } } catch { // The connection can now be either in the Connecting or Disposed state - only change the state to // Disconnected if the connection was in the Connecting state to not resurrect a Disposed connection ChangeState(from: ConnectionState.Connecting, to: ConnectionState.Disconnected); throw; } // if the connection is not in the Connecting state here it means the user called DisposeAsync while // the connection was starting if (ChangeState(from: ConnectionState.Connecting, to: ConnectionState.Connected) == ConnectionState.Connecting) { _closeTcs = new TaskCompletionSource <object>(); Input.OnWriterCompleted(async(exception, state) => { // Grab the exception and then clear it. // See comment at AbortAsync for more discussion on the thread-safety // StartAsync can't be called until the ChangeState below, so we're OK. var abortException = _abortException; _abortException = null; // There is an inherent race between receive and close. Removing the last message from the channel // makes Input.Completion task completed and runs this continuation. We need to await _receiveLoopTask // to make sure that the message removed from the channel is processed before we drain the queue. // There is a short window between we start the channel and assign the _receiveLoopTask a value. // To make sure that _receiveLoopTask can be awaited (i.e. is not null) we need to await _startTask. Log.ProcessRemainingMessages(_logger); await _startTcs.Task; await _receiveLoopTask; Log.DrainEvents(_logger); await Task.WhenAny(_eventQueue.Drain().NoThrow(), Task.Delay(_eventQueueDrainTimeout)); Log.CompleteClosed(_logger); _logScope.ConnectionId = null; // At this point the connection can be either in the Connected or Disposed state. The state should be changed // to the Disconnected state only if it was in the Connected state. // From this point on, StartAsync can be called at any time. ChangeState(from: ConnectionState.Connected, to: ConnectionState.Disconnected); _closeTcs.SetResult(null); try { if (exception != null) { Closed?.Invoke(exception); } else { // Call the closed event. If there was an abort exception, it will be flowed forward // However, if there wasn't, this will just be null and we're good Closed?.Invoke(abortException); } } catch (Exception ex) { // Suppress (but log) the exception, this is user code Log.ErrorDuringClosedEvent(_logger, ex); } }, null); _receiveLoopTask = ReceiveAsync(); } }
public IoTInterfaceConfig(NameValueCollection nameValueCollection) : base(nameValueCollection) { TransportType = (TransportType)Enum.Parse(typeof(TransportType), nameValueCollection[TransportTypeKey]); }
/// <summary> /// Create a ModuleClient from individual parameters /// </summary> /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param> /// <param name="gatewayHostname">The fully-qualified DNS hostname of Gateway</param> /// <param name="authenticationMethod">The authentication method that is used</param> /// <param name="transportType">The transportType used (Http1 or Amqp)</param> /// <returns>ModuleClient</returns> public static ModuleClient Create(string hostname, string gatewayHostname, IAuthenticationMethod authenticationMethod, TransportType transportType) { return(Create(() => ClientFactory.Create(hostname, gatewayHostname, authenticationMethod, transportType))); }
public void ClientStaysReconnectedAfterDisconnectTimeout(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(keepAlive: null, connectionTimeout: 2, disconnectTimeout: 6); var connection = CreateHubConnection(host); var reconnectingWh = new ManualResetEventSlim(); var reconnectedWh = new ManualResetEventSlim(); connection.Reconnecting += () => { reconnectingWh.Set(); Assert.Equal(ConnectionState.Reconnecting, connection.State); }; connection.Reconnected += () => { reconnectedWh.Set(); Assert.Equal(ConnectionState.Connected, connection.State); }; connection.Start(host.Transport).Wait(); // Force reconnect Thread.Sleep(TimeSpan.FromSeconds(5)); Assert.True(reconnectingWh.Wait(TimeSpan.FromSeconds(30))); Assert.True(reconnectedWh.Wait(TimeSpan.FromSeconds(30))); Thread.Sleep(TimeSpan.FromSeconds(15)); Assert.NotEqual(ConnectionState.Disconnected, connection.State); connection.Stop(); } }
/// <summary> /// Create ModuleClient from the specified connection string using the specified transport type /// </summary> /// <param name="connectionString">Connection string for the IoT hub (including DeviceId)</param> /// <param name="transportType">Specifies whether Amqp or Http transport is used</param> /// <returns>ModuleClient</returns> public static ModuleClient CreateFromConnectionString(string connectionString, TransportType transportType) { return(Create(() => ClientFactory.CreateFromConnectionString(connectionString, transportType))); }
//[InlineData(HostType.IISExpress, TransportType.LongPolling)] public void ClientStopsReconnectingAfterDisconnectTimeout(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(disconnectTimeout: 6); var connection = CreateHubConnection(host); var reconnectWh = new ManualResetEventSlim(); var disconnectWh = new ManualResetEventSlim(); connection.Reconnecting += () => { reconnectWh.Set(); Assert.Equal(ConnectionState.Reconnecting, connection.State); }; connection.Closed += () => { disconnectWh.Set(); Assert.Equal(ConnectionState.Disconnected, connection.State); }; connection.Start(host.Transport).Wait(); host.Shutdown(); Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(25)), "Reconnect never fired"); Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(25)), "Closed never fired"); } }
public void ConnectionErrorCapturesExceptionsThrownInReceived(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { var errorsCaught = 0; var wh = new ManualResetEventSlim(); Exception thrown = new Exception(), caught = null; host.Initialize(); var connection = CreateConnection(host, "/multisend"); connection.Received += _ => { throw thrown; }; connection.Error += e => { caught = e; if (Interlocked.Increment(ref errorsCaught) == 2) { wh.Set(); } }; connection.Start(host.Transport).Wait(); Assert.True(wh.Wait(TimeSpan.FromSeconds(5))); Assert.Equal(thrown, caught); } }