System.Threading.Tasks.Task.FromException(System.Exception)

Here are the examples of the csharp api System.Threading.Tasks.Task.FromException(System.Exception) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

524 Examples 7

19 View Source File : PingServerAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "PingServerAsync")]
        [Fact(DisplayName = "PingServerAsync throws TimeoutException when wait times out")]
        public async Task PingServerAsync_Throws_TimeoutException_When_Wait_Times_Out()
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Throws(new TimeoutException());

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken?>()))
                .Returns(Task.FromException(new TimeoutException()));

            using (var s = new SoulseekClient(serverConnection: conn.Object, waiter: waiter.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.PingServerAsync(CancellationToken.None));

                replacedert.NotNull(ex);
                replacedert.IsType<TimeoutException>(ex);
            }
        }

19 View Source File : MessageConnectionTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "Connected")]
        [Theory(DisplayName = "Connected handler of server connection starts reading"), AutoData]
        public async Task Connected_Handler_Of_Server_Connection_Starts_Reading(IPEndPoint endpoint)
        {
            var streamMock = new Mock<INetworkStream>();
            streamMock.Setup(s => s.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<int>(new Exception()));

            var tcpMock = new Mock<ITcpClient>();

            using (var socket = new Socket(SocketType.Stream, ProtocolType.IP))
            {
                tcpMock.Setup(m => m.Client).Returns(socket);
                tcpMock.Setup(s => s.GetStream()).Returns(streamMock.Object);

                using (var c = new MessageConnection(endpoint, tcpClient: tcpMock.Object))
                {
                    await c.ConnectAsync();

                    // because the reading takes place in a separate task,
                    // and we need it to fail so it doesn't keep looping,
                    // and because ReadingContinuously is set to false when it fails,
                    // the best way to make sure this is actually starting the reading is to
                    // check the stream after a delay.
                    await Task.Delay(500);
                    streamMock.Verify(s => s.Close(), Times.Once);
                }
            }
        }

19 View Source File : BrowseAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "BrowseAsync")]
        [Theory(DisplayName = "BrowseAsync throws UserOfflineException on user not found"), AutoData]
        public async Task BrowseAsync_Throws_UserOfflineException_On_User_Not_Found(string username, IPEndPoint endpoint, string localUsername)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserAddressResponse>(new UserOfflineException()));

            var conn = new Mock<IMessageConnection>();

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: conn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("Username", localUsername);
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.BrowseAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<UserOfflineException>(ex);
            }
        }

19 View Source File : ConnectAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "Connect")]
        [Theory(DisplayName = "Throws SoulseekClientException if expected login messages are not sent"), AutoData]
        public async Task Throws_SoulseekClientException_If_Expected_Login_Messages_Are_Not_Sent(string user, string preplacedword)
        {
            var (client, mocks) = GetFixture();

            mocks.Waiter.Setup(m => m.Wait<LoginResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new LoginResponse(true, string.Empty)));
            mocks.Waiter.Setup(m => m.Wait<int>(It.Is<WaitKey>(w => w == new WaitKey(MessageCode.Server.WishlistInterval)), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<int>(new TimeoutException("timed out")));

            using (client)
            {
                var ex = await Record.ExceptionAsync(() => client.ConnectAsync(user, preplacedword));

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
                replacedert.True(ex.Message.ContainsInsensitive("did not receive one or more expected server messages"));
                replacedert.IsType<ConnectionException>(ex.InnerException);
                replacedert.IsType<TimeoutException>(ex.InnerException.InnerException);
            }
        }

19 View Source File : ConnectAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "Connect")]
        [Theory(DisplayName = "Throws SoulseekClientException on message write exception"), AutoData]
        public async Task LoginAsync_Throws_SoulseekClientException_On_Message_Write_Exception(string user, string preplacedword)
        {
            var (client, mocks) = GetFixture();

            mocks.ServerConnection.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<Exception>(new ConnectionWriteException()));

            using (client)
            {
                var ex = await Record.ExceptionAsync(() => client.ConnectAsync(user, preplacedword));

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
                replacedert.IsType<ConnectionWriteException>(ex.InnerException);
            }
        }

[Trait("Category", "DropPrivateRoomMembershipAsync")]
        [Theory(DisplayName = "DropPrivateRoomMembershipAsync throws when wait throws"), AutoData]
        public async Task DropPrivateRoomMembershipAsync_Throws_When_Wait_Throws(string roomName)
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var expectedEx = new TimeoutException();

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(expectedEx));

            using (var s = new SoulseekClient(serverConnection: conn.Object, waiter: waiter.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.DropPrivateRoomMembershipAsync(roomName));

                replacedert.NotNull(ex);
                replacedert.Equal(expectedEx, ex);
            }
        }

[Trait("Category", "DropPrivateRoomOwnershipAsync")]
        [Theory(DisplayName = "DropPrivateRoomOwnershipAsync throws when wait throws"), AutoData]
        public async Task DropPrivateRoomOwnershipAsync_Throws_When_Wait_Throws(string roomName)
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var expectedEx = new TimeoutException();

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(expectedEx));

            using (var s = new SoulseekClient(serverConnection: conn.Object, waiter: waiter.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.DropPrivateRoomOwnershipAsync(roomName));

                replacedert.NotNull(ex);
                replacedert.Equal(expectedEx, ex);
            }
        }

