System.Threading.Tasks.Task.FromResult(bool)

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

2835 Examples 7

19 View Source File : NavigationProxy.cs
License : MIT License
Project Creator : adamped

public Task ClearAsync()
        {
            _page = new NavigationPage();
            return Task.FromResult(true);
        }

19 View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver

public Task<bool> UpdateBlogAsync(BlogDTO objBlogs, IEnumerable<String> BlogCategories)
        {
            try
            {
                var ExistingBlogs =
                    _context.Blogs
                    .Include(x => x.BlogCategory)
                    .Where(x => x.BlogId == objBlogs.BlogId)
                    .FirstOrDefault();

                if (ExistingBlogs != null)
                {
                    ExistingBlogs.BlogDate =
                        objBlogs.BlogDate;

                    ExistingBlogs.Blogreplacedle =
                        objBlogs.Blogreplacedle;

                    ExistingBlogs.BlogSummary =
                        objBlogs.BlogSummary;

                    ExistingBlogs.BlogContent =
                        objBlogs.BlogContent;

                    if (BlogCategories == null)
                    {
                        ExistingBlogs.BlogCategory = null;
                    }
                    else
                    {
                        ExistingBlogs.BlogCategory =
                            GetSelectedBlogCategories(objBlogs, BlogCategories);
                    }

                    _context.SaveChanges();
                }
                else
                {
                    return Task.FromResult(false);
                }

                return Task.FromResult(true);
            }
            catch
            {
                DetachAllEnreplacedies();
                throw;
            }
        }

19 View Source File : RecordFSReaderBase.cs
License : Apache License 2.0
Project Creator : acblog

public override Task<bool> Delete(TId id, CancellationToken cancellationToken = default) => Task.FromResult(false);

19 View Source File : KeyFieldDeclarationFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public override Task RegisterCodeFixesAsync(CodeFixContext context)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var diagnostic = context.Diagnostics.FirstOrDefault(d => d.Id == Descriptors.PX1055_DacKeyFieldsWithIdenreplacedyKeyField.Id);

			if (diagnostic == null)
				return Task.FromResult(false);

			Doreplacedent doreplacedent = context.Doreplacedent;

			string codeActionIdenreplacedyKeyName = nameof(Resources.PX1055FixEditKeyFieldAttributes).GetLocalized().ToString();
			CodeAction codeActionIdenreplacedyKey = CodeAction.Create(codeActionIdenreplacedyKeyName,
																cToken => RemoveKeysFromFieldsAsync(doreplacedent,
																									cToken,
																									diagnostic,
																									CodeFixModes.EditKeyFieldAttributes),
																equivalenceKey: codeActionIdenreplacedyKeyName);

			string codeActionBoundKeysName = nameof(Resources.PX1055FixEditIdenreplacedyAttribute).GetLocalized().ToString();
			CodeAction codeActionBoundKeys = CodeAction.Create(codeActionBoundKeysName,
																cToken => RemoveKeysFromFieldsAsync(doreplacedent,
																									cToken,
																									diagnostic,
																									CodeFixModes.EditIdenreplacedyAttribute),
																equivalenceKey: codeActionBoundKeysName);

			string codeActionRemoveIdenreplacedyColumnName = nameof(Resources.PX1055FixRemoveIdenreplacedyAttribute).GetLocalized().ToString();
			CodeAction codeActionRemoveIdenreplacedyColumn = CodeAction.Create(codeActionRemoveIdenreplacedyColumnName,
																			cToken => RemoveKeysFromFieldsAsync(doreplacedent,
																												cToken,
																												diagnostic,
																												CodeFixModes.RemoveIdenreplacedyAttribute),
																			equivalenceKey: codeActionRemoveIdenreplacedyColumnName);

			context.RegisterCodeFix(codeActionIdenreplacedyKey, context.Diagnostics);
			context.RegisterCodeFix(codeActionBoundKeys, context.Diagnostics);
			context.RegisterCodeFix(codeActionRemoveIdenreplacedyColumn, context.Diagnostics);

			return Task.FromResult(true);
		}

