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 : MemoryDatabase.cs
License : MIT License
Project Creator : Azure

public Task DeleteAsync(string id, CancellationToken ct,
                OperationOptions options, string etag) {
                if (string.IsNullOrEmpty(id)) {
                    throw new ArgumentNullException(nameof(id));
                }
                lock (_data) {
                    if (!_data.TryGetValue(id, out var doc)) {
                        return Task.FromException(
                            new ResourceNotFoundException(id));
                    }
                    if (!string.IsNullOrEmpty(etag) && etag != doc.Etag) {
                        return Task.FromException<dynamic>(
                            new ResourceOutOfDateException(etag));
                    }
                    _data.Remove(id);
                    return Task.CompletedTask;
                }
            }

19 View Source File : ClientSession.cs
License : MIT License
Project Creator : Azure

public Task<bool> WaitForNewlyEnqueuedOperationAsync(int timeout) {
            while (!_cts.IsCancellationRequested) {
                var tcs = _enqueueEvent;
                // Wait on a fresh task or on the not yet completed on
                if (tcs.Task.IsCompleted) {
                    var newEvent = new TaskCompletionSource<bool>(
                        TaskCreationOptions.RunContinuationsAsynchronously);
                    if (Interlocked.CompareExchange(ref _enqueueEvent, newEvent, tcs) == tcs) {
                        // Exchanged safely now we can wait for it.
                        tcs = newEvent;
                    }
                }
                return Task.WhenAny(tcs.Task, Task.Delay(timeout, _cts.Token))
                    .ContinueWith(t => t.Result == tcs.Task);
            }
            return Task.FromException<bool>(new TaskCanceledException());
        }

19 View Source File : Plugin.Schedule.cs
License : MIT License
Project Creator : AlternateLife

internal Task<T> Schedule<T>(Func<T> action, bool forceSchedule = false)
        {
            if (forceSchedule == false && IsInMainThread())
            {
                try
                {
                    return Task.FromResult(action());
                }
                catch (Exception e)
                {
                    return Task.FromException<T>(e);
                }
            }

            return Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _taskScheduler);
        }

19 View Source File : FunctionExecutionHelper.cs
License : MIT License
Project Creator : Azure

public static async Task<WrappedFunctionResult> ExecuteFunctionInOrchestrationMiddleware(
            ITriggeredFunctionExecutor executor,
            TriggeredFunctionData triggerInput,
            DurableCommonContext context,
            CancellationToken cancellationToken)
        {
#pragma warning disable CS0618 // InvokeHandler approved for use by this extension
            if (triggerInput.InvokeHandler == null)
            {
                throw new ArgumentException(
                    $"{nameof(ExecuteFunctionInOrchestrationMiddleware)} should only be used when ${nameof(triggerInput)} has a value for ${nameof(TriggeredFunctionData.InvokeHandler)}");
            }

            try
            {
                context.ExecutorCalledBack = false;

                FunctionResult result = await executor.TryExecuteAsync(triggerInput, cancellationToken);

                if (context.ExecutorCalledBack)
                {
                    if (result.Succeeded)
                    {
                        return WrappedFunctionResult.Success();
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return WrappedFunctionResult.FunctionRuntimeFailure(result.Exception);
                    }

                    return WrappedFunctionResult.UserCodeFailure(result.Exception);
                }
                else
                {
                    // This can happen if the constructor for a non-static function fails.
                    // We want to treat this case exactly as if the function itself is throwing the exception.
                    // So we execute the middleware directly, instead of via the executor.
                    try
                    {
                        var exception = result.Exception ?? new InvalidOperationException("The function failed to start executing.");

                        await triggerInput.InvokeHandler(() => Task.FromException<object>(exception));

                        return WrappedFunctionResult.Success();
                    }
                    catch (Exception e) when (!cancellationToken.IsCancellationRequested)
                    {
                        return WrappedFunctionResult.UserCodeFailure(e);
                    }
                }
#pragma warning restore CS0618
            }
            catch (Exception e)
            {
                return WrappedFunctionResult.FunctionRuntimeFailure(e);
            }
        }

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldPreplacedLastKnownContinuationTokenToSynchronizer_IfParreplacedionSplitHappened()
        {
            //arrange
            DoreplacedentServiceLease lease = Mock.Of<DoreplacedentServiceLease>(l => l.CurrentLeaseToken == ParreplacedionId && l.ContinuationToken == InitialContinuationToken);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(It.Is<DoreplacedentServiceLease>(l => l.CurrentLeaseToken == ParreplacedionId && l.ContinuationToken == LastContinuationToken)))
                .ReturnsAsync((new[] { this.CreateMockLease(), this.CreateMockLease() }, true));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f => f.Create(lease) == parreplacedionSupervisor);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager => manager.AcquireAsync(lease) == Task.FromResult(lease));
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, Mock.Of<ChangeFeedProcessorHealthMonitor>());

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(synchronizer).VerifyAll();
        }