19 View Source File : GetDirectoryContentsAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetDirectoryContentsAsync")]
        [Theory(DisplayName = "GetDirectoryContentsAsync throws UserOfflineException on user offline"), AutoData]
        public async Task GetDirectoryContentsAsync_Throws_UserOfflineException_On_User_Offline(string username, string directory)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserAddressResponse>(new UserOfflineException()));

            var serverConn = new Mock<IMessageConnection>();
            var connManager = new Mock<IPeerConnectionManager>();

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                Directory dir = null;
                var ex = await Record.ExceptionAsync(async () => dir = await s.GetDirectoryContentsAsync(username, directory));

                replacedert.NotNull(ex);
                replacedert.IsType<UserOfflineException>(ex);
            }
        }

19 View Source File : GetDirectoryContentsAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetDirectoryContentsAsync")]
        [Theory(DisplayName = "GetDirectoryContentsAsync throws SoulseekClientException on throw"), AutoData]
        public async Task GetDirectoryContentsAsync_Throws_SoulseekClientException_On_Throw(string username, string directory)
        {
            var result = new Directory(directory);

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<Directory>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(result));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, IPAddress.Parse("127.0.0.1"), 1)));

            var serverConn = new Mock<IMessageConnection>();
            serverConn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new NullReferenceException()));

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, It.IsAny<IPEndPoint>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                Directory dir = null;
                var ex = await Record.ExceptionAsync(async () => dir = await s.GetDirectoryContentsAsync(username, directory));

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
                replacedert.IsType<NullReferenceException>(ex.InnerException);
            }
        }

19 View Source File : GetUserInfoAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetUserInfoAsync")]
        [Theory(DisplayName = "GetUserInfoAsync throws OperationCanceledException on cancellation"), AutoData]
        public async Task GetUserInfoAsync_Throws_OperationCanceledException_On_Cancellation(string username, string description, byte[] picture, int uploadSlots, int queueLength, bool hasFreeSlot)
        {
            var result = new UserInfo(description, picture, uploadSlots, queueLength, hasFreeSlot);

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserInfo>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(result));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, IPAddress.Parse("127.0.0.1"), 1)));

            var serverConn = new Mock<IMessageConnection>();
            serverConn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new OperationCanceledException()));

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, It.IsAny<IPEndPoint>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                UserInfo info = null;
                var ex = await Record.ExceptionAsync(async () => info = await s.GetUserInfoAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<OperationCanceledException>(ex);
            }
        }

19 View Source File : SearchAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "SearchAsync")]
        [Theory(DisplayName = "SearchAsync throws SoulseekClientException on error"), AutoData]
        public async Task SearchInternalAsync_Throws_SoulseekClientException_On_Error(string searchText, int token)
        {
            var options = new SearchOptions(searchTimeout: 1000);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new Exception("foo")));

            using (var s = new SoulseekClient(serverConnection: conn.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.SearchAsync(SearchQuery.FromText(searchText), SearchScope.Network, token, options, null));

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
            }
        }

19 View Source File : MessageConnectionTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "Connected")]
        [Theory(DisplayName = "Connected handler of peer connection starts reading"), AutoData]
        public async Task Connected_Handler_Of_Peer_Connection_Starts_Reading(string username, IPEndPoint endpoint)
        {
            var streamMock = new Mock<INetworkStream>();
            streamMock.Setup(s => s.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<int>(new Exception()));

            var tcpMock = new Mock<ITcpClient>();

            using (var socket = new Socket(SocketType.Stream, ProtocolType.IP))
            {
                tcpMock.Setup(m => m.Client).Returns(socket);
                tcpMock.Setup(s => s.GetStream()).Returns(streamMock.Object);

                using (var c = new MessageConnection(username, endpoint, tcpClient: tcpMock.Object))
                {
                    await c.ConnectAsync();

                    // because the reading takes place in a separate task,
                    // and we need it to fail so it doesn't keep looping,
                    // and because ReadingContinuously is set to false when it fails,
                    // the best way to make sure this is actually starting the reading is to
                    // check the stream after a delay.
                    await Task.Delay(500);
                    streamMock.Verify(s => s.Close(), Times.Once);
                }
            }
        }

19 View Source File : BrowseAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "BrowseAsync")]
        [Theory(DisplayName = "BrowseAsync throws OperationCanceledException on cancellation"), AutoData]
        public async Task BrowseAsync_Throws_OperationCanceledException_On_Cancellation(string username, IPEndPoint endpoint, string localUsername)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.WaitIndefinitely<BrowseResponse>(It.IsAny<WaitKey>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<BrowseResponse>(new OperationCanceledException()));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, endpoint.Address, endpoint.Port)));

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            waiter.Setup(m => m.Wait<(MessageReceivedEventArgs, IMessageConnection)>(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken?>()))
                .Returns(Task.FromResult((new MessageReceivedEventArgs(1, new byte[] { 0x0 }), conn.Object)));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: conn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("Username", localUsername);
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.BrowseAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<OperationCanceledException>(ex);
            }
        }

