Inheritance: IClientTransport
Beispiel #1
0
        public async Task AutoTransportDoesNotTryAnotherTransportIfTransportFailsDuringStartRequest()
        {
            var mockConnection = new Mock <IConnection>();

            mockConnection.Setup(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(5));
            mockConnection.Setup(c => c.JsonSerializer).Returns(JsonSerializer.CreateDefault());

            var mockHttpClient = new Mock <IHttpClient>();

            var mockFailingTransport = new Mock <ClientTransportBase>(mockHttpClient.Object, "fakeTransport")
            {
                CallBase = true
            };

            mockFailingTransport.Protected()
            .Setup("OnStart", ItExpr.IsAny <IConnection>(), ItExpr.IsAny <string>(), ItExpr.IsAny <CancellationToken>())
            .Callback <IConnection, string, CancellationToken>((c, d, t) =>
            {
                mockFailingTransport.Object.ProcessResponse(c,
                                                            "{\"C\":\"d-C6243495-A,0|B,0|C,1|D,0\",\"S\":1,\"M\":[]}");
            });

            var exception        = new Exception("test exception");
            var waitForException = new TaskCompletionSource <object>();

            mockHttpClient
            .Setup(c => c.Get(It.IsAny <string>(), It.IsAny <Action <IRequest> >(), It.IsAny <bool>()))
            .Returns <string, Action <IRequest>, bool>(async(url, prepareRequest, isLongRunning) =>
            {
                mockFailingTransport.Object.TransportFailed(exception);

                await waitForException.Task;

                return(Mock.Of <IResponse>());
            });

            var mockTransport = new Mock <IClientTransport>();

            mockTransport.Setup(t => t.Start(It.IsAny <IConnection>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <object>(null));

            var autoTransport = new AutoTransport(mockHttpClient.Object,
                                                  new List <IClientTransport> {
                mockFailingTransport.Object, mockTransport.Object
            });

            var startException = await Assert.ThrowsAsync <StartException>(
                async() => await autoTransport.Start(mockConnection.Object, string.Empty, CancellationToken.None));

            waitForException.TrySetResult(null);

            Assert.Same(exception, startException.InnerException);

            mockTransport.Verify(
                t => t.Start(It.IsAny <IConnection>(), It.IsAny <string>(), It.IsAny <CancellationToken>()),
                Times.Never());
        }
        public void AutoTransportDoesNotTryAnotherTransportIfTransportFailsDuringStartRequest()
        {
            var mockConnection = new Mock<IConnection>();
            mockConnection.Setup(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(5));
            mockConnection.Setup(c => c.JsonSerializer).Returns(JsonSerializer.CreateDefault());

            var mockHttpClient = new Mock<IHttpClient>();

            var mockFailingTransport = new Mock<ClientTransportBase>(mockHttpClient.Object, "fakeTransport") {CallBase = true};
            mockFailingTransport.Protected()
                .Setup("OnStart", ItExpr.IsAny<IConnection>(), ItExpr.IsAny<string>(), ItExpr.IsAny<CancellationToken>())
                .Callback<IConnection, string, CancellationToken>((c, d, t) =>
                {
                    mockFailingTransport.Object.ProcessResponse(c,
                        "{\"C\":\"d-C6243495-A,0|B,0|C,1|D,0\",\"S\":1,\"M\":[]}");
                });

            var exception = new Exception("test exception");
            mockHttpClient
                .Setup(c => c.Get(It.IsAny<string>(), It.IsAny<Action<IRequest>>(), It.IsAny<bool>()))
                .Returns<string, Action<IRequest>, bool>((url, prepareRequest, isLongRunning) =>
                {
                    mockFailingTransport.Object.TransportFailed(exception);

                    return Task.FromResult(Mock.Of<IResponse>());
                });

            var mockTransport = new Mock<IClientTransport>();
            mockTransport.Setup(t => t.Start(It.IsAny<IConnection>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult<object>(null));

            var autoTransport = new AutoTransport(mockHttpClient.Object,
                new List<IClientTransport> {mockFailingTransport.Object, mockTransport.Object});

            var startException =
                Assert.Throws<AggregateException>(() =>
                    autoTransport.Start(mockConnection.Object, string.Empty, CancellationToken.None)
                        .Wait(TimeSpan.FromSeconds(1))).InnerException;

            Assert.IsType<StartException>(startException);
            Assert.Same(exception, startException.InnerException);

            mockTransport.Verify(
                t => t.Start(It.IsAny<IConnection>(), It.IsAny<string>(), It.IsAny<CancellationToken>()),
                Times.Never());
        }
Beispiel #3
0
        public void CancelledTaskHandledinAutoTransport()
        {
            var tcs = new TaskCompletionSource<IResponse>();

            tcs.TrySetCanceled();

            var transport = new Mock<IClientTransport>();
            transport.Setup(t => t.Start(It.IsAny<IConnection>(), It.IsAny<string>(), CancellationToken.None))
                .Returns(tcs.Task);

            var transports = new List<IClientTransport>();
            transports.Add(transport.Object);

            var autoTransport = new AutoTransport(new DefaultHttpClient(), transports);
            var task = autoTransport.Start(new Connection("http://foo"), string.Empty, CancellationToken.None);

            Assert.IsType(typeof(OperationCanceledException), task.Exception.InnerException);
        }
Beispiel #4
0
 private static Task Do()
 {
     string url = "http://192.168.70.118:1980";
     var connection = new HubConnection(url);
     IHubProxy hub = connection.CreateHubProxy("echo");
     var httpClient = new DefaultHttpClient();
     var transport = new AutoTransport(
         httpClient,
         new IClientTransport[]
         {
             //new ServerSentEventsTransport(httpClient),
             new LongPollingTransport(httpClient)
         }
         );
     //connection.Error +=
     //    error => ConsoleColor.Red.AsColorFor(() => Console.WriteLine("Error from connection: {0}", error));
     connection.Closed += () =>
     {
         Console.WriteLine("Closed");
         //if (!connection.EnsureReconnecting())
         //{
         //    Task.Delay(TimeSpan.FromSeconds(30)).ContinueWith(t => connection.Start().Wait());
         //}
         if (!connection.EnsureReconnecting())
         {
             Task.Factory.StartNew(() => Thread.Sleep(TimeSpan.FromSeconds(30)))
                 .ContinueWith(t => connection.Start().Wait());
         }
     };
     connection.ConnectionSlow += () => Console.WriteLine("ConnectionSolw!");
     connection.Received += data => Console.WriteLine(string.Format("Received:{0}", data));
     connection.Reconnected += () => Console.WriteLine("Reconnected!");
     connection.StateChanged +=
         state =>
             Console.WriteLine("StateChanged:From {0} to {1}", state.OldState, state.NewState);
     return connection.Start(transport).ContinueWith(_ =>
     {
         Console.WriteLine("Connected, transport is :{0}", connection.Transport.Name);
         return hub;
     });
 }
Beispiel #5
0
        public void StartExceptionStopsAutoTransportFallback()
        {
            var errorTcs = new TaskCompletionSource<IResponse>();
            errorTcs.SetException(new StartException());

            var failingTransport = new Mock<IClientTransport>();
            failingTransport.Setup(t => t.Start(It.IsAny<IConnection>(), It.IsAny<string>(), CancellationToken.None))
                .Returns(errorTcs.Task)
                .Verifiable();

            var unusedTransport = new Mock<IClientTransport>();

            var transports = new List<IClientTransport>();
            transports.Add(failingTransport.Object);
            transports.Add(unusedTransport.Object);

            var autoTransport = new AutoTransport(new DefaultHttpClient(), transports);
            var startTask = autoTransport.Start(new Connection("http://foo"), string.Empty, CancellationToken.None);

            failingTransport.Verify();
            unusedTransport.Verify(t => t.Start(It.IsAny<IConnection>(), It.IsAny<string>(), CancellationToken.None), Times.Never());

            Assert.IsType(typeof(StartException), startTask.Exception.InnerException);
        }
Beispiel #6
0
        public override async Task Connect()
        {
            OnConnecting(EventArgs.Empty);

            if (string.IsNullOrEmpty(Address))
            {
                OnConnectError(new ConnectionErrorEventArgs(this, new Exception("Address is empty")));
                return;
            }
            if (UseSocialLogin)
            {
                if (string.IsNullOrEmpty(UserId))
                {
                    OnConnectError(new ConnectionErrorEventArgs(this, new NotAuthenticatedException("Not authenticated to this server")));
                    return;
                }
            }
            else if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password))
            {
                OnConnectError(new ConnectionErrorEventArgs(this, new NotAuthenticatedException("Username or password are not specified")));
                return;
            }

            //ServicePointManager.FindServicePoint (new Uri (Address)).ConnectionLimit = 100;

            // force long polling on mono, until SSE works reliably
            IClientTransport transport;
            if (EtoEnvironment.Platform.IsMono)
                transport = new LongPollingTransport();
            else
                transport = new AutoTransport(new DefaultHttpClient());

            Client = new jab.JabbRClient(Address, null, transport);

            if (UseSocialLogin)
            {
                throw new NotSupportedException();
            }

            bool connected = false;
            try
            {
                var logOnInfo = await Client.Connect(UserName, Password);
#if DEBUG
                var settings = Path.Combine(EtoEnvironment.GetFolderPath(EtoSpecialFolder.ApplicationSettings), "jabbreto.log");
                Client.Connection.TraceWriter = new TextWriterTraceListener(settings).Writer;
                Client.Connection.TraceLevel = TraceLevels.All;
#endif
                highlighRegex = null;
                connected = true;
                HookupEvents();

                this.OnGlobalMessageReceived (new NotificationEventArgs(new NotificationMessage (string.Format ("Using {0} transport", Client.Connection.Transport.Name))));
                var userInfo = await Client.GetUserInfo();
                this.CurrentUser = new JabbRUser(this, userInfo);
                loadingRooms = logOnInfo.Rooms.Select(r => new JabbRRoom(this, r)).ToList();
                InitializeChannels(loadingRooms);
                OnConnected(EventArgs.Empty);
            }
            catch (Exception ex)
            {
                Debug.Print(string.Format("Error: {0}", ex.GetBaseException().Message));
                OnConnectError(new ConnectionErrorEventArgs(this, ex));
                if (connected)
                    Client.Disconnect();
            }

            // load all room initial channel info/history
            while (true)
            {
                JabbRRoom room;
                lock (loadingRooms)
                {
                    if (loadingRooms.Count > 0)
                    {
                        room = loadingRooms[0];
                        loadingRooms.Remove(room);
                    }
                    else
                        break;
                }
                //Debug.WriteLine(string.Format("Loading messages for room {0}", room.Name));
                await room.LoadRoomInfo();
            }
        }
            public async Task FallbackToLongPollingIIS()
            {
                using (ITestHost host = CreateHost(HostType.IISExpress))
                {
                    // Reduce transportConnectionTimeout to 5 seconds
                    host.Initialize(transportConnectTimeout: 5);

                    var connection = CreateConnection(host, "/fall-back");

                    using (connection)
                    {
                        var tcs = new TaskCompletionSource<object>();

                        connection.StateChanged += change =>
                        {
                            if (change.NewState == ConnectionState.Reconnecting)
                            {
                                tcs.TrySetException(new Exception("The connection should not be reconnecting"));
                            }
                        };

                        var client = new DefaultHttpClient();
                        var transports = new IClientTransport[]  {
                            new ServerSentEventsTransport(client),
                            new LongPollingTransport(client)
                        };

                        var transport = new AutoTransport(client, transports);

                        await connection.Start(transport);

                        Assert.Equal(connection.Transport.Name, "longPolling");

                        Assert.False(tcs.Task.Wait(TimeSpan.FromSeconds(5)));
                    }
                }
            }
Beispiel #8
0
            public void FallbackToLongPollingIIS()
            {
                using (ITestHost host = new IISExpressTestHost())
                {
                    host.Initialize();

                    var connection = CreateConnection(host.Url + "/fall-back");
                    var tcs = new TaskCompletionSource<object>();

                    connection.StateChanged += change =>
                    {
                        if (change.NewState == ConnectionState.Reconnecting)
                        {
                            tcs.TrySetException(new Exception("The connection should not be reconnecting"));
                        }
                    };

                    var client = new DefaultHttpClient();
                    var transports = new IClientTransport[]  {
                        new ServerSentEventsTransport(client) { ConnectionTimeout = TimeSpan.Zero },
                        new LongPollingTransport(client)
                    };

                    var transport = new AutoTransport(client, transports);

                    connection.Start(transport).Wait();

                    Assert.Equal(connection.Transport.Name, "longPolling");

                    Assert.False(tcs.Task.Wait(TimeSpan.FromSeconds(5)));

                    connection.Stop();
                }
            }