19 View Source File : Control.cs
License : Apache License 2.0
Project Creator : akkadotnet

public Task Stop() => Task.FromException(Exception);

19 View Source File : SettingsRouter.cs
License : MIT License
Project Creator : Azure

public Task ApplyInternalAsync() {
                try {
                    if (_applyMethod == null) {
                        return Task.CompletedTask;
                    }
                    return (Task)_applyMethod.Invoke(Target, new object[] { });
                }
                catch (Exception e) {
                    return Task.FromException(e);
                }
            }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<List<IBlockIndex>> GetReversedBlockIndexes(Hash lastBlockHash, int count)
        {
            return await Task.FromException<List<IBlockIndex>>(new System.NotImplementedException());
        }

19 View Source File : ControllerTestClient.cs
License : MIT License
Project Creator : Azure

public Task<ValueWriteResponseApiModel> NodeValueWriteAsync(string endpointId,
            ValueWriteRequestApiModel content, CancellationToken ct) {
            return Task.FromException<ValueWriteResponseApiModel>(new NotImplementedException());
        }

19 View Source File : RetryActionTest.cs
License : Apache License 2.0
Project Creator : agoda-com

[Test]
        public async Task ExecuteAsync_Retry_And_Success()
        {
            var failUntilCount = 3;
            var mgr = new RetryAction<string>(() => "foo", UpdateWeight);

            var result = await mgr.ExecuteAsync(
                (str, attemptCount) =>
                {
                    if (attemptCount < failUntilCount)
                    {
                        return Task.FromException<int>(new InvalidOperationException());
                    }

                    return Task.FromResult(attemptCount);
                }, (attempt, exception) =>
                {
                    replacedert.LessOrEqual(attempt, failUntilCount);
                    replacedert.IsInstanceOf<InvalidOperationException>(exception);

                    return true;
                });

            replacedert.AreEqual(failUntilCount, result);

            replacedert.AreEqual(failUntilCount, _updateWeightSequence.Count);
            replacedert.IsFalse(_updateWeightSequence[0]);
            replacedert.IsFalse(_updateWeightSequence[1]);
            replacedert.IsTrue(_updateWeightSequence[2]);
        }

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldDeleteParentLease_IfChildLeaseAcquireThrows()
        {
            //arrange
            DoreplacedentServiceLease lease = this.CreateMockLease(ParreplacedionId);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            DoreplacedentServiceLease leaseChild2 = this.CreateMockLease();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(lease))
                .ReturnsAsync((new[] { this.CreateMockLease(), leaseChild2 }, true));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f => f.Create(lease) == parreplacedionSupervisor);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager =>
                manager.AcquireAsync(lease) == Task.FromResult(lease) &&
                manager.AcquireAsync(leaseChild2) == Task.FromException<DoreplacedentServiceLease>(new LeaseLostException())
                );
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            Mock<ChangeFeedProcessorHealthMonitor> monitor = new Mock<ChangeFeedProcessorHealthMonitor>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, monitor.Object);

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(leaseManager).Verify(manager => manager.DeleteAsync(lease), Times.Once);

            monitor.Verify(m => m.NotifyLeaseAcquireAsync(lease.CurrentLeaseToken), Times.Once);
            monitor.Verify(m => m.NotifyLeaseReleaseAsync(lease.CurrentLeaseToken), Times.Once);
        }

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldKeepParentLease_IfSplitThrows()
        {
            //arrange
            DoreplacedentServiceLease lease = this.CreateMockLease(ParreplacedionId);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>(s => s.HandleParreplacedionGoneAsync(lease) == Task.FromException<(IEnumerable<DoreplacedentServiceLease>,bool)>(new InvalidOperationException()));
            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f => f.Create(lease) == parreplacedionSupervisor);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>();
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, Mock.Of<ChangeFeedProcessorHealthMonitor>());

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(leaseManager).Verify(manager => manager.DeleteAsync(lease), Times.Never);
        }

