// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Rulesets.Osu.Edit;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Tests.Visual;
using osuTK.Input;

namespace osu.Game.Rulesets.Osu.Tests.Editor
{
    public class TestSceneOsuEditorGrids : EditorTestScene
    {
        protected override Ruleset CreateEditorRuleset() => new OsuRuleset();

        [Test]
        public void TestGridExclusivity()
        {
            AddStep("enable distance snap grid", () => InputManager.Key(Key.T));
            AddStep("select second object", () => EditorBeatmap.SelectedHitObjects.Add(EditorBeatmap.HitObjects.ElementAt(1)));
            AddUntilStep("distance snap grid visible", () => this.ChildrenOfType<OsuDistanceSnapGrid>().Any());

            AddStep("enable rectangular grid", () => InputManager.Key(Key.Y));
            AddUntilStep("distance snap grid hidden", () => !this.ChildrenOfType<OsuDistanceSnapGrid>().Any());
            AddUntilStep("rectangular grid visible", () => this.ChildrenOfType<RectangularPositionSnapGrid>().Any());

            AddStep("enable distance snap grid", () => InputManager.Key(Key.T));
            AddUntilStep("distance snap grid visible", () => this.ChildrenOfType<OsuDistanceSnapGrid>().Any());
            AddUntilStep("rectangular grid hidden", () => !this.ChildrenOfType<RectangularPositionSnapGrid>().Any());
        }
    }
}

Add test coverage for distance/rectangular grid exclusivity


using GitTools.Testing;
using LibGit2Sharp;
using NUnit.Framework;
using System.IO;
using GitVersionCore.Tests.Helpers;

namespace GitVersionCore.Tests.IntegrationTests
{

    [TestFixture]
    public class WorktreeScenarios : TestBase
    {

        [Test]
        [Category("NoMono")]
        [Description("LibGit2Sharp fails here when running under Mono")]
        public void UseWorktreeRepositoryForVersion()
        {
            using var fixture = new EmptyRepositoryFixture();
            var repoDir = new DirectoryInfo(fixture.RepositoryPath);
            var worktreePath = Path.Combine(repoDir.Parent.FullName, $"{repoDir.Name}-v1");

            fixture.Repository.MakeATaggedCommit("v1.0.0");
            var branchV1 = fixture.Repository.CreateBranch("support/1.0");

            fixture.Repository.MakeATaggedCommit("v2.0.0");
            fixture.AssertFullSemver("2.0.0");

            fixture.Repository.Worktrees.Add(branchV1.CanonicalName, "1.0", worktreePath, false);
            using var worktreeFixture = new LocalRepositoryFixture(new Repository(worktreePath));
            worktreeFixture.AssertFullSemver("1.0.0");
        }

    }
}

Add a worktree repository test

Add a worktree repository test


using JetBrains.Annotations;
using JetBrains.Application.changes;
using JetBrains.Application.FileSystemTracker;
using JetBrains.Application.Threading;
using JetBrains.DocumentManagers;
using JetBrains.DocumentModel;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features.Documents;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.Rider.Model;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
    [SolutionComponent]
    public class RiderUnityDocumentOperationsImpl : RiderDocumentOperationsImpl
    {
        [NotNull] private readonly ILogger myLogger;

        public RiderUnityDocumentOperationsImpl(Lifetime lifetime,
            [NotNull] SolutionModel solutionModel,
            [NotNull] SettingsModel settingsModel,
            [NotNull] ISolution solution,
            [NotNull] IShellLocks locks,
            [NotNull] ChangeManager changeManager,
            [NotNull] DocumentToProjectFileMappingStorage documentToProjectFileMappingStorage,
            [NotNull] IFileSystemTracker fileSystemTracker,
            [NotNull] ILogger logger)
            : base(lifetime, solutionModel, settingsModel, solution, locks, changeManager,
                documentToProjectFileMappingStorage, fileSystemTracker, logger)
        {
            myLogger = logger;
        }

        public override void SaveDocumentAfterModification(IDocument document, bool forceSaveOpenDocuments)
        {
            Locks.Dispatcher.AssertAccess();

            if (forceSaveOpenDocuments)
            {
                var projectFile = DocumentToProjectFileMappingStorage.TryGetProjectFile(document);
                var isUnitySharedProjectFile = projectFile != null
                                               && projectFile.IsShared()
                                               && projectFile.GetProject().IsUnityProject();
                if (isUnitySharedProjectFile)
                {
                    myLogger.Info($"Trying to save document {document.Moniker}. Force = true");
                    myLogger.Verbose("File is shared and contained in Unity project. Skip saving.");
                    return;
                }
            }

            base.SaveDocumentAfterModification(document, forceSaveOpenDocuments);
        }
    }
}

Fix autosave and refresh on shared projects


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.IO;
using BenchmarkDotNet.Attributes;
using osu.Framework.IO.Stores;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Formats;
using osu.Game.IO;
using osu.Game.IO.Archives;
using osu.Game.Resources;

namespace osu.Game.Benchmarks
{
    public class BenchmarkBeatmapParsing : BenchmarkTest
    {
        private readonly MemoryStream beatmapStream = new MemoryStream();

        public override void SetUp()
        {
            using (var resources = new DllResourceStore(OsuResources.ResourceAssembly))
            using (var archive = resources.GetStream("Beatmaps/241526 Soleily - Renatus.osz"))
            using (var reader = new ZipArchiveReader(archive))
                reader.GetStream("Soleily - Renatus (Gamu) [Insane].osu").CopyTo(beatmapStream);
        }

        [Benchmark]
        public Beatmap BenchmarkBundledBeatmap()
        {
            beatmapStream.Seek(0, SeekOrigin.Begin);
            var reader = new LineBufferedReader(beatmapStream); // no disposal

            var decoder = Decoder.GetDecoder<Beatmap>(reader);
            return decoder.Decode(reader);
        }
    }
}

Add beatmap parsing as sample benchmark.


using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;

namespace ProjectTracker.Library
{
  [Serializable()]
  public class ResourceList :
    ReadOnlyListBase<ResourceList, ResourceInfo>
  {
    #region Factory Methods

    public static ResourceList GetResourceList()
    {
      return DataPortal.Fetch<ResourceList>(new Criteria());
    }

    private ResourceList()
    { /* require use of factory methods */ }

    #endregion

    #region Data Access

    [Serializable()]
    private class Criteria
    { /* no criteria - retrieve all resources */ }

    private void DataPortal_Fetch(Criteria criteria)
    {
      this.RaiseListChangedEvents = false;
      using (SqlConnection cn = new SqlConnection(Database.PTrackerConnection))
      {
        cn.Open();
        using (SqlCommand cm = cn.CreateCommand())
        {
          cm.CommandType = CommandType.StoredProcedure;
          cm.CommandText = "getResources";

          using (SafeDataReader dr =
            new SafeDataReader(cm.ExecuteReader()))
          {
            IsReadOnly = false;
            while (dr.Read())
            {
              ResourceInfo info = new ResourceInfo(dr);
              this.Add(info);
            }
            IsReadOnly = false;
          }
        }
      }
      this.RaiseListChangedEvents = true;
    }

    #endregion

  }
}

using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;

namespace ProjectTracker.Library
{
  [Serializable()]
  public class ResourceList :
    ReadOnlyListBase<ResourceList, ResourceInfo>
  {
    #region Factory Methods

    public static ResourceList GetResourceList()
    {
      return DataPortal.Fetch<ResourceList>(new Criteria());
    }

    private ResourceList()
    { /* require use of factory methods */ }

    #endregion

    #region Data Access

    [Serializable()]
    private class Criteria
    { /* no criteria - retrieve all resources */ }

    private void DataPortal_Fetch(Criteria criteria)
    {
      this.RaiseListChangedEvents = false;
      using (SqlConnection cn = new SqlConnection(Database.PTrackerConnection))
      {
        cn.Open();
        using (SqlCommand cm = cn.CreateCommand())
        {
          cm.CommandType = CommandType.StoredProcedure;
          cm.CommandText = "getResources";

          using (SafeDataReader dr =
            new SafeDataReader(cm.ExecuteReader()))
          {
            IsReadOnly = false;
            while (dr.Read())
            {
              ResourceInfo info = new ResourceInfo(dr);
              this.Add(info);
            }
            IsReadOnly = true;
          }
        }
      }
      this.RaiseListChangedEvents = true;
    }

    #endregion

  }
}

Set list to readonly after fetch.

Set list to readonly after fetch.


using System;
using System.Collections.Generic;
using System.Linq;

namespace Glimpse.Web
{
    public class DefaultRequestRuntimeProvider : IRequestRuntimeProvider
    {
        private readonly ITypeService _typeService;

        public DefaultRequestRuntimeProvider(ITypeService typeService)
        {
            _typeService = typeService;
        }

        public IEnumerable<IRequestRuntime> Runtimes
        {
            get { return _typeService.Resolve<IRequestRuntime>().ToArray(); }
        }
    }
}

Add default provider for RequestRuntime

Add default provider for RequestRuntime


using System;

using NHibernate.Dialect;
using NHibernate.SqlCommand;

using NUnit.Framework;

namespace NHibernate.Test.SqlCommandTest
{

	[TestFixture]
	public class TemplateFixture
	{

		public TemplateFixture()
		{
		}