19 View Source File : RecordFSRepo.cs
License : Apache License 2.0
Project Creator : acblog

public override Task<bool> Exists(string id, CancellationToken cancellationToken = default)
        {
            return Task.FromResult(System.IO.File.Exists(GetPath(id)));
        }

19 View Source File : DocumentProtector.cs
License : Apache License 2.0
Project Creator : acblog

public Task<bool> IsProtected(Doreplacedent value, CancellationToken cancellationToken = default)
        {
            return Task.FromResult(value.Tag == _protectFlag);
        }

19 View Source File : FileAppender.cs
License : MIT License
Project Creator : adams85

public Task<bool> EnsureDirAsync(IFileInfo fileInfo, CancellationToken cancellationToken = default)
        {
            var dirPath = Path.GetDirectoryName(fileInfo.PhysicalPath);
            if (Directory.Exists(dirPath))
                return Task.FromResult(false);

            Directory.CreateDirectory(dirPath);
            return Task.FromResult(true);
        }

19 View Source File : DynamicProxyAttribute.cs
License : MIT License
Project Creator : 2881099

public virtual Task Before(DynamicProxyBeforeArguments args) => Task.FromResult(false);

19 View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver

public Task<bool> UpdateCategoryAsync(CategoryDTO objCategoryDTO)
        {
            try
            {
                int intCategoryId = Convert.ToInt32(objCategoryDTO.CategoryId);

                var ExistingCategory =
                    _context.Categorys
                    .Where(x => x.CategoryId == intCategoryId)
                    .FirstOrDefault();

                if (ExistingCategory != null)
                {
                    ExistingCategory.replacedle =
                        objCategoryDTO.replacedle;

                    ExistingCategory.Description =
                        objCategoryDTO.Description;

                    _context.SaveChanges();
                }
                else
                {
                    return Task.FromResult(false);
                }

                return Task.FromResult(true);
            }
            catch
            {
                DetachAllEnreplacedies();
                throw;
            }
        }

19 View Source File : BaseHub.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

protected async Task<bool> DoCommand(Func<Task> func)
        {
            //踢出自己
            var connectionId = await _mudOnlineProvider.GetConnectionId(_account.PlayerId);
            if (string.IsNullOrEmpty(connectionId))
            {
                await KickOut(Context.ConnectionId);
                await ShowSystemMessage(Context.ConnectionId, "你已经断线,请刷新或重新登录");
                Context.Abort();
                return await Task.FromResult(false);
            }

            if (connectionId != Context.ConnectionId)
            {
                await KickOut(Context.ConnectionId);
                await ShowSystemMessage(Context.ConnectionId, "你已经断线,请刷新或重新登录");
                Context.Abort();
                return await Task.FromResult(false);
            }

            await func?.Invoke();


            if (!IsValidOperation())
            {
                foreach (var notification in _notifications.GetNotifications())
                {
                    await ShowSystemMessage(Context.ConnectionId, notification.Content);
                }
                return await Task.FromResult(false);
            }
            return await Task.FromResult(true);
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnce()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    Ephemeral = true
                };

                var message = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);

                var runOnceJobCompleted = new TaskCompletionSource<bool>();
                _jobDispatcher.Setup(x => x.RunOnceJobCompleted)
                    .Returns(runOnceJobCompleted);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {
                        runOnceJobCompleted.TrySetResult(true);
                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job and exit
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);

                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
                     $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());

                // verify that we did try to delete local settings file (since we're ephemeral)
                _configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Once());
            }
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        //process 2 new job messages, and one cancel message
        public async void TestRunAsync()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242
                };

                var message = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message);
                var signalWorkerComplete = new SemapreplacedSlim(0, 1);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                signalWorkerComplete.Release();
                                await Task.Delay(2000, hc.RunnerShutdownToken);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {

                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job
                if (!await signalWorkerComplete.WaitAsync(2000))
                {
                    replacedert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked.");
                }
                else
                {
                    //Act
                    hc.ShutdownRunner(ShutdownReason.UserCancelled); //stop Runner

                    //replacedert
                    Task[] taskToWait2 = { runnerTask, Task.Delay(2000) };
                    //wait for the runner to exit
                    await Task.WhenAny(taskToWait2);

                    replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                    replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                    replacedert.True(runnerTask.IsCanceled);

                    _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()), Times.Once(),
                         $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                    _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                    _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                    _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                    _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());

                    // verify that we didn't try to delete local settings file (since we're not ephemeral)
                    _configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Never());
                }
            }
        }