19 View Source File : QueueDrainHelperTest.cs
License : Apache License 2.0
Project Creator : akarnokd

[Fact]
        public void DisposeCrash()
        {
            var task = Task.FromException(new InvalidOperationException());
            _disposeWip = 1;
            
            QueueDrainHelper.DisposeHandler(task, ref _disposeWip, ref _disposeError, _disposeTask);
            
            replacedert.Equal(0, _disposeWip);
            replacedert.Null(_disposeError);
            
            replacedert.True(_disposeTask.Task.IsFaulted);
            
            replacedert.True(_disposeTask.Task.Exception.InnerExceptions[0] is InvalidOperationException);
        }

19 View Source File : SettingsRouterTests.cs
License : MIT License
Project Creator : Azure

public Task ThrowAsync() {
                return Task.FromException(new Exception());
            }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<BlockHeader> GetBlockHeaderByHashAsync(Hash blockId)
        {
            return await Task.FromException<BlockHeader>(new System.NotImplementedException());
        }

19 View Source File : MemoryDatabase.cs
License : MIT License
Project Creator : Azure

public Task<IDoreplacedentInfo<T>> UpsertAsync<T>(T newItem, CancellationToken ct,
                string id, OperationOptions options, string etag) {
                var item = _outer._serializer.FromObject(newItem);
                var newDoc = new Doreplacedent<T>(id, item, options?.ParreplacedionKey);
                lock (_data) {
                    if (_data.TryGetValue(newDoc.Id, out var doc)) {
                        if (!string.IsNullOrEmpty(etag) && doc.Etag != etag) {
                            return Task.FromException<IDoreplacedentInfo<T>>(
                                new ResourceOutOfDateException(etag));
                        }
                        _data.Remove(newDoc.Id);
                    }

                    AddDoreplacedent(newDoc);
                    return Task.FromResult<IDoreplacedentInfo<T>>(newDoc);
                }
            }

19 View Source File : Command.cs
License : MIT License
Project Creator : allisterb

public virtual Task Run()
        {
            try
            {
                shell = new MeSh.Shell(o => o.WorkingDirectory(WorkingDirectory));
                meshCommand = shell.Run(Text, CommandOptions.ToArray());
                return Task = meshCommand.Task;
            }
            catch (Exception e)
            {
                Exception = e;
                L.Error(e, "An exception was thrown attempting to execute command {0}.", Text);
                _Success = false;
                return Task = Task.FromException(e);
            }    
        }

19 View Source File : MonitoredItemMessageEncoder.cs
License : MIT License
Project Creator : Azure

