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 : GetUserStatusAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jpdillingham

[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<UserStatus>(It.IsAny<WaitKey>(), null, It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserStatus>(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 : JoinLeaveRoomAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jpdillingham

[Trait("Category", "JoinRoomAsync")]
        [Theory(DisplayName = "JoinRoomAsync throws NoResponseException on wait timeout"), AutoData]
        public async Task JoinRoomAsync_Throws_NoResponseException_On_Wait_Timeout(string roomName)
        {
            var conn = new Mock<IMessageConnection>();

            var key = new WaitKey(MessageCode.Server.JoinRoom, roomName);
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait<RoomData>(It.Is<WaitKey>(k => k.Equals(key)), It.IsAny<int?>(), It.IsAny<CancellationToken?>()))
                .Returns(Task.FromException<RoomData>(new TimeoutException()));

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

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

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

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

[Trait("Category", "EnqueueDownloadAsync")]
        [Theory(DisplayName = "EnqueueDownloadAsync throws download exception on error before queue"), AutoData]
        public async Task EnqueueDownloadAsync_Throws_Download_Exception_On_Error_Before_Queue(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));

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

            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserAddressResponse>(expectedEx));

            // 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));
            connManager.Setup(m => m.GetTransferConnectionAsync(username, endpoint, token, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(transferConn.Object));

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

                var ex = await Record.ExceptionAsync(() => s.EnqueueDownloadAsync(username, filename, 0L, 0, token));

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

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

[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, uploadSlots, queueLength, hasFreeSlot, picture);

            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 : jpdillingham

[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, uploadSlots, queueLength, hasFreeSlot, picture);

            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 : GetUserInfoAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jpdillingham

[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, uploadSlots, queueLength, hasFreeSlot, picture);

            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 : JoinLeaveRoomAsyncTests.cs
License : GNU General Public License v3.0
Project Creator : jpdillingham

[Trait("Category", "LeaveRoomAsync")]
        [Theory(DisplayName = "LeaveRoomAsync throws NoResponseException on wait timeout"), AutoData]
        public async Task LeaveRoomAsync_Throws_NoResponseException_On_Wait_Timeout(string roomName)
        {
            var conn = new Mock<IMessageConnection>();
            conn.Setup(m => m.State)
                .Returns(ConnectionState.Connected);

            var key = new WaitKey(MessageCode.Server.LeaveRoom, roomName);
            var waiter = new Mock<IWaiter>();
            waiter.Setup(m => m.Wait(It.Is<WaitKey>(k => k.Equals(key)), 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.LeaveRoomAsync(roomName));

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

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

[Trait("Category", "EnqueueDownloadAsync")]
        [Theory(DisplayName = "EnqueueDownloadAsync throws download exception on error"), AutoData]
        public async Task EnqueueDownloadAsync_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 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, 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);
            }
        }

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 before queue"), AutoData]
        public async Task EnqueueDownloadAsync_Stream_Throws_Download_Exception_On_Error_Before_Queue(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));

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

            waiter.Setup(m => m.Wait<UserAddressResponse>(It.IsAny<WaitKey>(), It.IsAny<int?>(), It.IsAny<CancellationToken>()))
                .Returns(Task.FromException<UserAddressResponse>(expectedEx));

            // 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));
            connManager.Setup(m => m.GetTransferConnectionAsync(username, endpoint, token, It.IsAny<CancellationToken>()))
                .Returns(Task.FromResult(transferConn.Object));

            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 ex = await Record.ExceptionAsync(() => s.EnqueueDownloadAsync(username, filename, stream, 0L, 0, token));

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

19 View Source File : UniTaskExtensions.cs
License : MIT License
Project Creator : kdw9502

public static Task<T> AsTask<T>(this UniTask<T> task)
        {
            try
            {
                UniTask<T>.Awaiter awaiter;
                try
                {
                    awaiter = task.GetAwaiter();
                }
                catch (Exception ex)
                {
                    return Task.FromException<T>(ex);
                }

                if (awaiter.IsCompleted)
                {
                    try
                    {
                        var result = awaiter.GetResult();
                        return Task.FromResult(result);
                    }
                    catch (Exception ex)
                    {
                        return Task.FromException<T>(ex);
                    }
                }

                var tcs = new TaskCompletionSource<T>();

                awaiter.SourceOnCompleted(state =>
                {
                    using (var tuple = (StateTuple<TaskCompletionSource<T>, UniTask<T>.Awaiter>)state)
                    {
                        var (inTcs, inAwaiter) = tuple;
                        try
                        {
                            var result = inAwaiter.GetResult();
                            inTcs.SetResult(result);
                        }
                        catch (Exception ex)
                        {
                            inTcs.SetException(ex);
                        }
                    }
                }, StateTuple.Create(tcs, awaiter));

                return tcs.Task;
            }
            catch (Exception ex)
            {
                return Task.FromException<T>(ex);
            }
        }