		/// <summary>
		/// Tests that a column enclosed by <c>`</c> is enclosed by the Dialect.OpenQuote
		/// and Dialect.CloseQuote after the Template Renders the Where String.
		/// </summary>
		[Test]
		public void ReplaceWithDialectQuote()
		{
			Dialect.Dialect dialect = new Dialect.MsSql2000Dialect();
			string whereFragment = "column_name = 'string value' and `backtick` = 1";

			string expectedFragment = "$PlaceHolder.column_name = 'string value' and $PlaceHolder.[backtick] = 1";

			Assert.AreEqual( expectedFragment, Template.RenderWhereStringTemplate(whereFragment, dialect) );

		}

	}
}

Test Fixture for Template class.

Test Fixture for Template class.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@403


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Game.Overlays.News;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Framework.Allocation;

namespace osu.Game.Tests.Visual.Online
{
    public class TestSceneNewsHeader : OsuTestScene
    {
        [Cached]
        private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);

        private TestHeader header;

        [SetUp]
        public void Setup()
        {
            Child = header = new TestHeader
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre
            };
        }

        [Test]
        public void TestControl()
        {
            AddAssert("Front page selected", () => header.Current.Value == "frontpage");
            AddAssert("1 tab total", () => header.TabCount == 1);

            AddStep("Set article 1", () => header.SetArticle("1"));
            AddAssert("Article 1 selected", () => header.Current.Value == "1");
            AddAssert("2 tabs total", () => header.TabCount == 2);

            AddStep("Set article 2", () => header.SetArticle("2"));
            AddAssert("Article 2 selected", () => header.Current.Value == "2");
            AddAssert("2 tabs total", () => header.TabCount == 2);

            AddStep("Set front page", () => header.SetFrontPage());
            AddAssert("Front page selected", () => header.Current.Value == "frontpage");
            AddAssert("1 tab total", () => header.TabCount == 1);
        }

        private class TestHeader : NewsHeader
        {
            public int TabCount => TabControl.Items.Count;
        }
    }
}

Add test scene for NewsHeader

Add test scene for NewsHeader


using System;
using Microsoft.Framework.OptionsModel;

namespace Glimpse.Server
{
    public class GlimpseServerWebOptionsSetup : ConfigureOptions<GlimpseServerWebOptions>
    {
        public GlimpseServerWebOptionsSetup() : base(ConfigureGlimpseServerWebOptions)
        {
            Order = -1000;
        }

        public static void ConfigureGlimpseServerWebOptions(GlimpseServerWebOptions options)
        {
            // TODO: Setup different settings here
        }
    }
}

Add Server Web Options Setup

Add Server Web Options Setup


using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace BatteryCommander.Web.Controllers.API
{
    [Route("api/[controller]")]
    public class SoldiersController : Controller
    {
        private readonly Database db;

        public SoldiersController(Database db)
        {
            this.db = db;
        }

        // GET: api/soldiers
        [HttpGet]
        public async Task<IEnumerable<dynamic>> Get(SoldierSearchService.Query query)
        {
            return (await SoldierSearchService.Filter(db, query))
                .Select(s => new
                {
                    s.Id,
                    s.LastName,
                    s.FirstName
                })
                .ToList();
        }

        // GET api/soldiers/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/soldiers
        [HttpPost]
        public void Post([FromBody]string value)
        {
            // TODO
        }

        // PUT api/soldiers/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
            // TODO
        }
    }
}

Add first API stub endpoint

Add first API stub endpoint


// Copyright 2015 Coinprism, Inc.
//
// 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.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Xunit;

namespace Openchain.Sqlite.Tests
{
    public class SqliteAnchorStateBuilderTests
    {
        [Fact]
        public void Name_Success()
        {
            Assert.Equal("SQLite", new SqliteAnchorStateBuilder().Name);
        }

        [Fact]
        public async Task Build_Success()
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>() { ["path"] = ":memory:" };
            SqliteAnchorStateBuilder builder = new SqliteAnchorStateBuilder();

            await builder.Initialize(parameters);

            SqliteAnchorState ledger = builder.Build(null);

            Assert.NotNull(ledger);
        }

        [Fact]
        public async Task InitializeTables_CallTwice()
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>() { ["path"] = ":memory:" };
            SqliteAnchorStateBuilder builder = new SqliteAnchorStateBuilder();

            await builder.Initialize(parameters);

            SqliteAnchorState ledger = builder.Build(null);

            await SqliteAnchorStateBuilder.InitializeTables(ledger.Connection);
            await SqliteAnchorStateBuilder.InitializeTables(ledger.Connection);

            Assert.Equal(ConnectionState.Open, ledger.Connection.State);
        }
    }
}

Add unit tests for the SqliteAnchorStateBuilder class


using System;
using System.Threading.Tasks;
using Marten.Testing.Events.Aggregation;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
using Xunit.Abstractions;

namespace Marten.Testing.Events.Bugs
{
    public class Bug_1723_inline_projections_get_cut_off : AggregationContext
    {
        private readonly ITestOutputHelper _output;

        public Bug_1723_inline_projections_get_cut_off(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture)
        {
            _output = output;
        }

        [Fact]
        public async Task big_streams()
        {
            var stream1 = Guid.NewGuid();
            var stream2 = Guid.NewGuid();

            UsingDefinition<AllSync>();

            _output.WriteLine(_projection.SourceCode());

            await InlineProject(x =>
            {
                x.Streams[stream1].IsNew = true;
                x.Streams[stream1].Add(new CreateEvent(1, 2, 3, 4));

                for (int i = 0; i < 20; i++)
                {
                    x.Streams[stream1].A();
                    x.Streams[stream1].B();
                    x.Streams[stream1].B();
                    x.Streams[stream1].C();
                    x.Streams[stream1].C();
                    x.Streams[stream1].C();
                }

                x.Streams[stream2].IsNew = true;
                x.Streams[stream2].Add(new CreateEvent(3, 3, 3, 3));

                for (int i = 0; i < 100; i++)
                {
                    x.Streams[stream2].A();
                    x.Streams[stream2].B();
                    x.Streams[stream2].C();
                }

            });

            using var query = theStore.QuerySession();

            var aggregate1 = await query.LoadAsync<MyAggregate>(stream1);
            aggregate1.ACount.ShouldBe(21);
            aggregate1.BCount.ShouldBe(42);
            aggregate1.CCount.ShouldBe(63);

            var aggregate2 = await query.LoadAsync<MyAggregate>(stream2);
            aggregate2.ACount.ShouldBe(103);
            aggregate2.BCount.ShouldBe(103);

        }
    }
}

Test to verify inline projections with lots of events. Closes GH-1723


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Overlays.Notifications;
using osu.Game.Tests.Visual;

namespace osu.Game.Tests.Online
{
    [HeadlessTest]
    public class TestSceneBeatmapManager : OsuTestScene
    {
        private BeatmapManager beatmaps;
        private ProgressNotification recentNotification;

        private static readonly BeatmapSetInfo test_model = new BeatmapSetInfo { OnlineBeatmapSetID = 1 };

        [BackgroundDependencyLoader]
        private void load(BeatmapManager beatmaps)
        {
            this.beatmaps = beatmaps;

            beatmaps.PostNotification = n => recentNotification = n as ProgressNotification;
        }

        [TestCase(true)]
        [TestCase(false)]
        public void TestCancelDownloadFromRequest(bool closeFromRequest)
        {
            AddStep("download beatmap", () => beatmaps.Download(test_model));

            if (closeFromRequest)
                AddStep("cancel download from request", () => beatmaps.GetExistingDownload(test_model).Cancel());
            else
                AddStep("cancel download from notification", () => recentNotification.Close());

            AddUntilStep("is removed from download list", () => beatmaps.GetExistingDownload(test_model) == null);
            AddAssert("is notification cancelled", () => recentNotification.State == ProgressNotificationState.Cancelled);
        }
    }
}

Add headless test ensuring correct cancelling download behaviour


using AsmResolver.DotNet.Code.Cil;
using Xunit;

namespace AsmResolver.DotNet.Tests.Code.Cil
{
    public class CilLocalVariableCollectionTest
    {
        private readonly CilLocalVariableCollection _collection = new CilLocalVariableCollection();
        private readonly ModuleDefinition _module = new ModuleDefinition("Test.dll");

        private void AssertCollectionIndicesAreConsistent(CilLocalVariableCollection collection)
        {
            for (int i = 0; i < collection.Count; i++)
                Assert.Equal(i, collection[i].Index);
        }

        [Fact]
        public void NoIndex()
        {
            var variable = new CilLocalVariable(_module.CorLibTypeFactory.Object);
            Assert.Equal(-1, variable.Index);
        }

        [Fact]
        public void AddToEmptyListShouldSetIndexToZero()
        {
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            AssertCollectionIndicesAreConsistent(_collection);
        }

        [Fact]
        public void AddToEndOfListShouldSetIndexToCount()
        {
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));

            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            AssertCollectionIndicesAreConsistent(_collection);
        }

        [Fact]
        public void InsertShouldUpdateIndices()
        {
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));

            _collection.Insert(1, new CilLocalVariable(_module.CorLibTypeFactory.String));
            AssertCollectionIndicesAreConsistent(_collection);
        }

        [Fact]
        public void RemoveShouldUpdateIndices()
        {
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));

            var variable = _collection[1];
            _collection.RemoveAt(1);
            AssertCollectionIndicesAreConsistent(_collection);
            Assert.Equal(-1, variable.Index);
        }

        [Fact]
        public void ClearingVariablesShouldUpdateAllIndices()
        {
            var variables = new[]
            {
                new CilLocalVariable(_module.CorLibTypeFactory.Object),
                new CilLocalVariable(_module.CorLibTypeFactory.Object),
                new CilLocalVariable(_module.CorLibTypeFactory.Object),
                new CilLocalVariable(_module.CorLibTypeFactory.Object)
            };

            foreach (var variable in variables)
                _collection.Add(variable);

            _collection.Clear();

            foreach (var variable in variables)
                Assert.Equal(-1, variable.Index);
        }
    }
}

