@@ -50,7 +50,7 @@ namespace System.Drawing.Tests
         {
             try
             {
-                return new []
+                return new []
                 {
                     new ImageTestData(ImageFormat.Bmp),
                     new ImageTestData(ImageFormat.Jpeg),

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
using MicroBenchmarks;

namespace System.Drawing.Tests
{
    [BenchmarkCategory(Categories.Libraries)]
    public class Perf_Image_Load
    {
        // this field is lazy to avoid the exception during static ctor initialization of this type (harder to catch and handle properly)
        private static readonly Lazy<ImageTestData[]> LazyTestCases = new Lazy<ImageTestData[]>(CreateTestCases);

        public IEnumerable<object> ImageFormats() => LazyTestCases.Value;

        [Benchmark]
        [ArgumentsSource(nameof(ImageFormats))]
        public void Bitmap_FromStream(ImageTestData format)
        {
            using (new Bitmap(format.Stream))
            {
            }
        }

        [Benchmark]
        [ArgumentsSource(nameof(ImageFormats))]
        public void Image_FromStream(ImageTestData format)
        {
            using (Image.FromStream(format.Stream))
            {
            }
        }

        [Benchmark]
        [ArgumentsSource(nameof(ImageFormats))]
        public void Image_FromStream_NoValidation(ImageTestData format)
        {
            using (Image.FromStream(format.Stream, false, false))
            {
            }
        }

        private static ImageTestData[] CreateTestCases()
        {
            try
            {
                return new []
                {
                    new ImageTestData(ImageFormat.Bmp),
                    new ImageTestData(ImageFormat.Jpeg),
                    new ImageTestData(ImageFormat.Png),
                    new ImageTestData(ImageFormat.Gif)
                };
            }
            catch (Exception) when (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("libgdiplus is missing, you can install it by running 'apt-get install libgdiplus'");
                Console.ResetColor();

                throw;
            }
        }

        public class ImageTestData
        {
            public Stream Stream { get; }
            private string FormatName { get; }

            public ImageTestData(ImageFormat format)
            {
                Stream = CreateTestImage(format);
                FormatName = format.ToString();
            }

            // the value returned by ToString is used in the text representation of Benchmark ID in our reporting system
            public override string ToString() => FormatName;

            private static Stream CreateTestImage(ImageFormat format)
            {
                Random r = new Random(1066); // the seed must not be changed

                const int Size = 1000;
                Point RandomPoint() => new Point(r.Next(Size), r.Next(Size));

                var result = new MemoryStream();

                using (Bitmap bitmap = new Bitmap(Size, Size))
                using (Pen pen = new Pen(Color.Blue))
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    for (int i = 0; i < 100; i++)
                    {
                        graphics.DrawBezier(pen, RandomPoint(), RandomPoint(), RandomPoint(), RandomPoint());
                    }

                    bitmap.Save(result, format);
                }

                return result;
            }
        }
    }
}


@@ -152,6 +152,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
             finally
             {
                 CloseRawPipes();
+                _adaptedPipelineTcs.TrySetResult(null);
             }
         }

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Core.Adapter;
using Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Internal.System.IO.Pipelines;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
{
    public class FrameConnection : IConnectionContext
    {
        private readonly FrameConnectionContext _context;
        private readonly Frame _frame;
        private readonly List<IConnectionAdapter> _connectionAdapters;
        private readonly TaskCompletionSource<object> _frameStartedTcs = new TaskCompletionSource<object>();

        private AdaptedPipeline _adaptedPipeline;
        private Stream _filteredStream;
        private Task _adaptedPipelineTask = TaskCache.CompletedTask;

        public FrameConnection(FrameConnectionContext context)
        {
            _context = context;
            _frame = context.Frame;
            _connectionAdapters = context.ConnectionAdapters;
        }

        public string ConnectionId => _context.ConnectionId;
        public IPipeWriter Input => _context.Input.Writer;
        public IPipeReader Output => _context.Output.Reader;

        private PipeFactory PipeFactory => _context.PipeFactory;

        // Internal for testing
        internal PipeOptions AdaptedPipeOptions => new PipeOptions
        {
            ReaderScheduler = InlineScheduler.Default,
            WriterScheduler = InlineScheduler.Default,
            MaximumSizeHigh = _context.ServiceContext.ServerOptions.Limits.MaxRequestBufferSize ?? 0,
            MaximumSizeLow = _context.ServiceContext.ServerOptions.Limits.MaxRequestBufferSize ?? 0
        };

        private IKestrelTrace Log => _context.ServiceContext.Log;

        public void StartRequestProcessing()
        {
            _frame.Input = _context.Input.Reader;
            _frame.Output = _context.OutputProducer;

            if (_connectionAdapters.Count == 0)
            {
                _frame.Start();
                _frameStartedTcs.SetResult(null);
            }
            else
            {
                // Ensure that IConnectionAdapter.OnConnectionAsync does not run on the transport thread.
                _context.ServiceContext.ThreadPool.UnsafeRun(state =>
                {
                    // ApplyConnectionAdaptersAsync should never throw. If it succeeds, it will call _frame.Start().
                    // Otherwise, it will close the connection.
                    var ignore = ((FrameConnection)state).ApplyConnectionAdaptersAsync();
                }, this);
            }
        }

        public void OnConnectionClosed()
        {
            Log.ConnectionStop(ConnectionId);
            KestrelEventSource.Log.ConnectionStop(this);
        }

        public async Task StopAsync()
        {
            await _frameStartedTcs.Task;
            await _frame.StopAsync();
            await _adaptedPipelineTask;
        }

        public void Abort(Exception ex)
        {
            _frame.Abort(ex);
        }

        public void Timeout()
        {
            _frame.SetBadRequestState(RequestRejectionReason.RequestTimeout);
        }

        private async Task ApplyConnectionAdaptersAsync()
        {
            try
            {
                var rawSocketOutput = _frame.Output;
                var rawStream = new RawStream(_frame.Input, rawSocketOutput);
                var adapterContext = new ConnectionAdapterContext(rawStream);
                var adaptedConnections = new IAdaptedConnection[_connectionAdapters.Count];

                for (var i = 0; i < _connectionAdapters.Count; i++)
                {
                    var adaptedConnection = await _connectionAdapters[i].OnConnectionAsync(adapterContext);
                    adaptedConnections[i] = adaptedConnection;
                    adapterContext = new ConnectionAdapterContext(adaptedConnection.ConnectionStream);
                }

                if (adapterContext.ConnectionStream != rawStream)
                {
                    _filteredStream = adapterContext.ConnectionStream;
                    _adaptedPipeline = new AdaptedPipeline(
                        adapterContext.ConnectionStream,
                        PipeFactory.Create(AdaptedPipeOptions),
                        PipeFactory.Create(AdaptedPipeOptions));

                    _frame.Input = _adaptedPipeline.Input.Reader;
                    _frame.Output = _adaptedPipeline.Output;

                    _adaptedPipelineTask = RunAdaptedPipeline();
                }

                _frame.AdaptedConnections = adaptedConnections;
                _frame.Start();
                _frameStartedTcs.SetResult(null);
            }
            catch (Exception ex)
            {
                Log.LogError(0, ex, $"Uncaught exception from the {nameof(IConnectionAdapter.OnConnectionAsync)} method of an {nameof(IConnectionAdapter)}.");
                _frameStartedTcs.SetResult(null);
                CloseRawPipes();
            }
        }

        private async Task RunAdaptedPipeline()
        {
            try
            {
                await _adaptedPipeline.RunAsync();
            }
            catch (Exception ex)
            {
                // adaptedPipeline.RunAsync() shouldn't throw.
                Log.LogError(0, ex, $"{nameof(FrameConnection)}.{nameof(ApplyConnectionAdaptersAsync)}");
            }
            finally
            {
                CloseRawPipes();
            }
        }

        private void CloseRawPipes()
        {
            _filteredStream?.Dispose();
            _context.OutputProducer.Dispose();
            _context.Input.Reader.Complete();
        }
    }
}


@@ -13,11 +13,13 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 // </copyright>
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using OpenTelemetry.Resources;
 using Thrift.Protocols;
 using Thrift.Protocols.Entities;

// <copyright file="Process.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// 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.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocols;
using Thrift.Protocols.Entities;

namespace OpenTelemetry.Exporter.Jaeger.Implementation
{
    public class Process : TAbstractBase
    {
        public Process()
        {
        }

        public Process(string serviceName, IDictionary<string, object> processTags)
            : this()
        {
            this.ServiceName = serviceName;

            if (processTags != null)
            {
                this.Tags = new List<JaegerTag>();
                this.Tags.AddRange(processTags.Select(pt => pt.ToJaegerTag()));
            }
        }

        public string ServiceName { get; set; }

        public List<JaegerTag> Tags { get; set; }

        public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)
        {
            oprot.IncrementRecursionDepth();

            try
            {
                var struc = new TStruct("Process");
                await oprot.WriteStructBeginAsync(struc, cancellationToken);

                var field = new TField
                {
                    Name = "serviceName",
                    Type = TType.String,
                    ID = 1,
                };

                await oprot.WriteFieldBeginAsync(field, cancellationToken);
                await oprot.WriteStringAsync(this.ServiceName, cancellationToken);
                await oprot.WriteFieldEndAsync(cancellationToken);

                if (this.Tags != null)
                {
                    field.Name = "tags";
                    field.Type = TType.List;
                    field.ID = 2;

                    await oprot.WriteFieldBeginAsync(field, cancellationToken);
                    {
                        await oprot.WriteListBeginAsync(new TList(TType.Struct, this.Tags.Count), cancellationToken);

                        foreach (JaegerTag jt in this.Tags)
                        {
                            await jt.WriteAsync(oprot, cancellationToken);
                        }

                        await oprot.WriteListEndAsync(cancellationToken);
                    }

                    await oprot.WriteFieldEndAsync(cancellationToken);
                }

                await oprot.WriteFieldStopAsync(cancellationToken);
                await oprot.WriteStructEndAsync(cancellationToken);
            }
            finally
            {
                oprot.DecrementRecursionDepth();
            }
        }

        public override string ToString()
        {
            var sb = new StringBuilder("Process(");
            sb.Append(", ServiceName: ");
            sb.Append(this.ServiceName);

            if (this.Tags != null)
            {
                sb.Append(", Tags: ");
                sb.Append(this.Tags);
            }

            sb.Append(")");
            return sb.ToString();
        }
    }
}