19 View Source File : UniTaskExtensions.cs
License : MIT License
Project Creator : kdw9502

public static Task AsTask(this UniTask task)
        {
            try
            {
                UniTask.Awaiter awaiter;
                try
                {
                    awaiter = task.GetAwaiter();
                }
                catch (Exception ex)
                {
                    return Task.FromException(ex);
                }

                if (awaiter.IsCompleted)
                {
                    try
                    {
                        awaiter.GetResult(); // check token valid on Succeeded
                        return Task.CompletedTask;
                    }
                    catch (Exception ex)
                    {
                        return Task.FromException(ex);
                    }
                }

                var tcs = new TaskCompletionSource<object>();

                awaiter.SourceOnCompleted(state =>
                {
                    using (var tuple = (StateTuple<TaskCompletionSource<object>, UniTask.Awaiter>)state)
                    {
                        var (inTcs, inAwaiter) = tuple;
                        try
                        {
                            inAwaiter.GetResult();
                            inTcs.SetResult(null);
                        }
                        catch (Exception ex)
                        {
                            inTcs.SetException(ex);
                        }
                    }
                }, StateTuple.Create(tcs, awaiter));

                return tcs.Task;
            }
            catch (Exception ex)
            {
                return Task.FromException(ex);
            }
        }

19 View Source File : DataVault.cs
License : MIT License
Project Creator : Keeper-Security