Add CilLocalVariableCollection index consistency tests.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Recipe.ThreadAndConcurrent
{
    public static class EventRaiseExtentions
    {
        public static void Raise<TEventArgs>(this TEventArgs e, object sender,
            ref EventHandler<TEventArgs> eventDelegate)
        {
            EventHandler<TEventArgs> temp = Volatile.Read(ref eventDelegate);
            if (temp != null)
            {
                temp(sender, e);
            }
        }
    }
}

Add thread safe event trigger

Add thread safe event trigger


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Pather.CSharp.PathElements
{
    public class EnumerableAccessFactory : IPathElementFactory
    {
        public IPathElement Create(string pathElement)
        {
            var matches = Regex.Matches(pathElement, @"^(\w+)\[(\d+)\]$");
            Match match = matches[0];
            //0 is the whole match
            string property = match.Captures[1].Value;
            int index = int.Parse(match.Captures[2].Value); //the regex guarantees that the second group is an integer, so no further check is needed

            return new EnumerableAccess(property, index);
        }

        public bool IsApplicable(string pathElement)
        {
            return Regex.IsMatch(pathElement, @"^\w+\[\d+\]$");
        }
    }
}

Add factory for the PathElement class for array like access


using ServiceStack.ServiceHost;

namespace ServiceStack.ServiceInterface
{
    public class DefaultViewAttribute : RequestFilterAttribute
    {
        public string View { get; set; }
        public string Template { get; set; }

        public DefaultViewAttribute() { }
        public DefaultViewAttribute(string view) : this(view, null) { }
        public DefaultViewAttribute(string view, string template)
        {
            View = view;
            Template = template;
        }

        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (!string.IsNullOrEmpty(View))
                req.Items["View"] = View;
            if (!string.IsNullOrEmpty(Template))
                req.Items["Template"] = Template;
        }
    }
}

Add DefaultView RequestFilterAttribute to set a default view/template for attributed services/actions


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Game.Rulesets.Osu.Mods;

namespace osu.Game.Rulesets.Osu.Tests.Mods
{
    public class TestSceneOsuModFreezeFrame : OsuModTestScene
    {
        [Test]
        public void TestFreezeFrame()
        {
            CreateModTest(new ModTestData
            {
                Mod = new OsuModFreezeFrame(),
                PassCondition = () => true,
                Autoplay = false,
            });
        }
    }
}

Add test scene for "Freeze Frame" mod

Add test scene for "Freeze Frame" mod


using System.Collections.Generic;
using System.Linq;

namespace Glimpse.Agent.Web
{
    public class FixedRequestProfilerProvider : IRequestProfilerProvider
    {
        public FixedRequestProfilerProvider()
            : this(Enumerable.Empty<IRequestProfiler>())
        {
        }

        public FixedRequestProfilerProvider(IEnumerable<IRequestProfiler> controllerTypes)
        {
            Profilers = new List<IRequestProfiler>(controllerTypes);
        }

        public IList<IRequestProfiler> Profilers { get; }

        IEnumerable<IRequestProfiler> IRequestProfilerProvider.Profilers => Profilers;
    }
}

Add fixed implementation for RequestProfilers provider


// Copyright 2019 Google LLC
//
// 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
//
//     https://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 gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using sys = System;

namespace Google.Cloud.Container.V1
{
    // This is a partial class introduced for backward compatibility with earlier versions.
    public partial class ClusterManagerSettings
    {
        /// <summary>
        /// In previous releases, this property returned a filter used by default for "Idempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } =
            gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable);

        /// <summary>
        /// In previous releases, this property returned a filter used by default for "NonIdempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } =
            gaxgrpc::RetrySettings.FilterForStatusCodes();

        /// <summary>
        /// In previous releases, this method returned the backoff used by default for "Idempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings(
            delay: sys::TimeSpan.FromMilliseconds(1000),
            maxDelay: sys::TimeSpan.FromMilliseconds(32000),
            delayMultiplier: 1.3
        );

        /// <summary>
        /// In previous releases, this method returned the backoff used by default for "NonIdempotent" RPC methods.
        /// It is now unused, and may not represent the current default behavior.
        /// </summary>
        [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")]
        public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings(
            delay: sys::TimeSpan.FromMilliseconds(60000),
            maxDelay: sys::TimeSpan.FromMilliseconds(60000),
            delayMultiplier: 1.0
        );
    }
}

Add settings for backward compatibility

Add settings for backward compatibility


using System;
using Newtonsoft.Json;
using Xunit;

namespace ReactiveDomain.Messaging.Tests
{
    public sealed class when_serializing_ids
    {
        private readonly CorrelationId _corrId;
        private readonly SourceId _sourceId;
        private readonly SourceId _nullSourceId;

        public when_serializing_ids()
        {
            _corrId = CorrelationId.NewId();
            _sourceId = new SourceId(Guid.NewGuid());
            _nullSourceId = SourceId.NullSourceId();
        }

        [Fact]
        public void can_serialize_and_recover_ids()
        {
            var idTester = new IdTester(_corrId, _sourceId);
            var jsonString = JsonConvert.SerializeObject(idTester, Json.JsonSettings);
            var idTesterOut = JsonConvert.DeserializeObject<IdTester>(jsonString, Json.JsonSettings);
            Assert.IsType<IdTester>(idTesterOut);
            Assert.Equal(_corrId, idTester.CorrId);
            Assert.Equal(_sourceId, idTester.SrcId);
        }

        [Fact]
        public void can_serialize_and_recover_nullsourceid()
        {
            var idTester = new IdTester(_corrId, _nullSourceId);
            var jsonString = JsonConvert.SerializeObject(idTester, Json.JsonSettings);
            var idTesterOut = JsonConvert.DeserializeObject<IdTester>(jsonString, Json.JsonSettings);
            Assert.IsType<IdTester>(idTesterOut);
            Assert.Equal(_corrId, idTester.CorrId);
            Assert.Equal(_nullSourceId, idTester.SrcId);
        }
    }

    public class IdTester
    {
        public readonly CorrelationId CorrId;
        public readonly SourceId SrcId;

        public IdTester(
            CorrelationId correlationId,
            SourceId sourceId)
        {
            CorrId = correlationId;
            SrcId = sourceId;
        }
    }
}

Add tests for Id struct serialization and deserialization


using LonoNet.Client;
using LonoNet.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;

namespace LonoNetTest
{
    /// <summary>
    /// Early stage.  At this point, this is more of sample code to get you started.  Will work on actual unit tests soon.
    /// </summary>
    [TestClass]
    public class UnitTest1
    {
        public readonly string _clientId = "CLIENT KEY";
        public readonly string _clientSecret = "CLIENT SECRET";
        public readonly string _authToken = "AUTH TOKEN";
        public readonly string _deviceId = "DEVICE ID";

        public readonly string _authCode = "AUTH CODE";

        [TestMethod]
        public void TestMethod1()
        {
            LonoNetClient client = new LonoNetClient(_clientId, _clientSecret, _authToken, _deviceId);
            var login = client.GetAccessToken(_authCode, "http://localhost");

            ZoneState zs = client.GetActiveZone();
            ZoneInfo zi = client.GetAllZones();
            DeviceInfo di = client.GetDeviceInfo();
            client.SetZoneOn(1);
            Thread.Sleep(10);
            client.SetZoneOff(1);
        }

        [TestMethod]
        public void TestMethod2()
        {
            LonoNetClient client = new LonoNetClient(_clientId, _clientSecret, _deviceId);
            string url = client.BuildAuthorizeUrl(LonoNet.Authenticators.OAuth2AuthorizationFlow.Code, "http://localhost", "write");
            // Launch url
            // set _authCode to value returned in url
            var login = client.GetAccessToken(_authCode, "http://localhost");

            ZoneState zs = client.GetActiveZone();
            ZoneInfo zi = client.GetAllZones();
            DeviceInfo di = client.GetDeviceInfo();
            client.SetZoneOn(1);
            Thread.Sleep(10);
            client.SetZoneOff(1);
        }
    }
}

Add sample code to the unit test project for now.


@{
    ViewData["Title"] = "Access Denied";
}

Creating Initiative projects is unavailable.

        You do not have appropriate permissions to create Initiative projects. Please create a Draft project.

Add view for "Initiative Create Closed" error page.


using Microsoft.Live;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Storage;

namespace ClumsyWordsUniversal.Data
{
    public class LocalDataSource : DataSource
    {
        public LocalDataSource() { }

        private static readonly StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        private readonly string _fileName = "definitions.json";

        /// <summary>
        /// Initializes the data source trying to load data
        /// </summary>
        /// <returns></returns>
        public override async Task InitAsync()
        {
            await this.LoadDataAsync();
        }