19 View Source File : MockDataStore.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public async Task<bool> DeleteItemAsync(string id)
        {
            var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault();
            items.Remove(oldItem);

            return await Task.FromResult(true);
        }

19 View Source File : FileVideoSource.cs
License : MIT License
Project Creator : adamfisher

public override Task<bool> Cancel()
        {
            return Task.FromResult(false);
        }

19 View Source File : DefaultPolicy.cs
License : MIT License
Project Creator : 2881099

public Task OnGetAsync(Object<T> obj)
        {
            OnGetObject?.Invoke(obj);
            return Task.FromResult(true);
        }

19 View Source File : Share.cs
License : MIT License
Project Creator : adamped

public Task Show( string replacedle, string message, string filePath)
		{
			var extension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower();
			var contentType = string.Empty;
		
			switch (extension)
			{
				case "pdf":
					contentType = "application/pdf";
					break;
				case "png":
					contentType = "image/png";
					break;
				default:
					contentType = "application/octetstream";
					break;
			}

			var intent = new Intent(Intent.ActionSend);
			intent.SetType(contentType);
			intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + filePath));
			intent.PutExtra(Intent.ExtraText, message ?? string.Empty);
			intent.PutExtra(Intent.ExtraSubject, replacedle ?? string.Empty);

			var chooserIntent = Intent.CreateChooser(intent, replacedle ?? string.Empty);
			chooserIntent.SetFlags(ActivityFlags.ClearTop);
			chooserIntent.SetFlags(ActivityFlags.NewTask);
			_context.StartActivity(chooserIntent);

			return Task.FromResult(true);
		}

19 View Source File : IRecordRepository.cs
License : Apache License 2.0
Project Creator : acblog

public virtual Task<bool> Exists(TId id, CancellationToken cancellationToken = default) => Task.FromResult(false);

19 View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver

public Task<bool> DeleteBlogAsync(BlogDTO objBlogs)
        {
            var ExistingBlogs =
                _context.Blogs
                .Where(x => x.BlogId == objBlogs.BlogId)
                .FirstOrDefault();

            if (ExistingBlogs != null)
            {
                _context.Blogs.Remove(ExistingBlogs);
                _context.SaveChanges();
            }
            else
            {
                return Task.FromResult(false);
            }

            return Task.FromResult(true);
        }

19 View Source File : MemoryCacheHandler.cs
License : MIT License
Project Creator : 17MKH

public Task<bool> Remove(string key)
    {
        _cache.Remove(key);
        return Task.FromResult(true);
    }

19 View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver

public Task<bool> CreateCategoryAsync(CategoryDTO objCategoryDTO)
        {
            try
            {
                Categorys objCategorys = new Categorys();
                objCategorys.replacedle = objCategoryDTO.replacedle;
                objCategorys.Description = objCategoryDTO.Description;

                _context.Categorys.Add(objCategorys);
                _context.SaveChanges();
                return Task.FromResult(true);
            }
            catch
            {
                DetachAllEnreplacedies();
                throw;
            }
        }

19 View Source File : NetDiskInfo.cs
License : MIT License
Project Creator : Accelerider

public virtual Task<bool> RefreshAsync() => Task.FromResult(false);