public Task<IEnumerable<NetworkMessageModel>> EncodeAsync(
            IEnumerable<DataSetMessageModel> messages, int maxMessageSize) {
            try {
                var resultJson = EncodeAsJson(messages, maxMessageSize);
                var resultUadp = EncodeAsUadp(messages, maxMessageSize);
                var result = resultJson.Concat(resultUadp);
                return Task.FromResult(result);
            }
            catch (Exception e) {
                return Task.FromException<IEnumerable<NetworkMessageModel>>(e);
            }
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<Chain> CreateChainAsync(Block block, IEnumerable<Transaction> transactions)
        {
            return await Task.FromException<Chain>(new System.NotImplementedException());
        }

19 View Source File : ControllerTestClient.cs
License : MIT License
Project Creator : Azure

public Task<WriteResponseApiModel> NodeWriteAsync(string endpointId,
            WriteRequestApiModel content, CancellationToken ct) {
            return Task.FromException<WriteResponseApiModel>(new NotImplementedException());
        }

19 View Source File : ExampleHealthCheckService.cs
License : MIT License
Project Creator : ARKlab

public Task CheckHealthAsync(
            CancellationToken cancellationToken = default)
        {
            var healthCheckResultHealthy = true;

            if (healthCheckResultHealthy)
            {
                return Task.CompletedTask;
            }

            return Task.FromException(new Exception("Failed"));
        }

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldSignalSynchronizerSplitParreplacedion_IfParreplacedionSplitHappened()
        {
            //arrange
            DoreplacedentServiceLease lease = this.CreateMockLease(ParreplacedionId);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(lease))
                .ReturnsAsync((new[] { this.CreateMockLease(), this.CreateMockLease() }, true));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f => f.Create(lease) == parreplacedionSupervisor);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager => manager.AcquireAsync(lease) == Task.FromResult(lease));
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, Mock.Of<ChangeFeedProcessorHealthMonitor>());

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(synchronizer).VerifyAll();
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task AddBlockAsync(Block block)
        {
            await Task.FromException(new System.NotImplementedException());
        }

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldCopyParentLeaseProperties_IfParreplacedionSplitHappened()
        {
            //arrange
            Dictionary<string, string> customProperties = new Dictionary<string, string> { { "key", "value" } };
            DoreplacedentServiceLease lease = Mock.Of<DoreplacedentServiceLease>(l => l.CurrentLeaseToken == ParreplacedionId && l.Properties == customProperties);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            DoreplacedentServiceLease leaseChild1 = this.CreateMockLease();
            DoreplacedentServiceLease leaseChild2 = this.CreateMockLease();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(It.Is<DoreplacedentServiceLease>(l => l.CurrentLeaseToken == ParreplacedionId && l.ContinuationToken == LastContinuationToken)))
                .ReturnsAsync((new[] { leaseChild1, leaseChild2 }, true));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f => f.Create(lease) == parreplacedionSupervisor);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager => manager.AcquireAsync(lease) == Task.FromResult(lease));
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, Mock.Of<ChangeFeedProcessorHealthMonitor>());

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            await sut.ShutdownAsync().ConfigureAwait(false);
            Mock.Get(leaseChild1)
                    .VerifySet(l => l.Properties = customProperties, Times.Once);
            Mock.Get(leaseChild2)
                .VerifySet(l => l.Properties = customProperties, Times.Once);
        }