19 View Source File : SearchResponderTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "TryRespondAsync")]
        [Theory(DisplayName = "TryRespondAsync returns false on failure"), AutoData]
        public async Task TryRespondAsync_Returns_False_On_Failure(string username, int token, string query, SearchResponse searchResponse, IPEndPoint endpoint, int responseToken)
        {
            var (responder, mocks) = GetFixture(new SoulseekClientOptions(searchResponseResolver: (u, t, q) => Task.FromResult(searchResponse)));

            mocks.Client.Setup(m => m.GetUserEndPointAsync(username, It.IsAny<CancellationToken?>()))
                .Returns(Task.FromResult(endpoint));
            mocks.Client.Setup(m => m.GetNextToken())
                .Returns(responseToken);

            var ex = new ConnectionException();

            mocks.PeerConnectionManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, responseToken, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<IMessageConnection>(ex));

            var responded = await responder.TryRespondAsync(username, token, query);

            replacedert.False(responded);
        }

19 View Source File : SearchResponderTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "TryRespondAsync")]
        [Theory(DisplayName = "TryRespondAsync caches response on connect failure"), AutoData]
        public async Task TryRespondAsync_Caches_Response_On_Connect_Failure(string username, int token, string query, SearchResponse searchResponse, IPEndPoint endpoint, int responseToken)
        {
            var cache = new Mock<ISearchResponseCache>();

            var (responder, mocks) = GetFixture(new SoulseekClientOptions(
                searchResponseCache: cache.Object,
                searchResponseResolver: (u, t, q) => Task.FromResult(searchResponse)));

            mocks.Client.Setup(m => m.GetUserEndPointAsync(username, It.IsAny<CancellationToken?>()))
                .Returns(Task.FromResult(endpoint));
            mocks.Client.Setup(m => m.GetNextToken())
                .Returns(responseToken);

            var ex = new ConnectionException();

            mocks.PeerConnectionManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, responseToken, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<IMessageConnection>(ex));

            var responded = await responder.TryRespondAsync(username, token, query);

            replacedert.False(responded);

            var value = (username, token, query, searchResponse);
            cache.Verify(m => m.AddOrUpdate(responseToken, value), Times.Once);
        }

19 View Source File : SearchResponderTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "TryRespondAsync")]
        [Theory(DisplayName = "TryRespondAsync generates warning on cache add failure"), AutoData]
        public async Task TryRespondAsync_Generates_Warning_On_Cache_Add_Failure(string username, int token, string query, SearchResponse searchResponse, IPEndPoint endpoint, int responseToken)
        {
            var value = (username, token, query, searchResponse);
            var cacheEx = new Exception();

            var cache = new Mock<ISearchResponseCache>();
            cache.Setup(m => m.AddOrUpdate(responseToken, value))
                .Throws(cacheEx);

            var (responder, mocks) = GetFixture(new SoulseekClientOptions(
                searchResponseCache: cache.Object,
                searchResponseResolver: (u, t, q) => Task.FromResult(searchResponse)));

            mocks.Client.Setup(m => m.GetUserEndPointAsync(username, It.IsAny<CancellationToken?>()))
                .Returns(Task.FromResult(endpoint));
            mocks.Client.Setup(m => m.GetNextToken())
                .Returns(responseToken);

            var ex = new ConnectionException();

            mocks.PeerConnectionManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, responseToken, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<IMessageConnection>(ex));

            var responded = await responder.TryRespondAsync(username, token, query);

            replacedert.False(responded);

            mocks.Diagnostic.Verify(m => m.Warning(It.Is<string>(s => s.ContainsInsensitive("Error caching undelivered search response")), cacheEx), Times.Once);
        }

19 View Source File : SearchResponderTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "TryRespondAsync")]
        [Theory(DisplayName = "TryRespondAsync generates debug on failure"), AutoData]
        public async Task TryRespondAsync_Generates_Debug_On_Failure(string username, int token, string query, SearchResponse searchResponse, IPEndPoint endpoint, int responseToken)
        {
            var (responder, mocks) = GetFixture(new SoulseekClientOptions(searchResponseResolver: (u, t, q) => Task.FromResult(searchResponse)));

            mocks.Client.Setup(m => m.GetUserEndPointAsync(username, It.IsAny<CancellationToken?>()))
                .Returns(Task.FromResult(endpoint));
            mocks.Client.Setup(m => m.GetNextToken())
                .Returns(responseToken);

            var ex = new ConnectionException();

            mocks.PeerConnectionManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, responseToken, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<IMessageConnection>(ex));

            var responded = await responder.TryRespondAsync(username, token, query);

            replacedert.False(responded);

            mocks.Diagnostic.Verify(m => m.Debug(It.Is<string>(s => s.ContainsInsensitive("Failed to send search response")), ex), Times.Once);
        }

19 View Source File : AddPrivateRoomMemberAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "AddPrivateRoomMemberAsync")]
        [Theory(DisplayName = "AddPrivateRoomMemberAsync throws when wait throws"), AutoData]
        public async Task AddPrivateRoomMemberAsync_Throws_When_Wait_Throws(string roomName, string username)
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var expectedEx = new TimeoutException();

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(expectedEx));

            using (var s = new SoulseekClient(serverConnection: conn.Object, waiter: waiter.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.AddPrivateRoomMemberAsync(roomName, username));

                replacedert.NotNull(ex);
                replacedert.Equal(expectedEx, ex);
            }
        }

19 View Source File : AddPrivateRoomModeratorAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "AddPrivateRoomModeratorAsync")]
        [Theory(DisplayName = "AddPrivateRoomModeratorAsync throws when wait throws"), AutoData]
        public async Task AddPrivateRoomModeratorAsync_Throws_When_Wait_Throws(string roomName, string username)
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var expectedEx = new TimeoutException();

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(expectedEx));

            using (var s = new SoulseekClient(serverConnection: conn.Object, waiter: waiter.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.AddPrivateRoomModeratorAsync(roomName, username));

                replacedert.NotNull(ex);
                replacedert.Equal(expectedEx, ex);
            }
        }

19 View Source File : BrowseAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "BrowseAsync")]
        [Theory(DisplayName = "BrowseAsync throws SoulseekClientException on disconnect"), AutoData]
        public async Task BrowseAsync_Throws_SoulseekClientException_On_Disconnect(string username, IPEndPoint endpoint, string localUsername)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, endpoint.Address, endpoint.Port)));
            waiter.Setup(m => m.WaitIndefinitely<BrowseResponse>(It.IsAny<WaitKey>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<BrowseResponse>(new ConnectionException("disconnected unexpectedly")));

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask)
                .Raises(m => m.Disconnected += null, conn.Object, new ConnectionDisconnectedEventArgs(string.Empty));

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            waiter.Setup(m => m.Wait<(MessageReceivedEventArgs, IMessageConnection)>(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken?>()))
                .Returns(Task.FromResult((new MessageReceivedEventArgs(1, new byte[] { 0x0 }), conn.Object)));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: conn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("Username", localUsername);
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.BrowseAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
                replacedert.IsType<ConnectionException>(ex.InnerException);
                replacedert.Contains("disconnected unexpectedly", ex.InnerException.Message, StringComparison.InvariantCultureIgnoreCase);
            }
        }

19 View Source File : GetUserInfoAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetUserInfoAsync")]
        [Theory(DisplayName = "GetUserInfoAsync throws TimeoutException on timeout"), AutoData]
        public async Task GetUserInfoAsync_Throws_TimeoutException_On_Timeout(string username, string description, byte[] picture, int uploadSlots, int queueLength, bool hasFreeSlot)
        {
            var result = new UserInfo(description, picture, uploadSlots, queueLength, hasFreeSlot);

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserInfo>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(result));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, IPAddress.Parse("127.0.0.1"), 1)));

            var serverConn = new Mock<IMessageConnection>();
            serverConn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new TimeoutException()));

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, It.IsAny<IPEndPoint>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                UserInfo info = null;
                var ex = await Record.ExceptionAsync(async () => info = await s.GetUserInfoAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<TimeoutException>(ex);
            }
        }

19 View Source File : GetUserInfoAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetUserInfoAsync")]
        [Theory(DisplayName = "GetUserInfoAsync throws UserOfflineException on user offline"), AutoData]
        public async Task GetUserInfoAsync_Throws_UserOfflineException_On_User_Offline(string username)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserAddressResponse>(new UserOfflineException()));

            var serverConn = new Mock<IMessageConnection>();
            var connManager = new Mock<IPeerConnectionManager>();

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                UserInfo info = null;
                var ex = await Record.ExceptionAsync(async () => info = await s.GetUserInfoAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<UserOfflineException>(ex);
            }
        }

19 View Source File : GetUserInfoAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetUserInfoAsync")]
        [Theory(DisplayName = "GetUserInfoAsync throws SoulseekClientException on throw"), AutoData]
        public async Task GetUserInfoAsync_Throws_SoulseekClientException_On_Throw(string username, string description, byte[] picture, int uploadSlots, int queueLength, bool hasFreeSlot)
        {
            var result = new UserInfo(description, picture, uploadSlots, queueLength, hasFreeSlot);

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserInfo>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(result));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, IPAddress.Parse("127.0.0.1"), 1)));

            var serverConn = new Mock<IMessageConnection>();
            serverConn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(new ConnectionException("foo")));

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, It.IsAny<IPEndPoint>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                UserInfo info = null;
                var ex = await Record.ExceptionAsync(async () => info = await s.GetUserInfoAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
                replacedert.IsType<ConnectionException>(ex.InnerException);
            }
        }

