Inheritance: Microsoft.AspNet.SignalR.Client.Transports.HttpBasedTransport
        public void LongPollingDoesNotPollAfterClose()
        {
            var disconnectCts = new CancellationTokenSource();

            var mockConnection = new Mock<Client.IConnection>();
            mockConnection.SetupGet(c => c.JsonSerializer).Returns(JsonSerializer.CreateDefault());
            mockConnection.Setup(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(5));
            mockConnection.SetupProperty(c => c.MessageId);

            var pollTaskCompletionSource = new TaskCompletionSource<IResponse>();
            var pollingWh = new ManualResetEvent(false);

            var mockHttpClient = CreateFakeHttpClient(
                (url, request, postData, isLongRunning) =>
                {
                    var responseMessage = string.Empty;
                    if (url.Contains("connect?"))
                    {
                        responseMessage = "{\"C\":\"d-C6243495-A,0|B,0|C,1|D,0\",\"S\":1,\"M\":[]}";
                    }
                    else if (url.Contains("poll?"))
                    {
                        pollingWh.Set();
                        return pollTaskCompletionSource.Task;
                    }

                    return Task.FromResult(CreateResponse(responseMessage));
                });
                
            var longPollingTransport = new LongPollingTransport(mockHttpClient.Object);

            Assert.True(
                longPollingTransport.Start(mockConnection.Object, string.Empty, disconnectCts.Token)
                    .Wait(TimeSpan.FromSeconds(15)));

            // wait for the first polling request
            Assert.True(pollingWh.WaitOne(TimeSpan.FromSeconds(2)));
            
            // stop polling loop
            disconnectCts.Cancel();

            // finish polling request
            pollTaskCompletionSource.SetResult(CreateResponse(string.Empty));

            // give it some time to make sure a new poll was not setup after verification
            Thread.Sleep(1000);

            mockHttpClient
                .Verify(c => c.Post(It.Is<string>(url => url.StartsWith("poll?")), It.IsAny<Action<Client.Http.IRequest>>(),
                    It.IsAny<IDictionary<string, string>>(), It.IsAny<bool>()), Times.Once());
        }
Exemplo n.º 2
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();
            }
        }
Exemplo n.º 3
0
        public void CancelledTaskHandledWhenStartingLongPolling()
        {
            var tcs = new TaskCompletionSource<IResponse>();
            tcs.SetCanceled();

            var httpClient = new Mock<IHttpClient>();

            httpClient.Setup(c => c.Post(It.IsAny<string>(),
                It.IsAny<Action<IRequest>>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<bool>()))
                .Returns(tcs.Task);

            var mockConnection = new Mock<IConnection>();
            mockConnection.Setup(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(15));

            var longPollingTransport = new LongPollingTransport(httpClient.Object);

            var unwrappedException = Assert.Throws<AggregateException>(() =>
                longPollingTransport.Start(mockConnection.Object, null, CancellationToken.None)
                    .Wait(TimeSpan.FromSeconds(5))).InnerException;

            Assert.IsType<OperationCanceledException>(unwrappedException);
        }
        public void PollingLoopNotRestartedIfStartFails()
        {
            var disconnectCts = new CancellationTokenSource();

            var mockConnection = new Mock<Client.IConnection>();
            mockConnection.SetupGet(c => c.JsonSerializer).Returns(JsonSerializer.CreateDefault());
            mockConnection.Setup(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(500));
            mockConnection.SetupProperty(c => c.MessageId);

            var mockHttpClient = CreateFakeHttpClient((url, request, postData, isLongRunning) =>
            {
                var tcs = new TaskCompletionSource<IResponse>();
                tcs.SetException(new InvalidOperationException("Request rejected"));
                return tcs.Task;
            });

            mockHttpClient.Setup(
                m => m.Get(It.IsAny<string>(), It.IsAny<Action<Client.Http.IRequest>>(), It.IsAny<bool>()))
                .Returns<string, Action<Client.Http.IRequest>, bool>(
                    (url, request, isLongRunning) => Task.FromResult(CreateResponse("{ \"Response\" : \"started\"}")));

            var longPollingTransport = new LongPollingTransport(mockHttpClient.Object);

            Assert.Throws<AggregateException>(() =>
                longPollingTransport.Start(mockConnection.Object, string.Empty, disconnectCts.Token)
                    .Wait(TimeSpan.FromSeconds(15)));

            // give it some time to settle
            Thread.Sleep(TimeSpan.FromSeconds(1));

            mockHttpClient
                .Verify(c => c.Post(It.Is<string>(url => url.StartsWith("poll?")), It.IsAny<Action<Client.Http.IRequest>>(),
                    It.IsAny<IDictionary<string, string>>(), It.IsAny<bool>()), Times.Never());
        }
        public void InitDoesNotHaveToBeFirstMessage()
        {
            var disconnectCts = new CancellationTokenSource();

            var mockConnection = new Mock<Client.IConnection>();
            mockConnection.SetupGet(c => c.JsonSerializer).Returns(JsonSerializer.CreateDefault());
            mockConnection.Setup(c => c.TotalTransportConnectTimeout).Returns(TimeSpan.FromSeconds(500));
            mockConnection.SetupProperty(c => c.MessageId);

            var mockHttpClient = CreateFakeHttpClient((url, request, postData, isLongRunning) =>
                Task.FromResult(CreateResponse(url.StartsWith("poll?")
                    ? "{\"C\":\"d-C6243495-A,0|B,0|C,1|D,0\",\"S\":1,\"M\":[]}"
                    : "{\"C\":\"d-C6243495-A,0|B,0|C,1|D,0\",\"M\":[]}")));

            var longPollingTransport = new LongPollingTransport(mockHttpClient.Object);

            Assert.True(
                longPollingTransport.Start(mockConnection.Object, string.Empty, disconnectCts.Token)
                    .Wait(TimeSpan.FromSeconds(15)));

            // stop polling loop
            disconnectCts.Cancel();
        }