@@ -69,7 +69,7 @@ namespace Nethermind.Runner.Ethereum.Steps

             var validator = new AuRaValidatorProcessorFactory(
                     readOnlyTxProcessingEnv.StateProvider,
-                    new AbiEncoder(),
+                    _context.AbiEncoder,
                     readOnlyTxProcessingEnv.TransactionProcessor,
                     new ReadOnlyTransactionProcessorSource(readOnlyTxProcessingEnv),
                     readOnlyTxProcessingEnv.BlockTree,

//  Copyright (c) 2018 Demerzel Solutions Limited
//  This file is part of the Nethermind library.
//
//  The Nethermind library is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  The Nethermind library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.

using Nethermind.Abi;
using Nethermind.Blockchain;
using Nethermind.Blockchain.Processing;
using Nethermind.Consensus.AuRa;
using Nethermind.Consensus.AuRa.Config;
using Nethermind.Db;
using Nethermind.Logging;
using Nethermind.Runner.Ethereum.Context;
using Nethermind.Store;

namespace Nethermind.Runner.Ethereum.Steps
{
    [RunnerStepDependencies(typeof(InitializeNetwork), typeof(InitializeFinalizationAuRa), typeof(SetupKeyStore))]
    public class StartBlockProducerAuRa : StartBlockProducer
    {
        private readonly AuRaEthereumRunnerContext _context;

        public StartBlockProducerAuRa(AuRaEthereumRunnerContext context) : base(context)
        {
            _context = context;
        }

        protected override void BuildProducer()
        {
            if (_context.NodeKey == null) throw new StepDependencyException(nameof(_context.NodeKey));
            if (_context.ChainSpec == null) throw new StepDependencyException(nameof(_context.ChainSpec));

            ILogger logger = _context.LogManager.GetClassLogger();
            if (logger.IsWarn) logger.Warn("Starting AuRa block producer & sealer");

            IAuRaStepCalculator stepCalculator = new AuRaStepCalculator(_context.ChainSpec.AuRa.StepDuration, _context.Timestamper);
            BlockProducerContext producerContext = GetProducerChain();
            var auraConfig = _context.Config<IAuraConfig>();
            _context.BlockProducer = new AuRaBlockProducer(
                producerContext.PendingTxSelector,
                producerContext.ChainProcessor,
                producerContext.ReadOnlyStateProvider,
                _context.Sealer,
                _context.BlockTree,
                _context.BlockProcessingQueue,
                _context.Timestamper,
                _context.LogManager,
                stepCalculator,
                auraConfig,
                _context.NodeKey.Address);
        }

        protected override BlockProcessor CreateBlockProcessor(ReadOnlyTxProcessingEnv readOnlyTxProcessingEnv, IReadOnlyDbProvider readOnlyDbProvider)
        {
            if (_context.RewardCalculatorSource == null) throw new StepDependencyException(nameof(_context.RewardCalculatorSource));
            if (_context.ValidatorStore == null) throw new StepDependencyException(nameof(_context.ValidatorStore));
            if (_context.ChainSpec == null) throw new StepDependencyException(nameof(_context.ChainSpec));

            var validator = new AuRaValidatorProcessorFactory(
                    readOnlyTxProcessingEnv.StateProvider,
                    new AbiEncoder(),
                    readOnlyTxProcessingEnv.TransactionProcessor,
                    new ReadOnlyTransactionProcessorSource(readOnlyTxProcessingEnv),
                    readOnlyTxProcessingEnv.BlockTree,
                    _context.ReceiptStorage,
                    _context.ValidatorStore,
                    _context.LogManager)
                .CreateValidatorProcessor(_context.ChainSpec.AuRa.Validators);

            var blockProducer = new AuRaBlockProcessor(
                _context.SpecProvider,
                _context.BlockValidator,
                _context.RewardCalculatorSource.Get(readOnlyTxProcessingEnv.TransactionProcessor),
                readOnlyTxProcessingEnv.TransactionProcessor,
                readOnlyDbProvider.StateDb,
                readOnlyDbProvider.CodeDb,
                readOnlyTxProcessingEnv.StateProvider,
                readOnlyTxProcessingEnv.StorageProvider,
                _context.TxPool,
                _context.ReceiptStorage,
                _context.LogManager,
                validator);

            validator.SetFinalizationManager(_context.FinalizationManager, true);

            return blockProducer;
        }
    }
}


@@ -117,8 +117,8 @@ namespace Nethermind.Consensus.AuRa.Transactions
         {
             public const int MaxCacheSize = 4096;

-            internal ICache<(Keccak ParentHash, Address Sender), ITransactionPermissionContract.TxPermissions?> Permissions { get; } =
-                new LruCache<(Keccak ParentHash, Address Sender), ITransactionPermissionContract.TxPermissions?>(MaxCacheSize, "TxPermissions");
+            internal ICache<(Keccak ParentHash, Address Sender), (ITransactionPermissionContract.TxPermissions Permissions, bool ContractExists)> Permissions { get; } =
+                new LruCache<(Keccak ParentHash, Address Sender), (ITransactionPermissionContract.TxPermissions Permissions, bool ContractExists)>(MaxCacheSize, "TxPermissions");
         }
     }
 }

//  Copyright (c) 2021 Demerzel Solutions Limited
//  This file is part of the Nethermind library.
//
//  The Nethermind library is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  The Nethermind library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Diagnostics;
using Nethermind.Abi;
using Nethermind.Consensus.AuRa.Contracts;
using Nethermind.Consensus.Transactions;
using Nethermind.Core;
using Nethermind.Core.Caching;
using Nethermind.Core.Crypto;
using Nethermind.Logging;
using Nethermind.State;

namespace Nethermind.Consensus.AuRa.Transactions
{
    public class PermissionBasedTxFilter : ITxFilter
    {
        private readonly VersionedContract<ITransactionPermissionContract> _contract;
        private readonly Cache _cache;
        private readonly IReadOnlyStateProvider _stateProvider;
        private readonly ILogger _logger;

        public PermissionBasedTxFilter(
            VersionedContract<ITransactionPermissionContract> contract,
            Cache cache,
            IReadOnlyStateProvider stateProvider,
            ILogManager logManager)
        {
            _contract = contract ?? throw new ArgumentNullException(nameof(contract));
            _cache = cache ?? throw new ArgumentNullException(nameof(cache));
            _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider));
            _logger = logManager?.GetClassLogger<PermissionBasedTxFilter>() ?? throw new ArgumentNullException(nameof(logManager));
        }

        public (bool Allowed, string Reason) IsAllowed(Transaction tx, BlockHeader parentHeader)
        {
            if (parentHeader.Number + 1 < _contract.Activation)
            {
                return (true, string.Empty);
            }

            var txType = GetTxType(tx);
            var txPermissions = GetPermissions(tx, parentHeader);
            if (_logger.IsTrace) _logger.Trace($"Given transaction: {tx.Hash} sender: {tx.SenderAddress} to: {tx.To} value: {tx.Value}, gas_price: {tx.GasPrice}. " +
                                               $"Permissions required: {txType}, got: {txPermissions}.");
            return (txPermissions & txType) == txType ? (true, string.Empty) : (false, "permission denied");
        }

        private ITransactionPermissionContract.TxPermissions GetPermissions(Transaction tx, BlockHeader parentHeader)
        {
            var key = (parentHeader.Hash, tx.SenderAddress);
            var txCachedPermissions = _cache.Permissions.Get(key);
            return txCachedPermissions ?? GetPermissionsFromContract(tx, parentHeader, key);
        }

        private ITransactionPermissionContract.TxPermissions GetPermissionsFromContract(
            Transaction tx,
            BlockHeader parentHeader,
            in (Keccak Hash, Address SenderAddress) key)
        {
            ITransactionPermissionContract.TxPermissions txPermissions = ITransactionPermissionContract.TxPermissions.None;
            bool shouldCache = true;

            ITransactionPermissionContract versionedContract = GetVersionedContract(parentHeader);
            if (versionedContract is null)
            {
                if (_logger.IsError) _logger.Error("Unknown version of tx permissions contract is used.");
            }
            else
            {
                if (_logger.IsTrace) _logger.Trace($"Version of tx permission contract: {versionedContract.Version}.");

                try
                {
                    (txPermissions, shouldCache) = versionedContract.AllowedTxTypes(parentHeader, tx);
                }
                catch (AbiException e)
                {
                    if (_logger.IsError) _logger.Error($"Error calling tx permissions contract on {parentHeader.ToString(BlockHeader.Format.FullHashAndNumber)} for tx {tx.ToShortString()} {new StackTrace()}.", e);
                }
            }

            if (shouldCache)
            {
                _cache.Permissions.Set(key, txPermissions);
            }

            return txPermissions;
        }

        private ITransactionPermissionContract? GetVersionedContract(BlockHeader blockHeader)
            => _contract.ResolveVersion(blockHeader);

        private ITransactionPermissionContract.TxPermissions GetTxType(Transaction tx) =>
            tx.IsContractCreation
                ? ITransactionPermissionContract.TxPermissions.Create
                : (_stateProvider.GetCode(tx.To) ?? Array.Empty<byte>()).Length != 0
                    ? ITransactionPermissionContract.TxPermissions.Call
                    : ITransactionPermissionContract.TxPermissions.Basic;

        public class Cache
        {
            public const int MaxCacheSize = 4096;

            internal ICache<(Keccak ParentHash, Address Sender), ITransactionPermissionContract.TxPermissions?> Permissions { get; } =
                new LruCache<(Keccak ParentHash, Address Sender), ITransactionPermissionContract.TxPermissions?>(MaxCacheSize, "TxPermissions");
        }
    }
}