19 View Source File : GetUserStatusAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "GetUserStatusAsync")]
        [Theory(DisplayName = "GetUserStatusAsync throws UserOfflineException on user offline"), AutoData]
        public async Task GetUserStatusAsync_Throws_UserOfflineException_On_User_Offline(string username)
        {
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<UserStatusResponse>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserStatusResponse>(new UserOfflineException()));

            var serverConn = new Mock<IMessageConnection>();

            using (var s = new SoulseekClient(waiter: waiter.Object, serverConnection: serverConn.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.GetUserStatusAsync(username));

                replacedert.NotNull(ex);
                replacedert.IsType<UserOfflineException>(ex);
            }
        }

19 View Source File : RemovePrivateRoomMemberAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "RemovePrivateRoomMemberAsync")]
        [Theory(DisplayName = "RemovePrivateRoomMemberAsync throws when wait throws"), AutoData]
        public async Task RemovePrivateRoomMemberAsync_Throws_When_Wait_Throws(string roomName, string username)
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var expectedEx = new TimeoutException();

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(expectedEx));

            using (var s = new SoulseekClient(serverConnection: conn.Object, waiter: waiter.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.RemovePrivateRoomMemberAsync(roomName, username));

                replacedert.NotNull(ex);
                replacedert.Equal(expectedEx, ex);
            }
        }

[Trait("Category", "RemovePrivateRoomModeratorAsync")]
        [Theory(DisplayName = "RemovePrivateRoomModeratorAsync throws when wait throws"), AutoData]
        public async Task RemovePrivateRoomModeratorAsync_Throws_When_Wait_Throws(string roomName, string username)
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var expectedEx = new TimeoutException();

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException(expectedEx));

            using (var s = new SoulseekClient(serverConnection: conn.Object, waiter: waiter.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var ex = await Record.ExceptionAsync(() => s.RemovePrivateRoomModeratorAsync(roomName, username));

                replacedert.NotNull(ex);
                replacedert.Equal(expectedEx, ex);
            }
        }

19 View Source File : DistributedMessageHandlerTests.cs
License : GNU General Public License v3.0
Project Creator : jackBonadies

[Trait("Category", "HandleChildMessageRead")]
        [Theory(DisplayName = "HandleChildMessageRead produces warning on Exception"), AutoData]
        public void HandleChildMessageRead_Produces_Warning_On_Exception(int token)
        {
            var (handler, mocks) = GetFixture();

            mocks.Client.Setup(m => m.GetNextToken())
                .Returns(token);

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.WriteAsync(It.IsAny<IOutgoingMessage>(), It.IsAny<CancellationToken?>()))
                .Returns(Task.FromException(new Exception()));

            var message = new DistributedPingRequest().ToByteArray();

            handler.HandleChildMessageRead(conn.Object, message);

            mocks.Diagnostic.Verify(m => m.Warning(It.Is<string>(s => s.ContainsInsensitive("error handling distributed child message")), It.IsAny<Exception>()), Times.Once);
        }

19 View Source File : Result.cs
License : Apache License 2.0
Project Creator : JetBrains

public static Task UnwrapTask(this Result<Task> result)
    {
      if (result.Succeed) 
        return result.Value;
      
      if (!result.Canceled) 
        return Task.FromException(result.Exception);
      
      if (result.Exception is OperationCanceledException oce)
        return Task.FromCanceled(oce.CancellationToken);
      else
        return Task.FromCanceled(Lifetime.Terminated);
    }

19 View Source File : Result.cs
License : Apache License 2.0
Project Creator : JetBrains

public static Task<T> UnwrapTask<T>(this Result<Task<T>> result)
    {
      if (result.Succeed) 
        return result.Value;
      
      if (!result.Canceled) 
        return Task.FromException<T>(result.Exception);
      
      if (result.Exception is OperationCanceledException oce)
        return Task.FromCanceled<T>(oce.CancellationToken);
      else
        return Task.FromCanceled<T>(Lifetime.Terminated);
    }

19 View Source File : Result.cs
License : Apache License 2.0
Project Creator : JetBrains