protected Task<byte[]> MockExecuteRest(string endpoint, ApiRequestPayload payload, IAuth auth)
        {
            if (auth.Endpoint.Server != DataVault.DefaultEnvironment)
            {
                return Task.FromException<byte[]>(new KeeperRegionRedirect(DataVault.DefaultEnvironment));
            }

            byte[] response = null;
            switch (endpoint)
            {
                case "authentication/register_device":
                {
                    var device = new Device()
                    {
                        EncryptedDeviceToken = ByteString.CopyFrom(CryptoUtils.GetRandomBytes(64)),
                    };
                    response = device.ToByteArray();
                }
                    break;
                case "authentication/start_login":
                {
                    var lrs = new LoginResponse
                    {
                        EncryptedLoginToken = ByteString.CopyFrom(DataVault.EncryptedLoginToken),

                    };
                    if (StopAtDeviceApproval)
                    {
                        lrs.LoginState = LoginState.DeviceApprovalRequired;
                    }
                    else if (StopAtTwoFactor)
                    {
                        lrs.LoginState = LoginState.Requires2Fa;
                        lrs.Channels.Add(new TwoFactorChannelInfo
                        {
                            ChannelType = TwoFactorChannelType.TwoFaCtTotp,
                            ChannelUid = ByteString.CopyFrom(CryptoUtils.GetRandomBytes(8)),
                            ChannelName = "Mock",
                        });
                    }
                    else if (StopAtPreplacedword)
                    {
                        lrs.LoginState = LoginState.RequiresAuthHash;
                        lrs.Salt.Add(new Salt
                        {
                            Iterations = DataVault.UserIterations,
                            Salt_ = ByteString.CopyFrom(DataVault.UserSalt),
                            Name = "Mock",
                            Uid = ByteString.CopyFrom(CryptoUtils.GetRandomBytes(8)),
                        });
                    }
                    else
                    {
                        lrs.LoginState = LoginState.LoggedIn;
                        lrs.AccountUid = ByteString.CopyFrom(DataVault.AccountUid);
                        lrs.PrimaryUsername = DataVault.UserName;
                        lrs.CloneCode = ByteString.CopyFrom(CryptoUtils.GetRandomBytes(8));
                        lrs.EncryptedSessionToken = ByteString.CopyFrom(DataVault.SessionToken);
                        var device = auth.Storage.Devices.List.FirstOrDefault();
                        var devicePrivateKey = CryptoUtils.LoadPrivateEcKey(device.DeviceKey);
                        var devicePublicKey = CryptoUtils.GetPublicEcKey(devicePrivateKey);
                        lrs.EncryptedDataKey = ByteString.CopyFrom(CryptoUtils.EncryptEc(DataVault.UserDataKey, devicePublicKey));
                        lrs.EncryptedDataKeyType = EncryptedDataKeyType.ByDevicePublicKey;
                    }

                    response = lrs.ToByteArray();
                }
                    break;

                case "authentication/validate_auth_hash":
                {
                    var request = ValidateAuthHashRequest.Parser.ParseFrom(payload.Payload);
                    var expectedPreplacedword = CryptoUtils.DeriveV1KeyHash(DataVault.UserPreplacedword, DataVault.UserSalt, DataVault.UserIterations);
                    if (request.AuthResponse.SequenceEqual(expectedPreplacedword))
                    {
                        var lrs = new LoginResponse
                        {
                            LoginState = LoginState.LoggedIn,
                            EncryptedLoginToken = ByteString.CopyFrom(DataVault.EncryptedLoginToken),
                            AccountUid = ByteString.CopyFrom(DataVault.AccountUid),
                            PrimaryUsername = DataVault.UserName,
                            CloneCode = ByteString.CopyFrom(CryptoUtils.GetRandomBytes(8)),
                            EncryptedSessionToken = ByteString.CopyFrom(DataVault.SessionToken),
                            EncryptedDataKey = ByteString.CopyFrom(DataVault.EncryptionParams),
                            EncryptedDataKeyType = EncryptedDataKeyType.ByPreplacedword,
                        };
                        response = lrs.ToByteArray();
                    }
                    else
                    {
                        return Task.FromException<byte[]>(new KeeperAuthFailed("unit test"));
                    }

                }
                    break;

                case "authentication/request_device_verification":
                    StopAtDeviceApproval = false;
                    response = new byte[0];
                    break;

                case "authentication/2fa_send_push":
                    if (StopAtDeviceApproval)
                    {
                        StopAtDeviceApproval = false;
                    }

                    response = new byte[0];
                    break;

                case "authentication/2fa_validate":
                    var tfvr = TwoFactorValidateRequest.Parser.ParseFrom(payload.Payload);
                    if (tfvr.Value == DataVault.TwoFactorOneTimeToken)
                    {
                        StopAtTwoFactor = false;
                        var tfars = new TwoFactorValidateResponse
                        {
                            EncryptedLoginToken = tfvr.EncryptedLoginToken
                        };
                        response = tfars.ToByteArray();
                    }
                    else
                    {
                        return Task.FromException<byte[]>(new KeeperAuthFailed("unit test"));
                    }

                    break;

                case "vault/execute_v2_command":
                    break;

                case "authentication/validate_device_verification_code":
                    var vdvcr = ValidateDeviceVerificationCodeRequest.Parser.ParseFrom(payload.Payload);
                    if (vdvcr.VerificationCode == DataVault.DeviceVerificationEmailCode)
                    {
                        StopAtDeviceApproval = false;
                        response = new byte[0];
                    }
                    else
                    {
                        return Task.FromException<byte[]>(new KeeperAuthFailed("unit test test"));
                    }

                    break;
                case "login/account_summary":
                {
                    response = auth.ProcessAccountSummary().ToByteArray();
                }
                    break;
            }

            if (response != null)
            {
                return Task.FromResult(response);
            }

            return Task.FromException<byte[]>(new KeeperCanceled());
        }

19 View Source File : SyncDownTest.cs
License : MIT License
Project Creator : Keeper-Security

public IAuthentication GetConnectedAuthContext()
        {
            var context = new Mock<IAuthContext>();
            context.Setup(x => x.SessionToken).Returns(_vaultEnv.SessionToken);
            context.Setup(x => x.ClientKey).Returns(_vaultEnv.ClientKey);
            context.Setup(x => x.DataKey).Returns(_vaultEnv.DataKey);
            context.Setup(x => x.PrivateKey).Returns(_vaultEnv.PrivateKey);

            var endpoint = new Mock<IKeeperEndpoint>();
            endpoint.Setup(x => x.DeviceName).Returns("C# Unit Tests");
            endpoint.Setup(x => x.ClientVersion).Returns("c15.0.0");
            endpoint.Setup(x => x.Server).Returns(DataVault.DefaultEnvironment);

            var auth = new Mock<IAuthentication>();
            auth.Setup(x => x.AuthContext).Returns(context.Object);
            auth.Setup(x => x.Endpoint).Returns(endpoint.Object);
            auth.Setup(x => x.ExecuteAuthCommand(It.IsAny<SyncDownCommand>(), It.IsAny<Type>(), It.IsAny<bool>()))
                .Returns<SyncDownCommand, Type, bool>((command, _, __) =>
                {
                    try
                    {
                        return Task.FromResult((KeeperApiResponse) _vaultEnv.GetSyncDownResponse());
                    }
                    catch (Exception e)
                    {
                        return Task.FromException<KeeperApiResponse>(e);
                    }
                });
            return auth.Object;
        }