@@ -38,7 +38,7 @@ namespace Datadog.Trace.ClrProfiler.IntegrationTests
     public class AspNetMvc4TestsCallTargetClassic : AspNetMvc4Tests
     {
         public AspNetMvc4TestsCallTargetClassic(IisFixture iisFixture, ITestOutputHelper output)
-            : base(iisFixture, output, enableCallTarget: true, classicMode: true)
+            : base(iisFixture, output, enableCallTarget: true, classicMode: true, enableFeatureFlag: false)
         {
         }
     }

// <copyright file="AspNetMvc4Tests.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>

#if NET461
#pragma warning disable SA1402 // File may only contain a single class
#pragma warning disable SA1649 // File name must match first type name

using System.Net;
using System.Threading.Tasks;
using Datadog.Trace.TestHelpers;
using Xunit;
using Xunit.Abstractions;

namespace Datadog.Trace.ClrProfiler.IntegrationTests
{
    [CollectionDefinition("IisTests", DisableParallelization = true)]
    [Collection("IisTests")]
    public class AspNetMvc4TestsCallsiteClassic : AspNetMvc4Tests
    {
        public AspNetMvc4TestsCallsiteClassic(IisFixture iisFixture, ITestOutputHelper output)
            : base(iisFixture, output, enableCallTarget: false, classicMode: true)
        {
        }
    }

    [Collection("IisTests")]
    public class AspNetMvc4TestsCallsiteIntegrated : AspNetMvc4Tests
    {
        public AspNetMvc4TestsCallsiteIntegrated(IisFixture iisFixture, ITestOutputHelper output)
            : base(iisFixture, output, enableCallTarget: false, classicMode: false)
        {
        }
    }

    [Collection("IisTests")]
    public class AspNetMvc4TestsCallTargetClassic : AspNetMvc4Tests
    {
        public AspNetMvc4TestsCallTargetClassic(IisFixture iisFixture, ITestOutputHelper output)
            : base(iisFixture, output, enableCallTarget: true, classicMode: true)
        {
        }
    }

    [Collection("IisTests")]
    public class AspNetMvc4TestsCallTargetIntegrated : AspNetMvc4Tests
    {
        public AspNetMvc4TestsCallTargetIntegrated(IisFixture iisFixture, ITestOutputHelper output)
            : base(iisFixture, output, enableCallTarget: true, classicMode: false)
        {
        }
    }

    public abstract class AspNetMvc4Tests : TestHelper, IClassFixture<IisFixture>
    {
        private readonly IisFixture _iisFixture;

        public AspNetMvc4Tests(IisFixture iisFixture, ITestOutputHelper output, bool enableCallTarget, bool classicMode)
            : base("AspNetMvc4", @"test\test-applications\aspnet", output)
        {
            SetServiceVersion("1.0.0");
            SetCallTargetSettings(enableCallTarget);

            _iisFixture = iisFixture;
            _iisFixture.TryStartIis(this, classicMode);
        }

        [Theory]
        [Trait("Category", "EndToEnd")]
        [Trait("RunOnWindows", "True")]
        [Trait("LoadFromGAC", "True")]
        [MemberData(nameof(AspNetMvc4TestData.WithoutFeatureFlag), MemberType = typeof(AspNetMvc4TestData))]
        public async Task SubmitsTraces(
            string path,
            string expectedAspNetResourceName,
            string expectedResourceName,
            HttpStatusCode expectedStatusCode,
            bool isError,
            string expectedErrorType,
            string expectedErrorMessage,
            SerializableDictionary tags)
        {
            await AssertWebServerSpan(
                path,
                _iisFixture.Agent,
                _iisFixture.HttpPort,
                expectedStatusCode,
                isError,
                expectedAspNetErrorType: expectedErrorType,
                expectedAspNetErrorMessage: expectedErrorMessage,
                expectedErrorType: expectedErrorType,
                expectedErrorMessage: expectedErrorMessage,
                "web",
                "aspnet-mvc.request",
                expectedAspNetResourceName,
                expectedResourceName,
                "1.0.0",
                tags);
        }
    }
}
#endif