19 View Source File : RecordFSRepo.cs
License : Apache License 2.0
Project Creator : acblog

public override Task<bool> Delete(string id, CancellationToken cancellationToken = default)
        {
            string path = GetPath(id);
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
                return Task.FromResult(true);
            }
            return Task.FromResult(false);
        }

19 View Source File : BrokerClientExecutionHandler.cs
License : MIT License
Project Creator : 1iveowl

private async Task<IResourcePermissionResponse> GetResourceTokenThroughCache(IUserContext userContext, CancellationToken ct)
        {
            return await _resourceTokenCache.TryGetFromCache(
                userContext.UserIdentifier,
                RenewObjectFunc,
                IsCachedObjectValidFunc);

            // local function fetching a new Resource Permission Response from the Resource Token Broker
            // User the first time and whenever an existing Resource Permission Response object in the cache has expired.
           Task<IResourcePermissionResponse> RenewObjectFunc() => _brokerTransportClient.GetResourceToken(userContext.AccessToken, ct);

            // local function evaluating the validity of the object stored in the cache.
            static Task<bool> IsCachedObjectValidFunc(IResourcePermissionResponse cachedPermissionObj)
            {
                if (cachedPermissionObj is null)
                {
                    return Task.FromResult(false);
                }

                // Get the Permission that is closed to expire.
                var expires = cachedPermissionObj.ResourcePermissions?.OrderBy(resourcePermission => resourcePermission.ExpiresUtc)
                    .FirstOrDefault()
                    ?.ExpiresUtc ?? default;

                // Set expiration permission five minutes before actual expiration to be on safe side. 
                return Task.FromResult(DateTime.UtcNow <= expires - TimeSpan.FromMinutes(5));
            }
        }

19 View Source File : AcceleriderUser.cs
License : MIT License
Project Creator : Accelerider

public virtual Task<bool> RefreshAsync()
        {
            return Task.FromResult(true);
        }

19 View Source File : DelayedQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<bool> Publish<T>(int playerId, T t, int delayMin, int delayMax = 0)
        {
            var channel = t.GetType().Name.ToLower();

            Random rnd = new Random();
            var delay = delayMax > delayMin ? rnd.Next(delayMin, delayMax) : delayMin;
            var timestamp = DateTimeOffset.Now.AddSeconds(delay).ToUnixTimeSeconds();

            var hasAdd = await _redisDb.SortedSetAdd($"{queueName}_{channel}", playerId.ToString(), timestamp);
            if (hasAdd)
            {
                return await _redisDb.StringSet($"{queueName}_{channel}_{playerId}", t, DateTime.Now.AddSeconds(delay).AddDays(1));
            }
            return await Task.FromResult(false);
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnceHandleUpdateMessage()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                hc.SetSingleton<ISelfUpdater>(_updater.Object);

                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    AgentId = 5678,
                    Ephemeral = true
                };

                var message1 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(new AgentRefreshMessage(settings.AgentId, "2.123.0")),
                    MessageId = 4234,
                    MessageType = AgentRefreshMessage.MessageType
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message1);
                _updater.Setup(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), It.IsAny<bool>(), It.IsAny<CancellationToken>()))
                        .Returns(Task.FromResult(true));
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to exit with right return code
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.RunOnceRunnerUpdating);

                _updater.Verify(x => x.SelfUpdate(It.IsAny<AgentRefreshMessage>(), It.IsAny<IJobDispatcher>(), false, It.IsAny<CancellationToken>()), Times.Once);
                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Never());
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once());
            }
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Theory]
        [MemberData(nameof(RunreplacederviceTestData))]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestExecuteCommandForRunreplacedervice(string[] args, bool configurereplacedervice, Times expectedTimes)
        {
            using (var hc = new TestHostContext(this))
            {
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);

                var command = new CommandSettings(hc, args);

                _configurationManager.Setup(x => x.IsConfigured()).Returns(true);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(new RunnerSettings { });

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(configurereplacedervice);

                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult(false));

                var runner = new Runner.Listener.Runner();
                runner.Initialize(hc);
                await runner.ExecuteCommand(command);

                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), expectedTimes);
            }
        }