        /// <summary>
        /// Loads data from local storage and populates the data source
        /// </summary>
        /// <returns></returns>
        public override async Task LoadDataAsync()
        {
            bool exists = true;
            StorageFile file = null;
            try
            {
                file = await LocalDataSource.localFolder.GetFileAsync(this._fileName);
            }
            catch (FileNotFoundException)
            {
                exists = false;
            }
            if (!exists)
            {
                file = await LocalDataSource.localFolder.CreateFileAsync(this._fileName);
                return;
            }
            var result = await FileIO.ReadTextAsync(file);

            this.groupsMap = await JsonConvert.DeserializeObjectAsync<Dictionary<string, DefinitionsDataGroup>>(result);
            if (this.groupsMap == null)
                this.groupsMap = new Dictionary<string, DefinitionsDataGroup>();
        }

        /// <summary>
        /// Saves data to local storage
        /// </summary>
        /// <returns></returns>
        public override async Task SaveDataAsync()
        {
            var file = await LocalDataSource.localFolder.CreateFileAsync(this._fileName, CreationCollisionOption.ReplaceExisting);

            string jsonData = await JsonConvert.SerializeObjectAsync(this.groupsMap, Formatting.None);
            await FileIO.WriteTextAsync(file, jsonData);
        }

        /// <summary>
        /// Saves data to local storage
        /// </summary>
        /// <param name="filename">The name of the file to write in</param>
        /// <param name="data">The data object to be serialized and written in the file</param>
        /// <returns></returns>
        public override async Task SaveDataAsync(string filename, object data)
        {
            var file = await LocalDataSource.localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            string jsonData = await JsonConvert.SerializeObjectAsync(data, Formatting.None);
            await FileIO.WriteTextAsync(file, jsonData);
        }
    }
}

Create data source for local storage

Create data source for local storage


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;

namespace osu.Framework.Tests.Visual.Sprites
{
    public class TestSceneRomanisableSpriteText : FrameworkTestScene
    {
        private FillFlowContainer flow;

        public TestSceneRomanisableSpriteText()
        {
            Children = new Drawable[]
            {
                new BasicScrollContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    Children = new[]
                    {
                        flow = new FillFlowContainer
                        {
                            Anchor = Anchor.TopLeft,
                            AutoSizeAxes = Axes.Y,
                            RelativeSizeAxes = Axes.X,
                            Direction = FillDirection.Vertical,
                        }
                    }
                }
            };

            flow.Add(new SpriteText { Text = new RomanisableString("music", "ongaku") });
            flow.Add(new SpriteText { Text = new RomanisableString("music", "") });
            flow.Add(new SpriteText { Text = new RomanisableString("", "ongaku") });
        }

        [Resolved]
        private FrameworkConfigManager config { get; set; }

        [Test]
        public void TestToggleRomanisedState()
        {
            AddStep("prefer romanised", () => config.Set(FrameworkSetting.ShowUnicode, false));
            AddAssert("check strings correct", () => flow.OfType<SpriteText>().Select(st => st.Current.Value).SequenceEqual(new[] { "music", "music", "ongaku" }));

            AddStep("prefer unicode", () => config.Set(FrameworkSetting.ShowUnicode, true));
            AddAssert("check strings correct", () => flow.OfType<SpriteText>().Select(st => st.Current.Value).SequenceEqual(new[] { "ongaku", "music", "ongaku" }));
        }
    }
}