19 View Source File : ProblemDetailsMiddlewareTests.cs
License : MIT License
Project Creator : khellang

private static RequestDelegate ResponseThrows(Exception exception = null)
        {
            return context => Task.FromException(exception ?? new InvalidOperationException("Request failed."));
        }

19 View Source File : TaskExtensions.cs
License : MIT License
Project Creator : Kirill-Maurin

public static bool CheckException<T>(this Task task, out Task<T> result)
        {
            var c = task.TryGetException(out var e);
            result = c ? Task.FromException<T>(e) : default;
            return c;
        }

19 View Source File : UdpSender.cs
License : MIT License
Project Creator : KIT-ISAS

public Task PublishAndWaitAsync(in T message, CancellationToken token)
        {
            return !IsAlive
                ? Task.FromException(new InvalidOperationException("Sender has been disposed."))
                : senderQueue.EnqueueAsync(message, token, ref numDropped, ref bytesDropped);
        }

19 View Source File : TcpSender.cs
License : MIT License
Project Creator : KIT-ISAS

public Task PublishAndWaitAsync(in T message, CancellationToken token)
        {
            return !IsRunning
                ? Task.FromException(new InvalidOperationException("Sender has been disposed."))
                : senderQueue.EnqueueAsync(message, token, ref numDropped, ref bytesDropped);
        }

19 View Source File : Task.cs
License : MIT License
Project Creator : la-yumba

async Task<string> Fail(string message = null) => await Task.FromException<string>(new Exception(message));

19 View Source File : AsyncEventPool.cs
License : Apache License 2.0
Project Creator : luyikk

public Task<int> SendSync(Socket sock)
        {
            Task<int> t;

            if (sock.SendAsync(this))
            {
                t = GetCompletionResponsibility(out bool responsibleForReturningToPool).Task;

                if (responsibleForReturningToPool)
                    Reset();
            }
            else
            {
                if (SocketError == SocketError.Success)
                    return Task.FromResult(BytesTransferred);
                else
                    return Task.FromException<int>(GetException(SocketError));

            }

            return t;
        }

19 View Source File : ReleaseUpdateOrchestrationContextBuilder.cs
License : MIT License
Project Creator : marcduiker

public static Mock<IDurableOrchestrationContext> BuildWithHistoryAndWithGitHubWithDifferentReleasesButFailsOnSaveLatestRelease()
        {
            // Enable the orchestration to post updates.
            Environment.SetEnvironmentVariable(Toggles.DoPostUpdateVariableName, "true");

            const string repository1Name = "repo-1";
            const int releaseIdHistoryRepo1 = 2;
            const int releaseIdGithubRepo1 = 3;
            var mockContext = new Mock<IDurableOrchestrationContext>(MockBehavior.Strict);
            var repoConfigurations = RepositoryConfigurationBuilder.BuildListWithOne(repository1Name);

            // Setup GetRepositoryConfigurations
            mockContext
                .Setup(c => c.CallActivityWithRetryAsync<IReadOnlyList<RepositoryConfiguration>>(
                        nameof(GetRepositoryConfigurationsActivity),
                        It.IsAny<RetryOptions>(),
                        null))
                .ReturnsAsync(repoConfigurations);

            // Setup GetLatestReleaseFromGitHub
            mockContext
                .Setup(c => c.CallActivityWithRetryAsync<GitHubRepositoryRelease>(
                        nameof(GetLatestReleaseFromGitHubActivity),
                        It.IsAny<RetryOptions>(),
                        It.Is<RepositoryConfiguration>(r => r.RepositoryName.Equals(repository1Name))))
                 .ReturnsAsync(RepositoryReleaseBuilder.BuildOneWithReleaseId<GitHubRepositoryRelease>(repository1Name, releaseIdGithubRepo1));

            // Setup GetLatestReleaseFromHistory
            mockContext
                .Setup(c => c.CallActivityWithRetryAsync<HistoryRepositoryRelease>(
                        nameof(GetLatestReleaseFromHistoryActivity),
                        It.IsAny<RetryOptions>(),
                        It.Is<RepositoryConfiguration>(r => r.RepositoryName.Equals(repository1Name))))
                .ReturnsAsync(RepositoryReleaseBuilder.BuildOneWithReleaseId<HistoryRepositoryRelease>(repository1Name, releaseIdHistoryRepo1));

            mockContext.Setup(c => c.SetCustomStatus(It.IsAny<string>()));

            // Setup SaveLatestRelease, throws
            mockContext
                .Setup(c => c.CallActivityWithRetryAsync<RepositoryRelease>(
                        nameof(SaveLatestReleaseActivity),
                        It.IsAny<RetryOptions>(),
                        It.Is<RepositoryRelease>(r => r.RepositoryName.Equals(repository1Name))))
                .Returns(Task.FromException<RepositoryRelease>(new FunctionFailedException("failed")));

            // PostUpdate should not be called

            return mockContext;
        }