19 View Source File : MockDataStore.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public async Task<bool> UpdateItemAsync(Item item)
        {
            var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault();
            items.Remove(oldItem);
            items.Add(item);

            return await Task.FromResult(true);
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestRunOnceOnlyTakeOneJobMessage()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var runner = new Runner.Listener.Runner();
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IJobNotification>(_jobNotification.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);
                runner.Initialize(hc);
                var settings = new RunnerSettings
                {
                    PoolId = 43242,
                    Ephemeral = true
                };

                var message1 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4234,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };
                var message2 = new TaskAgentMessage()
                {
                    Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId = 4235,
                    MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
                };

                var messages = new Queue<TaskAgentMessage>();
                messages.Enqueue(message1);
                messages.Enqueue(message2);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                        {
                            if (0 == messages.Count)
                            {
                                await Task.Delay(2000);
                            }

                            return messages.Dequeue();
                        });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
                    .Returns(Task.CompletedTask);

                var runOnceJobCompleted = new TaskCompletionSource<bool>();
                _jobDispatcher.Setup(x => x.RunOnceJobCompleted)
                    .Returns(runOnceJobCompleted);
                _jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
                    .Callback(() =>
                    {
                        runOnceJobCompleted.TrySetResult(true);
                    });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
                    .Callback(() =>
                    {

                    });

                hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var command = new CommandSettings(hc, new string[] { "run" });
                Task<int> runnerTask = runner.ExecuteCommand(command);

                //replacedert
                //wait for the runner to run one job and exit
                await Task.WhenAny(runnerTask, Task.Delay(30000));

                replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
                replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
                replacedert.True(runnerTask.Result == Constants.Runner.ReturnCode.Success);

                _jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), true), Times.Once(),
                     $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.Once());
            }
        }

19 View Source File : RedisClientPool.cs
License : MIT License
Project Creator : 2881099

public Task OnGetAsync(Object<RedisClient> obj)
        {
            OnGet(obj); //todo
            return Task.FromResult(false);
        }

19 View Source File : MemoryCacheProvider.cs
License : MIT License
Project Creator : ad313

public async Task<bool> Set(string key, object value, Type type, DateTime absoluteExpiration)
        {
            if (string.IsNullOrWhiteSpace(key) || value == null)
            {
                return false;
            }

            _cache.Set(key, _serializerProvider.Clone(value, type), new DateTimeOffset(absoluteExpiration));

            return await Task.FromResult(true);
        }

19 View Source File : SimRoute.cs
License : MIT License
Project Creator : abdullin

public Task Send(SimPacket msg) {
            

            if (_def.PacketLoss != null && _def.PacketLoss(_network.Rand)) {
                    Debug(LogType.Fault,  msg, $"LOST {msg.BodyString()}", _def.LogFaults);
                // we just lost a packet.
                return Task.FromResult(true);
            }
            Debug(LogType.Info, msg, $"Send {msg.BodyString()}");
            
            // TODO: network cancellation
            _factory.StartNew(async () => {
                // delivery wait
                try {
                    var latency = _def.Latency(_network.Rand);
                    await SimDelayTask.Delay(latency);
                    _network.InternalDeliver(msg);
                } catch (Exception ex) {
                    Debug(LogType.Error,  msg, $"FATAL: {ex}");
                }
            });
            return Task.FromResult(true);
        }

19 View Source File : VideoSource.cs
License : MIT License
Project Creator : adamfisher

public virtual Task<bool> Cancel()
        {
            if (!IsLoading)
                return Task.FromResult(false);

            var completionSource1 = new TaskCompletionSource<bool>();
            var completionSource2 = Interlocked.CompareExchange(ref _completionSource, completionSource1, null);

            if (completionSource2 == null)
                _cancellationTokenSource.Cancel();
            else
                completionSource1 = completionSource2;

            return completionSource1.Task;
        }