Add failing test covering RomanisableString usage in SpriteText


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace LiteDB
{
    public partial class LiteCollection<T>
    {
        /// <summary>
        /// Remove all document based on a Query object. Returns removed document counts
        /// </summary>
        public int Delete(Query query)
        {
            if(query == null) throw new ArgumentNullException("query");

            return _engine.DeleteDocuments(_name, query);
        }

        /// <summary>
        /// Remove all document based on a LINQ query. Returns removed document counts
        /// </summary>
        public int Delete(Expression<Func<T, bool>> predicate)
        {
            return this.Delete(_visitor.Visit(predicate));
        }

        /// <summary>
        /// Remove an document in collection using Document Id - returns false if not found document
        /// </summary>
        public bool Delete(BsonValue id)
        {
            if (id == null || id.IsNull) throw new ArgumentNullException("id");

            return this.Delete(Query.EQ("_id", id)) > 0;
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace LiteDB
{
    public partial class LiteCollection<T>
    {
        /// <summary>
        /// Remove all document based on a Query object. Returns removed document counts
        /// </summary>
        public int Delete(Query query)
        {
            if(query == null) throw new ArgumentNullException("query");

            // keep trying execute query to auto-create indexes when not found
            while (true)
            {
                try
                {
                    return _engine.DeleteDocuments(_name, query);
                }
                catch (IndexNotFoundException ex)
                {
                    // if query returns this exception, let's auto create using mapper (or using default options)
                    var options = _mapper.GetIndexFromMapper<T>(ex.Field) ?? new IndexOptions();

                    _engine.EnsureIndex(ex.Collection, ex.Field, options);
                }
            }
        }

        /// <summary>
        /// Remove all document based on a LINQ query. Returns removed document counts
        /// </summary>
        public int Delete(Expression<Func<T, bool>> predicate)
        {
            return this.Delete(_visitor.Visit(predicate));
        }

        /// <summary>
        /// Remove an document in collection using Document Id - returns false if not found document
        /// </summary>
        public bool Delete(BsonValue id)
        {
            if (id == null || id.IsNull) throw new ArgumentNullException("id");

            return this.Delete(Query.EQ("_id", id)) > 0;
        }
    }
}

Add delete auto index creation

Add delete auto index creation


using System;

public partial class Settings : System.Web.UI.Page
{
  //---------------------------------------------------------------------------

  protected void Page_Load( object sender, EventArgs e )
  {
    // Don't allow people to skip the login page.
    if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null ||
        (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false )
    {
      Response.Redirect( "Default.aspx" );
    }

    dataSource.ConnectionString = Database.DB_CONNECTION_STRING;
  }

  //---------------------------------------------------------------------------
}

Remove reference to settings icon

Remove reference to settings icon


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using MessagePack;
using NUnit.Framework;
using osu.Game.Online;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Multiplayer.MatchTypes.TeamVersus;

namespace osu.Game.Tests.Online
{
    [TestFixture]
    public class TestMultiplayerMessagePackSerialization
    {
        [Test]
        public void TestSerialiseRoom()
        {
            var room = new MultiplayerRoom(1)
            {
                MatchState = new TeamVersusRoomState()
            };

            var serialized = MessagePackSerializer.Serialize(room);

            var deserialized = MessagePackSerializer.Deserialize<MultiplayerRoom>(serialized);

            Assert.IsTrue(deserialized.MatchState is TeamVersusRoomState);
        }

        [Test]
        public void TestSerialiseUserStateExpected()
        {
            var state = new TeamVersusUserState();

            var serialized = MessagePackSerializer.Serialize(typeof(MatchUserState), state);
            var deserialized = MessagePackSerializer.Deserialize<MatchUserState>(serialized);

            Assert.IsTrue(deserialized is TeamVersusUserState);
        }

        [Test]
        public void TestSerialiseUnionFailsWithSingalR()
        {
            var state = new TeamVersusUserState();

            // SignalR serialises using the actual type, rather than a base specification.
            var serialized = MessagePackSerializer.Serialize(typeof(TeamVersusUserState), state);

            // works with explicit type specified.
            MessagePackSerializer.Deserialize<TeamVersusUserState>(serialized);

            // fails with base (union) type.
            Assert.Throws<MessagePackSerializationException>(() => MessagePackSerializer.Deserialize<MatchUserState>(serialized));
        }

        [Test]
        public void TestSerialiseUnionSucceedsWithWorkaround()
        {
            var state = new TeamVersusUserState();

            // SignalR serialises using the actual type, rather than a base specification.
            var serialized = MessagePackSerializer.Serialize(typeof(TeamVersusUserState), state, SignalRUnionWorkaroundResolver.OPTIONS);

            // works with explicit type specified.
            MessagePackSerializer.Deserialize<TeamVersusUserState>(serialized);

            // works with custom resolver.
            var deserialized = MessagePackSerializer.Deserialize<MatchUserState>(serialized, SignalRUnionWorkaroundResolver.OPTIONS);
            Assert.IsTrue(deserialized is TeamVersusUserState);
        }
    }
}

Add test coverage of multiplayer room/state messagepack serialisation


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Audio;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
using osu.Game.Skinning;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestSceneGameplaySamplePlayback : PlayerTestScene
    {
        [Test]
        public void TestAllSamplesStopDuringSeek()
        {
            DrawableSlider slider = null;
            DrawableSample[] samples = null;
            ISamplePlaybackDisabler gameplayClock = null;

            AddStep("get variables", () =>
            {
                gameplayClock = Player.ChildrenOfType<FrameStabilityContainer>().First().GameplayClock;
                slider = Player.ChildrenOfType<DrawableSlider>().OrderBy(s => s.HitObject.StartTime).First();
                samples = slider.ChildrenOfType<DrawableSample>().ToArray();
            });

            AddUntilStep("wait for slider sliding then seek", () =>
            {
                if (!slider.Tracking.Value)
                    return false;

                if (!samples.Any(s => s.Playing))
                    return false;

                Player.ChildrenOfType<GameplayClockContainer>().First().Seek(40000);
                return true;
            });

            AddAssert("sample playback disabled", () => gameplayClock.SamplePlaybackDisabled.Value);

            // because we are in frame stable context, it's quite likely that not all samples are "played" at this point.
            // the important thing is that at least one started, and that sample has since stopped.
            AddAssert("no samples are playing", () => Player.ChildrenOfType<PausableSkinnableSound>().All(s => !s.IsPlaying));

            AddAssert("sample playback still disabled", () => gameplayClock.SamplePlaybackDisabled.Value);

            AddUntilStep("seek finished, sample playback enabled", () => !gameplayClock.SamplePlaybackDisabled.Value);
            AddUntilStep("any sample is playing", () => Player.ChildrenOfType<PausableSkinnableSound>().Any(s => s.IsPlaying));
        }

        protected override bool Autoplay => true;

        protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
    }
}

Add failing test coverage of gameplay sample pausing (during seek)


using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("Com.OneSignal.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("OneSignal")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion ("3.10.6")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

Add assembly info to OneSignal.Core

Add assembly info to OneSignal.Core


using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers.API
{
    [Route("api/[controller]"), Authorize]
    public class VehiclesController : Controller
    {
        private readonly Database db;

        public VehiclesController(Database db)
        {
            this.db = db;
        }

        [HttpGet]
        public async Task<IEnumerable<dynamic>> Get()
        {
            // GET: api/vehicles

            return
                await db
                .Vehicles
                .Select(_ => new
                {
                    _.Id,
                    _.UnitId,
                    _.Bumper,
                    _.Registration,
                    _.Nomenclature,
                    _.Notes,
                    _.Serial,
                    _.Status,
                    _.Type,
                    _.HasFuelCard,
                    _.HasJBCP,
                    _.HasTowBar
                })
                .ToListAsync();
        }
    }
}

Add stub endpoint for getting vehicle info


#if NETSTANDARD_1plus
using NLog.LayoutRenderers;
using System.Text;

using Microsoft.AspNetCore.Routing;

using NLog.Web.Internal;

namespace NLog.Web.LayoutRenderers
{
    /// <summary>
    /// ASP.NET content type.
    /// </summary>
    /// <example>
    /// <code lang="NLog Layout Renderer">
    /// ${aspnet-request-contenttype}
    /// </code>
    /// </example>
    [LayoutRenderer("aspnet-request-contenttype")]
    public class AspNetRequestContentTypeLayoutRenderer : AspNetLayoutRendererBase
    {
        /// <summary>
        /// Renders the specified ASP.NET Application variable and appends it to the specified <see cref="StringBuilder" />.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
        {
            var request = HttpContextAccessor?.HttpContext?.TryGetRequest();

            var contentType = request?.ContentType;

            if (!string.IsNullOrEmpty(contentType))
                    builder.Append(contentType);

        }
    }
}
#endif

Add ${aspnet-request-contenttype} (ASP.NET Core only)


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.RealtimeMultiplayer;
using osu.Game.Screens.Multi.Lounge.Components;
using osu.Game.Screens.Multi.RealtimeMultiplayer;

namespace osu.Game.Tests.Visual.RealtimeMultiplayer
{
    public class RealtimeMultiplayerTestScene : MultiplayerTestScene
    {
        [Cached(typeof(StatefulMultiplayerClient))]
        public TestRealtimeMultiplayerClient Client { get; }

        [Cached(typeof(RealtimeRoomManager))]
        public TestRealtimeRoomManager RoomManager { get; }

        [Cached]
        public Bindable<FilterCriteria> Filter { get; }

        protected override Container<Drawable> Content => content;
        private readonly TestRealtimeRoomContainer content;

        private readonly bool joinRoom;

        public RealtimeMultiplayerTestScene(bool joinRoom = true)
        {
            this.joinRoom = joinRoom;
            base.Content.Add(content = new TestRealtimeRoomContainer { RelativeSizeAxes = Axes.Both });

            Client = content.Client;
            RoomManager = content.RoomManager;
            Filter = content.Filter;
        }

        [SetUp]
        public new void Setup() => Schedule(() =>
        {
            RoomManager.Schedule(() => RoomManager.PartRoom());

            if (joinRoom)
            {
                Room.RoomID.Value = 1;
                RoomManager.Schedule(() => RoomManager.JoinRoom(Room, null, null));
            }
        });
    }
}

Add realtime multiplayer test scene abstract class


using System.Windows.Controls;
using System.Windows.Input;

namespace DevelopmentInProgress.WPFControls.NavigationPanel
{
    partial class NavigationPanelResources
    {
        private void ExpanderImageMouseDown(object sender, MouseButtonEventArgs e)
        {
            throw new System.NotImplementedException();

                                    //            <!--<i:Interaction.Triggers>
                                    //    <i:EventTrigger EventName="MouseDown">
                                    //        <i:InvokeCommandAction Command="{Binding ExpanderChangedCommand, RelativeSource={RelativeSource TemplatedParent}}"
                                    //                               CommandParameter="{Binding SelectedItem, ElementName=modulesList}"/>
                                    //    </i:EventTrigger>
                                    //</i:Interaction.Triggers>-->

        }

        private void ModulesListOnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {

                                //            <!--<i:Interaction.Triggers>
                                //    <i:EventTrigger EventName="SelectionChanged">
                                //        <i:InvokeCommandAction Command="{Binding SelectionChangedCommand, RelativeSource={RelativeSource TemplatedParent}}"
                                //                               CommandParameter="{Binding SelectedItem, ElementName=modulesList}"/>
                                //    </i:EventTrigger>
                                //</i:Interaction.Triggers>-->
        }
    }
}

Add code behind for the Navigation Panel resource file

Add code behind for the Navigation Panel resource file


using System;
using System.Windows.Input;
using ReactiveUI;

namespace WalletWasabi.Fluent.ViewModels.NavBar
{
	public class SearchItemViewModel : RoutableViewModel
	{
		public SearchItemViewModel(NavigationStateViewModel navigationState, NavigationTarget navigationTarget, string iconName, string title, Func<RoutableViewModel> createTargetView) : base(navigationState, navigationTarget)
		{
			IconName = iconName;

			Title = title;

			OpenCommand = ReactiveCommand.Create(() =>
			{
				NavigateToTargetView(navigationState, navigationTarget, createTargetView);
			});
		}

		public string IconName { get; }

		public string Title { get; }

		public ICommand OpenCommand { get; }

		private void NavigateToTargetView(NavigationStateViewModel navigationState, NavigationTarget navigationTarget, Func<RoutableViewModel> createTargetView)
		{
			switch (navigationTarget)
			{
				case NavigationTarget.Default:
				case NavigationTarget.Home:
					navigationState.HomeScreen?.Invoke().Router.Navigate.Execute(createTargetView());
					break;

				case NavigationTarget.Dialog:
					navigationState.DialogScreen?.Invoke().Router.Navigate.Execute(createTargetView());
					break;
			}
		}

		public override string ToString()
		{
			return Title;
		}
	}
}

Add search item view model

Add search item view model


namespace FakeItEasy.Expressions.ArgumentConstraints
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using FakeItEasy.Core;

    internal class EqualityArgumentConstraint
        : IArgumentConstraint
    {
        public EqualityArgumentConstraint(object expectedValue)
        {
            this.ExpectedValue = expectedValue;
        }

        public object ExpectedValue { get; }

        public string ConstraintDescription => this.ToString();

        public bool IsValid(object argument)
        {
            return object.Equals(this.ExpectedValue, argument);
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Any type of exception may be encountered.")]
        public override string ToString()
        {
            if (this.ExpectedValue == null)
            {
                return "<NULL>";
            }

            var stringValue = this.ExpectedValue as string;
            if (stringValue != null)
            {
                return $@"""{stringValue}""";
            }

            try
            {
                return this.ExpectedValue.ToString();
            }
            catch (Exception)
            {
                FakeManager manager = Fake.TryGetFakeManager(this.ExpectedValue);
                return manager != null
                    ? "Faked " + manager.FakeObjectType
                    : this.ExpectedValue.GetType().ToString();
            }
        }

        public void WriteDescription(IOutputWriter writer)
        {
            writer.Write(this.ConstraintDescription);
        }
    }
}

namespace FakeItEasy.Expressions.ArgumentConstraints
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using FakeItEasy.Core;

    internal class EqualityArgumentConstraint
        : IArgumentConstraint
    {
        public EqualityArgumentConstraint(object expectedValue)
        {
            this.ExpectedValue = expectedValue;
        }

        public object ExpectedValue { get; }

        public string ConstraintDescription => this.ToString();

        public bool IsValid(object argument)
        {
            return object.Equals(this.ExpectedValue, argument);
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Any type of exception may be encountered.")]
        public override string ToString()
        {
            try
            {
                var writer = ServiceLocator.Current.Resolve<StringBuilderOutputWriter>();
                writer.WriteArgumentValue(this.ExpectedValue);
                return writer.Builder.ToString();
            }
            catch (Exception)
            {
                FakeManager manager = Fake.TryGetFakeManager(this.ExpectedValue);
                return manager != null
                    ? "Faked " + manager.FakeObjectType
                    : this.ExpectedValue.GetType().ToString();
            }
        }

        public void WriteDescription(IOutputWriter writer)
        {
            writer.Write(this.ConstraintDescription);
        }
    }
}

[green] Use value formatters to describe asserted call


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Edit;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Screens.Edit;
using osu.Game.Tests.Visual;

namespace osu.Game.Rulesets.Mania.Tests
{
    public class TestSceneManiaHitObjectComposer : EditorClockTestScene
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(ManiaBlueprintContainer)
        };

        [Cached(typeof(EditorBeatmap))]
        [Cached(typeof(IBeatSnapProvider))]
        private readonly EditorBeatmap editorBeatmap;

        protected override Container<Drawable> Content { get; }

        private ManiaHitObjectComposer composer;

        public TestSceneManiaHitObjectComposer()
        {
            base.Content.Add(new Container
            {
                RelativeSizeAxes = Axes.Both,
                Children = new Drawable[]
                {
                    editorBeatmap = new EditorBeatmap(new ManiaBeatmap(new StageDefinition { Columns = 4 }))
                    {
                        BeatmapInfo = { Ruleset = new ManiaRuleset().RulesetInfo }
                    },
                    Content = new Container
                    {
                        RelativeSizeAxes = Axes.Both,
                    }
                },
            });

            for (int i = 0; i < 10; i++)
            {
                editorBeatmap.Add(new Note { StartTime = 100 * i });
            }
        }

        [SetUp]
        public void Setup() => Schedule(() =>
        {
            Children = new Drawable[]
            {
                composer = new ManiaHitObjectComposer(new ManiaRuleset())
            };

            BeatDivisor.Value = 8;
        });
    }
}

Add test scene for mania composer

Add test scene for mania composer


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Graphics.UserInterfaceV2;

namespace osu.Game.Tests.Visual.UserInterface
{
    public class TestSceneLabelledDropdown : OsuTestScene
    {
        [Test]
        public void TestLabelledDropdown()
            => AddStep(@"create dropdown", () => Child = new LabelledDropdown<string>
            {
                Label = @"Countdown speed",
                Items = new[]
                {
                    @"Half",
                    @"Normal",
                    @"Double"
                },
                Description = @"This is a description"
            });

        [Test]
        public void TestLabelledEnumDropdown()
            => AddStep(@"create dropdown", () => Child = new LabelledEnumDropdown<BeatmapSetOnlineStatus>
            {
                Label = @"Beatmap status",
                Description = @"This is a description"
            });
    }
}

Add test scene for labelled dropdowns

Add test scene for labelled dropdowns


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Framework.Input;
using osu.Framework.Testing;
using osuTK;
using osuTK.Input;

namespace osu.Framework.Tests.Visual.Testing
{
    public class TestSceneManualInputManagerTestScene : ManualInputManagerTestScene
    {
        protected override Vector2 InitialMousePosition => new Vector2(10f);

        [Test]
        public void TestResetInput()
        {
            AddStep("move mouse", () => InputManager.MoveMouseTo(Vector2.Zero));
            AddStep("press mouse", () => InputManager.PressButton(MouseButton.Left));
            AddStep("press key", () => InputManager.PressKey(Key.Z));
            AddStep("press joystick", () => InputManager.PressJoystickButton(JoystickButton.Button1));

            AddStep("reset input", ResetInput);

            AddAssert("mouse position reset", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition);
            AddAssert("all input states released", () =>
                InputManager.CurrentState.Mouse.Buttons.HasAnyButtonPressed &&
                InputManager.CurrentState.Keyboard.Keys.HasAnyButtonPressed &&
                InputManager.CurrentState.Joystick.Buttons.HasAnyButtonPressed);
        }

        [Test]
        public void TestMousePositionSetToInitial() => AddAssert("mouse position set to initial", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition);
    }
}

Add test scene ensuring input reset works properly and mouse position set initially


// Copyright 2019 Google LLC
//
// 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
//
//     https://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 Grpc.Core;
using System;
using System.Linq;
using Xunit;
using static Google.Cloud.Language.V1.AnnotateTextRequest.Types;

namespace Google.Cloud.Language.V1.Tests
{
    public class ApiClientHeaderTest
    {
        [Fact]
        public void ClientProvidesHeader()
        {
            var invoker = new FakeCallInvoker();
            var client = new LanguageServiceClientBuilder { CallInvoker = invoker }.Build();
            client.AnnotateText(Document.FromPlainText("Some text"), new Features { ClassifyText = true });
            var metadata = invoker.Metadata;
            var entry = metadata.FirstOrDefault(pair => pair.Key == "x-goog-api-client");
            Assert.NotNull(entry);
            var keys = entry.Value.Split(' ')
                .Select(value => value.Split('/')[0])
                .OrderBy(key => key)
                .ToList();
            string[] expectedKeys = { "gapic", "gax", "gccl", "gl-dotnet", "grpc" };
            Assert.Equal(expectedKeys, keys);
        }

        private class FakeCallInvoker : CallInvoker
        {
            public Metadata Metadata { get; private set; }

            public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options) =>
                throw new NotImplementedException();

            public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options) =>
                throw new NotImplementedException();

            public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request) =>
                throw new NotImplementedException();

            public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request) =>
                throw new NotImplementedException();

            public override TResponse BlockingUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
            {
                Metadata = options.Headers;
                return (TResponse) Activator.CreateInstance(typeof(TResponse));
            }
        }
    }
}