19 View Source File : UdpWrapper.cs
License : MIT License
Project Creator : MarkusKgit

public Task<UdpReceiveResult> ReceiveAsync()
        {
            IAsyncResult asyncResult = _udpClient.BeginReceive(null, null);
            asyncResult.AsyncWaitHandle.WaitOne(_receiveTimeout);
            if (asyncResult.IsCompleted)
            {
                IPEndPoint remoteEP = null;
                byte[] receivedData = _udpClient.EndReceive(asyncResult, ref remoteEP);
                return Task.FromResult(new UdpReceiveResult(receivedData, remoteEP));
            }
            else
            {
                return Task.FromException<UdpReceiveResult>(new TimeoutException());
            }
        }

19 View Source File : UdpWrapper.cs
License : MIT License
Project Creator : MarkusKgit

public Task<int> SendAsync(byte[] datagram, int bytes)
        {
            IAsyncResult asyncResult = _udpClient.BeginSend(datagram, bytes, null, null);
            asyncResult.AsyncWaitHandle.WaitOne(_sendTimeout);
            if (asyncResult.IsCompleted)
            {
                int num = _udpClient.EndSend(asyncResult);
                return Task.FromResult(num);
            }
            else
            {
                return Task.FromException<int>(new TimeoutException());
            }
        }

19 View Source File : ConnectionCompletionTests.cs
License : MIT License
Project Creator : Matthias247

public Task WriteAsync(ArraySegment<byte> buffer)
            {
                if (!FailNextWrite)
                {
                    return inner.WriteAsync(buffer);
                }
                return Task.FromException(new Exception("Write should fail"));
            }

19 View Source File : SocketExtensions.cs
License : MIT License
Project Creator : Matthias247

public ValueTask<StreamReadResult> ReadAsync(ArraySegment<byte> buffer)
            {
                if (buffer.Count == 0)
                {
                    throw new Exception("Reading 0 bytes is not supported");
                }

                var offset = buffer.Offset;
                var count = buffer.Count;

                if (tryNonBlockingRead)
                {
                    // Try a nonblocking read if the last read yielded all required bytes
                    // This means there are most likely bytes left in the socket buffer
                    SocketError ec;
                    var rcvd = socket.Receive(buffer.Array, offset, count, SocketFlags.None, out ec);
                    if (ec != SocketError.Success &&
                        ec != SocketError.WouldBlock &&
                        ec != SocketError.TryAgain)
                    {
                        return new ValueTask<StreamReadResult>(
                            Task.FromException<StreamReadResult>(
                                new SocketException((int)ec)));
                    }

                    if (rcvd != count)
                    {
                        // Socket buffer seems empty
                        // Use an async read next time
                        tryNonBlockingRead = false;
                    }

                    if (ec == SocketError.Success)
                    {
                        return new ValueTask<StreamReadResult>(
                            new StreamReadResult
                            {
                                BytesRead = rcvd,
                                EndOfStream = rcvd == 0,
                            });
                    }

                    // In the other case we got EAGAIN, which means we try
                    // an async read now
                    // replacedert that we have nothing read yet - otherwise the
                    // logic here would be broken
                    if (rcvd != 0)
                    {
                        throw new Exception(
                            "Unexpected reception of data in TryAgain case");
                    }
                }

                var readTask = socket.ReceiveAsync(buffer, SocketFlags.None);
                Task<StreamReadResult> transformedTask = readTask.ContinueWith(tt =>
                {
                    if (tt.Exception != null)
                    {
                        throw tt.Exception;
                    }

                    var res = tt.Result;
                    if (res == count)
                    {
                        // All required data was read
                        // Try a speculative nonblocking read next time
                        tryNonBlockingRead = true;
                    }

                    return new StreamReadResult
                    {
                        BytesRead = res,
                        EndOfStream = res == 0,
                    };
                });

                return new ValueTask<StreamReadResult>(transformedTask);
            }

