<commit_before>// <copyright file="IntegratedPipelineContextStage.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Owin.Host.SystemWeb.Infrastructure;

namespace Microsoft.Owin.Host.SystemWeb.IntegratedPipeline
{
    internal class IntegratedPipelineContextStage
    {
        private readonly IntegratedPipelineContext _context;
        private readonly IntegratedPipelineBlueprintStage _stage;
        private StageAsyncResult _result;
        private bool _responseShouldEnd;

        public IntegratedPipelineContextStage(IntegratedPipelineContext context, IntegratedPipelineBlueprintStage stage)
        {
            _context = context;
            _stage = stage;
        }

        public void Reset()
        {
            _result = null;
            _responseShouldEnd = false;
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Directing to callback")]
        public IAsyncResult BeginEvent(object sender, EventArgs e, AsyncCallback cb, object extradata)
        {
            if (_result != null)
            {
                throw new InvalidOperationException();
            }

            if (_context.PreventNextStage)
            {
                var noop = new StageAsyncResult(cb, extradata, () => { });
                noop.TryComplete();
                noop.InitialThreadReturning();
                return noop;
            }

            _context.PreventNextStage = true;
            _responseShouldEnd = true;
            _context.PushExecutingStage(this);

            Func<IDictionary<string, object>, Task> entryPoint = _stage.EntryPoint ?? _context.PrepareInitialContext((HttpApplication)sender);
            IDictionary<string, object> environment = _context.TakeLastEnvironment();
            TaskCompletionSource<object> tcs = _context.TakeLastCompletionSource();

            var result = new StageAsyncResult(cb, extradata, () =>
            {
                var application = ((HttpApplication)sender);

                if (_responseShouldEnd)
                {
                    application.CompleteRequest();
                }
            });

            _result = result;

            environment[Constants.IntegratedPipelineCurrentStage] = _stage.Name;

            try
            {
                entryPoint.Invoke(environment)
                    .CopyResultToCompletionSource(tcs, null)
                    .ContinueWith(t => result.TryComplete(), TaskContinuationOptions.ExecuteSynchronously)
                    .Catch(ci => ci.Handled());
            }
            catch (Exception ex)
            {
                result.Fail(ErrorState.Capture(ex));
                tcs.TrySetException(ex);
                return result;<commit_msg>SystemWeb, Intergrated Pipeline: Make sure sync exceptions flow correctly back through the OWIN pipeline.<commit_after>// <copyright file="IntegratedPipelineContextStage.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Owin.Host.SystemWeb.Infrastructure;

namespace Microsoft.Owin.Host.SystemWeb.IntegratedPipeline
{
    internal class IntegratedPipelineContextStage
    {
        private readonly IntegratedPipelineContext _context;
        private readonly IntegratedPipelineBlueprintStage _stage;
        private StageAsyncResult _result;
        private bool _responseShouldEnd;

        public IntegratedPipelineContextStage(IntegratedPipelineContext context, IntegratedPipelineBlueprintStage stage)
        {
            _context = context;
            _stage = stage;
        }

        public void Reset()
        {
            _result = null;
            _responseShouldEnd = false;
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Directing to callback")]
        public IAsyncResult BeginEvent(object sender, EventArgs e, AsyncCallback cb, object extradata)
        {
            if (_result != null)
            {
                throw new InvalidOperationException();
            }

            if (_context.PreventNextStage)
            {
                var noop = new StageAsyncResult(cb, extradata, () => { });
                noop.TryComplete();
                noop.InitialThreadReturning();
                return noop;
            }

            _context.PreventNextStage = true;
            _responseShouldEnd = true;
            _context.PushExecutingStage(this);

            Func<IDictionary<string, object>, Task> entryPoint = _stage.EntryPoint ?? _context.PrepareInitialContext((HttpApplication)sender);
            IDictionary<string, object> environment = _context.TakeLastEnvironment();
            TaskCompletionSource<object> tcs = _context.TakeLastCompletionSource();

            var result = new StageAsyncResult(cb, extradata, () =>
            {
                var application = ((HttpApplication)sender);

                if (_responseShouldEnd)
                {
                    application.CompleteRequest();
                }
            });

            _result = result;

            environment[Constants.IntegratedPipelineCurrentStage] = _stage.Name;

            try
            {
                entryPoint.Invoke(environment)
                    .CopyResultToCompletionSource(tcs, null)
                    .ContinueWith(t => result.TryComplete(), TaskContinuationOptions.ExecuteSynchronously)
                    .Catch(ci => ci.Handled());
            }
            catch (Exception ex)
            {
                // Flow the exception back through the OWIN pipeline.
                tcs.TrySetException(ex);
                result.TryComplete();
                return result;
{'fraction_non_alphanumeric': 0.08086143843965868, 'fraction_numerical': 0.00433428145740214, 'mean_word_length': 2.2788632326820606, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4559605', 'n_tokens_mistral': 1769, 'n_tokens_neox': 1674, 'n_words': 476}