19 View Source File : InteractionPaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public Task<PaginationEmojis> GetEmojisAsync()
            => Task.FromException<PaginationEmojis>(new NotSupportedException("Emojis aren't supported for this request."));

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldIgnoreProcessingChildParreplacedion_IfParreplacedionAlreadyAdded()
        {
            //arrange
            DoreplacedentServiceLease lease = this.CreateMockLease(ParreplacedionId);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            DoreplacedentServiceLease leaseChild1 = this.CreateMockLease();
            DoreplacedentServiceLease leaseChild2 = this.CreateMockLease();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(It.Is<DoreplacedentServiceLease>(l => l.CurrentLeaseToken == ParreplacedionId && l.ContinuationToken == LastContinuationToken)))
                .ReturnsAsync((new[] { leaseChild1, leaseChild2 }, true));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisor parreplacedionSupervisor1 = Mock.Of<ParreplacedionSupervisor>();
            Mock.Get(parreplacedionSupervisor1).Setup(o => o.RunAsync(It.IsAny<CancellationToken>())).Returns<CancellationToken>(token => Task.Delay(TimeSpan.FromHours(1), token));
            ParreplacedionSupervisor parreplacedionSupervisor2 = Mock.Of<ParreplacedionSupervisor>();
            Mock.Get(parreplacedionSupervisor2).Setup(o => o.RunAsync(It.IsAny<CancellationToken>())).Returns<CancellationToken>(token => Task.Delay(TimeSpan.FromHours(1), token));

            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f =>
                f.Create(lease) == parreplacedionSupervisor && f.Create(leaseChild1) == parreplacedionSupervisor1 && f.Create(leaseChild2) == parreplacedionSupervisor2);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager => manager.AcquireAsync(lease) == Task.FromResult(lease));
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, Mock.Of<ChangeFeedProcessorHealthMonitor>());

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);
            await sut.AddOrUpdateLeaseAsync(leaseChild2).ConfigureAwait(false);
            await sut.AddOrUpdateLeaseAsync(leaseChild2).ConfigureAwait(false);
            await sut.AddOrUpdateLeaseAsync(leaseChild2).ConfigureAwait(false);
            await sut.AddOrUpdateLeaseAsync(leaseChild2).ConfigureAwait(false);
            await sut.AddOrUpdateLeaseAsync(leaseChild2).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(leaseManager)
                .Verify(manager => manager.AcquireAsync(leaseChild2), Times.Once);

            Mock.Get(leaseManager)
                .Verify(manager => manager.UpdatePropertiesAsync(leaseChild2), Times.Exactly(5));

            Mock.Get(parreplacedionSupervisorFactory)
                .Verify(f => f.Create(leaseChild2), Times.Once);
        }

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldRunProcessingOnChildParreplacedions_IfHappyPath()
        {
            //arrange
            DoreplacedentServiceLease lease = this.CreateMockLease(ParreplacedionId);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            DoreplacedentServiceLease leaseChild1 = this.CreateMockLease();
            DoreplacedentServiceLease leaseChild2 = this.CreateMockLease();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(It.Is<DoreplacedentServiceLease>(l => l.CurrentLeaseToken == ParreplacedionId && l.ContinuationToken == LastContinuationToken)))
                .ReturnsAsync((new[] { leaseChild1, leaseChild2 }, true));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisor parreplacedionSupervisor1 = Mock.Of<ParreplacedionSupervisor>();
            Mock.Get(parreplacedionSupervisor1).Setup(o => o.RunAsync(It.IsAny<CancellationToken>())).Returns<CancellationToken>(token => Task.Delay(TimeSpan.FromHours(1), token));
            ParreplacedionSupervisor parreplacedionSupervisor2 = Mock.Of<ParreplacedionSupervisor>();
            Mock.Get(parreplacedionSupervisor2).Setup(o => o.RunAsync(It.IsAny<CancellationToken>())).Returns<CancellationToken>(token => Task.Delay(TimeSpan.FromHours(1), token));

            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f =>
                f.Create(lease) == parreplacedionSupervisor && f.Create(leaseChild1) == parreplacedionSupervisor1 && f.Create(leaseChild2) == parreplacedionSupervisor2);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager => manager.AcquireAsync(lease) == Task.FromResult(lease));
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            Mock<ChangeFeedProcessorHealthMonitor> monitor = new Mock<ChangeFeedProcessorHealthMonitor>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, monitor.Object);

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(leaseManager).Verify(manager => manager.AcquireAsync(leaseChild1), Times.Once);
            Mock.Get(leaseManager).Verify(manager => manager.AcquireAsync(leaseChild2), Times.Once);

            Mock.Get(parreplacedionSupervisorFactory).Verify(f => f.Create(leaseChild1), Times.Once);
            Mock.Get(parreplacedionSupervisorFactory).Verify(f => f.Create(leaseChild2), Times.Once);

            Mock.Get(parreplacedionSupervisor1).Verify(p => p.RunAsync(It.IsAny<CancellationToken>()), Times.Once);
            Mock.Get(parreplacedionSupervisor2).Verify(p => p.RunAsync(It.IsAny<CancellationToken>()), Times.Once);

            monitor.Verify(m => m.NotifyLeaseAcquireAsync(leaseChild1.CurrentLeaseToken), Times.Once);
            monitor.Verify(m => m.NotifyLeaseReleaseAsync(leaseChild2.CurrentLeaseToken), Times.Once);
        }