19 View Source File : MyService.cs
License : MIT License
Project Creator : merken

public Task<string> ThrowsMyServiceExceptionAsync()
        {
            return Task.FromException<string>(new MyServiceException(value));
        }

public Task<ITriggerData> BindAsync(object value, ValueBindingContext context)
        {
            var orchestrationContext = (EventStreamBackedClreplacedifierTriggerValue)value;
            Type destinationType = this.parameterInfo.ParameterType;



            object convertedValue = null;

            if (destinationType == typeof(EventStreamBackedClreplacedifierTriggerValue))
            {
                convertedValue = orchestrationContext;
            }
            else if (destinationType == typeof(string))
            {
                convertedValue = EventStreamBackedClreplacedifierOrchestrationToString(orchestrationContext);
            }

            return Task.FromException<ITriggerData>(new NotImplementedException());

#if TODO

            // Need to work out how to return the binding ??

            var bindingData = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            bindingData[this.parameterInfo.Name] = convertedValue;

            // We don't specify any return value binding 
            var triggerData = new TriggerData(inputValueProvider, bindingData);
            return Task.FromResult<ITriggerData>(triggerData);
#endif
        }

19 View Source File : EventStreamBackedCommandOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<ICommandResponse> RunCommandAsync(string commandName,
            string instanceId,
            JObject commandParameters = null)
        {

            // Validate the inputs...
            if (string.IsNullOrWhiteSpace(commandName))
            {
                throw new ArgumentException($"Projection name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the command
            return await Task.FromException<ICommandResponse>(new NotImplementedException());
        }

19 View Source File : EventStreamBackedCommandOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IQueryResponse> RunQueryAsync(string queryName, 
            string instanceId, 
            JObject queryParameters, 
            DateTime? asOfDate = null)
        {
            if (string.IsNullOrWhiteSpace(queryName))
            {
                throw new ArgumentException($"Query name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IQueryResponse>(new NotImplementedException());
        }

19 View Source File : EventStreamBackedCommandOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IProjectionResponse > RunProjectionAsync(string projectionName, 
            string instanceId, 
            string aggregateKey, 
            DateTime? asOfDate = null, 
            int? asOfSequence = null)
        {
            // Validate the inputs...
            if (string.IsNullOrWhiteSpace(projectionName ))
            {
                throw new ArgumentException($"Projection name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            if (string.IsNullOrWhiteSpace(aggregateKey ) )
            {
                throw new ArgumentException($"Projection requires a valid aggregate key");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IProjectionResponse>(new NotImplementedException()); 
        }

19 View Source File : EventStreamBackedCommandOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IEnumerable<IIdentifierGroupMemberResponse>> GetIdentifierGroupMembersAsync(string groupName, 
            string instanceId, 
            DateTime? asOfDate = null)
        {
            if (string.IsNullOrWhiteSpace(groupName))
            {
                throw new ArgumentException($"Group name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IEnumerable<IIdentifierGroupMemberResponse>>(new NotImplementedException());
        }

19 View Source File : EventStreamBackedCommandOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IClreplacedifierResponse> RunClreplacedifierAsync(string clreplacedifierName, 
            string instanceId, 
            string aggregateKey, 
            DateTime? asOfDate = null, 
            int? asOfSequence = null)
        {

            // Validate the inputs...
            if (string.IsNullOrWhiteSpace(clreplacedifierName))
            {
                throw new ArgumentException($"Clreplacedifier name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            if (string.IsNullOrWhiteSpace(aggregateKey))
            {
                throw new ArgumentException($"Clreplacedifier requires a valid aggregate key");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IClreplacedifierResponse>(new NotImplementedException());
        }

19 View Source File : EventStreamBackedIdentifierGroupOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IProjectionResponse> RunProjectionAsync(string projectionName,
            string instanceId,
            string aggregateKey,
            DateTime? asOfDate = null,
            int? asOfSequence = null)
        {
            // Validate the inputs...
            if (string.IsNullOrWhiteSpace(projectionName))
            {
                throw new ArgumentException($"Projection name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            if (string.IsNullOrWhiteSpace(aggregateKey))
            {
                throw new ArgumentException($"Projection requires a valid aggregate key");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IProjectionResponse>(new NotImplementedException());
        }

19 View Source File : EventStreamBackedIdentifierGroupOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IClreplacedifierResponse> RunClreplacedifierAsync(string clreplacedifierName,
            string instanceId,
            string aggregateKey,
            DateTime? asOfDate = null,
            int? asOfSequence = null)
        {

            // Validate the inputs...
            if (string.IsNullOrWhiteSpace(clreplacedifierName))
            {
                throw new ArgumentException($"Clreplacedifier name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            if (string.IsNullOrWhiteSpace(aggregateKey))
            {
                throw new ArgumentException($"Clreplacedifier requires a valid aggregate key");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IClreplacedifierResponse>(new NotImplementedException());
        }

19 View Source File : EventStreamBackedQueryOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IQueryResponse> RunQueryAsync(string queryName,
            string instanceId,
            JObject queryParameters,
            DateTime? asOfDate = null)
        {
            if (string.IsNullOrWhiteSpace(queryName))
            {
                throw new ArgumentException($"Query name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IQueryResponse>(new NotImplementedException());
        }

19 View Source File : EventStreamBackedQueryOrchestrator.cs
License : The Unlicense
Project Creator : MerrionComputing

public async Task<IEnumerable<IIdentifierGroupMemberResponse>> GetIdentifierGroupMembersAsync(string groupName,
            string instanceId,
            DateTime? asOfDate = null)
        {
            if (string.IsNullOrWhiteSpace(groupName))
            {
                throw new ArgumentException($"Group name not set");
            }

            if (string.IsNullOrEmpty(instanceId))
            {
                instanceId = Guid.NewGuid().ToString("N");
            }

            // TODO: Build a callout/callback definition

            // TODO: Spawn the projection
            return await Task.FromException<IEnumerable<IIdentifierGroupMemberResponse>>(new NotImplementedException());
        }

19 View Source File : Classification.cs
License : MIT License
Project Creator : MerrionComputing

public async Task<ClreplacedificationResponse> Clreplacedify(IClreplacedification clreplacedificationToRun, 
            DateTime? asOfDate = null)
        {
            if (null != _clreplacedificationProcessor)
            {
                ClreplacedificationResponse ret = await _clreplacedificationProcessor.Clreplacedify(clreplacedificationToRun,
                    asOfDate);
                if (null != _notificationDispatcher)
                {
                    await _notificationDispatcher.ClreplacedificationCompleted(this,
                        ClreplacedificationNameAttribute.GetClreplacedificationName(clreplacedificationToRun.GetType()),
                        _clreplacedificationProcessor.Parameters,
                        ret.AsOfSequence,
                        asOfDate,
                        ret);
                }
                return ret;
            }
            else
            {
                return await Task.FromException<ClreplacedificationResponse>(
                    new Exception("Clreplacedification processor not initialised"));
            }
        }

19 View Source File : Classification.cs
License : MIT License
Project Creator : MerrionComputing

public async Task<IEnumerable<string > > GetAllInstanceKeys(DateTime? asOfDate = null)
        {
            if (null != _clreplacedificationProcessor)
            {
                return await _clreplacedificationProcessor.GetAllInstanceKeys(asOfDate);
            }
            else
            {
                return await Task.FromException<IEnumerable<string>>(new Exception("Clreplacedification processor not initialised"));
            }
        }

19 View Source File : Projection.cs
License : MIT License
Project Creator : MerrionComputing

public async Task<TProjection> Process<TProjection>(TProjection projectionToRun, Nullable<DateTime> asOfDate = null) where TProjection : IProjection
        {
            if (null != _projectionProcessor)
            {
                TProjection ret = await _projectionProcessor.Process<TProjection>(projectionToRun, asOfDate);
                if (null != _notificationDispatcher)
                {
                    // Dispatch a projection-completed notification
                    await _notificationDispatcher.ProjectionCompleted(this,
                        ProjectionNameAttribute.GetProjectionName(typeof(TProjection)),
                        ret.CurrentSequenceNumber,
                        asOfDate,
                        ret);
                }
                return ret;
            }
            else
            {
                return await Task.FromException<TProjection>(new Exception("Projection processor not initialised"));
            }
        }

19 View Source File : TaskExtensionsTests.cs
License : MIT License
Project Creator : meziantou

[Fact]
        public void ForgetTest_Faulted()
        {
            var task = Task.FromException(new InvalidOperationException(""));
            task.Forget(); // Should not throw exception
        }

19 View Source File : WebexAdapter.cs
License : MIT License
Project Creator : microsoft

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(new NotSupportedException("Webex adapter does not support updateActivity."));
        }

19 View Source File : FacebookAdapter.cs
License : MIT License
Project Creator : microsoft

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(new NotImplementedException("Facebook adapter does not support updateActivity."));
        }

19 View Source File : FacebookAdapter.cs
License : MIT License
Project Creator : microsoft

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
        {
            return Task.FromException(new NotImplementedException("Facebook adapter does not support deleteActivity."));
        }

19 View Source File : TwilioAdapter.cs
License : MIT License
Project Creator : microsoft

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(
                new NotSupportedException("Twilio SMS does not support updating activities."));
        }

19 View Source File : TwilioAdapter.cs
License : MIT License
Project Creator : microsoft

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(
                new NotSupportedException("Twilio SMS does not support deleting activities."));
        }

19 View Source File : TraceTests.cs
License : MIT License
Project Creator : microsoft

Task IDebugTransport.SendAsync(JToken token, CancellationToken cancellationToken)
            {
                try
                {
                    lock (_gate)
                    {
                        _trace.Add(new Event(++_order, token, false));
                    }

                    var incoming = token.ToObject<Incoming>();
                    if (incoming.Type == "event")
                    {
                        switch (incoming.Event)
                        {
                            case "initialized":
                                Request(new Attach() { BreakOnStart = true });
                                Request(new ConfigurationDone());
                                Request(new Threads());
                                break;
                            case "stopped":
                                Request(new Next() { ThreadId = incoming.Body.ThreadId });
                                break;
                        }
                    }

                    return Task.CompletedTask;
                }
                catch (OperationCanceledException error)
                {
                    return Task.FromCanceled(error.CancellationToken);
                }
                catch (Exception error)
                {
                    return Task.FromException(error);
                }
            }

19 View Source File : EchoDialog.cs
License : MIT License
Project Creator : microsoft

public Task StartAsync(IDialogContext context)
        {
            try
            {
                context.Wait(MessageReceivedAsync);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }

            return Task.CompletedTask;
        }

19 View Source File : WeChatHttpAdapter.cs
License : MIT License
Project Creator : microsoft

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(new NotSupportedException("WeChat does not support deleting activities."));
        }

19 View Source File : WeChatHttpAdapter.cs
License : MIT License
Project Creator : microsoft

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(new NotSupportedException("WeChat does not support updating activities."));
        }

19 View Source File : ExtensionsTest.cs
License : MIT License
Project Creator : microsoft

[TestMethod, TestCategory("Extensions")]
        public void Extensions_JavaScript_ToPromise_Faulted()
        {
            const string message = "No task for you!";
            var task = Task.FromException<double>(new UnauthorizedAccessException(message));

            engine.Script.promise = task.ToPromise(engine);
            engine.Execute("(async function () { try { result = await promise; } catch (exception) { result = exception.hostException.InnerException.InnerException.Message; } })()");
            replacedert.AreEqual(message, engine.Script.result);

            engine.Script.task = task;
            engine.Execute("(async function () { try { result = await task.ToPromise(); } catch (exception) { result = exception.hostException.InnerException.InnerException.Message; } })()");
            replacedert.AreEqual(message, engine.Script.result);
        }

19 View Source File : ExtensionsTest.cs
License : MIT License
Project Creator : microsoft

[TestMethod, TestCategory("Extensions")]
        public void Extensions_JavaScript_ToPromise_NoResult_Faulted()
        {
            const string message = "No task for you!";
            var task = Task.FromException(new UnauthorizedAccessException(message));

            engine.Script.promise = task.ToPromise(engine);
            engine.Execute("(async function () { try { result = await promise; } catch (exception) { result = exception.hostException.InnerException.InnerException.Message; } })()");
            replacedert.AreEqual(message, engine.Script.result);

            engine.Script.task = task;
            engine.Execute("(async function () { try { result = await task.ToPromise(); } catch (exception) { result = exception.hostException.InnerException.InnerException.Message; } })()");
            replacedert.AreEqual(message, engine.Script.result);
        }

See More Examples