@@ -12,7 +12,7 @@ using Datadog.Trace.DuckTyping;
 namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Testing.MsTestV2
 {
     /// <summary>
-    /// Microsoft.VisualStudio.TestPlatform.TestFramework.Execute calltarget instrumentation
+    /// Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodRunner.Execute calltarget instrumentation
     /// </summary>
     [InstrumentMethod(
         AssemblyName = "Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter",

// <copyright file="TestMethodRunnerExecuteIntegration.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>

using System;
using System.ComponentModel;
using Datadog.Trace.Ci.Tags;
using Datadog.Trace.ClrProfiler.CallTarget;
using Datadog.Trace.DuckTyping;

namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Testing.MsTestV2
{
    /// <summary>
    /// Microsoft.VisualStudio.TestPlatform.TestFramework.Execute calltarget instrumentation
    /// </summary>
    [InstrumentMethod(
        AssemblyName = "Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter",
        TypeName = "Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestMethodRunner",
        MethodName = "Execute",
        ReturnTypeName = "Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestResult",
        ParameterTypeNames = new string[0],
        MinimumVersion = "14.0.0",
        MaximumVersion = "14.*.*",
        IntegrationName = MsTestIntegration.IntegrationName)]
    [Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public class TestMethodRunnerExecuteIntegration
    {
        /// <summary>
        /// OnMethodBegin callback
        /// </summary>
        /// <typeparam name="TTarget">Type of the target</typeparam>
        /// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
        /// <returns>Calltarget state value</returns>
        public static CallTargetState OnMethodBegin<TTarget>(TTarget instance)
        {
            if (!MsTestIntegration.IsEnabled)
            {
                return CallTargetState.GetDefault();
            }

            return new CallTargetState((Scope)null, instance);
        }

        /// <summary>
        /// OnAsyncMethodEnd callback
        /// </summary>
        /// <typeparam name="TTarget">Type of the target</typeparam>
        /// <typeparam name="TReturn">Type of the return value</typeparam>
        /// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
        /// <param name="returnValue">Return value</param>
        /// <param name="exception">Exception instance in case the original code threw an exception.</param>
        /// <param name="state">Calltarget state value</param>
        /// <returns>A response value, in an async scenario will be T of Task of T</returns>
        public static CallTargetReturn<TReturn> OnMethodEnd<TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state)
            where TTarget : ITestMethodRunner
        {
            if (returnValue is Array returnValueArray && returnValueArray.Length == 1)
            {
                object unitTestResultObject = returnValueArray.GetValue(0);
                if (unitTestResultObject != null && unitTestResultObject.TryDuckCast<UnitTestResultStruct>(out var unitTestResult))
                {
                    var outcome = unitTestResult.Outcome;
                    if (outcome == UnitTestResultOutcome.Inconclusive || outcome == UnitTestResultOutcome.NotRunnable || outcome == UnitTestResultOutcome.Ignored)
                    {
                        // This instrumentation catches all tests being ignored
                        if (state.State != null && state.State.TryDuckCast<ITestMethodRunner>(out var testMethodRunner))
                        {
                            var scope = MsTestIntegration.OnMethodBegin(testMethodRunner.TestMethodInfo, testMethodRunner.GetType());
                            scope.Span.SetTag(TestTags.Status, TestTags.StatusSkip);
                            scope.Span.SetTag(TestTags.SkipReason, unitTestResult.ErrorMessage);
                            scope.Dispose();
                        }
                    }
                }
            }

            return new CallTargetReturn<TReturn>(returnValue);
        }
    }
}


@@ -118,29 +118,30 @@ namespace MvvmCross.Droid.Support.V7.RecyclerView
         public IEnumerable ItemsSource
         {
             get { return Adapter.ItemsSource; }
-            set { Adapter.ItemsSource = value; }
+            set
+            {
+                var adapter = Adapter;
+                if (adapter != null)
+                    adapter.ItemsSource = value;
+            }
         }

         public int ItemTemplateId
         {
             get
             {
-                var singleItemDefaultTemplateSelector = ItemTemplateSelector as MvxDefaultTemplateSelector;
-
-                if (singleItemDefaultTemplateSelector == null)
+                if (!(ItemTemplateSelector is MvxDefaultTemplateSelector singleItemDefaultTemplateSelector))
                     throw new InvalidOperationException(
-                        $"If you wan't to use single item-template RecyclerView Adapter you can't change it's" +
+                        $"If you don't want to use single item-template RecyclerView Adapter you can't change it's" +
                         $"{nameof(IMvxTemplateSelector)} to anything other than {nameof(MvxDefaultTemplateSelector)}");

                 return singleItemDefaultTemplateSelector.ItemTemplateId;
             }
             set
             {
-                var singleItemDefaultTemplateSelector = ItemTemplateSelector as MvxDefaultTemplateSelector;
-
-                if (singleItemDefaultTemplateSelector == null)
+                if (!(ItemTemplateSelector is MvxDefaultTemplateSelector singleItemDefaultTemplateSelector))
                     throw new InvalidOperationException(
-                        $"If you wan't to use single item-template RecyclerView Adapter you can't change it's" +
+                        $"If you don't want to use single item-template RecyclerView Adapter you can't change it's" +
                         $"{nameof(IMvxTemplateSelector)} to anything other than {nameof(MvxDefaultTemplateSelector)}");

                 singleItemDefaultTemplateSelector.ItemTemplateId = value;

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections;
using System.Windows.Input;
using Android.Content;
using Android.Runtime;
using Android.Util;
using MvvmCross.Binding.Attributes;
using MvvmCross.Droid.Support.V7.RecyclerView.AttributeHelpers;
using MvvmCross.Droid.Support.V7.RecyclerView.ItemTemplates;
using MvvmCross.Platforms.Android.Binding.Views;

namespace MvvmCross.Droid.Support.V7.RecyclerView
{
    [Register("mvvmcross.droid.support.v7.recyclerview.MvxRecyclerView")]
    public class MvxRecyclerView : Android.Support.V7.Widget.RecyclerView
    {
        public MvxRecyclerView(IntPtr javaReference, JniHandleOwnership transfer)
            : base(javaReference, transfer)
        {
        }

        public MvxRecyclerView(Context context, IAttributeSet attrs) :
            this(context, attrs, 0, new MvxRecyclerAdapter())
        {
        }

        public MvxRecyclerView(Context context, IAttributeSet attrs, int defStyle)
            : this(context, attrs, defStyle, new MvxRecyclerAdapter())
        {
        }

        public MvxRecyclerView(Context context, IAttributeSet attrs, int defStyle, IMvxRecyclerAdapter adapter)
            : base(context, attrs, defStyle)
        {
            // Note: Any calling derived class passing a null adapter is responsible for setting
            // it's own ItemTemplateSelector
            if (adapter == null)
                return;

            var currentLayoutManager = GetLayoutManager();

            // Love you Android
            // https://code.google.com/p/android/issues/detail?id=77846#c10
            // Don't believe those bastards, it's not fixed - workaround hack hack hack
            if (currentLayoutManager == null)
                SetLayoutManager(new MvxGuardedLinearLayoutManager(context));

            var itemTemplateId = MvxAttributeHelpers.ReadListItemTemplateId(context, attrs);
            var itemTemplateSelector = MvxRecyclerViewAttributeExtensions.BuildItemTemplateSelector(context, attrs, itemTemplateId);

            adapter.ItemTemplateSelector = itemTemplateSelector;
            Adapter = adapter;

            if (itemTemplateId == 0)
                itemTemplateId = global::Android.Resource.Layout.SimpleListItem1;

            if (itemTemplateSelector.GetType() == typeof(MvxDefaultTemplateSelector))
                ItemTemplateId = itemTemplateId;
        }

        public sealed override void SetLayoutManager(LayoutManager layout)
        {
            base.SetLayoutManager(layout);
        }

        protected override void OnDetachedFromWindow()
        {
            base.OnDetachedFromWindow();

            // Remove all the views that are currently in play.
            // This clears out all of the ViewHolder DataContexts by detaching the ViewHolder.
            // Eventually the GC will come along and clear out the binding contexts.
            // Issue #1405
            GetLayoutManager()?.RemoveAllViews();
        }

        public new IMvxRecyclerAdapter Adapter
        {
            get
            {
                return GetAdapter() as IMvxRecyclerAdapter;
            }
            set
            {
                var existing = Adapter;

                if (existing == value)
                    return;

                // Support lib doesn't seem to have anything similar to IListAdapter yet
                // hence cast to Adapter.
                if (value != null && existing != null)
                {
                    value.ItemsSource = existing.ItemsSource;
                    value.ItemTemplateSelector = existing.ItemTemplateSelector;
                    value.ItemClick = existing.ItemClick;
                    value.ItemLongClick = existing.ItemLongClick;

                    SwapAdapter((Adapter)value, false);
                }
                else
                {
                    SetAdapter((Adapter)value);
                }

                if (existing != null)
                {
                    existing.ItemsSource = null;
                }
            }
        }

        [MvxSetToNullAfterBinding]
        public IEnumerable ItemsSource
        {
            get { return Adapter.ItemsSource; }
            set { Adapter.ItemsSource = value; }
        }

        public int ItemTemplateId
        {
            get
            {
                var singleItemDefaultTemplateSelector = ItemTemplateSelector as MvxDefaultTemplateSelector;

                if (singleItemDefaultTemplateSelector == null)
                    throw new InvalidOperationException(
                        $"If you wan't to use single item-template RecyclerView Adapter you can't change it's" +
                        $"{nameof(IMvxTemplateSelector)} to anything other than {nameof(MvxDefaultTemplateSelector)}");

                return singleItemDefaultTemplateSelector.ItemTemplateId;
            }
            set
            {
                var singleItemDefaultTemplateSelector = ItemTemplateSelector as MvxDefaultTemplateSelector;

                if (singleItemDefaultTemplateSelector == null)
                    throw new InvalidOperationException(
                        $"If you wan't to use single item-template RecyclerView Adapter you can't change it's" +
                        $"{nameof(IMvxTemplateSelector)} to anything other than {nameof(MvxDefaultTemplateSelector)}");

                singleItemDefaultTemplateSelector.ItemTemplateId = value;
                Adapter.ItemTemplateSelector = singleItemDefaultTemplateSelector;
            }
        }

        public IMvxTemplateSelector ItemTemplateSelector
        {
            get { return Adapter.ItemTemplateSelector; }
            set { Adapter.ItemTemplateSelector = value; }
        }

        public ICommand ItemClick
        {
            get { return Adapter.ItemClick; }
            set { Adapter.ItemClick = value; }
        }

        public ICommand ItemLongClick
        {
            get { return Adapter.ItemLongClick; }
            set { Adapter.ItemLongClick = value; }
        }
    }
}


@@ -53,15 +53,15 @@ namespace MvvmCross.Forms.Platforms.Android.Presenters
             FormsPagePresenter.RegisterAttributeTypes();
         }

-        public override void ChangePresentation(MvxPresentationHint hint)
+        public override async Task<bool> ChangePresentation(MvxPresentationHint hint)
         {
-            FormsPagePresenter.ChangePresentation(hint);
-            base.ChangePresentation(hint);
+            await FormsPagePresenter.ChangePresentation(hint);
+            return await base.ChangePresentation(hint);
         }

-        public override void Close(IMvxViewModel viewModel)
+        public override Task<bool> Close(IMvxViewModel viewModel)
         {
-            FormsPagePresenter.Close(viewModel);
+            return FormsPagePresenter.Close(viewModel);
         }

         public virtual bool ShowPlatformHost(Type hostViewModel = null)

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.

using MvvmCross.Droid.Support.V7.AppCompat;
using MvvmCross.Forms.Presenters;
using System;
using System.Collections.Generic;
using System.Reflection;
using MvvmCross.Forms.Core;
using MvvmCross.Platforms.Android.Views;
using MvvmCross.ViewModels;
using MvvmCross.Forms.Platforms.Android.Views;
using Xamarin.Forms;

namespace MvvmCross.Forms.Platforms.Android.Presenters
{
    public class MvxFormsAndroidViewPresenter
        : MvxAppCompatViewPresenter, IMvxFormsViewPresenter
    {
        public MvxFormsAndroidViewPresenter(IEnumerable<Assembly> androidViewAssemblies, Application formsApplication) : base(androidViewAssemblies)
        {
            FormsApplication = formsApplication ?? throw new ArgumentNullException(nameof(formsApplication), "MvxFormsApplication cannot be null");
        }

        private Application _formsApplication;
        public Application FormsApplication
        {
            get { return _formsApplication; }
            set { _formsApplication = value; }
        }

        private IMvxFormsPagePresenter _formsPagePresenter;
        public virtual IMvxFormsPagePresenter FormsPagePresenter
        {
            get
            {
                if (_formsPagePresenter == null)
                    throw new ArgumentNullException(nameof(FormsPagePresenter), "IMvxFormsPagePresenter cannot be null. Set the value in CreateViewPresenter in the setup.");
                return _formsPagePresenter;
            }
            set { _formsPagePresenter = value; }
        }

        public override void Show(MvxViewModelRequest request)
        {
            FormsPagePresenter.Show(request);
        }

        public override void RegisterAttributeTypes()
        {
            base.RegisterAttributeTypes();
            FormsPagePresenter.RegisterAttributeTypes();
        }

        public override void ChangePresentation(MvxPresentationHint hint)
        {
            FormsPagePresenter.ChangePresentation(hint);
            base.ChangePresentation(hint);
        }

        public override void Close(IMvxViewModel viewModel)
        {
            FormsPagePresenter.Close(viewModel);
        }

        public virtual bool ShowPlatformHost(Type hostViewModel = null)
        {
            // if there is no Actitivty host associated, assume is the current activity
            if (hostViewModel == null)
                hostViewModel = GetCurrentActivityViewModelType();

            var currentHostViewModelType = GetCurrentActivityViewModelType();
            if (hostViewModel != currentHostViewModelType)
            {
                var hostViewModelRequest = MvxViewModelRequest.GetDefaultRequest(hostViewModel);
                Show(hostViewModelRequest);
            }
            return true;
        }

        public virtual bool ClosePlatformViews()
        {
            CloseFragments();
            if (!(CurrentActivity is MvxFormsAppCompatActivity || CurrentActivity is MvxFormsApplicationActivity) &&
                !(CurrentActivity is MvxSplashScreenActivity || CurrentActivity is MvxSplashScreenAppCompatActivity))
                CurrentActivity?.Finish();
            return true;
        }
    }
}


@@ -91,5 +91,24 @@ namespace OpenTelemetry.Exporter

             return ExportResult.Success;
         }
+
+        /// <inheritdoc />
+        protected override bool OnShutdown(int timeoutMilliseconds)
+        {
+            if (this.Channel == null)
+            {
+                return true;
+            }
+
+            if (timeoutMilliseconds == -1)
+            {
+                this.Channel.ShutdownAsync().Wait();
+                return true;
+            }
+            else
+            {
+                return Task.WaitAny(new Task[] { this.Channel.ShutdownAsync(), Task.Delay(timeoutMilliseconds) }) == 0;
+            }
+        }
     }
 }

// <copyright file="OtlpMetricsExporter.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// 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 Grpc.Core;
using OpenTelemetry.Exporter.OpenTelemetryProtocol;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
using OpenTelemetry.Metrics;
using OtlpCollector = Opentelemetry.Proto.Collector.Metrics.V1;

namespace OpenTelemetry.Exporter
{
    /// <summary>
    /// Exporter consuming <see cref="Metric"/> and exporting the data using
    /// the OpenTelemetry protocol (OTLP).
    /// </summary>
    public class OtlpMetricsExporter : BaseOtlpExporter<Metric>
    {
        private readonly OtlpCollector.MetricsService.IMetricsServiceClient metricsClient;

        /// <summary>
        /// Initializes a new instance of the <see cref="OtlpMetricsExporter"/> class.
        /// </summary>
        /// <param name="options">Configuration options for the exporter.</param>
        public OtlpMetricsExporter(OtlpExporterOptions options)
            : this(options, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="OtlpMetricsExporter"/> class.
        /// </summary>
        /// <param name="options">Configuration options for the exporter.</param>
        /// <param name="metricsServiceClient"><see cref="OtlpCollector.MetricsService.IMetricsServiceClient"/>.</param>
        internal OtlpMetricsExporter(OtlpExporterOptions options, OtlpCollector.MetricsService.IMetricsServiceClient metricsServiceClient = null)
            : base(options)
        {
            if (metricsServiceClient != null)
            {
                this.metricsClient = metricsServiceClient;
            }
            else
            {
                this.Channel = options.CreateChannel();
                this.metricsClient = new OtlpCollector.MetricsService.MetricsServiceClient(this.Channel);
            }
        }

        /// <inheritdoc />
        public override ExportResult Export(in Batch<Metric> batch)
        {
            // Prevents the exporter's gRPC and HTTP operations from being instrumented.
            using var scope = SuppressInstrumentationScope.Begin();

            var request = new OtlpCollector.ExportMetricsServiceRequest();

            request.AddBatch(this.ProcessResource, batch);
            var deadline = DateTime.UtcNow.AddMilliseconds(this.Options.TimeoutMilliseconds);

            try
            {
                this.metricsClient.Export(request, headers: this.Headers, deadline: deadline);
            }
            catch (RpcException ex)
            {
                OpenTelemetryProtocolExporterEventSource.Log.FailedToReachCollector(ex);
                return ExportResult.Failure;
            }
            catch (Exception ex)
            {
                OpenTelemetryProtocolExporterEventSource.Log.ExportMethodException(ex);
                return ExportResult.Failure;
            }
            finally
            {
                request.Return();
            }

            return ExportResult.Success;
        }
    }
}


@@ -3,6 +3,7 @@

 using System;
 using System.Collections.Generic;
+using System.Linq;
 using System.Reflection;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Hosting.Server;

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Http;
using Microsoft.AspNetCore.Server.Kestrel.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Server.Kestrel
{
    public class KestrelServer : IServer
    {
        private Stack<IDisposable> _disposables;
        private readonly IApplicationLifetime _applicationLifetime;
        private readonly ILogger _logger;
        private readonly IServerAddressesFeature _serverAddresses;

        public KestrelServer(IOptions<KestrelServerOptions> options, IApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (applicationLifetime == null)
            {
                throw new ArgumentNullException(nameof(applicationLifetime));
            }

            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            Options = options.Value ?? new KestrelServerOptions();
            _applicationLifetime = applicationLifetime;
            _logger = loggerFactory.CreateLogger(typeof(KestrelServer).GetTypeInfo().Namespace);
            Features = new FeatureCollection();
            var componentFactory = new HttpComponentFactory(Options);
            Features.Set<IHttpComponentFactory>(componentFactory);
            _serverAddresses = new ServerAddressesFeature();
            Features.Set<IServerAddressesFeature>(_serverAddresses);
        }

        public IFeatureCollection Features { get; }

        public KestrelServerOptions Options { get; }

        public void Start<TContext>(IHttpApplication<TContext> application)
        {
            if (_disposables != null)
            {
                // The server has already started and/or has not been cleaned up yet
                throw new InvalidOperationException("Server has already started.");
            }
            _disposables = new Stack<IDisposable>();

            try
            {
                var componentFactory = Features.Get<IHttpComponentFactory>();
                var dateHeaderValueManager = new DateHeaderValueManager();
                var trace = new KestrelTrace(_logger);
                var engine = new KestrelEngine(new ServiceContext
                {
                    FrameFactory = context =>
                    {
                        return new Frame<TContext>(application, context);
                    },
                    AppLifetime = _applicationLifetime,
                    Log = trace,
                    ThreadPool = new LoggingThreadPool(trace),
                    DateHeaderValueManager = dateHeaderValueManager,
                    ServerOptions = Options,
                    HttpComponentFactory = componentFactory
                });

                _disposables.Push(engine);
                _disposables.Push(dateHeaderValueManager);

                var threadCount = Options.ThreadCount;

                if (threadCount <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(threadCount),
                        threadCount,
                        "ThreadCount must be positive.");
                }

                engine.Start(threadCount);
                var atLeastOneListener = false;

                foreach (var address in _serverAddresses.Addresses)
                {
                    var parsedAddress = ServerAddress.FromUrl(address);
                    if (parsedAddress == null)
                    {
                        throw new FormatException("Unrecognized listening address: " + address);
                    }
                    else
                    {
                        atLeastOneListener = true;
                        _disposables.Push(engine.CreateServer(
                            parsedAddress));
                    }
                }

                if (!atLeastOneListener)
                {
                    throw new InvalidOperationException("No recognized listening addresses were configured.");
                }
            }
            catch
            {
                Dispose();
                throw;
            }
        }

        public void Dispose()
        {
            if (_disposables != null)
            {
                while (_disposables.Count > 0)
                {
                    _disposables.Pop().Dispose();
                }
                _disposables = null;
            }
        }
    }
}


@@ -42,11 +42,15 @@ namespace pwiz.Common.SystemUtil
         private Exception _readException;

         private readonly List<string> _readLines = new List<string>();
+        private StringBuilder _errorLines;

-        public ProcessStreamReader(Process process)
+        public ProcessStreamReader(Process process, bool keepErrorLines = false)
         {
-            Thread threadOut = new Thread(() => ReadStream(process.StandardOutput, ref _isOutComplete));
-            Thread threadErr = new Thread(() => ReadStream(process.StandardError, ref _isErrComplete));
+            if (keepErrorLines)
+                _errorLines = new StringBuilder();
+
+            Thread threadOut = new Thread(() => ReadStream(process.StandardOutput, ref _isOutComplete, null));
+            Thread threadErr = new Thread(() => ReadStream(process.StandardError, ref _isErrComplete, _errorLines));
             threadOut.Start();
             threadErr.Start();
         }

/*
 * Original author: Nicholas Shulman <nicksh .at. u.washington.edu>,
 *                  MacCoss Lab, Department of Genome Sciences, UW
 *
 * Copyright 2009 University of Washington - Seattle, WA
 *
 * 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.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace pwiz.Common.SystemUtil
{
    /// <summary>
    /// Class for reading both standard out and standard error from a process.
    /// <para>
    /// This is a tough problem, since TextReader.ReadLine() blocks, until it
    /// has a line to return, or the process ends.  It did not seem possible
    /// to solve this on a single thread to present real-time feedback to the
    /// user based on process output.
    /// </para><para>
    /// One solution presented on the web looked promising, but it did not
    /// correctly interleave output from both streams reliably.</para>
    /// </summary>
    public class ProcessStreamReader
    {
        private bool _isOutComplete;
        private bool _isErrComplete;
        private Exception _readException;

        private readonly List<string> _readLines = new List<string>();

        public ProcessStreamReader(Process process)
        {
            Thread threadOut = new Thread(() => ReadStream(process.StandardOutput, ref _isOutComplete));
            Thread threadErr = new Thread(() => ReadStream(process.StandardError, ref _isErrComplete));
            threadOut.Start();
            threadErr.Start();
        }

        /// <summary>
        /// Public access to read the next line from the interleaved output
        /// of both standard out and standard error.
        /// </summary>
        public string ReadLine(IProgressMonitor progressMonitor)
        {
            int timeout = progressMonitor == null ? Timeout.Infinite : 10000;
            lock (_readLines)
            {
                for (;;)
                {
                    if (progressMonitor != null && progressMonitor.IsCanceled)
                    {
                        return string.Empty;
                    }
                    if (_readLines.Count > 0)
                    {
                        string line = _readLines[0];
                        _readLines.RemoveAt(0);
                        return line;
                    }
                    if (_readException != null)
                        throw _readException;
                    if (_isOutComplete && _isErrComplete)
                        return null;
                    Monitor.Wait(_readLines, timeout);
                }
            }
        }

        public string ReadLine()
        {
            return ReadLine(null);
        }

        /// <summary>
        /// Handles reading from a single stream, and noting its completion
        /// on a background thread.
        /// </summary>
        private void ReadStream(TextReader reader, ref bool isComplete)
        {
            try
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lock (_readLines)
                    {
                        _readLines.Add(line);
                        Monitor.Pulse(_readLines);
                    }
                }

                lock(_readLines)
                {
                    isComplete = true;
                    Monitor.Pulse(_readLines);
                }
            }
            catch (Exception x)
            {
                lock (_readLines)
                {
                    _readException = x;
                    Monitor.Pulse(_readLines);
                }
            }
        }
    }
}


@@ -1,4 +1,4 @@
-// MvxAppStart.cs
+// MvxAppStart.cs

 // MvvmCross is licensed using Microsoft Public License (Ms-PL)
 // Contributions and inspirations noted in readme.md and license.txt

// MvxAppStart.cs

// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using System;
using MvvmCross.Platform.Platform;

namespace MvvmCross.Core.ViewModels
{
    [Obsolete("Please use MvxNavigationServiceAppStart instead")]
    public class MvxAppStart<TViewModel>
        : MvxNavigatingObject, IMvxAppStart
        where TViewModel : IMvxViewModel
    {
        public void Start(object hint = null)
        {
            if (hint != null)
            {
                MvxTrace.Trace("Hint ignored in default MvxAppStart");
            }
            ShowViewModel<TViewModel>();
        }
    }
}


@@ -16,6 +16,7 @@

 using FluentAssertions;
 using Nethermind.Blockchain.Validators;
+using Nethermind.Core;
 using Nethermind.Core.Crypto;
 using Nethermind.Core.Specs;
 using Nethermind.Core.Test.Builders;

//  Copyright (c) 2021 Demerzel Solutions Limited
//  This file is part of the Nethermind library.
//
//  The Nethermind library is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  The Nethermind library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.

using FluentAssertions;
using Nethermind.Blockchain.Validators;
using Nethermind.Core.Crypto;
using Nethermind.Core.Specs;
using Nethermind.Core.Test.Builders;
using Nethermind.Specs.Forks;
using NSubstitute;
using NUnit.Framework;

namespace Nethermind.Blockchain.Test.Validators
{
    [TestFixture]
    public class TxValidatorTests
    {
        [SetUp]
        public void Setup()
        {
        }

        [Test]
        public void Zero_r_is_not_valid()
        {
            byte[] sigData = new byte[65];
            // r is zero
            sigData[63] = 1; // correct s

            Signature signature = new Signature(sigData);
            var tx = Build.A.Transaction.WithSignature(signature).TestObject;

            TxValidator txValidator = new TxValidator(1);
            txValidator.IsWellFormed(tx, MuirGlacier.Instance).Should().BeFalse();
        }

        [Test]
        public void Zero_s_is_not_valid()
        {
            byte[] sigData = new byte[65];
            sigData[31] = 1; // correct r
            // s is zero

            Signature signature = new Signature(sigData);
            var tx = Build.A.Transaction.WithSignature(signature).TestObject;

            TxValidator txValidator = new TxValidator(1);
            txValidator.IsWellFormed(tx, MuirGlacier.Instance).Should().BeFalse();
        }

        [Test]
        public void Bad_chain_id_is_not_valid()
        {
            byte[] sigData = new byte[65];
            sigData[31] = 1; // correct r
            sigData[63] = 1; // correct s
            sigData[64] = 39;
            Signature signature = new Signature(sigData);
            var tx = Build.A.Transaction.WithSignature(signature).TestObject;

            TxValidator txValidator = new TxValidator(1);
            txValidator.IsWellFormed(tx, MuirGlacier.Instance).Should().BeFalse();
        }

        [Test]
        public void No_chain_id_tx_is_valid()
        {
            byte[] sigData = new byte[65];
            sigData[31] = 1; // correct r
            sigData[63] = 1; // correct s
            Signature signature = new Signature(sigData);
            var tx = Build.A.Transaction.WithSignature(signature).TestObject;

            TxValidator txValidator = new TxValidator(1);
            txValidator.IsWellFormed(tx, MuirGlacier.Instance).Should().BeTrue();
        }

        [Test]
        public void Is_valid_with_valid_chain_id()
        {
            byte[] sigData = new byte[65];
            sigData[31] = 1; // correct r
            sigData[63] = 1; // correct s
            sigData[64] = 38;
            Signature signature = new Signature(sigData);
            var tx = Build.A.Transaction.WithSignature(signature).TestObject;

            TxValidator txValidator = new TxValidator(1);
            txValidator.IsWellFormed(tx, MuirGlacier.Instance).Should().BeTrue();
        }

        [TestCase(true)]
        [TestCase(false)]
        public void Before_eip_155_has_to_have_valid_chain_id_unless_overridden(bool validateChainId)
        {
            byte[] sigData = new byte[65];
            sigData[31] = 1; // correct r
            sigData[63] = 1; // correct s
            sigData[64] = 41;
            Signature signature = new Signature(sigData);
            var tx = Build.A.Transaction.WithSignature(signature).TestObject;

            IReleaseSpec releaseSpec = Substitute.For<IReleaseSpec>();
            releaseSpec.IsEip155Enabled.Returns(false);
            releaseSpec.ValidateChainId.Returns(validateChainId);

            TxValidator txValidator = new TxValidator(1);
            txValidator.IsWellFormed(tx, releaseSpec).Should().Be(!validateChainId);
        }
    }
}


@@ -79,6 +79,11 @@ namespace Nethermind.JsonRpc.Data
         [JsonProperty(NullValueHandling = NullValueHandling.Include)]
         public byte[]? Input { get; set; }

+        [JsonConverter(typeof(ByteConverter))]
+        public byte Type { get; set; }
+
+        public AccessListItemForRpc[]? AccessList { get; set; }
+
         public UInt256? V { get; set; }

         public UInt256? S { get; set; }

//  Copyright (c) 2021 Demerzel Solutions Limited
//  This file is part of the Nethermind library.
//
//  The Nethermind library is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  The Nethermind library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.

using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Extensions;
using Nethermind.Int256;
using Newtonsoft.Json;

namespace Nethermind.JsonRpc.Data
{
    public class TransactionForRpc
    {
        public TransactionForRpc(Transaction transaction) : this(null, null, null, transaction) { }

        public TransactionForRpc(Keccak? blockHash, long? blockNumber, int? txIndex, Transaction transaction)
        {
            Hash = transaction.Hash;
            Nonce = transaction.Nonce;
            BlockHash = blockHash;
            BlockNumber = blockNumber;
            TransactionIndex = txIndex;
            From = transaction.SenderAddress;
            To = transaction.To;
            Value = transaction.Value;
            GasPrice = transaction.GasPrice;
            Gas = transaction.GasLimit;
            Input = Data = transaction.Data;

            Signature? signature = transaction.Signature;
            if (signature != null)
            {
                R = new UInt256(signature.R, true);
                S = new UInt256(signature.S, true);
                V = (UInt256?)signature.V;
            }
        }

        // ReSharper disable once UnusedMember.Global
        public TransactionForRpc()
        {
        }

        public Keccak? Hash { get; set; }
        public UInt256? Nonce { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Include)]
        public Keccak? BlockHash { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Include)]
        public long? BlockNumber { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Include)]
        public long? TransactionIndex { get; set; }

        public Address? From { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Include)]
        public Address? To { get; set; }

        public UInt256? Value { get; set; }
        public UInt256? GasPrice { get; set; }
        public long? Gas { get; set; }
        public byte[]? Data { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Include)]
        public byte[]? Input { get; set; }

        public UInt256? V { get; set; }

        public UInt256? S { get; set; }

        public UInt256? R { get; set; }

        public Transaction ToTransactionWithDefaults()
        {
            Transaction tx = new();
            tx.GasLimit = Gas ?? 90000;
            tx.GasPrice = GasPrice ?? 20.GWei();
            tx.Nonce = (ulong)(Nonce ?? 0); // here pick the last nonce?
            tx.To = To;
            tx.SenderAddress = From;
            tx.Value = Value ?? 0;
            tx.Data = Data ?? Input;

            return tx;
        }

        public Transaction ToTransaction()
        {
            Transaction tx = new();
            tx.GasLimit = Gas ?? 0;
            tx.GasPrice = GasPrice ?? 0;
            tx.Nonce = (ulong)(Nonce ?? 0); // here pick the last nonce?
            tx.To = To;
            tx.SenderAddress = From;
            tx.Value = Value ?? 0;
            tx.Data = Data ?? Input;

            return tx;
        }
    }
}


@@ -6,9 +6,7 @@ using System.Buffers;
 using System.IO.Pipelines;
 using System.Threading;
 using System.Threading.Tasks;
-using Microsoft.AspNetCore.Http.Features;
 using Microsoft.AspNetCore.Connections;
-using Microsoft.AspNetCore.Connections.Features;
 using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
 using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
 using Microsoft.Extensions.Logging;

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
{
    public class ConnectionDispatcher : IConnectionDispatcher
    {
        private static long _lastConnectionId = long.MinValue;

        private readonly ServiceContext _serviceContext;
        private readonly ConnectionDelegate _connectionDelegate;

        public ConnectionDispatcher(ServiceContext serviceContext, ConnectionDelegate connectionDelegate)
        {
            _serviceContext = serviceContext;
            _connectionDelegate = connectionDelegate;
        }

        private IKestrelTrace Log => _serviceContext.Log;

        public Task OnConnection(TransportConnection connection)
        {
            // REVIEW: Unfortunately, we still need to use the service context to create the pipes since the settings
            // for the scheduler and limits are specified here
            var inputOptions = GetInputPipeOptions(_serviceContext, connection.MemoryPool, connection.InputWriterScheduler);
            var outputOptions = GetOutputPipeOptions(_serviceContext, connection.MemoryPool, connection.OutputReaderScheduler);

            var pair = DuplexPipe.CreateConnectionPair(inputOptions, outputOptions);

            // Set the transport and connection id
            connection.ConnectionId = CorrelationIdGenerator.GetNextId();
            connection.Transport = pair.Transport;

            // This *must* be set before returning from OnConnection
            connection.Application = pair.Application;

            return Execute(new KestrelConnection(connection));
        }

        private async Task Execute(KestrelConnection connection)
        {
            var id = Interlocked.Increment(ref _lastConnectionId);
            var connectionContext = connection.TransportConnection;

            try
            {
                _serviceContext.ConnectionManager.AddConnection(id, connection);

                Log.ConnectionStart(connectionContext.ConnectionId);
                KestrelEventSource.Log.ConnectionStart(connectionContext);

                using (BeginConnectionScope(connectionContext))
                {
                    try
                    {
                        await _connectionDelegate(connectionContext);
                    }
                    catch (Exception ex)
                    {
                        Log.LogCritical(0, ex, $"{nameof(ConnectionDispatcher)}.{nameof(Execute)}() {connectionContext.ConnectionId}");
                    }
                    finally
                    {
                        // Complete the transport PipeReader and PipeWriter after calling into application code
                        connectionContext.Transport.Input.Complete();
                        connectionContext.Transport.Output.Complete();
                    }

                    // Wait for the transport to close
                    await CancellationTokenAsTask(connectionContext.ConnectionClosed);
                }
            }
            finally
            {
                Log.ConnectionStop(connectionContext.ConnectionId);
                KestrelEventSource.Log.ConnectionStop(connectionContext);

                connection.Complete();

                _serviceContext.ConnectionManager.RemoveConnection(id);
            }
        }

        private IDisposable BeginConnectionScope(ConnectionContext connectionContext)
        {
            if (Log.IsEnabled(LogLevel.Critical))
            {
                return Log.BeginScope(new ConnectionLogScope(connectionContext.ConnectionId));
            }

            return null;
        }

        private static Task CancellationTokenAsTask(CancellationToken token)
        {
            if (token.IsCancellationRequested)
            {
                return Task.CompletedTask;
            }

            // Transports already dispatch prior to tripping ConnectionClosed
            // since application code can register to this token.
            var tcs = new TaskCompletionSource<object>();
            token.Register(state => ((TaskCompletionSource<object>)state).SetResult(null), tcs);
            return tcs.Task;
        }

        // Internal for testing
        internal static PipeOptions GetInputPipeOptions(ServiceContext serviceContext, MemoryPool<byte> memoryPool, PipeScheduler writerScheduler) => new PipeOptions
        (
            pool: memoryPool,
            readerScheduler: serviceContext.Scheduler,
            writerScheduler: writerScheduler,
            pauseWriterThreshold: serviceContext.ServerOptions.Limits.MaxRequestBufferSize ?? 0,
            resumeWriterThreshold: serviceContext.ServerOptions.Limits.MaxRequestBufferSize ?? 0,
            useSynchronizationContext: false,
            minimumSegmentSize: KestrelMemoryPool.MinimumSegmentSize
        );

        internal static PipeOptions GetOutputPipeOptions(ServiceContext serviceContext, MemoryPool<byte> memoryPool, PipeScheduler readerScheduler) => new PipeOptions
        (
            pool: memoryPool,
            readerScheduler: readerScheduler,
            writerScheduler: serviceContext.Scheduler,
            pauseWriterThreshold: GetOutputResponseBufferSize(serviceContext),
            resumeWriterThreshold: GetOutputResponseBufferSize(serviceContext),
            useSynchronizationContext: false,
            minimumSegmentSize: KestrelMemoryPool.MinimumSegmentSize
        );

        private static long GetOutputResponseBufferSize(ServiceContext serviceContext)
        {
            var bufferSize = serviceContext.ServerOptions.Limits.MaxResponseBufferSize;
            if (bufferSize == 0)
            {
                // 0 = no buffering so we need to configure the pipe so the the writer waits on the reader directly
                return 1;
            }

            // null means that we have no back pressure
            return bufferSize ?? 0;
        }
    }
}


@@ -11,6 +11,7 @@ namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities
     using Microsoft.VisualStudio.TestPlatform.Common.Interfaces;
     using Microsoft.VisualStudio.TestPlatform.ObjectModel;
     using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities;
+    using Microsoft.VisualStudio.TestPlatform.Common;

     /// <summary>
     /// Utilities to get the run settings from the provider and the commandline options specified.

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities
{
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Xml;

    using Microsoft.VisualStudio.TestPlatform.Utilities;
    using Microsoft.VisualStudio.TestPlatform.Common.Interfaces;
    using Microsoft.VisualStudio.TestPlatform.ObjectModel;
    using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities;

    /// <summary>
    /// Utilities to get the run settings from the provider and the commandline options specified.
    /// </summary>
    internal class RunSettingsUtilities
    {
        private const string EmptyRunSettings = @"<RunSettings></RunSettings>";

        /// <summary>
        /// Gets the run settings to be used for the session.
        /// </summary>
        /// <param name="runSettingsProvider"> The current provider of run settings.</param>
        /// <param name="commandlineOptions"> The command line options specified. </param>
        /// <returns></returns>
        internal static string GetRunSettings(IRunSettingsProvider runSettingsProvider, CommandLineOptions commandlineOptions)
        {
            var runSettings = runSettingsProvider?.ActiveRunSettings?.SettingsXml;

            if (string.IsNullOrWhiteSpace(runSettings))
            {
                runSettings = EmptyRunSettings;
            }

            runSettings = GetEffectiveRunSettings(runSettings, commandlineOptions);

            return runSettings;
        }

        /// <summary>
        /// Gets the effective run settings adding the commandline options to the run settings if not already present.
        /// </summary>
        /// <param name="runSettings"> The run settings XML. </param>
        /// <param name="commandLineOptions"> The command line options. </param>
        /// <returns> Effective run settings. </returns>
        [SuppressMessage("Microsoft.Security.Xml", "CA3053:UseXmlSecureResolver",
            Justification = "XmlDocument.XmlResolver is not available in core. Suppress until fxcop issue is fixed.")]
        private static string GetEffectiveRunSettings(string runSettings, CommandLineOptions commandLineOptions)
        {
            var architecture = Constants.DefaultPlatform;

            if (commandLineOptions != null && commandLineOptions.ArchitectureSpecified)
            {
                architecture = commandLineOptions.TargetArchitecture;
            }

            var framework = Framework.DefaultFramework;

            if (commandLineOptions != null && commandLineOptions.FrameworkVersionSpecified)
            {
                framework = commandLineOptions.TargetFrameworkVersion;
            }

            var defaultResultsDirectory = Path.Combine(Directory.GetCurrentDirectory(), Constants.ResultsDirectoryName);

            using (var stream = new StringReader(runSettings))
            using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings))
            {
                var document = new XmlDocument();
                document.Load(reader);

                var navigator = document.CreateNavigator();

                InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(navigator, architecture, framework, defaultResultsDirectory);

                if (commandLineOptions != null && commandLineOptions.Parallel)
                {
                    ParallelRunSettingsUtilities.UpdateRunSettingsWithParallelSettingIfNotConfigured(navigator);
                }

                return navigator.OuterXml;
            }
        }
    }
}


@@ -120,6 +120,7 @@ namespace Nethermind.DataMarketplace.Infrastructure
             EthJsonRpcClientProxy = ethJsonRpcClientProxy;
             HttpClient = httpClient;
             MonitoringService = monitoringService;
+            BloomStorage = bloomStorage;
         }
     }
 }

//  Copyright (c) 2018 Demerzel Solutions Limited
//  This file is part of the Nethermind library.
//
//  The Nethermind library is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  The Nethermind library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.

using Nethermind.Blockchain;
using Nethermind.Blockchain.Filters;
using Nethermind.Blockchain.Receipts;
using Nethermind.Blockchain.TxPools;
using Nethermind.Config;
using Nethermind.Core;
using Nethermind.Core.Crypto;
using Nethermind.Core.Specs;
using Nethermind.Crypto;
using Nethermind.Specs;
using Nethermind.DataMarketplace.Channels;
using Nethermind.DataMarketplace.Core;
using Nethermind.DataMarketplace.Core.Configs;
using Nethermind.DataMarketplace.Core.Services;
using Nethermind.DataMarketplace.Infrastructure.Persistence.Mongo;
using Nethermind.Facade.Proxy;
using Nethermind.Grpc;
using Nethermind.JsonRpc.Modules;
using Nethermind.KeyStore;
using Nethermind.Logging;
using Nethermind.Monitoring;
using Nethermind.Network;
using Nethermind.Serialization.Json;
using Nethermind.Store;
using Nethermind.Wallet;

namespace Nethermind.DataMarketplace.Infrastructure
{
    public class NdmRequiredServices
    {
        public IConfigProvider ConfigProvider { get; }
        public IConfigManager ConfigManager { get; }
        public INdmConfig NdmConfig { get; }
        public string BaseDbPath { get; }
        public IDbProvider RocksProvider { get; }
        public IMongoProvider MongoProvider { get; }
        public ILogManager LogManager { get; }
        public IBlockTree BlockTree { get; }
        public ITxPool TransactionPool { get; }
        public ISpecProvider SpecProvider { get; }
        public IReceiptStorage ReceiptStorage { get; }
        public IFilterStore FilterStore { get; }
        public IFilterManager FilterManager { get; }
        public IWallet Wallet { get; }
        public ITimestamper Timestamper { get; }
        public IEthereumEcdsa Ecdsa { get; }
        public IKeyStore KeyStore { get; }
        public IRpcModuleProvider RpcModuleProvider { get; }
        public IJsonSerializer JsonSerializer { get; }
        public ICryptoRandom CryptoRandom { get; }
        public IEnode Enode { get; }
        public INdmConsumerChannelManager NdmConsumerChannelManager { get; }
        public INdmDataPublisher NdmDataPublisher { get; }
        public IGrpcServer GrpcServer { get; }
        public IEthRequestService EthRequestService { get; }
        public INdmNotifier Notifier { get; }
        public bool EnableUnsecuredDevWallet { get; }
        public IBlockProcessor BlockProcessor { get; }
        public IJsonRpcClientProxy JsonRpcClientProxy { get; }
        public IEthJsonRpcClientProxy EthJsonRpcClientProxy { get; }
        public IHttpClient HttpClient { get; }
        public IMonitoringService MonitoringService { get; }

        public NdmRequiredServices(IConfigProvider configProvider, IConfigManager configManager, INdmConfig ndmConfig,
            string baseDbPath, IDbProvider rocksProvider, IMongoProvider mongoProvider, ILogManager logManager,
            IBlockTree blockTree, ITxPool transactionPool, ISpecProvider specProvider, IReceiptStorage receiptStorage,
            IFilterStore filterStore, IFilterManager filterManager, IWallet wallet, ITimestamper timestamper,
            IEthereumEcdsa ecdsa, IKeyStore keyStore, IRpcModuleProvider rpcModuleProvider,
            IJsonSerializer jsonSerializer, ICryptoRandom cryptoRandom, IEnode enode,
            INdmConsumerChannelManager ndmConsumerChannelManager, INdmDataPublisher ndmDataPublisher,
            IGrpcServer grpcServer, IEthRequestService ethRequestService, INdmNotifier notifier,
            bool enableUnsecuredDevWallet, IBlockProcessor blockProcessor, IJsonRpcClientProxy jsonRpcClientProxy,
            IEthJsonRpcClientProxy ethJsonRpcClientProxy, IHttpClient httpClient, IMonitoringService monitoringService)
        {
            ConfigProvider = configProvider;
            ConfigManager = configManager;
            NdmConfig = ndmConfig;
            BaseDbPath = baseDbPath;
            RocksProvider = rocksProvider;
            MongoProvider = mongoProvider;
            LogManager = logManager;
            BlockTree = blockTree;
            TransactionPool = transactionPool;
            SpecProvider = specProvider;
            ReceiptStorage = receiptStorage;
            FilterStore = filterStore;
            FilterManager = filterManager;
            Wallet = wallet;
            Timestamper = timestamper;
            Ecdsa = ecdsa;
            KeyStore = keyStore;
            RpcModuleProvider = rpcModuleProvider;
            JsonSerializer = jsonSerializer;
            CryptoRandom = cryptoRandom;
            Enode = enode;
            NdmConsumerChannelManager = ndmConsumerChannelManager;
            NdmDataPublisher = ndmDataPublisher;
            GrpcServer = grpcServer;
            EthRequestService = ethRequestService;
            Notifier = notifier;
            EnableUnsecuredDevWallet = enableUnsecuredDevWallet;
            BlockProcessor = blockProcessor;
            JsonRpcClientProxy = jsonRpcClientProxy;
            EthJsonRpcClientProxy = ethJsonRpcClientProxy;
            HttpClient = httpClient;
            MonitoringService = monitoringService;
        }
    }
}


@@ -11,7 +11,6 @@ namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.DataCollection
     using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.DataCollection.Interfaces;
     using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers;
     using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers.Interfaces;
-    using Microsoft.VisualStudio.TestPlatform.ObjectModel;

     /// <summary>
     /// The datacollection launcher.

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.DataCollection
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;

    using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.DataCollection.Interfaces;
    using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers;
    using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers.Interfaces;
    using Microsoft.VisualStudio.TestPlatform.ObjectModel;

    /// <summary>
    /// The datacollection launcher.
    /// This works for Desktop local scenarios
    /// </summary>
    internal class DataCollectionLauncher : IDataCollectionLauncher
    {
        private const string DataCollectorProcessName = "datacollector.exe";
        private const string DotnetProcessName = "dotnet.exe";
        private const string DotnetProcessNameXPlat = "dotnet";

        private string dataCollectorProcessName;
        private Process dataCollectorProcess;
        private IProcessHelper processHelper;

        /// <summary>
        /// The constructor.
        /// </summary>
        public DataCollectionLauncher()
            : this(new ProcessHelper())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DataCollectionLauncher"/> class.
        /// </summary>
        /// <param name="processHelper">
        /// The process helper.
        /// </param>
        internal DataCollectionLauncher(IProcessHelper processHelper)
        {
            this.processHelper = processHelper;
            this.dataCollectorProcess = null;
        }

        /// <summary>
        /// Initialize with desired architecture for the host
        /// </summary>
        /// <param name="architecture">architecture for the host</param>
        public void Initialize(Architecture architecture)
        {
            this.dataCollectorProcessName = DataCollectorProcessName;
        }

        /// <summary>
        /// Launches the test host for discovery/execution.
        /// </summary>
        /// <param name="environmentVariables">Environment variables for the process.</param>
        /// <param name="commandLineArguments">The command line arguments to pass to the process.</param>
        /// <returns>ProcessId of launched Process. 0 means not launched.</returns>
        public virtual int LaunchDataCollector(IDictionary<string, string> environmentVariables, IList<string> commandLineArguments)
        {
            var currentWorkingDirectory = Path.GetDirectoryName(typeof(DataCollectionLauncher).GetTypeInfo().Assembly.Location);
            string dataCollectorProcessPath, processWorkingDirectory = null;

            // TODO: DRY: Move this code to a common place
            // If we are running in the dotnet.exe context we do not want to launch dataCollector.exe but dotnet.exe with the dataCollector assembly.
            // Since dotnet.exe is already built for multiple platforms this would avoid building dataCollector.exe also in multiple platforms.
            var currentProcessFileName = this.processHelper.GetCurrentProcessFileName();
            if (currentProcessFileName.EndsWith(DotnetProcessName) || currentProcessFileName.EndsWith(DotnetProcessNameXPlat))
            {
                dataCollectorProcessPath = currentProcessFileName;
                var dataCollectorAssemblyPath = Path.Combine(currentWorkingDirectory, this.dataCollectorProcessName.Replace("exe", "dll"));
                commandLineArguments.Insert(0, dataCollectorAssemblyPath);
                processWorkingDirectory = Path.GetDirectoryName(currentProcessFileName);
            }
            else
            {
                dataCollectorProcessPath = Path.Combine(currentWorkingDirectory, this.dataCollectorProcessName);
                // For IDEs and other scenario - Current directory should be the working directory - not the vstest.console.exe location
                // For VS - this becomes the solution directory for example
                // "TestResults" directory will be created at "current directory" of test host
                processWorkingDirectory = Directory.GetCurrentDirectory();
            }

            var argumentsString = string.Join(" ", commandLineArguments);

            this.dataCollectorProcess = this.processHelper.LaunchProcess(dataCollectorProcessPath, argumentsString, processWorkingDirectory);
            return this.dataCollectorProcess.Id;
        }

    }
}


@@ -63,7 +63,7 @@ namespace Microsoft.AspNet.Server.Kestrel.Networking
             }
             catch (Exception ex)
             {
-                Trace.WriteLine("UvConnectRequest " + ex.ToString());
+                req._log.LogError("UvConnectRequest", ex);
             }
         }
     }

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Microsoft.AspNet.Server.Kestrel.Networking
{
    /// <summary>
    /// Summary description for UvWriteRequest
    /// </summary>
    public class UvConnectRequest : UvRequest
    {
        private readonly static Libuv.uv_connect_cb _uv_connect_cb = UvConnectCb;

        private Action<UvConnectRequest, int, Exception, object> _callback;
        private object _state;

        public void Init(UvLoopHandle loop)
        {
            var requestSize = loop.Libuv.req_size(Libuv.RequestType.CONNECT);
            CreateMemory(
                loop.Libuv,
                loop.ThreadId,
                requestSize);
        }

        public void Connect(
            UvPipeHandle pipe,
            string name,
            Action<UvConnectRequest, int, Exception, object> callback,
            object state)
        {
            _callback = callback;
            _state = state;

            Pin();
            Libuv.pipe_connect(this, pipe, name, _uv_connect_cb);
        }

        private static void UvConnectCb(IntPtr ptr, int status)
        {
            var req = FromIntPtr<UvConnectRequest>(ptr);
            req.Unpin();

            var callback = req._callback;
            req._callback = null;

            var state = req._state;
            req._state = null;

            Exception error = null;
            if (status < 0)
            {
                req.Libuv.Check(status, out error);
            }

            try
            {
                callback(req, status, error, state);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("UvConnectRequest " + ex.ToString());
            }
        }
    }
}