19 View Source File : Error.cs
License : Apache License 2.0
Project Creator : akarnokd

public ValueTask<bool> MoveNextAsync()
            {
                if (_once)
                {
                    return new ValueTask<bool>(false);
                }
                _once = true;
                return new ValueTask<bool>(Task.FromException<bool>(_error));
            }

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldDeleteParentLease_IfChildLeasesCreatedByAnotherHost()
        {
            //arrange
            DoreplacedentServiceLease lease = this.CreateMockLease(ParreplacedionId);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(lease))
                .ReturnsAsync((new DoreplacedentServiceLease[] { }, true));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));
            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f => f.Create(lease) == parreplacedionSupervisor);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager =>
                manager.AcquireAsync(lease) == Task.FromResult(lease)
            );
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, Mock.Of<ChangeFeedProcessorHealthMonitor>());

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(leaseManager).Verify(manager => manager.DeleteAsync(lease), Times.Once);
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<Block> GetBlockByHashAsync(Hash blockId)
        {
            return await Task.FromException<Block>(new System.NotImplementedException());
        }

19 View Source File : MethodHandlerAdapter.cs
License : MIT License
Project Creator : Azure

public Task<byte[]> InvokeAsync(string method, byte[] payload,
            string contentType) {
            if (_calltable.TryGetValue(method, out var invoker)) {
                return invoker.InvokeAsync(payload, contentType, this);
            }
            return Task.FromException<byte[]>(
                new InvalidOperationException($"{method} invoker not registered"));
        }

19 View Source File : TakeUntil.cs
License : Apache License 2.0
Project Creator : akarnokd

public ValueTask<bool> MoveNextAsync()
            {
                for (; ; )
                {
                    var task = Volatile.Read(ref _currentTask);
                    if (task == TakeUntilHelper.UntilTask)
                    {
                        if (_otherError != null)
                        {
                            return new ValueTask<bool>(Task.FromException<bool>(_otherError));
                        }
                        return new ValueTask<bool>(false);
                    }
                    var newTask = new TaskCompletionSource<bool>();
                    if (Interlocked.CompareExchange(ref _currentTask, newTask, task) == task)
                    {
                        if (Interlocked.Increment(ref _disposeMain) == 1)
                        {
                            _source.MoveNextAsync().AsTask()
                                .ContinueWith(t => HandleMain(t, newTask));
                            return new ValueTask<bool>(newTask.Task);
                        }
                    }
                }
            }

19 View Source File : MemoryDatabase.cs
License : MIT License
Project Creator : Azure

public Task<IDoreplacedentInfo<T>> AddAsync<T>(T newItem,
                CancellationToken ct, string id, OperationOptions options) {
                var item = _outer._serializer.FromObject(newItem);
                var newDoc = new Doreplacedent<T>(id, item, options?.ParreplacedionKey);
                lock (_data) {
                    if (_data.TryGetValue(newDoc.Id, out var existing)) {
                        return Task.FromException<IDoreplacedentInfo<T>>(
                            new ConflictingResourceException(newDoc.Id));
                    }
                    AddDoreplacedent(newDoc);
                    return Task.FromResult<IDoreplacedentInfo<T>>(newDoc);
                }
            }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task SetBestChainAsync(Chain chain, long bestChainHeight, Hash bestChainHash)
        {
            await Task.FromException(new System.NotImplementedException());
        }

19 View Source File : MemoryDatabase.cs
License : MIT License
Project Creator : Azure