public Task<T> AsCompletedTask()
    {
      if (Succeed) 
        return Task.FromResult(Value);
      
      if (!Canceled) return Task.FromException<T>(Exception);
      
      if (Exception is OperationCanceledException oce)
        return Task.FromCanceled<T>(oce.CancellationToken);
      else
        return Task.FromCanceled<T>(Lifetime.Terminated);
    }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("authmaint", RunMode = RunMode.Async), Summary("Activates Teamspeak check")]
        [RequireRole]
        public async Task AuthMaint()
        {
            try
            {
                await Functions.AuthMaint(Context);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "AuthMaint", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("reauth", RunMode = RunMode.Async), Summary("Reauth all users")]
        [RequireRole]
        public async Task Reauth()
        {
            try
            {
                await Functions.AuthCheck(Context);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("auth", RunMode = RunMode.Async), Summary("Auth User")]
        public async Task Auth()
        {
            if (Convert.ToBoolean(Program.Settings.GetSection("config")["authWeb"]))
            {
                try
                {
                    await ReplyAsync($"{Context.Message.Author.Mention} To Auth please visit {(string)Program.Settings.GetSection("auth")["authurl"]} and Login with your main");
                }
                catch (Exception ex)
                {
                    await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                    await Task.FromException(ex);
                }
            }
            else
            {
                await ReplyAsync($"{Context.Message.Author.Mention}, Auth is disabled on this server");
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("auth", RunMode = RunMode.Async), Summary("Auth User")]
        public async Task Auth([Remainder] string x)
        {
            if (Convert.ToBoolean(Program.Settings.GetSection("config")["authWeb"]))
            {
                try
                {
                    if (Helpers.IsUserMention(Context))
                    {
                        await Functions.SendAuthMessage(Context);
                    }
                    else
                    {
                        await Functions.AuthUser(Context, x);
                    }
                }
                catch (Exception ex)
                {
                    await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                    await Task.FromException(ex);
                }
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("evetime", RunMode = RunMode.Async), Summary("EVE TQ Time")]
        public async Task EveTime()
        {
            if (Convert.ToBoolean(Program.Settings.GetSection("config")["time"]))
            {
                try
                {
                    await Functions.EveTime(Context);
                }
                catch (Exception ex)
                {
                    await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                    await Task.FromException(ex);
                }
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("motd", RunMode = RunMode.Async), Summary("Shows MOTD")]
        public async Task Motd()
        {
            if (Convert.ToBoolean(Program.Settings.GetSection("config")["MOTD"]))
            {
                try
                {
                    await Functions.MOTD(Context);
                }
                catch (Exception ex)
                {
                    await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                    await Task.FromException(ex);
                }
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("about", RunMode = RunMode.Async), Summary("About Opux")]
        public async Task About()
        {
            try
            {
                await Functions.About(Context);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("char", RunMode = RunMode.Async), Summary("Character Details")]
        public async Task Char([Remainder] string x)
        {
            try
            {
                if (Convert.ToBoolean(Program.Settings.GetSection("config")["charcorp"]))
                    await Functions.Char(Context, x);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("dupes", RunMode = RunMode.Async), Summary("Deletes Duplicate Discord ID's from the MYSQL database")]
        [RequireRole]
        public async Task Dupes()
        {
            try
            {
                await Functions.Dupes(Context, null);
                await Context.Channel.SendMessageAsync("Duplicates Removed. Check logs for errors", false, null, null).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("ts reset", RunMode = RunMode.Async), Summary("Activates Teamspeak check")]
        public async Task TsReset()
        {
            try
            {
                await Functions.TS_Reset(Context);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Teamspeak", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("corp", RunMode = RunMode.Async), Summary("Corporation Details")]
        public async Task Corp([Remainder] string x)
        {
            try
            {
                if (Convert.ToBoolean(Program.Settings.GetSection("config")["charcorp"]))
                    await Functions.Corp(Context, x);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Modules", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("ts", RunMode = RunMode.Async), Summary("Activates Teamspeak check")]
        public async Task Ts()
        {
            try
            {
                await Functions.TS_Check(Context);
            }
            catch (Exception ex)
            {
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Teamspeak", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : Modules.cs
License : GNU General Public License v3.0
Project Creator : Jimmy062006

[Command("ts reset", RunMode = RunMode.Async), Summary("Activates Teamspeak check")]
        [RequireRole]
        public async Task TsReset([Remainder] string x)
        {
            try
            {
                await Functions.TS_Reset(Context, x);
            }
            catch (Exception ex)
            {
                await Context.Message.Channel.SendMessageAsync("ERROR");
                await Logger.DiscordClient_Log(new Discord.LogMessage(Discord.LogSeverity.Error, "Teamspeak", ex.Message, ex));
                await Task.FromException(ex);
            }
        }

19 View Source File : FusionCacheExecutionUtils.cs
License : MIT License
Project Creator : jodydonetti

public static async Task RunAsyncActionWithTimeoutAsync(Func<CancellationToken, Task> asyncAction, TimeSpan timeout, bool cancelIfTimeout = true, Action<Task>? timedOutTaskProcessor = null, CancellationToken token = default)
		{
			token.ThrowIfCancellationRequested();

			if (timeout == TimeSpan.Zero || timeout < Timeout.InfiniteTimeSpan)
			{
				var exc = new SyntheticTimeoutException();
				if (cancelIfTimeout == false)
					timedOutTaskProcessor?.Invoke(Task.FromException(exc));
				throw exc;
			}

			if (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None)
			{
				await asyncAction(token).ConfigureAwait(false);
				return;
			}

			var ctsFunc = cancelIfTimeout
				? CancellationTokenSource.CreateLinkedTokenSource(token)
				: null;

			try
			{
				using (var ctsDelay = CancellationTokenSource.CreateLinkedTokenSource(token))
				{
					var actionTask = asyncAction(ctsFunc?.Token ?? token);
					var delayTask = Task.Delay(timeout, ctsDelay.Token);

					await Task.WhenAny(actionTask, delayTask).ConfigureAwait(false);

					if (delayTask.IsCompleted == false && delayTask.IsFaulted == false)
					{
						ctsDelay.Cancel();
					}

					if (actionTask.IsCompleted == false && actionTask.IsFaulted == false)
					{
						ctsFunc?.Cancel();
					}

					token.ThrowIfCancellationRequested();

					if (actionTask.IsCompleted)
					{
						await actionTask.ConfigureAwait(false);
						return;
					}

					if (cancelIfTimeout == false)
						timedOutTaskProcessor?.Invoke(actionTask);

					throw new SyntheticTimeoutException();
				}
			}
			finally
			{
				ctsFunc?.Dispose();
			}
		}

19 View Source File : FusionCacheExecutionUtils.cs
License : MIT License
Project Creator : jodydonetti

public static void RunAsyncActionWithTimeout(Func<CancellationToken, Task> asyncAction, TimeSpan timeout, bool cancelIfTimeout = true, Action<Task>? timedOutTaskProcessor = null, CancellationToken token = default)
		{
			token.ThrowIfCancellationRequested();

			if (timeout == TimeSpan.Zero || timeout < Timeout.InfiniteTimeSpan)
			{
				var exc = new SyntheticTimeoutException();
				if (cancelIfTimeout == false)
					timedOutTaskProcessor?.Invoke(Task.FromException(exc));
				throw exc;
			}

			Task task;

			if (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None)
			{
				task = _taskFactory.StartNew(() => asyncAction(token), token).Unwrap();
			}
			else
			{
				task = _taskFactory.StartNew(() => RunAsyncActionWithTimeoutAsync(asyncAction, timeout, cancelIfTimeout, timedOutTaskProcessor, token), token).Unwrap();
			}

			task.GetAwaiter().GetResult();
		}

19 View Source File : FusionCacheExecutionUtils.cs
License : MIT License
Project Creator : jodydonetti

public static async Task<TResult> RunAsyncFuncWithTimeoutAsync<TResult>(Func<CancellationToken, Task<TResult>> asyncFunc, TimeSpan timeout, bool cancelIfTimeout = true, Action<Task<TResult>>? timedOutTaskProcessor = null, CancellationToken token = default)
		{
			token.ThrowIfCancellationRequested();

			if (timeout == TimeSpan.Zero || timeout < Timeout.InfiniteTimeSpan)
			{
				var exc = new SyntheticTimeoutException();
				if (cancelIfTimeout == false)
					timedOutTaskProcessor?.Invoke(Task.FromException<TResult>(exc));
				throw exc;
			}

			if (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None)
			{
				return await asyncFunc(token).ConfigureAwait(false);
			}

			var ctsFunc = cancelIfTimeout
				? CancellationTokenSource.CreateLinkedTokenSource(token)
				: null;

			try
			{
				using (var ctsDelay = CancellationTokenSource.CreateLinkedTokenSource(token))
				{
					var funcTask = asyncFunc(ctsFunc?.Token ?? token);
					var delayTask = Task.Delay(timeout, ctsDelay.Token);

					await Task.WhenAny(funcTask, delayTask).ConfigureAwait(false);

					if (delayTask.IsCompleted == false && delayTask.IsFaulted == false)
					{
						ctsDelay.Cancel();
					}

					if (funcTask.IsCompleted == false && funcTask.IsFaulted == false)
					{
						ctsFunc?.Cancel();
					}

					token.ThrowIfCancellationRequested();

					if (funcTask.IsCompleted)
					{
						return await funcTask.ConfigureAwait(false);
					}

					if (cancelIfTimeout == false)
						timedOutTaskProcessor?.Invoke(funcTask);

					throw new SyntheticTimeoutException();
				}
			}
			finally
			{
				ctsFunc?.Dispose();
			}
		}

19 View Source File : FusionCacheExecutionUtils.cs
License : MIT License
Project Creator : jodydonetti

public static TResult RunAsyncFuncWithTimeout<TResult>(Func<CancellationToken, Task<TResult>> asyncFunc, TimeSpan timeout, bool cancelIfTimeout = true, Action<Task<TResult>>? timedOutTaskProcessor = null, CancellationToken token = default)
		{
			token.ThrowIfCancellationRequested();

			if (timeout == TimeSpan.Zero || timeout < Timeout.InfiniteTimeSpan)
			{
				var exc = new SyntheticTimeoutException();
				if (cancelIfTimeout == false)
					timedOutTaskProcessor?.Invoke(Task.FromException<TResult>(exc));
				throw exc;
			}

			Task<TResult> task;

			if (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None)
			{
				task = _taskFactory.StartNew(() => asyncFunc(token), token).Unwrap();
			}
			else
			{
				task = _taskFactory.StartNew(() => RunAsyncFuncWithTimeoutAsync(asyncFunc, timeout, cancelIfTimeout, timedOutTaskProcessor, token), token).Unwrap();
			}

			return task.GetAwaiter().GetResult();
		}

19 View Source File : FusionCacheExecutionUtils.cs
License : MIT License
Project Creator : jodydonetti

public static TResult RunSyncFuncWithTimeout<TResult>(Func<CancellationToken, TResult> syncFunc, TimeSpan timeout, bool cancelIfTimeout = true, Action<Task<TResult>>? timedOutTaskProcessor = null, CancellationToken token = default)
		{
			token.ThrowIfCancellationRequested();

			if (timeout == TimeSpan.Zero || timeout < Timeout.InfiniteTimeSpan)
			{
				var exc = new SyntheticTimeoutException();
				if (cancelIfTimeout == false)
					timedOutTaskProcessor?.Invoke(Task.FromException<TResult>(exc));
				throw exc;
			}

			Task<TResult> task;

			if (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None)
			{
				//task = _taskFactory.StartNew(() => syncFunc(token), token);
				return syncFunc(token);
			}
			else
			{
				task = RunAsyncFuncWithTimeoutAsync(ct => _taskFactory.StartNew(() => syncFunc(ct), ct), timeout, cancelIfTimeout, timedOutTaskProcessor, token);
			}

			return task.GetAwaiter().GetResult();
		}

19 View Source File : FusionCacheExecutionUtils.cs
License : MIT License
Project Creator : jodydonetti

public static void RunSyncActionWithTimeout(Action<CancellationToken> syncAction, TimeSpan timeout, bool cancelIfTimeout = true, Action<Task>? timedOutTaskProcessor = null, CancellationToken token = default)
		{
			token.ThrowIfCancellationRequested();

			if (timeout == TimeSpan.Zero || timeout < Timeout.InfiniteTimeSpan)
			{
				var exc = new SyntheticTimeoutException();
				if (cancelIfTimeout == false)
					timedOutTaskProcessor?.Invoke(Task.FromException(exc));
				throw exc;
			}

			Task task;

			if (timeout == Timeout.InfiniteTimeSpan && token == CancellationToken.None)
			{
				//task = _taskFactory.StartNew(() => syncAction(token), token);
				syncAction(token);
				return;
			}
			else
			{
				task = RunAsyncActionWithTimeoutAsync(ct => _taskFactory.StartNew(() => syncAction(ct), ct), timeout, cancelIfTimeout, timedOutTaskProcessor, token);
			}

			task.GetAwaiter().GetResult();
		}

19 View Source File : EnqueueDownloadAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jpdillingham

[Trait("Category", "EnqueueDownloadAsync")]
        [Theory(DisplayName = "EnqueueDownloadAsync stream throws download exception on error"), AutoData]
        public async Task EnqueueDownloadAsync_Stream_Throws_Download_Exception_On_Error(string username, string filename, long size, int token, IPEndPoint endpoint)
        {
            var options = new SoulseekClientOptions(messageTimeout: 5);

            var response = new TransferResponse(token, size); // allowed, will start download immediately
            var responseWaitKey = new WaitKey(MessageCode.Peer.TransferResponse, username, token);

            var request = new TransferRequest(TransferDirection.Download, token, filename, size);

            var transferConn = new Mock<IConnection>();
            transferConn.Setup(m => m.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);

            var tcs = new TaskCompletionSource<byte[]>(TaskCreationOptions.RunContinuationsAsynchronously);
            var data = new byte[] { 0x0, 0x1, 0x2, 0x3 };

            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<TransferResponse>(It.Is<WaitKey>(w => w.Equals(responseWaitKey)), It.IsAny<int?>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(response));
            waiter.Setup(m => m.WaitIndefinitely<TransferRequest>(It.IsAny<WaitKey>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(request));
            waiter.Setup(m => m.Wait(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken>()))
                .Returns(Task.CompletedTask);
            waiter.Setup(m => m.Wait<IConnection>(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(transferConn.Object));
            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(new UserAddressResponse(username, endpoint)));

            // make download wait for our task completion source
            waiter.Setup(m => m.WaitIndefinitely(It.IsAny<WaitKey>(), It.IsAny<CancellationToken>()))
                .Returns(tcs.Task);

            // complete our TCS when the disconnected event handler fires
            waiter.Setup(m => m.Complete(It.IsAny<WaitKey>()))
                .Callback(() => tcs.TrySetResult(data));

            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);

            var connManager = new Mock<IPeerConnectionManager>();
            connManager.Setup(m => m.GetOrAddMessageConnectionAsync(username, endpoint, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(conn.Object));

            var expectedEx = new Exception("some problem");

            connManager.Setup(m => m.GetTransferConnectionAsync(username, endpoint, token, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<IConnection>(expectedEx));

            using (var stream = new MemoryStream())
            using (var s = new SoulseekClient(options, waiter: waiter.Object, serverConnection: conn.Object, peerConnectionManager: connManager.Object))
            {
                s.SetProperty("State", SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn);

                var downloadTask = await s.EnqueueDownloadAsync(username, filename, stream, 0L, 0, token);

                replacedert.NotNull(downloadTask);

                transferConn.Raise(m => m.Disconnected += null, new ConnectionDisconnectedEventArgs("done"));

                var ex = await Record.ExceptionAsync(() => downloadTask);

                replacedert.NotNull(ex);
                replacedert.IsType<SoulseekClientException>(ex);
                replacedert.Equal(expectedEx, ex.InnerException);
            }
        }

See More Examples