Test for headers in GAPIC client libraries

There's nothing particularly special about Language here - it's just a fairly vanilla GAPIC libary.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Mpdn.RenderScript.Config;
using Mpdn.PlayerExtensions.GitHub;
using YAXLib;

namespace Mpdn.RenderScript
{
    namespace Mpdn.ScriptChain
    {
        public abstract class PresetRenderScript : IRenderScriptUi
        {
            protected abstract RenderScriptPreset Preset { get; }

            protected virtual IRenderScriptUi Script { get { return Preset.Script; } }

            public virtual IRenderScript CreateRenderScript()
            {
                return Script.CreateRenderScript();
            }

            public virtual void Destroy()
            {
                Script.Destroy();
            }

            public virtual void Initialize() { }

            public virtual bool ShowConfigDialog(IWin32Window owner)
            {
                return Script.ShowConfigDialog(owner);
            }

            public virtual ScriptDescriptor Descriptor
            {
                get
                {
                    var descriptor = Script.Descriptor;
                    descriptor.Guid = Preset.Guid;
                    return descriptor;
                }
            }
        }

        public class ActivePresetRenderScript : PresetRenderScript
        {
            private Guid m_Guid = new Guid("B1F3B882-3E8F-4A8C-B225-30C9ABD67DB1");

            protected override RenderScriptPreset Preset
            {
                get { return PresetExtension.ActivePreset ?? new RenderScriptPreset() { Script = new ScriptChainScript() }; }
            }

            public override void Initialize()
            {
                base.Initialize();

                PresetExtension.ScriptGuid = m_Guid;
            }

            public override ScriptDescriptor Descriptor
            {
                get
                {
                    var descriptor = base.Descriptor;
                    descriptor.Name = "Preset";
                    descriptor.Guid = m_Guid;
                    descriptor.Description = "Active Preset";
                    return descriptor;
                }
            }
        }
    }
}

Add renderscript for the Preset playerextension.


using System.IO;
using System.Threading.Tasks;
using NuGet.Versioning;
using NuKeeper.Configuration;
using NuKeeper.Inspection.RepositoryInspection;
using NuKeeper.NuGet.Process;
using NUnit.Framework;

namespace NuKeeper.Integration.Tests.NuGet.Process
{
    [TestFixture]
    public class DotNetUpdatePackageCommandTests
    {
        private readonly string _testWebApiProject =
@"<Project ToolsVersion=""15.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
  <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
  <ItemGroup><PackageReference Include=""Microsoft.AspNet.WebApi.Client""><Version>5.2.3</Version></PackageReference></ItemGroup>
  <PropertyGroup>
    <VisualStudioVersion Condition=""'$(VisualStudioVersion)' == ''"">10.0</VisualStudioVersion>
    <VSToolsPath Condition=""'$(VSToolsPath)' == ''"">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
  </PropertyGroup>
  <Import Project=""$(MSBuildBinPath)\Microsoft.CSharp.targets"" />
  <Import Project=""$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets"" Condition=""'$(VSToolsPath)' != ''"" />
</Project>";

        [Test]
        [Ignore("Known failure, issue #239")]
        public async Task ShouldNotThrowOnWebProjectMixedStyleUpdates()
        {
            const string testFolder = nameof(ShouldNotThrowOnWebProjectMixedStyleUpdates);
            const string testProject = "TestWebApiProject.csproj";
            const string packageSource = "https://api.nuget.org/v3/index.json";
            var workDirectory = Path.Combine(TestContext.CurrentContext.WorkDirectory, testFolder);
            Directory.CreateDirectory(workDirectory);
            File.WriteAllText(Path.Combine(workDirectory, testProject), _testWebApiProject);

            var command =
                new DotNetUpdatePackageCommand(
                    new UserSettings {NuGetSources = new[] {packageSource}});

            await command.Invoke(new NuGetVersion("5.2.4"), packageSource,
                new PackageInProject("Microsoft.AspNet.WebApi.Client", "5.2.3",
                    new PackagePath(workDirectory, testProject, PackageReferenceType.ProjectFile)));
        }
    }
}

Test replicating the asp webapi failure scenario


using Cosmos.Logging.Events;

namespace Cosmos.Logging.ExtraSupports
{
    public static class ExtraMessagePropertyExtensions
    {
        public static ExtraMessageProperty AsExtra(this MessageProperty property) => new ExtraMessageProperty(property);
    }
}