public Task<IDoreplacedentInfo<T>> ReplaceAsync<T>(IDoreplacedentInfo<T> existing, T value,
                CancellationToken ct, OperationOptions options) {
                if (existing == null) {
                    throw new ArgumentNullException(nameof(existing));
                }
                var item = _outer._serializer.FromObject(value);
                var newDoc = new Doreplacedent<T>(existing.Id, item, existing.ParreplacedionKey);
                lock (_data) {
                    if (_data.TryGetValue(newDoc.Id, out var doc)) {
                        if (!string.IsNullOrEmpty(existing.Etag) && doc.Etag != existing.Etag) {
                            return Task.FromException<IDoreplacedentInfo<T>>(
                                new ResourceOutOfDateException(existing.Etag));
                        }
                        _data.Remove(newDoc.Id);
                    }
                    else {
                        return Task.FromException<IDoreplacedentInfo<T>>(
                            new ResourceNotFoundException(newDoc.Id));
                    }
                    AddDoreplacedent(newDoc);
                    return Task.FromResult<IDoreplacedentInfo<T>>(newDoc);
                }
            }

19 View Source File : Control.cs
License : Apache License 2.0
Project Creator : akkadotnet

public Task Shutdown() => Task.FromException(Exception);

19 View Source File : MethodRouter.cs
License : MIT License
Project Creator : Azure

public Task<byte[]> InvokeAsync(byte[] payload, string contentType,
                IMethodHandler handler) {
                object task;
                try {
                    object[] inputs;
                    if (_methodParams.Length == 0) {
                        inputs = new object[0];
                    }
                    else if (_methodParams.Length == 1) {
                        var data = _serializer.Deserialize(payload, _methodParams[0].ParameterType);
                        inputs = new[] { data };
                    }
                    else {
                        var data = _serializer.Parse(payload);
                        inputs = _methodParams.Select(param => {
                            if (data.TryGetProperty(param.Name,
                                out var value, StringComparison.InvariantCultureIgnoreCase)) {
                                return value.ConvertTo(param.ParameterType);
                            }
                            return param.HasDefaultValue ? param.DefaultValue : null;
                        }).ToArray();
                    }
                    task = _controllerMethod.Invoke(_controller, inputs);
                }
                catch (Exception e) {
                    task = Task.FromException(e);
                }
                if (_methodTaskContinuation == null) {
                    return VoidContinuation((Task)task);
                }
                return (Task<byte[]>)_methodTaskContinuation.Invoke(this, new[] {
                    task
                });
            }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<Chain> GetChainAsync()
        {
            return await Task.FromException<Chain>(new System.NotImplementedException());
        }

19 View Source File : MethodRouterTests.cs
License : MIT License
Project Creator : Azure

public Task<byte[]> Test2Async(byte[] request) {
                if (request == null) {
                    throw new ArgumentNullException(nameof(request));
                }
                return Task.FromException<byte[]>(
                    new ArgumentNullException(nameof(request)));
            }

19 View Source File : Plugin.Schedule.cs
License : MIT License
Project Creator : AlternateLife

internal Task Schedule(Action action, bool forceSchedule = false)
        {
            if (forceSchedule == false && IsInMainThread())
            {
                try
                {
                    action();

                    return Task.CompletedTask;
                }
                catch (Exception e)
                {
                    return Task.FromException(e);
                }
            }

            return Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _taskScheduler);
        }

19 View Source File : MonitoredItemMessageEncoder.cs
License : MIT License
Project Creator : Azure