19 View Source File : MemoryCacheHandler.cs
License : MIT License
Project Creator : 17MKH

public Task<bool> Set<T>(string key, T value, TimeSpan expires)
    {
        _cache.Set(key, value, expires);
        return Task.FromResult(true);
    }

19 View Source File : NavigationProxy.cs
License : MIT License
Project Creator : adamped

public Task SilentPopAsync(int indexFromTop)
        {
			var page = _page.Navigation.NavigationStack[_page.Navigation.NavigationStack.Count - indexFromTop - 1];
			_page.Navigation.RemovePage(page);
			 return Task.FromResult(true);
        }

19 View Source File : IRecordRepository.cs
License : Apache License 2.0
Project Creator : acblog

public virtual Task<bool> Delete(TId id, CancellationToken cancellationToken = default) => Task.FromResult(false);

19 View Source File : Share.cs
License : MIT License
Project Creator : adamped

public Task Show(string replacedle, string message, string filePath)
		{
			_replacedle = replacedle ?? string.Empty;
			_filePath = filePath;
			_message = message ?? string.Empty;
			
			DataTransferManager.ShowShareUI();
			
			return Task.FromResult(true);
		}

19 View Source File : DynamicProxyAttribute.cs
License : MIT License
Project Creator : 2881099

public virtual Task After(DynamicProxyAfterArguments args) => Task.FromResult(false);

19 View Source File : MemoryFileAppender.cs
License : MIT License
Project Creator : adams85

public Task<bool> EnsureDirAsync(IFileInfo fileInfo, CancellationToken cancellationToken = default)
        {
            var memoryFileInfo = (MemoryFileInfo)fileInfo;

            var dirPath = (MemoryFileInfo)FileProvider.GetFileInfo(Path.GetDirectoryName(memoryFileInfo.LogicalPath));
            if (dirPath.Exists)
                return Task.FromResult(false);

            FileProvider.CreateDir(dirPath.LogicalPath);

            return Task.FromResult(true);
        }

19 View Source File : IRecordRepository.cs
License : Apache License 2.0
Project Creator : acblog

public virtual Task<bool> Update(T value, CancellationToken cancellationToken = default) => Task.FromResult(false);

19 View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver

public Task<bool> UpdateBlogAsync(BlogDTO objBlogs)
        {
            try
            {
                var ExistingBlogs =
                    _context.Blogs
                    .Include(x => x.BlogCategory)
                    .Where(x => x.BlogId == objBlogs.BlogId)
                    .FirstOrDefault();

                if (ExistingBlogs != null)
                {
                    ExistingBlogs.BlogDate =
                        objBlogs.BlogDate;

                    ExistingBlogs.Blogreplacedle =
                        objBlogs.Blogreplacedle;

                    ExistingBlogs.BlogSummary =
                        objBlogs.BlogSummary;

                    ExistingBlogs.BlogContent =
                        objBlogs.BlogContent;

                    _context.SaveChanges();
                }
                else
                {
                    return Task.FromResult(false);
                }

                return Task.FromResult(true);
            }
            catch
            {
                DetachAllEnreplacedies();
                throw;
            }
        }

19 View Source File : MemoryCacheHandler.cs
License : MIT License
Project Creator : 17MKH

public Task<bool> Set<T>(string key, T value, int expires)
    {
        _cache.Set(key, value, new TimeSpan(0, 0, expires, 0));
        return Task.FromResult(true);
    }

19 View Source File : BlogsService.cs
License : MIT License
Project Creator : ADefWebserver

