System.Threading.Tasks.Task.ContinueWith(System.Func, object, System.Threading.CancellationToken, System.Threading.Tasks.TaskContinuationOptions, System.Threading.Tasks.TaskScheduler)

Here are the examples of the csharp api System.Threading.Tasks.Task.ContinueWith(System.Func, object, System.Threading.CancellationToken, System.Threading.Tasks.TaskContinuationOptions, System.Threading.Tasks.TaskScheduler) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

925 Examples 7

19 View Source File : CelesteNetUtils.cs
License : MIT License
Project Creator : 0x0ade

public static T Await<T>(this Task<T> task) {
            T? result = default;
            task.ContinueWith(_ => result = task.Result).Wait();
            if (result is null)
                throw new NullReferenceException("Task returned null: " + task);
            return result;
        }

19 View Source File : RtmpSession.cs
License : MIT License
Project Creator : a1q123456

internal void CommandHandler(RtmpController controller, CommandMessage command)
        {
            MethodInfo method = null;
            object[] arguments = null;
            try
            {
                _rpcService.PrepareMethod(controller, command, out method, out arguments);
                var result = method.Invoke(controller, arguments);
                if (result != null)
                {
                    var resType = method.ReturnType;
                    if (resType.IsGenericType && resType.GetGenericTypeDefinition() == typeof(Task<>))
                    {
                        var tsk = result as Task;
                        tsk.ContinueWith(t =>
                        {
                            var taskResult = resType.GetProperty("Result").GetValue(result);
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = true;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = taskResult;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnRanToCompletion);
                        tsk.ContinueWith(t =>
                        {
                            var exception = tsk.Exception;
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = false;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = exception.Message;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                    else if (resType == typeof(Task))
                    {
                        var tsk = result as Task;
                        tsk.ContinueWith(t =>
                        {
                            var exception = tsk.Exception;
                            var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                            retCommand.IsSuccess = false;
                            retCommand.TranscationID = command.TranscationID;
                            retCommand.CommandObject = null;
                            retCommand.ReturnValue = exception.Message;
                            _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                    else if (resType != typeof(void))
                    {
                        var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                        retCommand.IsSuccess = true;
                        retCommand.TranscationID = command.TranscationID;
                        retCommand.CommandObject = null;
                        retCommand.ReturnValue = result;
                        _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                    }
                }
            }
            catch (Exception e)
            {
                var retCommand = new ReturnResultCommandMessage(command.AmfEncodingVersion);
                retCommand.IsSuccess = false;
                retCommand.TranscationID = command.TranscationID;
                retCommand.CommandObject = null;
                retCommand.ReturnValue = e.Message;
                _ = controller.MessageStream.SendMessageAsync(controller.ChunkStream, retCommand);
                return;
            }
        }

19 View Source File : FileChecker.cs
License : Apache License 2.0
Project Creator : AantCoder

private static void GetCheckSum(ModelFileInfo mfi, string fileName, FastComputeHash computeHash)
        {
            try
            {
                if (computeHash.ReadFile != null) computeHash.ReadFile.Wait();

                computeHash.ReadFile = Task.Run(() =>
                {
                    try
                    {
                        if (!File.Exists(fileName)) return null;
                        var fileData = File.ReadAllBytes(fileName);
                        mfi.Size = fileData.Length;
                        return fileData;
                    }
                    catch (Exception exp)
                    {
                        ExceptionUtil.ExceptionLog(exp, "GetCheckSum 2 " + fileName);
                    }
                    return null;
                });
                computeHash.GetHash = computeHash.ReadFile.ContinueWith((task) =>
                {
                    try
                    {
                        if (task.Result == null)
                        {
                            mfi.Hash = null;
                            return;
                        }
                        var sha = SHA512.Create();
                        mfi.Hash = sha.ComputeHash(task.Result);
                    }
                    catch(Exception exp)
                    {
                        ExceptionUtil.ExceptionLog(exp, "GetCheckSum 3 " + fileName);
                    }
                });

                /*
                var sha = SHA512.Create();
                using (var fs = new FileStream(fileName, FileMode.Open))
                {
                    return sha.ComputeHash(fileData);
                }
                */
            }
            catch(Exception exp)
            {
                ExceptionUtil.ExceptionLog(exp, "GetCheckSum 1 " + fileName);
            }
        }

19 View Source File : FrmCaptcha.cs
License : MIT License
Project Creator : ACBrNet

private void RefreshCaptcha()
		{
			var primaryTask = Task<Image>.Factory.StartNew(() => getCaptcha());
			primaryTask.ContinueWith(task =>
			{
				if (task.Result.IsNull()) return;

				captchaPictureBox.Image = task.Result;
				captchaTextBox.Text = string.Empty;
			}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

			primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring()),
				CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
		}

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet

private void procurarIbgeCodigoButton_Click(object sender, EventArgs e)
        {
            var primaryTask = Task<int>.Factory.StartNew(() => acbrIbge.BuscarPorCodigo(codigoIbgeTextBox.Text.ToInt32()));
            primaryTask.ContinueWith(
                task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
                CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet

private void procurarIbgeNomeButton_Click(object sender, EventArgs e)
        {
            var primaryTask = Task<int>.Factory.StartNew(() => acbrIbge.Buscarreplacedome(nomeIbgeTextBox.Text));
            primaryTask.ContinueWith(
                task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
                CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet

private void buscaCepButton_Click(object sender, EventArgs e)
        {
            var primaryTask = Task<int>.Factory.StartNew(() => acbrCEP.BuscarPorCEP(cepTextBox.Text));
            primaryTask.ContinueWith(
                task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
                CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet

private void buscaLogradouroButton_Click(object sender, EventArgs e)
        {
            var uf = (ConsultaUF)ufCepComboBox.SelectedItem;
            var municipio = municipioCepTextBox.Text;
            var logradouro = logradouroCepTextBox.Text;

            var primaryTask = Task<int>.Factory.StartNew(() => acbrCEP.BuscarPorLogradouro(uf, municipio, logradouro));
            primaryTask.ContinueWith(
                task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text),
                CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet

private void ProcurarCNPJ()
        {
            var primaryTask = Task<ACBrEmpresa>.Factory.StartNew(() => acbrCnpj.Consulta(cnpjMaskedTextBox.Text));
            primaryTask.ContinueWith(task =>
            {
                var retorno = task.Result;
                tipoEmpresaTextBox.Text = retorno.TipoEmpresa;
                razaoSocialTextBox.Text = retorno.RazaoSocial;
                dataAberturaTextBox.Text = retorno.DataAbertura.ToShortDateString();
                nomeFantasiaTextBox.Text = retorno.NomeFantasia;
                cnaePrimarioTextBox.Text = retorno.CNAE1;
                logradouroTextBox.Text = retorno.Logradouro;
                numeroTextBox.Text = retorno.Numero;
                complementoTextBox.Text = retorno.Complemento;
                bairroTextBox.Text = retorno.Bairro;
                municipioTextBox.Text = retorno.Municipio;
                ufTextBox.Text = retorno.UF.ToString();
                cepCnpjTextBox.Text = retorno.CEP;
                situacaoTextBox.Text = retorno.Situacao;
                naturezaJuridicaTextBox.Text = retorno.NaturezaJuridica;
                cnaeSecundariosTextBox.Text = retorno.CNAE2.replacedtring();
            }, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

            primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error),
                CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet

private void ProcurarCPF()
        {
            var primaryTask = Task<ACBrPessoa>.Factory.StartNew(() => acbrCpf.Consulta(cpfMaskedTextBox.Text, dataNascimentoMaskedTextBox.Text.ToData()));
            primaryTask.ContinueWith(task =>
            {
                var retorno = task.Result;
                nomeTextBox.Text = retorno.Nome;
                situacaoCpfTextBox.Text = retorno.Situacao;
                digitoTextBox.Text = retorno.DigitoVerificador;
                comprovanteTextBox.Text = retorno.Emissao;
                dataInscricaoTextBox.Text = retorno.DataInscricao.ToShortDateString();
                codControleTextBox.Text = retorno.CodCtrlControle;
            }, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

            primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error),
                CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
        }

19 View Source File : FrmMain.cs
License : MIT License
Project Creator : ACBrNet

private void ProcurarSintegra()
        {
            LimparCamposSintegra();

            var uf = (ConsultaUF)ufSintegraComboBox.SelectedItem;
            var cnpj = cnpjSintegraMaskedTextBox.Text;
            var ie = inscricaoSintegraTextBox.Text;

            if (!cnpj.IsEmpty() && !cnpj.IsCNPJ())
            {
                MessageBox.Show(this, "CNPJ informado não é valido.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!ie.IsEmpty() && !ie.IsIE(uf.Sigla()))
            {
                MessageBox.Show(this, "IE informado não é valido.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var primaryTask = Task<ACBrEmpresa>.Factory.StartNew(() => acbrConsultaSintegra.Consulta(uf, cnpj, ie));
            primaryTask.ContinueWith(task =>
            {
                var retorno = task.Result;
                razaoSocialSintegraTextBox.Text = retorno.RazaoSocial;
                dataAberturaSintegraTextBox.Text = retorno.DataAbertura.ToShortDateString();
                cnpjSintegraTextBox.Text = retorno.CNPJ;
                ieSintegraTextBox.Text = retorno.InscricaoEstadual;
                logradouroSintegraTextBox.Text = retorno.Logradouro;
                numeroSintegraTextBox.Text = retorno.Numero;
                complementoSintegraTextBox.Text = retorno.Complemento;
                bairroSintegraTextBox.Text = retorno.Bairro;
                municipioSintegraTextBox.Text = retorno.Municipio;
                ufSintegraTextBox.Text = retorno.UF.ToString();
                cepSintegraTextBox.Text = retorno.CEP;
                situacaoSintegraTextBox.Text = retorno.Situacao;
            }, CancellationToken.None, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

            primaryTask.ContinueWith(task => MessageBox.Show(this, task.Exception.InnerExceptions.Select(x => x.Message).replacedtring(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error),
                CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
        }

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

public Task<IDisposable> LockAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            // Don't preplaced cancellationToken to the semapreplaced. If we can't acquire the semapreplaced immediately
            // we'll still get the waitTask returned immediately (with IsCompleted = false)
            // and then we'll end up in the else block where we add a continuation to the waitTask which will honor the cancellationToken
            Task waitTask = m_semapreplaced.WaitAsync();

            if (waitTask.IsCompleted)
            {
                return m_releaser;
            }
            else
            {
                return waitTask.ContinueWith(
                    (task, state) => (IDisposable)state,
                    m_releaser.Result,
                    cancellationToken,
                    TaskContinuationOptions.ExecuteSynchronously,
                    TaskScheduler.Default);
            }
        }

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

public Task<Releaser> LockAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            var wait = _semapreplaced.WaitAsync(cancellationToken);

            return wait.IsCompleted
                ? _releaserTask
                : wait.ContinueWith(
                    (_, state) => ((AsyncLock)state)._releaser,
                    this, CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }

19 View Source File : VideoPlayer.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void PART_MouseOver_Area_MouseLeave(object sender, MouseEventArgs e)
      {
         if (IsPlaying)
         {
            _isOverBottomTool = false;
            Task.Delay(1000).ContinueWith((t) =>
            {
               Application.Current.Dispatcher.Invoke(() =>
                   {
                   if (!this._isOverBottomTool)
                   {
                      VisualStateManager.GoToState(this, "HideVideoTool", true);
                   }
                });
            });
         }
      }

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

public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(TRequest request,
            ClientInterceptorContext<TRequest, TResponse> context,
            AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
        {
            var currentRetry = 0;

            string headerTimeout = context.GetHeaderStringValue(GrpcConstants.TimeoutMetadataKey, true);
            int timeout = headerTimeout == null ? GrpcConstants.DefaultRequestTimeout : int.Parse(headerTimeout);
            var timeoutSpan = TimeSpan.FromMilliseconds(timeout);

            string headerRetryCount = context.GetHeaderStringValue(GrpcConstants.RetryCountMetadataKey, true);
            int retryCount = headerRetryCount == null
                ? NetworkConstants.DefaultRequestRetryCount
                : int.Parse(headerRetryCount);

            async Task<TResponse> RetryCallback(Task<TResponse> responseTask)
            {
                var response = responseTask;

                // if no problem occured return
                if (!response.IsFaulted)
                {
                    return response.Result;
                }

                // if a problem occured but reached the max retries
                if (currentRetry == retryCount)
                {
                    return response.Result;
                }

                currentRetry++;

                // try again
                var retryContext = BuildNewContext(context, timeoutSpan);

                var result = GetResponseAsync(continuation(request, retryContext), timeoutSpan)
                    .ContinueWith(RetryCallback).Unwrap();

                return await result;
            }

            var newContext = BuildNewContext(context, timeoutSpan);
            var responseContinuation = continuation(request, newContext);

            var responseAsync = GetResponseAsync(responseContinuation, timeoutSpan).ContinueWith(RetryCallback)
                .Unwrap();

            return new AsyncUnaryCall<TResponse>(
                responseAsync,
                responseContinuation.ResponseHeadersAsync,
                responseContinuation.GetStatus,
                responseContinuation.GetTrailers,
                responseContinuation.Dispose);
        }

19 View Source File : AutoCompleteModel.cs
License : Apache License 2.0
Project Creator : Aguafrommars

protected Task Filter()
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;

            return Task.Delay(200, token)
                    .ContinueWith(async task =>
                    {
                        if (task.IsCanceled)
                        {
                            return;
                        }
                        FilteredValues = await GetFilteredValues(CurrentValuereplacedtring, token)
                            .ConfigureAwait(false);
                       await JSRuntime.InvokeVoidAsync("bootstrapInteropt.showDropDownMenu", token, Id);
                       await InvokeAsync(StateHasChanged).ConfigureAwait(false);
                    }, TaskScheduler.Default);
        }

19 View Source File : EntitiesModel.cs
License : Apache License 2.0
Project Creator : Aguafrommars

protected Task OnFilterChanged(string filter)
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;
                       
            return Task.Delay(500, token)
                .ContinueWith(async task =>
                {
                    _pageRequest.Filter = CreateRequestFilter(filter);

                    var page = await AdminStore.GetAsync(_pageRequest, token)
                                .ConfigureAwait(false);

                    if (task.IsCanceled)
                    {
                        return;
                    }

                    EnreplacedyList = page.Items;

                    await InvokeAsync(() => StateHasChanged())
                        .ConfigureAwait(false);
                }, TaskScheduler.Default);
        }

19 View Source File : MockHttpExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static TaskCompletionSource<object> Capture(this MockHttpMessageHandler handler,
            string url,
            JsonSerializerOptions serializationSettings = null)
        {
            var tcs = new TaskCompletionSource<object>();

            handler.When(url).Respond(() =>
            {
                return tcs.Task.ContinueWith(task =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(JsonSerializer.Serialize(task.Result, serializationSettings ?? DefaultJsonSerializerOptions))
                    };
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    return response;
                });
            });

            return tcs;
        }

19 View Source File : OAuthDelegatingHandlerTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public static TaskCompletionSource<object> Capture(MockHttpMessageHandler handler,
            string url)
        {
            var tcs = new TaskCompletionSource<object>();
            handler.When(url).Respond(() =>
            {
                return tcs.Task.ContinueWith(task =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(JsonSerializer.Serialize(task.Result, DefaultJsonSerializerOptions))
                    };
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    return response;
                });
            });

            return tcs;
        }

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

internal void SetTask(Task task)
            {
                _task = task.ContinueWith(async t =>
                {
                    if (_disposeRequested)
                    {
                        return;
                    }
                    await ResumeHelper.Await(ref _consumed);
                    ResumeHelper.Clear(ref _consumed);
                    if (_disposeRequested)
                    {
                        return;
                    }

                    _error = ExceptionHelper.Extract(t.Exception);

                    ResumeHelper.Resume(ref _valueReady);
                }, Token);
            }

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

public static async Task Main(string[] args)
        {

            Config fallbackConfig = ConfigurationFactory.ParseString(@"
                    akka.suppress-json-serializer-warning=true
                    akka.loglevel = DEBUG
                ").WithFallback(ConfigurationFactory.FromResource<ConsumerSettings<object, object>>("Akka.Streams.Kafka.reference.conf"));

            var system = ActorSystem.Create("TestKafka", fallbackConfig);
            var materializer = system.Materializer();

            var consumerSettings = ConsumerSettings<Null, string>.Create(system, null, null)
                .WithBootstrapServers($"{EventHubNamespace}.servicebus.windows.net:9093")
                .WithGroupId(EventHubConsumerGroup)
                .WithProperties(new Dictionary<string, string>
                {
                    {"security.protocol", "SASL_SSL"},
                    {"sasl.mechanism", "PLAIN"},
                    {"sasl.username", "$ConnectionString"},
                    {"sasl.preplacedword", EventHubConnectionString},
                });

            var subscription = Subscriptions.Topics(EventHubName);

            var committerDefaults = CommitterSettings.Create(system);

            // Comment for simple no-commit consumer
            DrainingControl<NotUsed> control = KafkaConsumer.CommittableSource(consumerSettings, subscription)
                .SelectAsync(1, msg => 
                    Business(msg.Record).ContinueWith(done => (ICommittable) msg.CommitableOffset))
                .ToMaterialized(
                    Committer.Sink(committerDefaults.WithMaxBatch(1)), 
                    DrainingControl<NotUsed>.Create)
                .Run(materializer);
            
            // Uncomment for simple no-commit consumer
            /*
            await KafkaConsumer.PlainSource(consumerSettings, subscription)
                .RunForeach(result =>
                {
                    Console.WriteLine($"Consumer: {result.Topic}/{result.Parreplacedion} {result.Offset}: {result.Value}");
                }, materializer);
            */

            Console.WriteLine("Press any key to stop consumer.");
            Console.ReadKey();

            // Comment for simple no-commit consumer
            await control.Stop();
            await system.Terminate();
        }

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

public static DrainingControl<NotUsed> Create((IControl, Task) tuple)
        {
            return new DrainingControl<NotUsed>(tuple.Item1, tuple.Item2.ContinueWith(t => NotUsed.Instance, TaskContinuationOptions.NotOnFaulted));
        }

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

public static DrainingControl<NotUsed> Create(IControl control, Task streamCompletion)
        {
            return new DrainingControl<NotUsed>(control, streamCompletion.ContinueWith(t => NotUsed.Instance, TaskContinuationOptions.NotOnFaulted));
        }

19 View Source File : EnsembleManager.cs
License : GNU Affero General Public License v3.0
Project Creator : akira0245

private IntPtr HandleUpdateMetronome(IntPtr agentMetronome, byte currentBeat)
    {
        try
        {
            var original = UpdateMetronomeHook.Original(agentMetronome, currentBeat);
            if (MidiBard.config.MonitorOnEnsemble)
            {
                byte Ensemble;
                byte beatsPerBar;
                int barElapsed;
                unsafe
                {
                    var metronome = ((AgentMetronome.AgentMetronomeStruct*)agentMetronome);
                    beatsPerBar = metronome->MetronomeBeatsPerBar;
                    barElapsed = metronome->MetronomeBeatsElapsed;
                    Ensemble = metronome->EnsembleModeRunning;
                }

                if (barElapsed == 0 && currentBeat == 0)
                {
                    if (Ensemble != 0)
                    {
                        // 箭头后面是每种乐器的的延迟,所以要达成同步每种乐器需要提前于自己延迟的时间开始演奏
                        // 而提前开始又不可能, 所以把所有乐器的延迟时间减去延迟最大的鲁特琴(让所有乐器等待鲁特琴)
                        // 也就是105减去每种乐器各自的延迟
                        var compensation = 105 - MidiBard.CurrentInstrument switch
                        {
                            0 => 104,
                            1 => 85,
                            2 or 4 => 90,
                            3 => 104,
                            >= 5 and <= 8 => 95,
                            9 or 10 => 90,
                            11 or 12 => 80,
                            13 => 85,
                            >= 14 => 30
                        };

                        try
                        {
                            var midiClock = new MidiClock(false, new HighPrecisionTickGenerator(), TimeSpan.FromMilliseconds(compensation));
                            midiClock.Restart();
                            PluginLog.Warning($"setup midiclock compensation: {compensation}");
                            midiClock.Ticked += OnMidiClockOnTicked;

                            void OnMidiClockOnTicked(object o, EventArgs eventArgs)
                            {
                                try
                                {
                                    MidiBard.CurrentPlayback.Start();
                                    EnsembleStart?.Invoke();
                                    PluginLog.Warning($"Start ensemble: compensation: {midiClock.CurrentTime.TotalMilliseconds} ms / {midiClock.CurrentTime.Ticks} ticks");
                                }
                                catch (Exception e)
                                {
                                    PluginLog.Error(e, "error OnMidiClockOnTicked");
                                }
                                finally
                                {
                                    midiClock.Ticked -= OnMidiClockOnTicked;
                                }
                            }

                            Task.Delay(1000).ContinueWith(_ =>
                            {
                                midiClock.Dispose();
                                PluginLog.Information($"midi clock disposed.");
                            });
                        }
                        catch (Exception e)
                        {
                            PluginLog.Error(e, "error when starting ensemble playback");
                        }
                    }
                }

                if (barElapsed == -2 && currentBeat == 0)
                {
                    PluginLog.Warning($"Prepare: ensemble: {Ensemble}");
                    if (Ensemble != 0)
                    {
                        EnsemblePrepare?.Invoke();

                        Task.Run(async () =>
                        {
                            try
                            {
                                var playing = PlaylistManager.CurrentPlaying;
                                if (playing == -1)
                                {
                                    // if using BMP track name to switch and in ensemble mode already, do nothing here since switching instrument would interrupt the ensemble mode
                                    // the instrument should have been switched already when loading the song in this occasion.
                                    await FilePlayback.LoadPlayback(0, false, !config.bmpTrackNames);
                                }
                                else
                                {
                                    await FilePlayback.LoadPlayback(playing, false, !config.bmpTrackNames);
                                }

                                MidiBard.CurrentPlayback.Stop();
                                MidiBard.CurrentPlayback.MoveToStart();
                            }
                            catch (Exception e)
                            {
                                PluginLog.Error(e, "error when loading playback for ensemble");
                            }
                        });
                    }
                }

                PluginLog.Verbose($"[Metronome] {barElapsed} {currentBeat}/{beatsPerBar}");
            }

            return original;
        }

19 View Source File : SearchViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void CloseLittlePopup()
        {
            if (this.PopupManager.PopupDialog is LoadingControlViewModel)
            {
                if (this.IndexingTask != null && !(this.IndexingTask.IsCompleted || this.IndexingTask.IsCanceled))
                {
                    // handle cancellation and restart
                    this.CancellationTokenSource.Cancel();
                    this.IndexingTask.ContinueWith((l) =>
                    {
                        Avalonia.Threading.Dispatcher.UIThread.Post(() => this.CloseLittlePopup());
                    });
                    return;
                }
            }

            if (this.PopupManager.PopupDialog is IDisposable d)
            {
                d.Dispose();
            }

            this.PopupManager.PopupDialog = null;
        }

19 View Source File : SearchViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void StartIndexing()
        {
            if (this.IndexingTask != null && !(this.IndexingTask.IsCompleted || this.IndexingTask.IsCanceled))
            {
                // handle cancellation and restart
                this.CancellationTokenSource.Cancel();
                this.IndexingTask.ContinueWith(async (l) =>
                {
                    await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() => this.StartIndexing());
                });
                return;
            }

            this.CancellationTokenSource = new CancellationTokenSource();
            this.IndexingTask = this.IndexGroups();
        }

19 View Source File : AsyncLock.cs
License : MIT License
Project Creator : alexrainman

public Task<IDisposable> LockAsync()
        {
            var wait = m_semapreplaced.WaitAsync();
            return wait.IsCompleted ?
                m_releaser :
                wait.ContinueWith((_, state) => (IDisposable)state,
                    m_releaser.Result, CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }

19 View Source File : TouchVisualManager.cs
License : MIT License
Project Creator : AndreiMisiukevich

internal void HandleLongPress(TouchEff sender)
        {
            if (sender.State == TouchState.Regular)
            {
                _longPressTokenSource?.Cancel();
                _longPressTokenSource?.Dispose();
                _longPressTokenSource = null;
                return;
            }

            if (sender.LongPressCommand == null || sender.UserInteractionState == UserInteractionState.Idle)
                return;

            _longPressTokenSource = new CancellationTokenSource();
            Task.Delay(sender.LongPressDuration, _longPressTokenSource.Token).ContinueWith(t =>
            {
                if (t.IsCanceled)
                    return;

                sender.HandleUserInteraction(UserInteractionState.Idle);
                var involeLongPressCommand = new Action(() => sender.LongPressCommand?.Execute(sender.LongPressCommandParameter));
                if (Device.IsInvokeRequired)
                {
                    Device.BeginInvokeOnMainThread(involeLongPressCommand);
                    return;
                }
                involeLongPressCommand.Invoke();
            });
        }

19 View Source File : DockerNotifier.cs
License : GNU General Public License v3.0
Project Creator : Angelinsky7

private void M_Watcher_Changed(Object sender, FileSystemEventArgs e) {
            LogMessage($"File has changed : {e.ChangeType} - {e.FullPath} - {e.Name}");

            Notify(e.FullPath).ContinueWith((t) => {
                if (t.Exception != null && t.Exception.InnerException is DockerContainerNotFoundException) {
                    ReleaseContainer();
                }
            });
        }

19 View Source File : TableCompiler.Placeholders.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void RefreshPetPlaceholder()
        {
            if (!Settings.Default.EnabledPartyMemberPlaceholder)
            {
                return;
            }

            var playerJob = this.player.JobInfo;
            if (playerJob != null &&
                !playerJob.IsSummoner())
            {
                return;
            }

            void refreshPetID()
            {
                // 3秒毎に30秒間判定させる
                const int Interval = 3;
                for (int i = 0; i < 10; i++)
                {
                    try
                    {
                        var combatants = CombatantsManager.Instance.GetCombatants();
                        if (combatants == null)
                        {
                            continue;
                        }

                        var pet = (
                            from x in combatants
                            where
                            x.OwnerID == this.player.ID &&
                            (
                                x.Name.Contains("フェアリー・") ||
                                x.Name.Contains("・エギ") ||
                                x.Name.Contains("カーバンクル・")
                            )
                            select
                            x).FirstOrDefault();

                        if (pet != null)
                        {
                            lock (this.PlaceholderListSyncRoot)
                            {
                                this.placeholderList.RemoveAll(x => x.Type == PlaceholderTypes.Pet);
                                this.placeholderList.Add(new PlaceholderContainer(
                                    "<petid>",
                                    Convert.ToString((long)((ulong)pet.ID), 16).ToUpper(),
                                    PlaceholderTypes.Pet));
                            }

                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Write("refresh petid error:", ex);
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(Interval));
                }
            }

            Task.Run(() => refreshPetID())
                .ContinueWith((task) =>
                {
                    this.RecompileSpells();
                    this.RecompileTickers();
                });
        }

19 View Source File : SoundPlayerWrapper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static void LoadTTSCache()
        {
            if (Settings.Default.Player != WavePlayerTypes.WASAPIBuffered)
            {
                return;
            }

            var volume = Settings.Default.WaveVolume / 100f;

            WPFHelper.BeginInvoke(() =>
            {
            },
            DispatcherPriority.SystemIdle).Task.ContinueWith((_) => Task.Run(() =>
            {
                var count = 0;

                try
                {
                    Logger.Info("Started loading TTS caches.");
                    BufferedWavePlayer.PlayerSet.LoadTTSHistory();
                    count = BufferedWavePlayer.Instance.BufferWaves(volume);
                }
                finally
                {
                    Logger.Info($"Completed loading TTS caches. {count} files has loaded.");
                }
            }));
        }

19 View Source File : PageService.cs
License : MIT License
Project Creator : AntonyCorbett

private void PermanentBackDropHack()
        {
            if (_mediaWindow == null)
            {
                EnsureMediaWindowCreated();

                CheckMediaWindow();
                _mediaWindow!.Show();

                Task.Delay(10).ContinueWith(_ =>
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        RelocateMediaWindow();
                        _mediaWindow.Hide();
                    });
                });
            }
        }

19 View Source File : WebDisplayManager.cs
License : MIT License
Project Creator : AntonyCorbett

public void ShowMirror()
        {
            Log.Logger.Debug("Attempting to open mirror");

            if (Mutex.TryOpenExisting("OnlyMMirrorMutex", out var _))
            {
                Log.Logger.Debug("OnlyMMirrorMutex mutex exists");
                return;
            }

            var folder = Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly()?.Location);
            if (folder == null)
            {
                Log.Logger.Error("Could not get replacedembly folder");
                return;
            }

            const string mirrorExeFileName = "OnlyMMirror.exe";

            var mirrorExePath = Path.Combine(folder, mirrorExeFileName);
            if (!File.Exists(mirrorExePath))
            {
                Log.Logger.Error($"Could not find {mirrorExeFileName}");
                return;
            }

            Log.Logger.Debug($"Mirror path = {mirrorExePath}");

            var mainWindow = Application.Current.MainWindow;
            if (mainWindow == null)
            {
                Log.Logger.Error("Could not get main window");
                return;
            }

            var handle = new WindowInteropHelper(mainWindow).Handle;
            var onlyMMonitor = _monitorsService.GetMonitorForWindowHandle(handle);
            var mediaMonitor = _monitorsService.GetSystemMonitor(_optionsService.MediaMonitorId);

            if (onlyMMonitor?.MonitorId == null || mediaMonitor?.MonitorId == null)
            {
                Log.Logger.Error("Cannot get monitor - unable to display mirror");
                return;
            }

            if (mediaMonitor.MonitorId.Equals(onlyMMonitor.MonitorId))
            {
                Log.Logger.Error("Cannot display mirror since OnlyM and Media window share a monitor");
                return;
            }

            Log.Logger.Debug($"Main monitor = {onlyMMonitor.Monitor?.DeviceName}");
            Log.Logger.Debug($"Media monitor = {mediaMonitor.Monitor?.DeviceName}");

            StatusEvent?.Invoke(this, new WebBrowserProgressEventArgs { Description = Properties.Resources.LAUNCHING_MIRROR });

            try
            {
                var zoomStr = _optionsService.MirrorZoom.ToString(CultureInfo.InvariantCulture);
                var hotKey = _optionsService.MirrorHotKey;

                var commandLineArgs =
                    $"{onlyMMonitor.Monitor?.DeviceName} {mediaMonitor.Monitor?.DeviceName} {zoomStr} {hotKey}";

                Log.Logger.Debug($"Starting mirror exe with args = {commandLineArgs}");

                _mirrorProcess = new Process
                {
                    StartInfo =
                    {
                        FileName = mirrorExePath,
                        Arguments = commandLineArgs,
                    },
                    EnableRaisingEvents = true,
                };

                _mirrorProcess.Exited += HandleMirrorProcessExited;

                if (!_mirrorProcess.Start())
                {
                    Log.Logger.Error("Could not launch mirror");
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Could not launch mirror");
            }
            finally
            {
                Task.Delay(1000).ContinueWith(_ => Application.Current.Dispatcher.Invoke(() 
                    => StatusEvent?.Invoke(this, new WebBrowserProgressEventArgs { Description = string.Empty })));
            }
        }

19 View Source File : OperatorViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void HideMediaItem(Guid? mediaItemId)
        {
            if (mediaItemId == null)
            {
                return;
            }

            var mediaItem = GetMediaItem(mediaItemId.Value);
            if (mediaItem?.FilePath != null)
            {
                mediaItem.IsCommandPanelOpen = false;

                Task.Delay(400).ContinueWith(_ =>
                {
                    mediaItem.IsVisible = false;
                    _hiddenMediaItemsService.Add(mediaItem.FilePath);
                });
            }
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void GetVersionData()
        {
            if (IsInDesignMode())
            {
                IsNewVersionAvailable = true;
                OnPropertyChanged(nameof(IsNewVersionAvailable));
            }
            else
            {
                Task.Delay(2000).ContinueWith(_ =>
                {
                    var latestVersion = VersionDetection.GetLatestReleaseVersion(_latestReleaseUrl);
                    if (latestVersion != null && VersionDetection.GetCurrentVersion().CompareTo(latestVersion) < 0)
                    {
                        // there is a new version....
                        IsNewVersionAvailable = true;
                        OnPropertyChanged(nameof(IsNewVersionAvailable));
                    }
                });
            }
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void GetVersionData()
        {
            Task.Delay(2000).ContinueWith(_ =>
            {
                var latestVersion = VersionDetection.GetLatestReleaseVersion();
                if (latestVersion != null && latestVersion > VersionDetection.GetCurrentVersion())
                {
                    // there is a new version....
                    _snackbarService.Enqueue("Update available", Properties.Resources.VIEW, LaunchWebPage);
                }
            });
        }

19 View Source File : OperatorPageViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void GetVersionData()
        {
            if (!IsNewVersionAvailable)
            {
                Task.Delay(2000).ContinueWith(_ =>
                {
                    var latestVersion = VersionDetection.GetLatestReleaseVersion();
                    if (latestVersion != null && latestVersion > VersionDetection.GetCurrentVersion())
                    {
                        // there is a new version....
                        IsNewVersionAvailable = true;
                        OnPropertyChanged(nameof(IsNewVersionAvailable));
                    }
                });
            }
        }

19 View Source File : ClockControl.cs
License : MIT License
Project Creator : AntonyCorbett

private static void DurationSectorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sector = (DurationSector?)e.NewValue;
            var c = (ClockControl)d;

            if (sector == null)
            {
                c._sectorPath1.Data = null;
                c._sectorPath2.Data = null;
                c._sectorPath3.Data = null;
            }
            else
            {
                var delay = e.OldValue == null;
                if (delay)
                {
                    // the first time we display the sector we delay it for aesthetics
                    // (so it doesn't appear just as the clock is fading out)
                    Task.Delay(1000).ContinueWith(_ => { c.Dispatcher?.Invoke(() => { DrawSector(c, sector); }); });
                }
                else
                {
                    DrawSector(c, sector);
                }
            }
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void GetVersionData()
        {
            Task.Delay(2000).ContinueWith(_ =>
            {
                var latestVersion = VersionDetection.GetLatestReleaseVersion();
                if (latestVersion != null)
                {
                    if (latestVersion > VersionDetection.GetCurrentVersion())
                    {
                        // there is a new version....
                        ShowNewVersionButton = true;
                        RaisePropertyChanged(nameof(ShowNewVersionButton));

                        _snackbarService.Enqueue(
                            Properties.Resources.NEW_UPDATE_AVAILABLE,
                            Properties.Resources.VIEW,
                            LaunchReleasePage);
                    }
                }
            });
        }

19 View Source File : ChannelManager.cs
License : Apache License 2.0
Project Creator : apache

public Task<BaseCommand> Outgoing(CommandCloseConsumer command)
    {
        var consumerId = command.ConsumerId;

        Task<BaseCommand> response;

        using (TakeConsumerSenderLock(consumerId))
        {
            response = _requestResponseHandler.Outgoing(command);
        }

        _ = response.ContinueWith(result =>
        {
            if (result.Result.CommandType == BaseCommand.Type.Success)
                _ = _consumerChannels.Remove(consumerId);
        }, TaskContinuationOptions.OnlyOnRanToCompletion);

        return response;
    }

19 View Source File : ChannelManager.cs
License : Apache License 2.0
Project Creator : apache

public Task<BaseCommand> Outgoing(CommandCloseProducer command)
    {
        var producerId = command.ProducerId;

        Task<BaseCommand> response;

        using (TakeProducerSenderLock(producerId))
        {
            response = _requestResponseHandler.Outgoing(command);
        }

        _ = response.ContinueWith(result =>
        {
            if (result.Result.CommandType == BaseCommand.Type.Success)
                _ = _producerChannels.Remove(producerId);
        }, TaskContinuationOptions.OnlyOnRanToCompletion);

        return response;
    }

19 View Source File : ChannelManager.cs
License : Apache License 2.0
Project Creator : apache

public Task<BaseCommand> Outgoing(CommandUnsubscribe command)
    {
        var consumerId = command.ConsumerId;

        Task<BaseCommand> response;

        using (TakeConsumerSenderLock(consumerId))
        {
            response = _requestResponseHandler.Outgoing(command);
        }

        _ = response.ContinueWith(result =>
        {
            if (result.Result.CommandType == BaseCommand.Type.Success)
                _consumerChannels.Remove(consumerId)?.Unsubscribed();
        }, TaskContinuationOptions.OnlyOnRanToCompletion);

        return response;
    }

19 View Source File : RemoteKitWebServer.cs
License : Apache License 2.0
Project Creator : artemshuba

private async void ProcessRequestAsync(StreamSocket socket)
        {
            Debug.WriteLine("RemoteKit: connected " + socket.Information.RemoteAddress);

            RemoteKitHttpRequest _request = null;
            using (IInputStream input = socket.InputStream)
            {
                const int bufferSize = 8192;
                byte[] data = new byte[bufferSize];
                IBuffer buffer = data.AsBuffer();
                uint dataRead = bufferSize;
                var requestString = new StringBuilder();
                while (dataRead == bufferSize)
                {
                    await input.ReadAsync(buffer, bufferSize, InputStreamOptions.Partial);
                    requestString.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }

                _request = ParseRequest(requestString.ToString());
            }

            if (_request != null)
            {
                //longpoll endpoint
                if (_request.RequestTarget == "/notifier")
                {
                    var activeSocket = _activeSockets.FirstOrDefault(
                        s => s.Information.RemoteAddress.RawName == socket.Information.RemoteAddress.RawName);
                    if (activeSocket != null)
                    {
                        activeSocket.Dispose();
                        _activeSockets.Remove(activeSocket);
                    }

                    _activeSockets.Add(socket);

                    var token = _cts.Token;

                    await Task.Delay(TimeSpan.FromSeconds(LongPollTimeOut), token).ContinueWith(async t =>
                    {
                        if (token.IsCancellationRequested)
                            return;

                        while (_activeSockets.Count > 0)
                        {
                            var s = _activeSockets[_activeSockets.Count - 1];
                            _activeSockets.Remove(s);

                            //write ok response
                            await WriteResponse(s, new JsonResponse() { Body = "{}" });
                        }
                    }, token);
                }
                //api endpoint
                else if (_request.RequestTarget == _apiEndpoint)
                {
                    ProcessApiResponse(socket, _request);
                }
                //file endpoint
                else
                {
                    ProcessFileResponse(socket, _request);
                }
            }
        }

19 View Source File : EnvironmentContentTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public Task ItShouldContainRequestContextAndAnHttpContextBaseWhenCalledThroughRoute()
        {
            var routes = new RouteCollection();
            routes.MapOwinPath<AppDelegate>(string.Empty, WasCalledApp);
            RequestContext requestContext = NewRequestContext(routes, NewHttpContext(new Uri("http://localhost")));

            Task task = ExecuteRequestContext(requestContext);
            return task.ContinueWith(
                _ =>
                {
                    task.Exception.ShouldBe(null);
                    WasCalled.ShouldBe(true);
                    WasCalledInput.ShouldContainKeyAndValue(typeof(RequestContext).FullName, requestContext);
                    WasCalledInput.ShouldContainKey(typeof(HttpContextBase).FullName);
                });
        }

19 View Source File : EnvironmentContentTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public Task ItShouldFireOnSendingHeaders()
        {
            var stateObject = new object();
            bool onSendingHeadersFired = false;
            bool stateObjectMatched = false;

            var routes = new RouteCollection();
            routes.MapOwinPath<AppDelegate>(string.Empty,
                env =>
                {
                    var onSendingHeadersRegister = env.Get<Action<Action<object>, object>>("server.OnSendingHeaders");
                    onSendingHeadersRegister(
                        preplacededObject =>
                        {
                            onSendingHeadersFired = true;
                            stateObjectMatched = object.ReferenceEquals(preplacededObject, stateObject);
                        }, stateObject);
                    return Utils.CompletedTask;
                });
            RequestContext requestContext = NewRequestContext(routes, NewHttpContext(new Uri("http://localhost/alpha/beta")));

            Task task = ExecuteRequestContext(requestContext);
            return task.ContinueWith(
                _ =>
                {
                    task.Exception.ShouldBe(null);
                    onSendingHeadersFired.ShouldBe(true);
                    stateObjectMatched.ShouldBe(true);
                });
        }

19 View Source File : OwinHttpHandlerTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public Task ItShouldCallAppDelegateWhenBeginProcessRequestCalled()
        {
            var httpHandler = new OwinHttpHandler(string.Empty, OwinBuilder.Build(WasCalledApp));
            FakeHttpContext httpContext = NewHttpContext(new Uri("http://localhost"));

            Task task = Task.Factory.FromAsync(httpHandler.BeginProcessRequest, httpHandler.EndProcessRequest, httpContext, null);
            return task.ContinueWith(_ =>
            {
                task.Exception.ShouldBe(null);
                WasCalled.ShouldBe(true);
            });
        }

19 View Source File : EnvironmentContentTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public Task ItShouldContainAllOwinStandardKeys()
        {
            var routes = new RouteCollection();
            routes.MapOwinPath<AppDelegate>(string.Empty, WasCalledApp);
            RequestContext requestContext = NewRequestContext(routes, NewHttpContext(new Uri("http://localhost")));

            Task task = ExecuteRequestContext(requestContext);
            return task.ContinueWith(
                _ =>
                {
                    task.Exception.ShouldBe(null);
                    WasCalled.ShouldBe(true);
                    WasCalledInput.ShouldContainKey("owin.RequestMethod");
                    WasCalledInput.ShouldContainKey("owin.RequestPath");
                    WasCalledInput.ShouldContainKey("owin.RequestPathBase");
                    WasCalledInput.ShouldContainKey("owin.RequestQueryString");
                    WasCalledInput.ShouldContainKey("owin.RequestScheme");
                    WasCalledInput.ShouldContainKey("owin.Version");
                });
        }

19 View Source File : EnvironmentContentTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public Task ItShouldContainGivenRequestMethod()
        {
            var routes = new RouteCollection();
            routes.MapOwinPath<AppDelegate>(string.Empty, WasCalledApp);
            RequestContext requestContext = NewRequestContext(routes, NewHttpContext(new Uri("http://localhost"), "DELTA"));

            Task task = ExecuteRequestContext(requestContext);
            return task.ContinueWith(
                _ =>
                {
                    task.Exception.ShouldBe(null);
                    WasCalled.ShouldBe(true);
                    WasCalledInput.ShouldContainKeyAndValue("owin.RequestMethod", "DELTA");
                });
        }

19 View Source File : EnvironmentContentTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public Task ItShouldHaveEmptyPathBaseAndAbsolutePath()
        {
            var routes = new RouteCollection();
            routes.MapOwinPath<AppDelegate>(string.Empty, WasCalledApp);
            RequestContext requestContext = NewRequestContext(routes, NewHttpContext(new Uri("http://localhost/alpha/beta")));

            Task task = ExecuteRequestContext(requestContext);
            return task.ContinueWith(
                _ =>
                {
                    task.Exception.ShouldBe(null);
                    WasCalled.ShouldBe(true);
                    WasCalledInput.ShouldContainKeyAndValue("owin.RequestPathBase", string.Empty);
                    WasCalledInput.ShouldContainKeyAndValue("owin.RequestPath", "/alpha/beta");
                });
        }

19 View Source File : EnvironmentContentTests.cs
License : Apache License 2.0
Project Creator : aspnet

[Fact]
        public Task ItShouldHaveUnparsedAndEscapedQueryString()
        {
            var routes = new RouteCollection();
            routes.MapOwinPath<AppDelegate>(string.Empty, WasCalledApp);
            RequestContext requestContext = NewRequestContext(routes, NewHttpContext(new Uri("http://localhost/alpha/beta?gamma=delta&omega=%2fepsilon")));

            Task task = ExecuteRequestContext(requestContext);
            return task.ContinueWith(
                _ =>
                {
                    task.Exception.ShouldBe(null);
                    WasCalled.ShouldBe(true);
                    WasCalledInput.ShouldContainKeyAndValue("owin.RequestQueryString", "gamma=delta&omega=%2fepsilon");
                });
        }

See More Examples