public Task<IEnumerable<NetworkMessageModel>> EncodeBatchAsync(
            IEnumerable<DataSetMessageModel> messages, int maxMessageSize) {
            try {
                var resultJson = EncodeBatchAsJson(messages, maxMessageSize);
                var resultUadp = EncodeBatchAsUadp(messages, maxMessageSize);
                var result = resultJson.Concat(resultUadp);
                return Task.FromResult(result);
            }
            catch (Exception e) {
                return Task.FromException<IEnumerable<NetworkMessageModel>>(e);
            }
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<Hash> GetBlockHashByHeightAsync(Chain chain, long height, Hash chainBranchBlockHash)
        {
            return await Task.FromException<Hash>(new System.NotImplementedException());
        }

19 View Source File : ControllerTestClient.cs
License : MIT License
Project Creator : Azure

public Task<ReadResponseApiModel> NodeReadAsync(string endpointId,
            ReadRequestApiModel content, CancellationToken ct) {
            return Task.FromException<ReadResponseApiModel>(new NotImplementedException());
        }

19 View Source File : ConfigurationValidationLocation.cs
License : MIT License
Project Creator : arcus-azure

public Task<string> GetExpectedCertificateValueForConfiguredKeyAsync(string configurationKey, IServiceProvider services)
        {
            try
            {
                Guard.NotNullOrWhitespace(configurationKey, nameof(configurationKey), "Configured key cannot be blank");
                Guard.NotNull(services, nameof(services), "Registered services cannot be 'null'");

                var configuration = services.GetService<IConfiguration>();
                if (configuration == null)
                {
                    throw new KeyNotFoundException(
                        $"No configured {nameof(IConfiguration)} implementation found in the request service container. "
                        + "Please configure such an implementation (ex. in the Startup) of your application");
                }

                string value = configuration[configurationKey];
                return Task.FromResult(value);
            }
            catch (Exception ex)
            {
                return Task.FromException<string>(ex);
            }
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<List<Hash>> GetBlockHashesAsync(Chain chain, Hash firstHash, int count, Hash chainBranchBlockHash = null)
        {
            return await Task.FromException<List<Hash>>(new System.NotImplementedException());
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task SetIrreversibleBlockAsync(Chain chain, long irreversibleBlockHeight, Hash irreversibleBlockHash)
        {
            await Task.FromException(new System.NotImplementedException());
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<BlockAttachOperationStatus> AttachBlockToChainAsync(Chain chain, Block block)
        {
            return await Task.FromException<BlockAttachOperationStatus>(new System.NotImplementedException());
        }

19 View Source File : MockBlockchainService.cs
License : MIT License
Project Creator : AElfProject

public async Task<bool> HasBlockAsync(Hash blockId)
        {
            return await Task.FromException<bool>(new System.NotImplementedException());
        }

19 View Source File : ButtonPaginationRequest.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public Task<PaginationEmojis> GetEmojisAsync() => Task.FromException<PaginationEmojis>(new NotSupportedException("Emojis aren't supported for this request."));

19 View Source File : PartitionControllerSplitTests.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public async Task Controller_ShouldRunNotDeleteLease()
        {
            //arrange
            DoreplacedentServiceLease lease = this.CreateMockLease(ParreplacedionId);
            ParreplacedionSynchronizer synchronizer = Mock.Of<ParreplacedionSynchronizer>();
            Mock.Get(synchronizer)
                .Setup(s => s.HandleParreplacedionGoneAsync(It.Is<DoreplacedentServiceLease>(l => l.CurrentLeaseToken == ParreplacedionId && l.ContinuationToken == LastContinuationToken)))
                .ReturnsAsync((new[] { lease }, false));

            ParreplacedionSupervisor parreplacedionSupervisor = Mock.Of<ParreplacedionSupervisor>(o => o.RunAsync(It.IsAny<CancellationToken>()) == Task.FromException(new FeedRangeGoneException("message", LastContinuationToken)));

            ParreplacedionSupervisorFactory parreplacedionSupervisorFactory = Mock.Of<ParreplacedionSupervisorFactory>(f =>
                f.Create(lease) == parreplacedionSupervisor);
            DoreplacedentServiceLeaseManager leaseManager = Mock.Of<DoreplacedentServiceLeaseManager>(manager => manager.AcquireAsync(lease) == Task.FromResult(lease));
            DoreplacedentServiceLeaseContainer leaseContainer = Mock.Of<DoreplacedentServiceLeaseContainer>();

            ParreplacedionControllerCore sut = new ParreplacedionControllerCore(leaseContainer, leaseManager, parreplacedionSupervisorFactory, synchronizer, Mock.Of<ChangeFeedProcessorHealthMonitor>());

            await sut.InitializeAsync().ConfigureAwait(false);

            //act
            await sut.AddOrUpdateLeaseAsync(lease).ConfigureAwait(false);

            //replacedert
            await sut.ShutdownAsync().ConfigureAwait(false);

            Mock.Get(leaseManager).Verify(manager => manager.DeleteAsync(lease), Times.Never);
        }

See More Examples