protected virtual Task Refresh(IEnumerable <string> names) { if (names != null && names.Any()) { if (!names.Contains(CommonMetaData.Lyrics, StringComparer.OrdinalIgnoreCase)) { #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif } } return(this.Refresh()); }
protected virtual Task Reset(IEnumerable <string> names) { if (names != null && names.Any()) { if (!names.Contains(CommonImageTypes.FrontCover, true)) { #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif } } return(this.Reset()); }
public virtual PipelineDelegate <T> Build() { PipelineDelegate <T> currentDelegate = delegate { return(TaskEx.FromResult(0)); }; foreach (var action in _actions) { var prevDelegate = currentDelegate; currentDelegate = async context => { await action(context, prevDelegate); }; } return(currentDelegate); }
/// <summary> /// Starts downloading the request. /// </summary> /// <param name="request">The request data.</param> /// <param name="originator">The request's originator.</param> /// <returns>The active download.</returns> protected virtual IDownload DownloadAsync(Request request, INode originator) { var cancel = new CancellationTokenSource(); if (_filter.Invoke(request)) { var task = LoadAsync(request, cancel.Token); var download = new Download(task, cancel, request.Address, originator); Add(download); task.ContinueWith(m => Remove(download)); return(download); } return(new Download(TaskEx.FromResult(default(IResponse)), cancel, request.Address, originator)); }
public Task InvokeAsync(IInvocationComponent component) { switch (component.Id) { case SET_LIBRARY_RATING: return(this.SetLibraryRating(component.Name)); case SET_PLAYLIST_RATING: return(this.SetPlaylistRating(component.Name)); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
public virtual Task InvokeAsync(IInvocationComponent component) { switch (component.Id) { case CLEAR: return(this.Clear()); case EXIT: return(this.Exit()); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
public async Task Inlining() { var runOrder = new List <string>(); var act = new ActionTask(Token, _ => runOrder.Add($"started")) .Then(TaskEx.FromResult(1), TaskAffinity.Exclusive) .Then((_, n) => n + 1) .Then((_, n) => runOrder.Add(n.ToString())) .Then(TaskEx.FromResult(20f), TaskAffinity.Exclusive) .Then((_, n) => n + 1) .Then((_, n) => runOrder.Add(n.ToString())) .Finally((_, t) => runOrder.Add("done")) ; await act.StartAsAsync(); CollectionAssert.AreEqual(new string[] { "started", "2", "21", "done" }, runOrder); }
protected override async Task <DatabaseTaskOutcome> RunImplementation() { if (ApplicationModel.Current.Server.Value.SelectedDatabase.Value.Statistics.Value != null && ApplicationModel.Current.Server.Value.SelectedDatabase.Value.Statistics.Value.CountOfDocuments != 0) { return (await AskUser.ConfirmationWithContinuation("Override Documents?", "There are documents in the database :" + ApplicationModel.Current.Server.Value.SelectedDatabase.Value.Name + "." + Environment.NewLine + "This operation can override those documents.", ExecuteInternal, () => TaskEx.FromResult(DatabaseTaskOutcome.Abandoned))); } return(await ExecuteInternal()); }
public Task InvokeAsync(IInvocationComponent component) { switch (component.Id) { case NEW: return(this.New()); case MANAGE: return(this.Manage()); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
private Task AddToPlaylist(bool clear) { if (this.LibraryManager.SelectedItem == null) { #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif } return(this.PlaylistManager.Add( this.PlaylistManager.SelectedPlaylist, this.LibraryManager.SelectedItem, clear )); }
public async void LoadTexture(string path) { if (!path.StartsWith("jar") && !path.StartsWith("file://")) { path = "file://" + path; } var www = new WWW(path); while (!www.isDone) { await TaskEx.FromResult(true); } GetComponent <RawImage>().texture = www.textureNonReadable; }
protected virtual Task SortItems(PlaylistColumn playlistColumn, bool descending) { switch (playlistColumn.Type) { case PlaylistColumnType.Tag: return(this.SortItemsByMetaData(MetaDataItemType.Tag, playlistColumn.Tag, descending)); case PlaylistColumnType.Script: return(this.SortItemsByScript(playlistColumn.Script, descending)); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
public virtual Task <long> ReadAsync(CancellationToken cancellationToken) { CancellationTokenSource cancellationTokenSource = (CancellationTokenSource)null; TaskCompletionSource <long> completionSource1 = (TaskCompletionSource <long>)null; bool lockTaken = false; object obj; TaskCompletionSource <long> completionSource2; try { Monitor.Enter(obj = this._readerLock, ref lockTaken); Debug.Assert(this._readerTask == null || this._readerTask.IsCompleted); if (this._isClosed) { return(TaskEx.FromResult <long>(0L)); } if (this._readCancellationSource == null || this._readCancellationSource.IsCancellationRequested) { cancellationTokenSource = this._readCancellationSource; this._readCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); } if (this._readResultTask.Task.IsCompleted) { completionSource1 = this._readResultTask; this._readResultTask = new TaskCompletionSource <long>(); } completionSource2 = this._readResultTask; CancellationToken token = this._readCancellationSource.Token; this._readerTask = TaskEx.Run((Func <Task>)(() => this.ReadSegmentsAsync(token)), token); } finally { if (lockTaken) { Monitor.Exit(obj); } } if (null != completionSource1) { completionSource1.TrySetCanceled(); } if (null != cancellationTokenSource) { CancellationTokenExtensions.CancelDisposeSafe(cancellationTokenSource); } return(completionSource2.Task); }
public Task <KeyResponse <KeySignResponse> > SignAsync(KeySignRequest request, CancellationToken cancellationToken = new CancellationToken(), bool noWink = false) { if (request == null) { throw new ArgumentNullException(nameof(request)); } log.Info(">> authenticate"); var applicationSha256 = request.ApplicationSha256; var challengeSha256 = request.ChallengeSha256; var keyHandle = request.KeyHandle; log.Info(" -- Inputs --"); log.Info(" applicationSha256: " + applicationSha256.ToHexString()); log.Info(" challengeSha256: " + challengeSha256.ToHexString()); log.Info(" keyHandle: " + keyHandle.ToHexString()); var keyPair = dataStore.GetKeyPair(keyHandle); var counter = dataStore.IncrementCounter(); var userPresent = userPresenceVerifier.VerifyUserPresence(); if ((userPresent & UserPresenceVerifierConstants.UserPresentFlag) == 0) { return(TestOfUserPresenceRequired <KeySignResponse>()); } var signedData = RawMessageCodec.EncodeKeySignSignedBytes(applicationSha256, userPresent, counter, challengeSha256); log.Info("Signing bytes " + signedData.ToHexString()); var signature = crypto.Sign(signedData, keyPair.PrivateKey); log.Info(" -- Outputs --"); log.Info(" userPresence: " + userPresent); log.Info(" counter: " + counter); log.Info(" signature: " + signature.ToHexString()); log.Info("<< authenticate"); var response = new KeySignResponse(userPresent, counter, signature); var responseData = RawMessageCodec.EncodeKeySignResponse(response).Segment(); var apdu = new ApduResponse(ApduResponseStatus.NoError, responseData); var keyResponse = new KeyResponse <KeySignResponse>(apdu, response, KeyResponseStatus.Success); return(TaskEx.FromResult(keyResponse)); }
/// <summary>发生错误时</summary> /// <param name="client">客户端</param> /// <param name="exception">异常</param> /// <param name="state">状态数据</param> /// <returns></returns> public virtual Task OnError(HttpClient client, Exception exception, Object state) { // 识别ApiException if (exception is ApiException ae && ErrorCodes.Contains(ae.Code)) { // 马上过期 Expire = DateTime.MinValue; } #if NET40 return(TaskEx.FromResult(0)); #elif NET45 return(Task.FromResult(0)); #else return(Task.CompletedTask); #endif }
public Task Enqueue(IOutputStream outputStream, bool dequeue) { if (!this.Queue.TryAdd(outputStream.PlaylistItem, new OutputStreamQueueValue(outputStream))) { throw new InvalidOperationException("Failed to add the specified output stream to the queue."); } this.EnsureCapacity(outputStream.PlaylistItem); if (!dequeue) { #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif } return(this.Dequeue(outputStream.PlaylistItem)); }
/// <summary> /// Gets the raw content as byte array. /// </summary> /// <param name="maxBufferSize">The maximum buffer size</param> /// <returns>The task that loads the data into an internal buffer</returns> public Task LoadIntoBufferAsync(long maxBufferSize) { if (_buffer == null) { using (var temp = new MemoryStream()) { WriteTo(temp); _buffer = temp.ToArray(); } } #if USE_TASKEX return(TaskEx.FromResult(0)); #else return(Task.FromResult(0)); #endif }
public Task InvokeAsync(IInvocationComponent component) { switch (component.Id) { case SETTINGS: if (BassAsioDevice.IsInitialized && BassAsioDevice.Info != null) { BassAsioDevice.Info.ControlPanel(); } break; } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
public Task InvokeAsync(IInvocationComponent component) { switch (component.Id) { case QUIT: return(Windows.Invoke(() => { this.Disable(); this.OnClose(this, EventArgs.Empty); })); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
/// <summary> /// Modifies the request to ensure that the authentication requirements are met. /// </summary> /// <param name="client">Client executing this request</param> /// <param name="request">Request to authenticate</param> /// <param name="credentials">The credentials used for the authentication</param> /// <returns>The task the authentication is performed on</returns> public Task PreAuthenticate(IHttpClient client, IHttpRequestMessage request, ICredentials credentials) { if (!HasAuthorizationToken) { throw new InvalidOperationException(); } var authHeaderValue = $"{AuthenticationMethod} {_authToken}"; request.SetAuthorizationHeader(_authHeader, authHeaderValue); #if USE_TASKEX return(TaskEx.FromResult(0)); #else return(Task.FromResult(0)); #endif }
public Task Handle(IEnumerable <string> paths, FileActionType type) { switch (type) { case FileActionType.Playlist: var playlist = this.PlaylistManager.CurrentPlaylist ?? this.PlaylistManager.SelectedPlaylist; return(this.AddArchivesToPlaylist(playlist, paths)); case FileActionType.Library: return(this.AddArchivesToLibrary(paths)); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
/// <summary> /// Asynchronously copy the data to the given stream. /// </summary> /// <param name="stream">The stream to copy to</param> /// <returns>The task that copies the data to the stream</returns> public Task CopyToAsync(Stream stream) { if (_buffer != null) { stream.Write(_buffer, 0, _buffer.Length); } else { WriteTo(stream); } #if USE_TASKEX return(TaskEx.FromResult(0)); #else return(Task.FromResult(0)); #endif }
protected virtual Task SortItems(PlaylistColumn playlistColumn, bool descending) { Logger.Write(this, LogLevel.Debug, "Sorting playlist {0} by column {1}.", this.Playlist.Name, playlistColumn.Name); switch (playlistColumn.Type) { case PlaylistColumnType.Tag: return(this.SortItemsByMetaData(playlistColumn.Tag, descending)); case PlaylistColumnType.Script: return(this.SortItemsByScript(playlistColumn.Script, descending)); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
protected virtual Task OnSignal(object sender, ISignal signal) { switch (signal.Name) { case CommonSignals.MetaDataUpdated: var names = signal.State as IEnumerable <string>; return(this.Reset(names)); case CommonSignals.ImagesUpdated: return(this.Reset()); } #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif }
public Task EnumerateFilesAndDirectoriesAsync(CloudFileDirectory directory, Action <IListFileItem> enumerationAction, FileRequestOptions options, OperationContext operationContext, CancellationToken token) { IListFileItem[] enumerationItems; if (this.enumerationResults.TryGetValue(directory.Name, out enumerationItems)) { foreach (var item in enumerationItems) { enumerationAction(item); } return(TaskEx.FromResult(true)); } else { throw new MockupException("DirectoryNotFound"); } }
protected virtual Task Refresh() { if (this.Configuration == null) { #if NET40 return(TaskEx.FromResult(false)); #else return(Task.CompletedTask); #endif } return(Windows.Invoke(() => { this.Pages.Clear(); foreach (var section in this.Configuration.Sections.OrderBy(section => section.Id)) { if (section.Flags.HasFlag(ConfigurationSectionFlags.System)) { //System config should not be presented to the user. continue; } if (this.Sections != null) { if (!this.Sections.Contains(section.Id, StringComparer.OrdinalIgnoreCase)) { //Does not match section filter. continue; } } var sectionMatches = this.MatchesFilter(section); var elements = default(IEnumerable <ConfigurationElement>); if (sectionMatches) { elements = section.Elements; } else if (!this.MatchesFilter(section.Elements, out elements)) { continue; } var page = new ComponentSettingsPage(section.Name, elements); page.InitializeComponent(this.Core); this.Pages.Add(page); } this.SelectedPage = this.Pages.FirstOrDefault(); })); }
public Task <bool> Save() { if (Document.Text == Original) { return(TaskEx.FromResult(false)); } MarkpadDocument.MarkdownContent = Document.Text; //TODO async all the things var dispatcher = Dispatcher.CurrentDispatcher; return(MarkpadDocument.Save() .ContinueWith(t => { if (t.IsCanceled) { return false; } if (t.IsFaulted) { var saveResult = false; dispatcher.Invoke(new Action(() => { dialogService.ShowConfirmation( "MarkPad", "Cannot save file", "You may not have permission to save this file to the selected location, or the location may not be currently available. Error: " + t.Exception.InnerException.Message, new ButtonExtras(ButtonType.Yes, "Select a different location", "Save this file to a different location."), new ButtonExtras(ButtonType.No, "Cancel", "")); })); return saveResult == true && SaveAs().Result; } dispatcher.Invoke(new Action(() => { MarkpadDocument = t.Result; Original = MarkpadDocument.MarkdownContent; Document.Text = MarkpadDocument.MarkdownContent; })); return true; })); }
public async Task OpenDocument_RestoresAssociatedFiles() { // arrange const string toOpen = @"c:\Path\File.md"; const string content = @"Some text ![Alt](File_images\File1.png)"; fileSystem.File.Exists(@"c:\Path\File_images\File1.png").Returns(true); fileSystem.File.ReadAllTextAsync(toOpen).Returns(TaskEx.FromResult(content)); siteContextGenerator.GetContext(toOpen).Returns(new SingleFileContext(toOpen)); // act var document = await documentFactory.OpenDocument(toOpen); // assert Assert.Equal(1, document.AssociatedFiles.Count()); }
public async Task ExecuteJsonDeserializeSuccessfulWithChangeInJsonFormat() { //Arrange Mock <ISplitSdkApiClient> apiMock = new Mock <ISplitSdkApiClient>(); apiMock .Setup(x => x.FetchSplitChanges(-1)) .Returns(TaskEx.FromResult("{\"splits\": [ { \"trafficType\": \"user\", \"name\": \"Reset_Seed_UI\", \"seed\": 1552577712, \"status\": \"ACTIVE\", \"defaultTreatment\": \"off\", \"changeNumber\": 1469827821322, \"conditions\": [ { \"matcherGroup\": { \"combiner\": \"AND\", \"matchers\": [ { \"keySelector\": { \"trafficType\": \"user\", \"attribute\": null }, \"matcherType\": \"ALL_KEYS\", \"negate\": false, \"userDefinedSegmentMatcherData\": null, \"whitelistMatcherData\": null, \"unaryNumericMatcherData\": null, \"betweenMatcherData\": null } ] }, \"partitions\": [ { \"treatment\": \"on\", \"size\": 100 }, { \"treatment\": \"off\", \"size\": 0, \"addedField\": \"test\" } ] } ] } ], \"since\": 1469817846929, \"till\": 1469827821322 }\r\n")); ApiSplitChangeFetcher apiSplitChangeFetcher = new ApiSplitChangeFetcher(apiMock.Object); //Act var result = await apiSplitChangeFetcher.Fetch(-1); //Assert Assert.IsTrue(result != null); Assert.IsTrue(result.splits.Count > 0); }
/// <summary> /// Gets a webpayment transaction by it's reference filtering by type /// </summary> /// <param name="reference">The reference.</param> /// <returns>The webpayment transaction</returns> public Task <IResult <WebPaymentRequestModel> > Get(string reference, TransactionType type) { if (type == TransactionType.PREAUTH || type == TransactionType.PAYMENT) { var address = string.Format("{0}/{1}/{2}", Baseaddress, type, reference); return(GetInternal <WebPaymentRequestModel>(address)); } //Transactions can only be fetched by transation types PAYMENTS or PREAUTH return(TaskEx.FromResult <IResult <WebPaymentRequestModel> >(new Result <WebPaymentRequestModel>(null, new JudoApiErrorModel { ErrorMessage = "Wrong transaction type used", ErrorType = JudoApiError.General_Error }))); }