Add a convert extension for MessageProperty - convert message property to extra message property.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Aspose.Words.Examples.CSharp.Programming_Documents.Comments
{
    class RemoveRegionText
    {
        public static void Run()
        {
            // ExStart:RemoveRegionText
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithComments();
            string fileName = "TestFile.doc";

            // Open the document.
            Document doc = new Document(dataDir + fileName);

            CommentRangeStart commentStart = (CommentRangeStart)doc.GetChild(NodeType.CommentRangeStart, 0, true);
            CommentRangeEnd commentEnd = (CommentRangeEnd)doc.GetChild(NodeType.CommentRangeEnd, 0, true);

            Node currentNode = commentStart;
            Boolean isRemoving = true;
            while (currentNode != null && isRemoving)
            {
                if (currentNode.NodeType == NodeType.CommentRangeEnd)
                    isRemoving = false;

                Node nextNode = currentNode.NextPreOrder(doc);
                currentNode.Remove();
                currentNode = nextNode;
            }

            dataDir = dataDir + "RemoveRegionText_out.doc";
            // Save the document.
            doc.Save(dataDir);
            // ExEnd:RemoveRegionText
            Console.WriteLine("\nComments added successfully.\nFile saved at " + dataDir);
        }
    }
}

Remove text between CommentRangeStart and CommentRangeEnd


using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WalletWasabi.Backend.Models;
using WalletWasabi.Interfaces;

namespace WalletWasabi.WebClients.BlockchainInfo
{
	public class CoinstampExchangeRateProvider : IExchangeRateProvider
	{
		public async Task<List<ExchangeRate>> GetExchangeRateAsync()
		{
			using var httpClient = new HttpClient();
			httpClient.BaseAddress = new Uri("https://www.bitstamp.net");
			using var response = await httpClient.GetAsync("/api/v2/ticker/btcusd");
			using var content = response.Content;
			var rate = await content.ReadAsJsonAsync<CoinstampExchangeRate>();

			var exchangeRates = new List<ExchangeRate>
				{
					new ExchangeRate { Rate = rate.Rate, Ticker = "USD" }
				};

			return exchangeRates;
		}

		public class CoinstampExchangeRate
		{

			[JsonProperty(PropertyName = "bid")]
			public decimal Rate { get; set; }
		}
	}
}

Add Coinstamp as price provider

Add Coinstamp as price provider


using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Streams;
using Orleans.Providers;

namespace Tester.TestStreamProviders
{
    /// <summary>
    /// This is a test stream provider that throws exceptions when config file contains certain properties.
    /// </summary>
    public enum FailureInjectionStreamProviderMode
    {
        NoFault,
        InitializationThrowsException,
        StartThrowsException
    }

    public class FailureInjectionStreamProvider : IStreamProviderImpl
    {
        private FailureInjectionStreamProviderMode mode;

        public static string FailureInjectionModeString => "FAILURE_INJECTION_STREAM_PROVIDER_MODE";

        public string Name { get; set; }

        public IAsyncStream<T> GetStream<T>(Guid streamId, string streamNamespace)
        {
            throw new NotImplementedException();
        }

        public bool IsRewindable => false;

        public Task Close()
        {
            return TaskDone.Done;
        }

        public Task Init(string name, IProviderRuntime providerUtilitiesManager, IProviderConfiguration providerConfig)
        {
            Name = name;
            mode = providerConfig.GetEnumProperty(FailureInjectionModeString, FailureInjectionStreamProviderMode.NoFault);
            if (mode == FailureInjectionStreamProviderMode.InitializationThrowsException)
            {
                throw new ProviderInitializationException("Error initializing provider "+typeof(FailureInjectionStreamProvider));
            }
            return TaskDone.Done;
        }

        public Task Start()
        {
            if (mode == FailureInjectionStreamProviderMode.StartThrowsException)
            {
                throw new ProviderStartException("Error starting provider " + typeof(FailureInjectionStreamProvider).Name);
            }
            return TaskDone.Done;
        }
    }
}

using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Async;
using Orleans.Streams;
using Orleans.Providers;

namespace Tester.TestStreamProviders
{
    /// <summary>
    /// This is a test stream provider that throws exceptions when config file contains certain properties.
    /// </summary>
    public enum FailureInjectionStreamProviderMode
    {
        NoFault,
        InitializationThrowsException,
        StartThrowsException
    }

    public class FailureInjectionStreamProvider : IStreamProviderImpl
    {
        private FailureInjectionStreamProviderMode mode;

        public static string FailureInjectionModeString => "FAILURE_INJECTION_STREAM_PROVIDER_MODE";

        public string Name { get; set; }

        public IAsyncStream<T> GetStream<T>(Guid streamId, string streamNamespace)
        {
            throw new NotImplementedException();
        }

        public bool IsRewindable => false;

        public Task Close()
        {
            return TaskDone.Done;
        }

        public Task Init(string name, IProviderRuntime providerUtilitiesManager, IProviderConfiguration providerConfig)
        {
            Name = name;
            mode = providerConfig.GetEnumProperty(FailureInjectionModeString, FailureInjectionStreamProviderMode.NoFault);
            return mode == FailureInjectionStreamProviderMode.InitializationThrowsException
                ? TaskUtility.Faulted(new ProviderInitializationException("Error initializing provider " + typeof(FailureInjectionStreamProvider)))
                : TaskDone.Done;
        }

        public Task Start()
        {
            return mode == FailureInjectionStreamProviderMode.StartThrowsException
                ? TaskUtility.Faulted(new ProviderStartException("Error starting provider " + typeof(FailureInjectionStreamProvider).Name))
                : TaskDone.Done;
        }
    }
}

Return exceptions in faulted tasks.

Return exceptions in faulted tasks.


namespace Storm.Binding.AndroidTarget.Helper
{
	public static class NameGeneratorHelper
	{
		private const string VIEWHOLDER_FORMAT = "AutoGen_ViewHolder_{0}";
		private static int _viewHolderCounter;

		public static string GetViewHolderName()
		{
			return string.Format(VIEWHOLDER_FORMAT, _viewHolderCounter++);
		}
	}
}

Add helper class to generate all names

Add helper class to generate all names


using System.Globalization;

namespace Meziantou.Framework;

public static class FormattableExtensions
{
    public static string ToStringInvariant<T>(this T value) where T : IFormattable
    {
        return ToStringInvariant(value, format: null);
    }

    public static string ToStringInvariant<T>(this T value, string? format) where T : IFormattable
    {
        if (format != null)
            return value.ToString(format, CultureInfo.InvariantCulture);

        return "";
    }
}

Add ToStringInvariant method for IFormattable


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osuTK;

namespace osu.Framework.Tests.Visual.Input
{
    public class TestScenePlatformActionContainer : FrameworkTestScene
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            Add(new TestPlatformActionHandler
            {
                RelativeSizeAxes = Axes.Both
            });
        }

        private class TestPlatformActionHandler : CompositeDrawable
        {
            [BackgroundDependencyLoader]
            private void load()
            {
                InternalChild = new FillFlowContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    Padding = new MarginPadding(20),
                    Spacing = new Vector2(10),
                    ChildrenEnumerable = Enum.GetValues(typeof(PlatformAction))
                                             .Cast<PlatformAction>()
                                             .Select(action => new PlatformBindingBox(action))
                };
            }
        }

        private class PlatformBindingBox : CompositeDrawable, IKeyBindingHandler<PlatformAction>
        {
            private readonly PlatformAction platformAction;

            private Box background;

            public PlatformBindingBox(PlatformAction platformAction)
            {
                this.platformAction = platformAction;
            }

            [BackgroundDependencyLoader]
            private void load()
            {
                AutoSizeAxes = Axes.Both;
                InternalChildren = new Drawable[]
                {
                    background = new Box
                    {
                        RelativeSizeAxes = Axes.Both,
                        Colour = FrameworkColour.GreenDarker
                    },
                    new SpriteText
                    {
                        Text = platformAction.ToString(),
                        Margin = new MarginPadding(10)
                    }
                };
            }

            public bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
            {
                if (e.Action != platformAction)
                    return false;

                background.FlashColour(FrameworkColour.YellowGreen, 250, Easing.OutQuint);
                return true;
            }

            public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
            {
            }
        }
    }
}

Add basic test scene for testing platform actions


// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

// ****************************************************************
//              Generated by the NUnit Syntax Generator
//
// Command Line: __COMMANDLINE__
//
//                  DO NOT MODIFY THIS FILE DIRECTLY
// ****************************************************************

using System;
using System.Collections;
using NUnit.Framework.Constraints;

namespace NUnit.Framework
{
    /// <summary>
    /// Helper class with properties and methods that supply
    /// a number of constraints used in Asserts.
    /// </summary>
    public class Contains
    {
        // $$GENERATE$$ $$STATIC$$
    }
}

Add file missed in bug fix 440109

Add file missed in bug fix 440109

--HG--
branch : bug-fix-440109
extra : convert_revision : charlie%40nunit.com-20091011205012-8qlpq4dtg1kdfyv9


// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.IaasCmdletInfo
{
    using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.PowershellCore;
    using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;

    public class RemoveAzureDataDiskCmdletInfo : CmdletsInfo
    {
        public RemoveAzureDataDiskCmdletInfo(RemoveAzureDataDiskConfig discCfg)
        {
            this.cmdletName = Utilities.RemoveAzureDataDiskCmdletName;
            this.cmdletParams.Add(new CmdletParam("LUN", discCfg.lun));
            this.cmdletParams.Add(new CmdletParam("VM", discCfg.Vm));
        }
    }
}