public Task<bool> UpdateBlogCategoriesAsync(Blogs objBlog, IEnumerable<String> BlogCategories)
        {
            try
            {
                var ExistingBlogs =
                    _context.Blogs
                    .Include(x => x.BlogCategory)
                    .Where(x => x.BlogId == objBlog.BlogId)
                    .FirstOrDefault();

                if (ExistingBlogs != null)
                {
                    if (BlogCategories == null)
                    {
                        ExistingBlogs.BlogCategory = null;
                    }
                    else
                    {
                        BlogDTO objBlogs = new BlogDTO();
                        objBlogs.BlogId = objBlog.BlogId;

                        ExistingBlogs.BlogCategory =
                            GetSelectedBlogCategories(objBlogs, BlogCategories);
                    }

                    _context.SaveChanges();
                }
                else
                {
                    return Task.FromResult(false);
                }

                return Task.FromResult(true);
            }
            catch
            {
                DetachAllEnreplacedies();
                throw;
            }
        }

19 View Source File : RecordFSReaderBase.cs
License : Apache License 2.0
Project Creator : acblog

public override Task<bool> Update(T value, CancellationToken cancellationToken = default) => Task.FromResult(false);

19 View Source File : PlayerCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(InitGameCommand command, CancellationToken cancellationToken)
        {
            _logger.LogDebug($"Handle InitGameCommand:{JsonConvert.SerializeObject(command)}");

            var playerId = command.PlayerId;

            if (playerId <= 0)
            {
                await _bus.RaiseEvent(new DomainNotification($"请重新进入!"));
                return Unit.Value;
            }

            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var room = await _roomDomainService.Get(player.RoomId);
            if (room == null)
            {
                await _bus.RaiseEvent(new DomainNotification("房间不存在!"));
                return Unit.Value;
            }

            player.LastDate = DateTime.Now;


            await _cache.GetOrCreateAsync(CacheKey.IsActivityIn24Hours, async x => {
                x.AbsoluteExpiration = DateTime.UtcNow.AddHours(24);
                Random random = new Random();
                player.Kar = random.Next(1, 100);
                return await Task.FromResult(true);
            });

            player.Computed();


            await _playerDomainService.Update(player);



            if (await Commit())
            {
                await _bus.RaiseEvent(new InitGameEvent(player)).ConfigureAwait(false);
                await _bus.RaiseEvent(new PlayerInRoomEvent(player, room)).ConfigureAwait(false);
            }


            return Unit.Value;
        }

19 View Source File : MemoryCacheHandler.cs
License : MIT License
Project Creator : 17MKH

public Task<bool> Set<T>(string key, T value)
    {
        _cache.Set(key, value);
        return Task.FromResult(true);
    }

19 View Source File : MemoryCacheHandler.cs
License : MIT License
Project Creator : 17MKH

public Task<bool> Set<T>(string key, T value, DateTime expires)
    {
        _cache.Set(key, value, expires - DateTime.Now);
        return Task.FromResult(true);
    }

19 View Source File : DefaultPolicy.cs
License : MIT License
Project Creator : 2881099

public Task OnGetAsync(Object<T> obj)
        {
            //Console.WriteLine("GetAsync: " + obj);
            OnGetObject?.Invoke(obj);
            return Task.FromResult(true);
        }

19 View Source File : MockDataStore.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public async Task<bool> AddItemAsync(Item item)
        {
            items.Add(item);

            return await Task.FromResult(true);
        }

19 View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Runner")]
        public async void TestMachineProvisionerCLI()
        {
            using (var hc = new TestHostContext(this))
            {
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);
                hc.SetSingleton<IConfigurationStore>(_configStore.Object);

                var command = new CommandSettings(hc, new[] { "run" });

                _configurationManager.Setup(x => x.IsConfigured()).
                    Returns(true);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(new RunnerSettings { });

                _configStore.Setup(x => x.IsServiceConfigured())
                    .Returns(false);

                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult(false));

                var runner = new Runner.Listener.Runner();
                runner.Initialize(hc);
                await runner.ExecuteCommand(command);

                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
            }
        }

See More Examples