Add cmdlet information for Remove-AzureDataDisk


#region auto-generated FILE INFORMATION

// ==============================================
// This file is distributed under the MIT License
// ==============================================
//
// Filename: AssemblyInfo.cs
// Version:  2018-06-02 15:41
//
// Copyright (c) 2018, Si13n7 Developments (r)
// All rights reserved.
// ______________________________________________

#endregion

namespace SilDev
{
    using System;
    using System.Reflection;

    /// <summary>
    ///     Provides information for the current assembly.
    /// </summary>
    public static class AssemblyInfo
    {
        /// <summary>
        ///     Gets company name information.
        /// </summary>
        public static string Company => GetAssembly<AssemblyCompanyAttribute>()?.Company;

        /// <summary>
        ///     Gets configuration information.
        /// </summary>
        public static string Configuration => GetAssembly<AssemblyDescriptionAttribute>()?.Description;

        /// <summary>
        ///     Gets copyright information.
        /// </summary>
        public static string Copyright => GetAssembly<AssemblyCopyrightAttribute>()?.Copyright;

        /// <summary>
        ///     Gets description information.
        /// </summary>
        public static string Description => GetAssembly<AssemblyDescriptionAttribute>()?.Description;

        /// <summary>
        ///     Gets file version information.
        /// </summary>
        public static string FileVersion => GetAssembly<AssemblyFileVersionAttribute>()?.Version;

        /// <summary>
        ///     Gets product information.
        /// </summary>
        public static string Product => GetAssembly<AssemblyProductAttribute>()?.Product;

        /// <summary>
        ///     Gets title information.
        /// </summary>
        public static string Title => GetAssembly<AssemblyTitleAttribute>()?.Title;

        /// <summary>
        ///     Gets trademark information.
        /// </summary>
        public static string Trademark => GetAssembly<AssemblyTrademarkAttribute>()?.Trademark;

        /// <summary>
        ///     Gets version information.
        /// </summary>
        public static string Version => Assembly.GetEntryAssembly()?.GetName().Version?.ToString();

        private static TSource GetAssembly<TSource>() where TSource : Attribute
        {
            try
            {
                var assembly = Attribute.GetCustomAttribute(Assembly.GetEntryAssembly(), typeof(TSource));
                return (TSource)assembly;
            }
            catch
            {
                return default(TSource);
            }
        }
    }
}

Add class to get information about the current assembly.


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;

namespace osu.Game.Screens.Edit.Compose.Components
{
    /// <summary>
    /// Represents a display composite containing and managing the visibility state of the selection box's drag handles.
    /// </summary>
    public class SelectionBoxDragHandleDisplay : CompositeDrawable
    {
        private Container<SelectionBoxScaleHandle> scaleHandles;
        private Container<SelectionBoxRotationHandle> rotationHandles;

        private readonly List<SelectionBoxDragHandle> allDragHandles = new List<SelectionBoxDragHandle>();

        public new MarginPadding Padding
        {
            get => base.Padding;
            set => base.Padding = value;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            InternalChildren = new Drawable[]
            {
                scaleHandles = new Container<SelectionBoxScaleHandle>
                {
                    RelativeSizeAxes = Axes.Both,
                },
                rotationHandles = new Container<SelectionBoxRotationHandle>
                {
                    RelativeSizeAxes = Axes.Both,
                    Padding = new MarginPadding(-12.5f),
                },
            };
        }

        public void AddScaleHandle(SelectionBoxScaleHandle handle)
        {
            bindDragHandle(handle);
            scaleHandles.Add(handle);
        }

        public void AddRotationHandle(SelectionBoxRotationHandle handle)
        {
            handle.Alpha = 0;
            handle.AlwaysPresent = true;

            bindDragHandle(handle);
            rotationHandles.Add(handle);
        }

        private void bindDragHandle(SelectionBoxDragHandle handle)
        {
            handle.HoverGained += updateRotationHandlesVisibility;
            handle.HoverLost += updateRotationHandlesVisibility;
            handle.OperationStarted += updateRotationHandlesVisibility;
            handle.OperationEnded += updateRotationHandlesVisibility;
            allDragHandles.Add(handle);
        }

        private SelectionBoxRotationHandle displayedRotationHandle;
        private SelectionBoxDragHandle activeHandle;

        private void updateRotationHandlesVisibility()
        {
            if (activeHandle?.InOperation == true || activeHandle?.IsHovered == true)
                return;

            displayedRotationHandle?.FadeOut(SelectionBoxControl.TRANSFORM_DURATION, Easing.OutQuint);
            displayedRotationHandle = null;

            activeHandle = allDragHandles.SingleOrDefault(h => h.InOperation);
            activeHandle ??= allDragHandles.SingleOrDefault(h => h.IsHovered);

            if (activeHandle != null)
            {
                displayedRotationHandle = getCorrespondingRotationHandle(activeHandle, rotationHandles);
                displayedRotationHandle?.FadeIn(SelectionBoxControl.TRANSFORM_DURATION, Easing.OutQuint);
            }
        }

        /// <summary>
        /// Gets the rotation handle corresponding to the given handle.
        /// </summary>
        [CanBeNull]
        private static SelectionBoxRotationHandle getCorrespondingRotationHandle(SelectionBoxDragHandle handle, IEnumerable<SelectionBoxRotationHandle> rotationHandles)
        {
            if (handle is SelectionBoxRotationHandle rotationHandle)
                return rotationHandle;

            return rotationHandles.SingleOrDefault(r => r.Anchor == handle.Anchor);
        }
    }
}

Add composite managing display of selection box drag handles


namespace EventStore.Persistence.AcceptanceTests.Engines
{
	using MongoPersistence;
	using Serialization;

	public class AcceptanceTestMongoPersistenceFactory : MongoPersistenceFactory
	{
		public AcceptanceTestMongoPersistenceFactory()
			: base("Mongo", new NullDocumentSerializer())
		{
		}
		protected override string TransformConnectionString(string connectionString)
		{
			return connectionString
				.Replace("[HOST]", "host".GetSetting() ?? "localhost")
				.Replace("[PORT]", "port".GetSetting() ?? string.Empty)
				.Replace("[DATABASE]", "database".GetSetting() ?? "EventStore2")
				.Replace("[USER]", "user".GetSetting() ?? string.Empty)
				.Replace("[PASSWORD]", "password".GetSetting() ?? string.Empty);
		}
	}
}

namespace EventStore.Persistence.AcceptanceTests.Engines
{
	using MongoPersistence;
	using Serialization;

	public class AcceptanceTestMongoPersistenceFactory : MongoPersistenceFactory
	{
		public AcceptanceTestMongoPersistenceFactory()
			: base("Mongo", new DocumentObjectSerializer())
		{
		}
		protected override string TransformConnectionString(string connectionString)
		{
			return connectionString
				.Replace("[HOST]", "host".GetSetting() ?? "localhost")
				.Replace("[PORT]", "port".GetSetting() ?? string.Empty)
				.Replace("[DATABASE]", "database".GetSetting() ?? "EventStore2")
				.Replace("[USER]", "user".GetSetting() ?? string.Empty)
				.Replace("[PASSWORD]", "password".GetSetting() ?? string.Empty);
		}
	}
}

Use new DocumentObjectSerializer in Mongo test setup


// Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE

using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;

namespace Nuke.Common.Utilities
{
    public static partial class StringExtensions
    {
        [Pure]
        public static string Prepend(this string str, string prependText)
        {
            return prependText + str;
        }

        [Pure]
        public static string Append(this string str, string appendText)
        {
            return str + appendText;
        }
    }
}

Add Prepend and Append extension methods


// Copyright 2021 Google LLC
//
// 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
//
//     https://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 lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;

// Note: this will eventually be generated in ComputeLroAdaptation.g.cs. It's the last bit of generator work we need to do.

namespace Google.Cloud.Compute.V1
{
    partial class Operation
    {
        internal lro::Operation ToLroResponse(string name)
        {
            // TODO: Work this out much more carefully. In particular, consider whether a Compute LRO can complete successfully with errors...
            var proto = new lro::Operation
            {
                // Derived from [(google.cloud.operation_field) = STATUS]
                Done = Status == Types.Status.Done,
                // Taken from [(google.cloud.operation_field) = NAME]
                Name = name,
                // Always pack the raw response as metadata
                Metadata = wkt::Any.Pack(this)
            };
            if (proto.Done)
            {
                // Only pack the raw response as the LRO Response if we're done
                proto.Response = proto.Metadata;
            }
            // Derived from [(google.cloud.operation_field) = ERROR_CODE] and [(google.cloud.operation_field) = ERROR_MESSAGE]
            if (HasHttpErrorStatusCode)
            {
                // FIXME: Convert the HTTP status code into a suitable Rpc.Status code.
                proto.Error = new Rpc.Status { Code = HttpErrorStatusCode, Message = HttpErrorMessage };
            }
            return proto;
        }
    }
}

feat: Add handwritten code for Operation.ToLroResponse()

This will eventually be generated, but the details are still
somewhat volatile, and will be relatively fiddly to implement.

For now, we can add this code manually, and remove it later (even if
the API changes - it's internal).