using System;

namespace Toggl.Phoebe.Data.DataObjects
{
    public abstract class CommonData
    {
        protected CommonData ()
        {
            ModifiedAt = Time.UtcNow;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Toggl.Phoebe.Data.DataObjects.CommonData"/> class copying
        /// the data from the other object.
        /// </summary>
        /// <param name="other">Instance to copy data from.</param>
        protected CommonData (CommonData other)
        {
            Id = other.Id;
            ModifiedAt = other.ModifiedAt;
            DeletedAt = other.DeletedAt;
            IsDirty = other.IsDirty;
            RemoteId = other.RemoteId;
            RemoteRejected = other.RemoteRejected;
        }

        [DontDirty]
        [SQLite.PrimaryKey]
        public Guid Id { get; set; }

        public DateTime ModifiedAt { get; set; }

        public DateTime? DeletedAt { get; set; }

        [DontDirty]
        public bool IsDirty { get; set; }

        [DontDirty]
        [SQLite.Unique]
        public long? RemoteId { get; set; }

        [DontDirty]
        public bool RemoteRejected { get; set; }
    }
}

using System;
using SQLite;

namespace Toggl.Phoebe.Data.DataObjects
{
    public abstract class CommonData
    {
        protected CommonData ()
        {
            ModifiedAt = Time.UtcNow;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Toggl.Phoebe.Data.DataObjects.CommonData"/> class copying
        /// the data from the other object.
        /// </summary>
        /// <param name="other">Instance to copy data from.</param>
        protected CommonData (CommonData other)
        {
            Id = other.Id;
            ModifiedAt = other.ModifiedAt;
            DeletedAt = other.DeletedAt;
            IsDirty = other.IsDirty;
            RemoteId = other.RemoteId;
            RemoteRejected = other.RemoteRejected;
        }

        [DontDirty]
        [PrimaryKey, AutoIncrement]
        public Guid Id { get; set; }

        public DateTime ModifiedAt { get; set; }

        public DateTime? DeletedAt { get; set; }

        [DontDirty]
        public bool IsDirty { get; set; }

        [DontDirty]
        [Unique]
        public long? RemoteId { get; set; }

        [DontDirty]
        public bool RemoteRejected { get; set; }
    }
}

Make primary key auto increment.

Make primary key auto increment.


// 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.

#nullable enable

using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osu.Game.Tests.Visual;

namespace osu.Game.Tests.Rulesets
{
    [HeadlessTest]
    public class TestSceneBrokenRulesetHandling : OsuTestScene
    {
        [Resolved]
        private OsuGameBase gameBase { get; set; } = null!;

        [Test]
        public void TestNullModsReturnedByRulesetAreIgnored()
        {
            AddStep("set ruleset with null mods", () => Ruleset.Value = new TestRulesetWithNullMods().RulesetInfo);
            AddAssert("no null mods in available mods", () => gameBase.AvailableMods.Value.SelectMany(kvp => kvp.Value).All(mod => mod != null));
        }

#nullable disable // purposefully disabling nullability to simulate broken or unannotated API user code.

        private class TestRulesetWithNullMods : Ruleset
        {
            public override string ShortName => "nullmods";
            public override string Description => "nullmods";

            public override IEnumerable<Mod> GetModsFor(ModType type) => new Mod[] { null };

            public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => null;
            public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => null;
            public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => null;
        }

#nullable enable
    }
}

Add test coverage for ignoring null mods returned by rulesets


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

using System.Linq;
using Xunit;

namespace System.Diagnostics.Tests
{
    public class ProcessModuleTests : ProcessTestBase
    {
        [Fact]
        public void TestModuleProperties()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.True(modules.Count > 0);

            foreach (ProcessModule module in modules)
            {
                Assert.NotNull(module);

                Assert.NotNull(module.FileName);
                Assert.NotEmpty(module.FileName);

                Assert.InRange(module.BaseAddress.ToInt64(), 0, long.MaxValue);
                Assert.InRange(module.EntryPointAddress.ToInt64(), 0, long.MaxValue);
                Assert.InRange(module.ModuleMemorySize, 0, long.MaxValue);
            }
        }

        [Fact]
        [PlatformSpecific(PlatformID.AnyUnix)]
        public void TestModulesContainsCorerun()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("corerun"));
        }

        [Fact]
        [PlatformSpecific(PlatformID.Linux)] // OSX only includes the main module
        public void TestModulesContainsUnixNativeLibs()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("libcoreclr"));
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("System.Native"));
        }
    }
}

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

using System.Linq;
using Xunit;

namespace System.Diagnostics.Tests
{
    public class ProcessModuleTests : ProcessTestBase
    {
        [Fact]
        public void TestModuleProperties()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.True(modules.Count > 0);

            foreach (ProcessModule module in modules)
            {
                Assert.NotNull(module);

                Assert.NotNull(module.FileName);
                Assert.NotEmpty(module.FileName);

                Assert.InRange(module.BaseAddress.ToInt64(), long.MinValue, long.MaxValue);
                Assert.InRange(module.EntryPointAddress.ToInt64(), long.MinValue, long.MaxValue);
                Assert.InRange(module.ModuleMemorySize, 0, long.MaxValue);
            }
        }

        [Fact]
        [PlatformSpecific(PlatformID.AnyUnix)]
        public void TestModulesContainsCorerun()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("corerun"));
        }

        [Fact]
        [PlatformSpecific(PlatformID.Linux)] // OSX only includes the main module
        public void TestModulesContainsUnixNativeLibs()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("libcoreclr"));
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("System.Native"));
        }
    }
}

Change the check range for BaseAddress and EntryPointAddress

IntPtr::ToInt64() returns a signed value
so it should be checked btw long.MinValue and long.MaxValue.

Signed-off-by: Jiyoung Yun <888ab5aac88c5184952942ca1558a2962a0a2b47@samsung.com>


using UIKit;
using Foundation;

namespace OpenGLESSampleGameView
{
	// The name AppDelegate is referenced in the MainWindow.xib file.
	public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate
	{
		// This method is invoked when the application has loaded its UI and its ready to run
		public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
		{
			// If you have defined a view, add it here:
			// window.AddSubview (navigationController.View);

			glView.Run(60.0);

			window.MakeKeyAndVisible ();

			return true;
		}

		public override void OnResignActivation (UIApplication application)
		{
			glView.Stop();
			glView.Run(5.0);
		}

		// This method is required in iPhoneOS 3.0
		public override void OnActivated (UIApplication application)
		{
			glView.Stop();
			glView.Run(60.0);

		}
	}
}

using UIKit;
using Foundation;

namespace OpenGLESSampleGameView
{
	// The name AppDelegate is referenced in the MainWindow.xib file.
	public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate
	{
		// This method is invoked when the application has loaded its UI and its ready to run
		public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
		{
			glView.Run (60.0);
			var rootViewController = new UIViewController {
				View = glView
			};
			window.RootViewController = rootViewController;
			window.MakeKeyAndVisible ();

			return true;
		}

		public override void OnResignActivation (UIApplication application)
		{
			glView.Stop();
			glView.Run(5.0);
		}

		// This method is required in iPhoneOS 3.0
		public override void OnActivated (UIApplication application)
		{
			glView.Stop();
			glView.Run(60.0);

		}
	}
}

[OpenGLES-GameView] Fix startup error - setup root view controller


// 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.Threading.Tasks;
using Openchain.Ledger.Validation;
using Xunit;

namespace Openchain.Ledger.Tests
{
    public class P2pkhIssuanceImplicitLayoutTests
    {
        private static readonly string address = "n12RA1iohYEerfXiBixSoERZG8TP8xQFL2";
        private static readonly SignatureEvidence[] evidence = new[] { new SignatureEvidence(ByteString.Parse("abcdef"), ByteString.Empty) };

        [Fact]
        public async Task GetPermissions_Root()
        {
            P2pkhIssuanceImplicitLayout layout = new P2pkhIssuanceImplicitLayout(new KeyEncoder(111));

            PermissionSet result = await layout.GetPermissions(evidence, LedgerPath.Parse("/"), true, $"/asset/p2pkh/{address}/");

            Assert.Equal(Access.Unset, result.AccountModify);
            Assert.Equal(Access.Permit, result.AccountNegative);
            Assert.Equal(Access.Unset, result.AccountSpend);
            Assert.Equal(Access.Unset, result.DataModify);
        }

        [Fact]
        public async Task GetPermissions_Modify()
        {
            P2pkhIssuanceImplicitLayout layout = new P2pkhIssuanceImplicitLayout(new KeyEncoder(111));

            PermissionSet result = await layout.GetPermissions(evidence, LedgerPath.Parse($"/asset/p2pkh/mgToXgKQqY3asA76uYU82BXMLGrHNm5ZD9/"), true, $"/asset-path/");

            Assert.Equal(Access.Permit, result.AccountModify);
            Assert.Equal(Access.Unset, result.AccountNegative);
            Assert.Equal(Access.Unset, result.AccountSpend);
            Assert.Equal(Access.Unset, result.DataModify);
        }

        [Fact]
        public async Task GetPermissions_Spend()
        {
            P2pkhIssuanceImplicitLayout layout = new P2pkhIssuanceImplicitLayout(new KeyEncoder(111));

            PermissionSet result = await layout.GetPermissions(evidence, LedgerPath.Parse($"/asset/p2pkh/{address}/"), true, $"/asset-path/");

            Assert.Equal(Access.Permit, result.AccountModify);
            Assert.Equal(Access.Unset, result.AccountNegative);
            Assert.Equal(Access.Permit, result.AccountSpend);
            Assert.Equal(Access.Permit, result.DataModify);
        }
    }
}

Add unit tests for the P2pkhIssuanceImplicitLayout class


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.TemplateEngine.Abstractions;

namespace Microsoft.TemplateEngine.Edge
{
    public class AssemblyComponentCatalog : IReadOnlyList<KeyValuePair<Guid, Func<Type>>>
    {
        private readonly IReadOnlyList<Assembly> _assemblies;
        private IReadOnlyList<KeyValuePair<Guid, Func<Type>>> _lookup;

        public AssemblyComponentCatalog(IReadOnlyList<Assembly> assemblies)
        {
            _assemblies = assemblies;
        }

        public KeyValuePair<Guid, Func<Type>> this[int index]
        {
            get
            {
                EnsureLoaded();
                return _lookup[index];
            }
        }

        public int Count
        {
            get
            {
                EnsureLoaded();
                return _lookup.Count;
            }
        }

        public IEnumerator<KeyValuePair<Guid, Func<Type>>> GetEnumerator()
        {
            EnsureLoaded();
            return _lookup.GetEnumerator();
        }

        private void EnsureLoaded()
        {
            if(_lookup != null)
            {
                return;
            }

            Dictionary<Guid, Func<Type>> builder = new Dictionary<Guid, Func<Type>>();

            foreach (Assembly asm in _assemblies)
            {
                foreach (Type type in asm.GetTypes())
                {
                    if (!typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(type) || type.GetTypeInfo().GetConstructor(Type.EmptyTypes) == null || !type.GetTypeInfo().IsClass)
                    {
                        continue;
                    }

                    IReadOnlyList<Type> registerFor = type.GetTypeInfo().ImplementedInterfaces.Where(x => x != typeof(IIdentifiedComponent) && typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(x)).ToList();
                    if (registerFor.Count == 0)
                    {
                        continue;
                    }

                    IIdentifiedComponent instance = (IIdentifiedComponent)Activator.CreateInstance(type);
                    builder[instance.Id] = () => type;
                }
            }

            _lookup = builder.ToList();
        }

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}

Enable scanning at the assembly level for components for the dotnet CLI


using System;
using Xunit;
using OutputColorizer;
using System.IO;

namespace UnitTests
{
    public partial class ConsoleWriterTests
    {
        [Fact]
        public void TestGetForegroundColor()
        {
            ConsoleWriter cw = new ConsoleWriter();
            Assert.Equal(Console.ForegroundColor, cw.ForegroundColor);
        }

        [Fact]
        public void TestSetForegroundColor()
        {
            ConsoleWriter cw = new ConsoleWriter();
            ConsoleColor before = Console.ForegroundColor;

            cw.ForegroundColor = ConsoleColor.Black;

            Assert.Equal(Console.ForegroundColor, ConsoleColor.Black);

            cw.ForegroundColor = before;
            Assert.Equal(Console.ForegroundColor, before);
        }

        [Fact]
        public void TestWrite()
        {
            ConsoleWriter cw = new ConsoleWriter();
            StringWriter tw = new StringWriter();
            Console.SetOut(tw);

            cw.Write("test");
            cw.Write("bar");

            Assert.Equal("testbar", tw.GetStringBuilder().ToString());
        }

        [Fact]
        public void TestWriteLine()
        {
            ConsoleWriter cw = new ConsoleWriter();
            StringWriter tw = new StringWriter();
            Console.SetOut(tw);

            cw.WriteLine("test2");
            cw.WriteLine("bar");

            Assert.Equal("test2\nbar\n", tw.GetStringBuilder().ToString());
        }
    }
}

Add tests for the ConsoleWriter

Add tests for the ConsoleWriter


#region License
//
// Dasher
//
// Copyright 2015-2016 Drew Noakes
//
//    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.
//
// More information about this project is available at:
//
//    https://github.com/drewnoakes/dasher
//
#endregion

using System;
using System.Reflection;
using Xunit;

namespace Dasher.Tests
{
    public class MethodsTests
    {
        [Fact]
        public void AllReflectedMethodsNonNull()
        {
            var properties = typeof(DasherContext).GetTypeInfo().Assembly.GetType("Dasher.Methods", throwOnError: true).GetProperties();

            foreach (var property in properties)
            {
                var value = property.GetValue(null);

                Assert.True(value != null, $"Dasher.Methods.{property.Name} shouldn't be null");
            }
        }
    }
}

Add test that validates all reflected methods are non-null.


using System;
using System.Collections.Generic;
using CppSharp.AST;
using CppSharp.Generators;
using CppSharp.Generators.CLI;
using CppSharp.Passes;

namespace CppSharp
{
    public class ObjectOverridesPass : TranslationUnitPass
    {
        void OnUnitGenerated(GeneratorOutput output)
        {
            foreach (var template in output.Templates)
            {
                foreach (var block in template.FindBlocks(CLIBlockKind.MethodBody))
                {
                    var method = block.Declaration as Method;
                    switch (method.Name)
                    {
                    case "GetHashCode":
                        block.Write("return (int)NativePtr;");
                        break;
                    case "Equals":
                        block.WriteLine("if (!object) return false;");
                        block.Write("return Instance == safe_cast<ICppInstance^>({0})->Instance;",
                                    method.Parameters[0].Name);
                        break;
                    }
                }
            }
        }

        private bool isHooked;
        public override bool VisitClassDecl(Class @class)
        {
            // FIXME: Add a better way to hook the event
            if (!isHooked)
            {
                Driver.Generator.OnUnitGenerated += OnUnitGenerated;
                isHooked = true;
            }

            if (!VisitDeclaration(@class))
                return false;

            if (AlreadyVisited(@class))
                return true;

            if (@class.IsValueType)
                return false;

            var methodEqualsParam = new Parameter
            {
                Name = "object",
                QualifiedType = new QualifiedType(new CILType(typeof(Object))),
            };

            var methodEquals = new Method
            {
                Name = "Equals",
                Namespace = @class,
                ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Bool)),
                Parameters = new List<Parameter> { methodEqualsParam },
                IsSynthetized = true,
                IsOverride = true,
                IsProxy = true
            };
             @class.Methods.Add(methodEquals);

            var methodHashCode = new Method
            {
                Name = "GetHashCode",
                Namespace = @class,
                ReturnType = new QualifiedType(new BuiltinType(PrimitiveType.Int32)),
                IsSynthetized = true,
                IsOverride = true,
                IsProxy = true
            };

            @class.Methods.Add(methodHashCode);
            return true;
        }
    }
}

Add work-in-progress ObjectOverrides pass that adds GetHashCode and Equals overrides.


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Xamarin.Forms;

namespace ProjectTracker.Ui.Xamarin.Xaml
{
  public class BoolColorConverter : IValueConverter
  {
    public Color TrueColor { get; set; }
    public Color FalseColor { get; set; }
    public bool Invert { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      var v = (bool)value;
      if (Invert)
        v = !v;
      if (v)
        return TrueColor;
      else
        return FalseColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }
}

Use PropertyInfo control in mobile apps

Use PropertyInfo control in mobile apps


using System;
using slang.Lexing.Tokens;
namespace slang.Lexing.Trees.Nodes
{
    public class Transition
    {
        public Transition (Node target, Func<Token> tokenProducer = null)
        {
            Target = target;
            TokenProducer = tokenProducer;
        }

        public Token GetToken()
        {
            if(TokenProducer != null)
            {
                return TokenProducer ();
            }

            return null;
        }

        public Func<Token> TokenProducer { get; private set; }

        public void Returns (Func<Token> tokenProducer)
        {
            TokenProducer = tokenProducer;
        }

        public Node Target { get; }
    }
}

Add a model for transitions

Add a model for transitions

Add the token producer function to transition so it can be triggered when the transition is executed.


// 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.

#nullable enable
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using osu.Framework.Logging;

namespace osu.Game.Online.Multiplayer
{
    public static class MultiplayerClientExtensions
    {
        public static void FireAndForget(this Task task, Action? onSuccess = null, Action<Exception>? onError = null) =>
            task.ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    Exception? exception = t.Exception;

                    if (exception is AggregateException ae)
                        exception = ae.InnerException;

                    Debug.Assert(exception != null);

                    string message = exception is HubException
                        // HubExceptions arrive with additional message context added, but we want to display the human readable message:
                        // "An unexpected error occurred invoking 'AddPlaylistItem' on the server.InvalidStateException: Can't enqueue more than 3 items at once."
                        // We generally use the message field for a user-parseable error (eventually to be replaced), so drop the first part for now.
                        ? exception.Message.Substring(exception.Message.IndexOf(':') + 1).Trim()
                        : exception.Message;

                    Logger.Log(message, level: LogLevel.Important);
                    onError?.Invoke(exception);
                }
                else
                {
                    onSuccess?.Invoke();
                }
            });
    }
}

Add helper class to handle firing async multiplayer methods


using ScheduleManager.forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ScheduleManager.model;

namespace ScheduleManager.common
{
    class SingletonSesion
    {
        private volatile static SingletonSesion objetoUsuarios;
        private static object bloqueoObjeto = new object();
        private ScheduleManagerEntities contexto;

        private SingletonSesion()
        {

        }

        public static SingletonSesion CreacionInstancia()
        {
            if (objetoUsuarios == null)
            {
                lock (bloqueoObjeto)
                {
                    if (objetoUsuarios == null)
                    {
                        objetoUsuarios = new SingletonSesion();
                    }
                }
            }
            return objetoUsuarios;
        }

        public void AñadirUsuarios(int usuario)
        {
            contexto = new ScheduleManagerEntities();
            var query = contexto.Usuarios.FirstOrDefault(u => u.id_usuario == usuario && u.id_cuenta == 1);
            if (query != null)
            {
                UserAddForm forma = new UserAddForm();
                forma.Show();
            }
            else
            {
                MessageBox.Show("No tiene permiso");
            }
        }
    }
}

Add Singleton for the Session

Add Singleton for the Session


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cache;
using NHibernate.Cfg;
using NHibernate.Engine;
using NHibernate.Type;

namespace BoC.Persistence.NHibernate.Cache
{
    /// <summary>
    /// This class works around the bug that you can't request Projections
    /// when the query is set to cacheable...
    /// Should be fixed in the next nhibernate I hope, and then this class can be removed
    /// </summary>
    public class ProjectionEnabledQueryCache : StandardQueryCache, IQueryCache
    {
        public ProjectionEnabledQueryCache(Settings settings, IDictionary<string, string> props, UpdateTimestampsCache updateTimestampsCache, string regionName) : base(settings, props, updateTimestampsCache, regionName) {}

        bool IQueryCache.Put(QueryKey key, ICacheAssembler[] returnTypes, IList result, bool isNaturalKeyLookup, ISessionImplementor session)
        {
            //if the returntypes contains simple values, assume it's a projection:
            if (returnTypes.OfType<IType>().Any(t => t.ReturnedClass != null && (t.ReturnedClass.IsValueType || t.ReturnedClass.IsPrimitive || t.ReturnedClass == typeof(String))))
                return false;

            return this.Put(key, returnTypes, result, isNaturalKeyLookup, session);
        }
    }

    public class ProjectionEnabledQueryCacheFactory : IQueryCacheFactory
    {
        public IQueryCache GetQueryCache(string regionName,
                                                                         UpdateTimestampsCache updateTimestampsCache,
                                                                         Settings settings,
                                                                         IDictionary<string, string> props)
        {
            return new ProjectionEnabledQueryCache(settings, props, updateTimestampsCache, regionName);
        }
    }
}

Check if the query is a projection-query before trying to add it to the cache (nhibernate will choke on that)


/*
 * Copyright (c) 2021, Norsk Helsenett SF and contributors
 * See the file CONTRIBUTORS for details.
 *
 * This file is licensed under the MIT license
 * available at https://raw.githubusercontent.com/helsenorge/Helsenorge.Messaging/master/LICENSE
 */

using Helsenorge.Messaging.ServiceBus;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Helsenorge.Messaging.Tests.ServiceBus
{
    [TestClass]
    public class ServiceBusConnectionTests
    {
        private static string ConnectionString = "amqps://guest:guest@messagebroker.nhn.no/NameSpaceTest";

        [TestMethod]
        public void CanGetEnityNameForReceiverLinkForRabbitMQ()
        {
            var serviceBusConnection = new ServiceBusConnection(ConnectionString, MessageBrokerDialect.RabbitMQ, new Logger<ServiceBusConnectionTests>(new NullLoggerFactory()));
            var entityName = serviceBusConnection.GetEntityName("my-queue-name", LinkRole.Receiver);
            Assert.AreEqual("/amq/queue/my-queue-name", entityName);
        }

        [TestMethod]
        public void CanGetEnityNameForSenderLinkForRabbitMQ()
        {
            var serviceBusConnection = new ServiceBusConnection(ConnectionString, MessageBrokerDialect.RabbitMQ, new Logger<ServiceBusConnectionTests>(new NullLoggerFactory()));
            var entityName = serviceBusConnection.GetEntityName("my-queue-name", LinkRole.Sender);
            Assert.AreEqual("/exchange/NameSpaceTest/my-queue-name", entityName);
        }

        [TestMethod]
        public void CanGetEnityNameForReceiverLinkForServiceBus()
        {
            var serviceBusConnection = new ServiceBusConnection(ConnectionString, MessageBrokerDialect.ServiceBus, new Logger<ServiceBusConnectionTests>(new NullLoggerFactory()));
            var entityName = serviceBusConnection.GetEntityName("my-queue-name", LinkRole.Receiver);
            Assert.AreEqual("NameSpaceTest/my-queue-name", entityName);
        }

        [TestMethod]
        public void CanGetEnityNameForSenderLinkForServiceBus()
        {
            var serviceBusConnection = new ServiceBusConnection(ConnectionString, MessageBrokerDialect.ServiceBus, new Logger<ServiceBusConnectionTests>(new NullLoggerFactory()));
            var entityName = serviceBusConnection.GetEntityName("my-queue-name", LinkRole.Sender);
            Assert.AreEqual("NameSpaceTest/my-queue-name", entityName);
        }
    }
}

Tests: Verify correct output from ServiceBusConnection.GetEntityName

This adds tests to verify that we get the correct output from
ServiceBusConnection.GetEntityName based on Message Broker Dialect and
Role of the Link.


/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.ClientStack.LindenUDP;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;

namespace OpenSim.Region.OptionalModules.Avatar.Attachments
{
    /// <summary>
    /// A module that just holds commands for inspecting avatar appearance.
    /// </summary>
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TempAttachmentsModule")]
    public class TempAttachmentsModule : INonSharedRegionModule
    {
        public void Initialise(IConfigSource configSource)
        {
        }

        public void AddRegion(Scene scene)
        {
        }

        public void RemoveRegion(Scene scene)
        {
        }

        public void RegionLoaded(Scene scene)
        {
        }

        public void Close()
        {
        }

        public Type ReplaceableInterface
        {
            get { return null; }
        }

        public string Name
        {
            get { return "TempAttachmentsModule"; }
        }
    }
}

Add the skeleton for the temp attachments module


using System;
using NUnit.Framework;
using SevenDigital.Api.Wrapper.Exceptions;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.LockerEndpoint;

namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions
{
	[TestFixture]
	public class ApiXmlExceptionTests
	{
		[Test]
		public void Should_fail_correctly_if_xml_error_returned()
		{
			// -- Deliberate error response
			Console.WriteLine("Trying artist/details without artistId parameter...");
			var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Artist>.Get.Please());

			Assert.That(apiXmlException.Error.Code, Is.EqualTo(1001));
			Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("Missing parameter artistId."));
		}

		[Test]
		public void Should_fail_correctly_if_non_xml_error_returned_eg_unauthorised()
		{
				// -- Deliberate unauthorized response
				Console.WriteLine("Trying user/locker without any credentials...");
				var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Locker>.Get.Please());
				Assert.That(apiXmlException.Error.Code, Is.EqualTo(9001));
				Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("OAuth authentication error: Not authorised - no user credentials provided"));
		}
	}
}

using System;
using NUnit.Framework;
using SevenDigital.Api.Wrapper.Exceptions;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.LockerEndpoint;

namespace SevenDigital.Api.Wrapper.Integration.Tests.Exceptions
{
	[TestFixture]
	public class ApiXmlExceptionTests
	{
		[Test]
		public void Should_fail_correctly_if_xml_error_returned()
		{
			// -- Deliberate error response
			Console.WriteLine("Trying artist/details without artistId parameter...");
			var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Artist>.Get.Please());

			Assert.That(apiXmlException.Error.Code, Is.EqualTo(1001));
			Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("Missing parameter artistId."));
		}

		[Test]
		public void Should_fail_correctly_if_non_xml_error_returned_eg_unauthorised()
		{
				// -- Deliberate unauthorized response
				Console.WriteLine("Trying user/locker without any credentials...");
				var apiXmlException = Assert.Throws<ApiXmlException>(() => Api<Locker>.Get.Please());
				Assert.That(apiXmlException.Error.Code, Is.EqualTo(9001));
				Assert.That(apiXmlException.Error.ErrorMessage, Is.EqualTo("OAuth authentication error: Resource requires access token"));
		}
	}
}

Revert change to message assertion as the message is consumer key dependent and the key in the CI build causes a failure


namespace FakeItEasy.Specs
{
    using FakeItEasy.Core;
    using FluentAssertions;
    using Xbehave;

    public static class ObjectMembersSpecs
    {
        [Scenario]
        public static void DefaultEqualsWithSelf(IFoo fake, bool equals)
        {
            "Given a fake"
                .x(() => fake = A.Fake<IFoo>());

            "When Equals is called on the fake with the fake as the argument"
                .x(() => equals = fake.Equals(fake));

            "Then it returns true"
                .x(() => equals.Should().BeTrue());
        }

        [Scenario]
        public static void DefaultEqualsWithOtherFake(IFoo fake, IFoo otherFake, bool equals)
        {
            "Given a fake"
                .x(() => fake = A.Fake<IFoo>());

            "And another fake of the same type"
                .x(() => otherFake = A.Fake<IFoo>());

            "When Equals is called on the first fake with the other fake as the argument"
                .x(() => equals = fake.Equals(otherFake));

            "Then it returns false"
                .x(() => equals.Should().BeFalse());
        }

        [Scenario]
        public static void DefaultGetHashCode(IFoo fake, FakeManager manager, int fakeHashCode)
        {
            "Given a fake"
                .x(() => fake = A.Fake<IFoo>());

            "And its manager"
                .x(() => manager = Fake.GetFakeManager(fake));

            "When GetHashCode is called on the fake"
                .x(() => fakeHashCode = fake.GetHashCode());

            "Then it returns the manager's hash code"
                .x(() => fakeHashCode.Should().Be(manager.GetHashCode()));
        }

        [Scenario]
        public static void DefaultToString(IFoo fake, string? stringRepresentation)
        {
            "Given a fake"
                .x(() => fake = A.Fake<IFoo>());

            "When ToString is called on the fake"
                .x(() => stringRepresentation = fake.ToString());

            "Then it should return a string representation of the fake"
                .x(() => stringRepresentation.Should().Be("Faked FakeItEasy.Specs.ObjectMembersSpecs+IFoo"));
        }

        public interface IFoo
        {
            void Bar();
        }
    }
}

Add characterization tests for object members


namespace ZocMonLib.Web
{
    public class WebSettingsExtensionOptions
    {
        public ISerializer Serializer { get; set; }

        public IRuntime Runtime { get; set; }

        public IStorageFactory StorageFactory { get; set; }

        public ISystemLoggerProvider LoggerProvider { get; set; }

        public IConfigProvider ConfigProvider { get; set; }
    }
}

namespace ZocMonLib.Web
{
    public class WebSettingsExtensionOptions
    {
        public IResourceFinder ResourceFinder { get; set; }

        public ISerializer Serializer { get; set; }

        public IRuntime Runtime { get; set; }

        public IStorageFactory StorageFactory { get; set; }

        public ISystemLoggerProvider LoggerProvider { get; set; }

        public IConfigProvider ConfigProvider { get; set; }
    }
}

Add ResourceFinder as an option that can be set.


// Copyright (c) kuicker.org. All rights reserved.
// Modified By      YYYY-MM-DD
// kevinjong        2016-03-04 - Creation

using System;

namespace IsTo.Tests
{
	public struct TestStruct
	{
		public int Property11;
		public int Property12;
		public int Property13;
	}
}

Support convert to or from struct type

Support convert to or from struct type


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

namespace BenchmarkDotNet.Samples.Other
{
    [BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.RyuJit)]
    public class Cpu_Atomics
    {
        private int a;
        private object syncRoot = new object();

        [Benchmark]
        [OperationsPerInvoke(4)]
        public void Lock()
        {
            lock (syncRoot) a++;
            lock (syncRoot) a++;
            lock (syncRoot) a++;
            lock (syncRoot) a++;
        }

        [Benchmark]
        [OperationsPerInvoke(4)]
        public void Interlocked()
        {
            System.Threading.Interlocked.Increment(ref a);
            System.Threading.Interlocked.Increment(ref a);
            System.Threading.Interlocked.Increment(ref a);
            System.Threading.Interlocked.Increment(ref a);
        }

        [Benchmark]
        [OperationsPerInvoke(4)]
        public void NoLock()
        {
            a++;
            a++;
            a++;
            a++;
        }
    }
}

using BenchmarkDotNet.Tasks;

namespace BenchmarkDotNet.Samples.CPU
{
    [BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.RyuJit)]
    public class Cpu_Atomics
    {
        private int a;
        private object syncRoot = new object();

        [Benchmark]
        [OperationsPerInvoke(4)]
        public void Lock()
        {
            lock (syncRoot) a++;
            lock (syncRoot) a++;
            lock (syncRoot) a++;
            lock (syncRoot) a++;
        }

        [Benchmark]
        [OperationsPerInvoke(4)]
        public void Interlocked()
        {
            System.Threading.Interlocked.Increment(ref a);
            System.Threading.Interlocked.Increment(ref a);
            System.Threading.Interlocked.Increment(ref a);
            System.Threading.Interlocked.Increment(ref a);
        }

        [Benchmark]
        [OperationsPerInvoke(4)]
        public void NoLock()
        {
            a++;
            a++;
            a++;
            a++;
        }
    }
}

Move sample to correct namespace

Move sample to correct namespace


// 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;
using osu.Game.Screens.OnlinePlay.Multiplayer;

namespace osu.Game.Tests.Visual.Multiplayer
{
    public class TestSceneMultiplayerPlayer : MultiplayerTestScene
    {
        private MultiplayerPlayer player;

        [SetUpSteps]
        public override void SetUpSteps()
        {
            base.SetUpSteps();

            AddStep("set beatmap", () =>
            {
                Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
            });

            AddStep("initialise gameplay", () =>
            {
                Stack.Push(player = new MultiplayerPlayer(Client.CurrentMatchPlayingItem.Value, Client.Room?.Users.ToArray()));
            });
        }

        [Test]
        public void TestGameplay()
        {
            AddUntilStep("wait for gameplay start", () => player.LocalUserPlaying.Value);
        }
    }
}

Add test scene for `MultiplayerPlayer`

Add test scene for `MultiplayerPlayer`


// 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 System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Overlays.Settings;

namespace osu.Game.Configuration
{
    /// <summary>
    /// An attribute to mark a bindable as being exposed to the user via settings controls.
    /// Can be used in conjunction with <see cref="SettingSourceExtensions.CreateSettingsControls"/> to automatically create UI controls.
    /// </summary>
    [MeansImplicitUse]
    [AttributeUsage(AttributeTargets.Property)]
    public class SettingSourceAttribute : Attribute
    {
        public string Label { get; }

        public string Description { get; }

        public SettingSourceAttribute(string label, string description = null)
        {
            Label = label ?? string.Empty;
            Description = description ?? string.Empty;
        }
    }

    public static class SettingSourceExtensions
    {
        public static IEnumerable<Drawable> CreateSettingsControls(this object obj)
        {
            var configProperties = obj.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SettingSourceAttribute>(true) != null);

            foreach (var property in configProperties)
            {
                var attr = property.GetCustomAttribute<SettingSourceAttribute>(true);

                switch (property.GetValue(obj))
                {
                    case BindableNumber<float> bNumber:
                        yield return new SettingsSlider<float>
                        {
                            LabelText = attr.Label,
                            Bindable = bNumber
                        };

                        break;

                    case BindableNumber<double> bNumber:
                        yield return new SettingsSlider<double>
                        {
                            LabelText = attr.Label,
                            Bindable = bNumber
                        };

                        break;

                    case BindableNumber<int> bNumber:
                        yield return new SettingsSlider<int>
                        {
                            LabelText = attr.Label,
                            Bindable = bNumber
                        };

                        break;

                    case Bindable<bool> bBool:
                        yield return new SettingsCheckbox
                        {
                            LabelText = attr.Label,
                            Bindable = bBool
                        };

                        break;
                }
            }
        }
    }
}

Add a method for getting settings UI components automatically from a target class


using System;
using System.Configuration;
using System.Linq;
using System.Reflection;

namespace UnitTests.Helpers
{
    // the default app.config is used.
    /// <summary>
    ///     Allow to override default configuration file access via ConfigurationService for piece of code
    ///     Main purpose: unit tests
    ///     Do not use it in production code
    /// </summary>
    /// <example>
    ///     // the default app.config is used.
    ///     using(AppConfig.Change(tempFileName))
    ///     {
    ///     // the app.config in tempFileName is used
    ///     }
    /// </example>
    public abstract class AppConfig : IDisposable
    {
        public abstract void Dispose();

        public static AppConfig Change(string path)
        {
            return new ChangeAppConfig(path);
        }

        private class ChangeAppConfig : AppConfig
        {
            private readonly string oldConfig =
                AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();

            private bool disposedValue;

            public ChangeAppConfig(string path)
            {
                AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
                ResetConfigMechanism();
            }

            public override void Dispose()
            {
                if (!disposedValue)
                {
                    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig);
                    ResetConfigMechanism();

                    disposedValue = true;
                }
                GC.SuppressFinalize(this);
            }

            private static void ResetConfigMechanism()
            {
                typeof(ConfigurationManager)
                    .GetField("s_initState", BindingFlags.NonPublic |
                                             BindingFlags.Static)
                    .SetValue(null, 0);

                typeof(ConfigurationManager)
                    .GetField("s_configSystem", BindingFlags.NonPublic |
                                                BindingFlags.Static)
                    .SetValue(null, null);

                typeof(ConfigurationManager)
                    .Assembly.GetTypes()
                    .Where(x => x.FullName ==
                                "System.Configuration.ClientConfigPaths")
                    .First()
                    .GetField("s_current", BindingFlags.NonPublic |
                                           BindingFlags.Static)
                    .SetValue(null, null);
            }
        }
    }
}

Add possibility to mock ConfigurationManager


using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace Gnx.Models
{
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        //public System.Data.Entity.DbSet<Portal.Models.ModuleModels> ModuleModels { get; set; }
    }
}

Add ApplicationUser class for Identity and DbContext


#if PS20

using System;
using System.Collections.Generic;

namespace WpfCLR
{
	public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
	{
		public const string ReadOnlyErrorMessage = "Dictionary is read-only";

		private IDictionary<TKey, TValue> _innerDictionary;
		protected IDictionary<TKey, TValue> InnerDictionary { get { return _innerDictionary; } }

		public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
		{
			if (dictionary == null)
				throw new ArgumentNullException("dictionary");
			_innerDictionary = dictionary;
		}

		#region IDictionary<TKey, TValue> members

		public TValue this[TKey key] { get { return _innerDictionary[key]; } }

		TValue IDictionary<TKey, TValue>.this[TKey key]
		{
			get { return _innerDictionary[key]; }
			set { throw new NotSupportedException(ReadOnlyErrorMessage); }
		}

		public ICollection<TKey> Keys { get { return _innerDictionary.Keys; } }

		public ICollection<TValue> Values { get { return _innerDictionary.Values; } }

		void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { throw new NotSupportedException(ReadOnlyErrorMessage); }

		public bool ContainsKey(TKey key) { return _innerDictionary.ContainsKey(key); }

		bool IDictionary<TKey, TValue>.Remove(TKey key) { throw new NotSupportedException(ReadOnlyErrorMessage); }

		public bool TryGetValue(TKey key, out TValue value) { return _innerDictionary.TryGetValue(key, out value); }

		#endregion

		#region ICollection<KeyValuePair<TKey, TValue>> members

		public int Count { get { return _innerDictionary.Count; } }

		bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } }

		void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(ReadOnlyErrorMessage); }

		void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(ReadOnlyErrorMessage); }

		bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return _innerDictionary.Contains(item); }

		public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { _innerDictionary.CopyTo(array, arrayIndex); }

		bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(ReadOnlyErrorMessage); }

		#endregion

		#region IEnumerable members

		public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _innerDictionary.GetEnumerator(); }

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return (_innerDictionary as System.Collections.IEnumerable).GetEnumerator(); }

		#endregion
	}
}

#endif

Create read-only dictionary for .NET version 2.0


//  https://leetcode.com/problems/sort-characters-by-frequency/
//  https://leetcode.com/submissions/detail/83684155/
//
//  Submission Details
//  34 / 34 test cases passed.
//      Status: Accepted
//      Runtime: 188 ms
//          Submitted: 0 minutes ago

public class Solution {
    public string FrequencySort(string s) {
        return s.Aggregate(new Dictionary<char, int>(), (acc, x) => {
            if (!acc.ContainsKey(x)) {
                acc[x] = 0;
            }

            acc[x]++;
            return acc;
        })
        .OrderByDescending(x => x.Value)
        .Aggregate(new StringBuilder(), (acc, x) => {
            acc.Append(new String(x.Key, x.Value));
            return acc;
        })
        .ToString();
    }
}

Sort chars by freq - monad

Sort chars by freq - monad


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

namespace System.ComponentModel
{
    /// <summary>
    /// Provides functionality to commit or rollback changes to an object that is used as a data source.
    /// </summary>
    public interface IEditableObject
    {
        /// <summary>
        /// Begins an edit on an object.
        /// </summary>
        void BeginEdit();

        /// <summary>
        /// Discards changes since the last BeginEdit call.
        /// </summary>
        void EndEdit();

        /// <summary>
        /// Pushes changes since the last BeginEdit into the underlying object.
        /// </summary>
        void CancelEdit();
    }
}

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

namespace System.ComponentModel
{
    /// <summary>
    /// Provides functionality to commit or rollback changes to an object that is used as a data source.
    /// </summary>
    public interface IEditableObject
    {
        /// <summary>
        /// Begins an edit on an object.
        /// </summary>
        void BeginEdit();

        /// <summary>
        /// Pushes changes since the last BeginEdit into the underlying object.
        /// </summary>
        void EndEdit();

        /// <summary>
        /// Discards changes since the last BeginEdit call.
        /// </summary>
        void CancelEdit();
    }
}

Fix inverted documentation between two methods


// http://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/
//
// Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree,
// else return false. Expected time complexity is O(n).
//

using System;
using System.Collections.Generic;

static class Program
{
    static bool IsTraversal(this int[] a)
    {
        var stack = new Stack<int>();
        var root = int.MinValue;
        foreach (var node in a)
        {
            if (node < root)
            {
                return false;
            }

            while (stack.Count != 0 && stack.Peek() < node)
            {
                root = stack.Pop();
            }

            stack.Push(node);
        }

        return true;
    }

    static void Main()
    {
        if (!new [] {2, 4, 3}.IsTraversal())
        {
            throw new Exception("You are weak, expected true");
        }

        if (!new [] {40, 30, 35, 80, 100}.IsTraversal())
        {
            throw new Exception("You are weak, expected true");
        }

        if (new [] {2, 4, 1}.IsTraversal())
        {
            throw new Exception("You are weak, expected false");
        }

        if (new [] {40, 30, 35, 20, 80, 100}.IsTraversal())
        {
            throw new Exception("You are weak, expected false");
        }

        Console.WriteLine("All appears to be well");
    }
}

Check if an array is preorder

Check if an array is preorder


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IniFileParserTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IniFileParserTests")]
[assembly: AssemblyCopyright("Copyright ©  2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b45d3f26-a017-43e3-8f76-2516ad4ec9b2")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Revert "remove old assemblyinfo (wasn't included in the solution)"

This reverts commit 12c5601073c9af6f86b791abdabfb5c9b99f7fbe.


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

using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;

namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
    class CommentHelpRequest
    {
        public static readonly RequestType<CommentHelpRequestParams, CommentHelpRequestResult, object, object> Type
            = RequestType<CommentHelpRequestParams, CommentHelpRequestResult, object, object>.Create("powershell/getCommentHelp");
    }

    public class CommentHelpRequestResult
    {
        public string[] content;
    }

    public class CommentHelpRequestParams
    {
        public string DocumentUri { get; set; }
        public Position TriggerPosition { get; set; }
    }
}

Add type to request comment help

Add type to request comment help


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Gremlin.Net.Driver.Exceptions;

namespace ExRam.Gremlinq.Core
{
    public static class GremlinQueryExecutorExtensions
    {
        private sealed class ExponentialBackoffExecutor : IGremlinQueryExecutor
        {
            [ThreadStatic]
            private static Random? _rnd;

            private const int MaxTries = 32;

            private readonly IGremlinQueryExecutor _baseExecutor;
            private readonly Func<int, ResponseException, bool> _shouldRetry;

            public ExponentialBackoffExecutor(IGremlinQueryExecutor baseExecutor, Func<int, ResponseException, bool> shouldRetry)
            {
                _baseExecutor = baseExecutor;
                _shouldRetry = shouldRetry;
            }

            public IAsyncEnumerable<object> Execute(object serializedQuery, IGremlinQueryEnvironment environment)
            {
                return AsyncEnumerable.Create(Core);

                async IAsyncEnumerator<object> Core(CancellationToken ct)
                {
                    var hasSeenFirst = false;

                    for (var i = 0; i < MaxTries; i++)
                    {
                        await using (var enumerator = _baseExecutor.Execute(serializedQuery, environment).GetAsyncEnumerator(ct))
                        {
                            while (true)
                            {
                                try
                                {
                                    if (!await enumerator.MoveNextAsync())
                                        yield break;

                                    hasSeenFirst = true;
                                }
                                catch (ResponseException ex)
                                {
                                    if (hasSeenFirst)
                                        throw;

                                    if (!_shouldRetry(i, ex))
                                        throw;

                                    await Task.Delay((_rnd ??= new Random()).Next(i + 2) * 16, ct);
                                    break;
                                }

                                yield return enumerator.Current;
                            }
                        }
                    }
                }
            }
        }

        public static IGremlinQueryExecutor RetryWithExponentialBackoff(this IGremlinQueryExecutor executor, Func<int, ResponseException, bool> shouldRetry)
        {
            return new ExponentialBackoffExecutor(executor, shouldRetry);
        }
    }
}

Introduce exponential backoff for executors


using System;
using System.Threading.Tasks;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Middleware;
using Ocelot.Responses;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using Shouldly;
using TestStack.BDDfy;
using Xunit;

namespace Ocelot.UnitTests.LoadBalancer
{
    public class DelegateInvokingLoadBalancerCreatorTests
    {
        private readonly DelegateInvokingLoadBalancerCreator<FakeLoadBalancer> _creator;
        private readonly Func<DownstreamReRoute, IServiceDiscoveryProvider, ILoadBalancer> _creatorFunc;
        private readonly Mock<IServiceDiscoveryProvider> _serviceProvider;
        private DownstreamReRoute _reRoute;
        private ILoadBalancer _loadBalancer;
        private string _typeName;

        public DelegateInvokingLoadBalancerCreatorTests()
        {
            _creatorFunc = (reRoute, serviceDiscoveryProvider) =>
                new FakeLoadBalancer(reRoute, serviceDiscoveryProvider);
            _creator = new DelegateInvokingLoadBalancerCreator<FakeLoadBalancer>(_creatorFunc);
            _serviceProvider = new Mock<IServiceDiscoveryProvider>();
        }

        [Fact]
        public void should_return_expected_name()
        {
            this.When(x => x.WhenIGetTheLoadBalancerTypeName())
                .Then(x => x.ThenTheLoadBalancerTypeIs("FakeLoadBalancer"))
                .BDDfy();
        }

        [Fact]
        public void should_return_result_of_specified_creator_func()
        {
            var reRoute = new DownstreamReRouteBuilder()
                .Build();

            this.Given(x => x.GivenAReRoute(reRoute))
                .When(x => x.WhenIGetTheLoadBalancer())
                .Then(x => x.ThenTheLoadBalancerIsReturned<FakeLoadBalancer>())
                .BDDfy();
        }

        private void GivenAReRoute(DownstreamReRoute reRoute)
        {
            _reRoute = reRoute;
        }

        private void WhenIGetTheLoadBalancer()
        {
            _loadBalancer = _creator.Create(_reRoute, _serviceProvider.Object);
        }

        private void WhenIGetTheLoadBalancerTypeName()
        {
            _typeName = _creator.Type;
        }

        private void ThenTheLoadBalancerIsReturned<T>()
            where T : ILoadBalancer
        {
            _loadBalancer.ShouldBeOfType<T>();
        }

        private void ThenTheLoadBalancerTypeIs(string type)
        {
            _typeName.ShouldBe(type);
        }

        private class FakeLoadBalancer : ILoadBalancer
        {
            public FakeLoadBalancer(DownstreamReRoute reRoute, IServiceDiscoveryProvider serviceDiscoveryProvider)
            {
                ReRoute = reRoute;
                ServiceDiscoveryProvider = serviceDiscoveryProvider;
            }

            public DownstreamReRoute ReRoute { get; }
            public IServiceDiscoveryProvider ServiceDiscoveryProvider { get; }

            public Task<Response<ServiceHostAndPort>> Lease(DownstreamContext context)
            {
                throw new NotImplementedException();
            }

            public void Release(ServiceHostAndPort hostAndPort)
            {
                throw new NotImplementedException();
            }
        }
    }
}

Cover DelegateInvokingLoadBalancerCreator by unit tests.


using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;

namespace Abp.Web.EntityHistory
{
    /// <summary>
    /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
    /// </summary>
    public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
    {
        [CanBeNull]
        public override string Reason
        {
            get
            {
                if (OverridedValue != null)
                {
                    return OverridedValue.Reason;
                }

                return HttpContext.Current?.Request.Url.AbsoluteUri;
            }
        }

        public HttpRequestEntityChangeSetReasonProvider(
            IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
            ) : base(reasonOverrideScopeProvider)
        {
        }
    }
}

Add http request reason provider for Abp.Web


using System;
using System.ComponentModel;
using System.Reflection;

namespace Moq.Sdk
{
    /// <summary>
    /// Usability functions for <see cref="IMockFactory"/>.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    public static class MockFactoryExtensions
    {
        /// <summary>
        /// Creates a mock with the given parameters.
        /// </summary>
        /// <param name="mocksAssembly">Assembly where compile-time generated mocks exist.</param>
        /// <param name="baseType">The base type (or main interface) of the mock.</param>
        /// <returns>A mock that implements <see cref="IMocked"/> in addition to the specified interfaces (if any).</returns>
		public static T CreateMock<T>(this IMockFactory factory, Assembly mocksAssembly)
            => (T)factory.CreateMock(mocksAssembly, typeof(T), new Type[0], new object[0]);
    }
}

Add usability overload for IMockFactory

Add usability overload for IMockFactory

Allow creating a mock from a single type parameter and the mocks assembly.


using System;
using NUnit.Framework;

namespace FastExpressionCompiler.UnitTests
{
    [TestFixture]
    public class CastTests
    {
        [Test]
        public void Expressions_with_small_int_casts_should_not_crash()
        {
            //currently crashes with NullReferenceException
            var x = 65535;
            Assert.IsTrue(ExpressionCompiler.Compile(() => x == (long)x)());
        }

        [Test]
        public void Expressions_with_larger_int_casts_should_not_crash()
        {
            //currently tears down process: "The process was terminated due to an internal error in the .NET Runtime at IP 00007FFD35C25C22 (00007FFD35B90000) with exit code 80131506."
            var x = 65536;
            Assert.IsTrue(ExpressionCompiler.Compile(() => x == (long)x)());
        }
    }
}

Add test cases for crashes involving integer casts

was https://github.com/dadhi/FastExpressionCompiler/issues/2


namespace MassTransit.Tests
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using MassTransit.Serialization;
    using NUnit.Framework;
    using TestFramework;
    using TestFramework.Messages;

    [TestFixture]
    public class When_consuming_a_minimal_message_body :
        InMemoryTestFixture
    {
        [Test]
        public async Task Should_use_the_correct_intervals_for_each_redelivery()
        {
            await InputQueueSendEndpoint.Send(new PingMessage(), x => x.Serializer = new CopyBodySerializer(SystemTextJsonMessageSerializer.JsonContentType,
                new StringMessageBody(@"
{
    ""message"": {
            ""CorrelationId"": ""9BBCF5F0-596E-4E90-B3C5-1B27358C5AEB""
        },
        ""messageType"": [
        ""urn:message:MassTransit.TestFramework.Messages:PingMessage""
        ]
    }
")));

            await Task.WhenAll(_received.Select(x => x.Task));

            Assert.That(_timestamps[1] - _timestamps[0], Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(0.9)));

            TestContext.Out.WriteLine("Interval: {0}", _timestamps[1] - _timestamps[0]);
        }

        TaskCompletionSource<ConsumeContext<PingMessage>>[] _received;
        int _count;
        DateTime[] _timestamps;

        protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
        {
            _count = 0;
            _received = new[] { GetTask<ConsumeContext<PingMessage>>(), GetTask<ConsumeContext<PingMessage>>() };
            _timestamps = new DateTime[2];

            configurator.UseDelayedRedelivery(r => r.Intervals(1000));

            configurator.Handler<PingMessage>(async context =>
            {
                _received[_count].TrySetResult(context);
                _timestamps[_count] = DateTime.Now;

                _count++;

                throw new IntentionalTestException("I'm so not ready for this jelly.");
            });
        }
    }
}

Test to verify that minimal message body can be redelivered via the delayed transport (serialization issue)


//  https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
//   Given a sorted linked list, delete all nodes that have duplicate numbers,
//   leaving only distinct numbers from the original list.
//   https://leetcode.com/submissions/detail/58844735/
//
//   Submission Details
//   166 / 166 test cases passed.
//      Status: Accepted
//      Runtime: 152 ms
//
//          Submitted: 0 minutes ago
//  You are here!
//  Your runtime beats 95.74% of csharpsubmissions.

public class Solution {
    public ListNode DeleteDuplicates(ListNode head) {
        var dummy = new ListNode(-1) { next = head };
        var last = dummy;
        var it = head;
        while (it != null)
        {
            while (it.next != null && it.val == it.next.val)
            {
                it = it.next;
            }

            if (last.next == it)
            {
                last = last.next;
            }
            else
            {
                last.next = it.next;
            }

            it = it.next;
        }

        return dummy.next;
    }
}

Remove dupes from list II

Remove dupes from list II


namespace BigEgg.Tools.PowerMode.Tests.Utils
{
    using System.Drawing;
    using System.Linq;
    using System.Reflection;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using BigEgg.Tools.PowerMode.Utils;

    public class ColorExtensionTest
    {
        [TestClass]
        public class HSVConvert
        {
            [TestMethod]
            public void ConvertTest()
            {
                var colorProperties = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public);
                var colors = colorProperties.ToDictionary(p => p.Name, p => (Color)p.GetValue(null, null));

                foreach (var color in colors)
                {
                    color.Value.ColorToHSV(out double hue, out double saturation, out double value);
                    var newColor = ColorExtensions.ColorFromHSV(hue, saturation, value);

                    Assert.AreEqual(color.Value.R, newColor.R);
                    Assert.AreEqual(color.Value.G, newColor.G);
                    Assert.AreEqual(color.Value.B, newColor.B);
                }
            }
        }
    }
}

Add tests for converting RGB with HSV

Add tests for converting RGB with HSV


//Synchronous template
//-----------------------------------------------------------------------------------
// PCB-Investigator Automation Script
// Created on 30.03.2017
// Autor Guenther.Schindler
//
// Empty template to fill for synchronous script.
//-----------------------------------------------------------------------------------
// GUID newScript_636264684078812126

using System;
using System.Collections.Generic;
using System.Text;
using PCBI.Plugin;
using PCBI.Plugin.Interfaces;
using System.Windows.Forms;
using System.Drawing;
using PCBI.Automation;
using System.IO;
using System.Drawing.Drawing2D;
using PCBI.MathUtils;
using System.Collections;
// example line to import dll DLLImport C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\searchedDLL.dll;
//this line includes a custom dll, e.g. your own dll or other microsoft dlls

namespace PCBIScript
{
    public class PScript : IPCBIScript
    {
        public PScript()
        {
        }

        public void Execute(IPCBIWindow parent)
        {

            IFilter filter = new IFilter(parent);

            //your code here
            foreach (ILayer layer in parent.GetCurrentStep().GetActiveLayerList())
            {
             List<IODBObject> objectsToMove = new List<IODBObject>();
                foreach (IODBObject obj in layer.GetAllLayerObjects())
                {
                    foreach (DictionaryEntry entry in obj.GetAttributes())
                    {

                        if (entry.Key.ToString() == "_string")
                        {
                            objectsToMove.Add((IODBObject)obj);
                        }
                    }
                }

                IODBLayer newLayer = filter.CreateEmptyODBLayer(layer.GetLayerName() + "_1", parent.GetCurrentStep().Name);
                filter.InsertElementsToLayer(0, newLayer, objectsToMove, new PointD(0, 0), false, false, 0);

                foreach (IODBObject mo in objectsToMove)
                {
                    ((IODBLayer)layer).RemoveObject(mo);

                }
            }

            parent.UpdateControlsAndResetView();
        }

    }
}

Copy Text objects to other layer and delete surce


using System;
using StackExchange.Redis;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace CollapsedToto
{
    [Prefix("/round")]
    public class RoundModule : BaseModule
    {
        private static ConnectionMultiplexer redis = null;
        private static IDatabase Database
        {
            get
            {
                if (redis == null)
                {
                    redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,resolveDns=True");
                }

                return redis.GetDatabase();
            }
        }
        private string CurrentRoundKey = "CurrentRound";

        public RoundModule()
        {
        }

        [Get("/popular")]
        public async Task<dynamic> PopularKeyword(dynamic param, CancellationToken ct)
        {
            SortedSetEntry[] values = await Database.SortedSetRangeByRankWithScoresAsync(CurrentRoundKey, 0, 30);

            return JsonConvert.SerializeObject(values);
        }

        [Post("/bet")]
        public async Task<dynamic> BettingKeyword(dynamic param, CancellationToken ct)
        {
            bool result = false;
            dynamic data = Request.Form;
            if (data.Count == 0)
            {
                data = Request.Query;
            }
            string keyword = (data["keyword"].ToString()).Trim();
            int point = int.Parse(data["point"].ToString());
            await Database.SortedSetIncrementAsync(CurrentRoundKey, keyword, 1.0);

            // TODO: subtract user point
            result = true;

            return JsonConvert.SerializeObject(result);
        }
    }
}

Implement betting and getting popular keywords


/*
using BenchmarkDotNet.Attributes;
using Robust.Shared.IoC;

namespace Content.Benchmarks
{
    // To actually run this benchmark you'll have to make DependencyCollection public so it's accessible.

    public class DependencyInjectBenchmark
    {
        [Params(InjectMode.Reflection, InjectMode.DynamicMethod)]
        public InjectMode Mode { get; set; }

        private DependencyCollection _dependencyCollection;

        [GlobalSetup]
        public void Setup()
        {
            _dependencyCollection = new DependencyCollection();
            _dependencyCollection.Register<X1, X1>();
            _dependencyCollection.Register<X2, X2>();
            _dependencyCollection.Register<X3, X3>();
            _dependencyCollection.Register<X4, X4>();
            _dependencyCollection.Register<X5, X5>();

            _dependencyCollection.BuildGraph();

            switch (Mode)
            {
                case InjectMode.Reflection:
                    break;
                case InjectMode.DynamicMethod:
                    // Running this without oneOff will cause DependencyCollection to cache the DynamicMethod injector.
                    // So future injections (even with oneOff) will keep using the DynamicMethod.
                    // AKA, be fast.
                    _dependencyCollection.InjectDependencies(new TestDummy());
                    break;
            }
        }

        [Benchmark]
        public void Inject()
        {
            _dependencyCollection.InjectDependencies(new TestDummy(), true);
        }

        public enum InjectMode
        {
            Reflection,
            DynamicMethod
        }

        private sealed class X1 { }
        private sealed class X2 { }
        private sealed class X3 { }
        private sealed class X4 { }
        private sealed class X5 { }

        private sealed class TestDummy
        {
            [Dependency] private readonly X1 _x1;
            [Dependency] private readonly X2 _x2;
            [Dependency] private readonly X3 _x3;
            [Dependency] private readonly X4 _x4;
            [Dependency] private readonly X5 _x5;
        }
    }
}
*/

Add benchmark for dependency injection.

Add benchmark for dependency injection.


// 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 osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Testing;
using osuTK;

namespace osu.Framework.Tests.Visual.Sprites
{
    public class TestSceneTextureCropping : GridTestScene
    {
        public TestSceneTextureCropping()
            : base(3, 3)
        {
        }

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

            for (int i = 0; i < Rows; ++i)
            {
                for (int j = 0; j < Cols; ++j)
                {
                    RectangleF cropRectangle = new RectangleF(i / 3f, j / 3f, 1 / 3f, 1 / 3f);
                    Cell(i, j).AddRange(new Drawable[]
                    {
                        new SpriteText
                        {
                            Text = $"{cropRectangle}",
                            Font = new FontUsage(size: 14),
                        },
                        new Container
                        {
                            RelativeSizeAxes = Axes.Both,
                            Size = new Vector2(0.5f),
                            Anchor = Anchor.Centre,
                            Origin = Anchor.Centre,
                            Masking = true,
                            Children = new Drawable[]
                            {
                                new Sprite
                                {
                                    RelativeSizeAxes = Axes.Both,
                                    Texture = texture.Crop(cropRectangle, relativeSizeAxes: Axes.Both),
                                    Anchor = Anchor.Centre,
                                    Origin = Anchor.Centre,
                                }
                            }
                        }
                    });
                }
            }
        }

        private Texture texture;

        [BackgroundDependencyLoader]
        private void load(TextureStore store)
        {
            texture = store.Get(@"sample-texture");
        }
    }
}

Add texture cropping test case

Add texture cropping test case


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

using System.Diagnostics;
using System.Runtime.InteropServices;
using Xunit;

namespace System.IO.Tests
{
    public sealed class Directory_SetCurrentDirectory : RemoteExecutorTestBase
    {
        [Fact]
        public void Null_Path_Throws_ArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>(() => Directory.SetCurrentDirectory(null));
        }

        [Fact]
        public void Empty_Path_Throws_ArgumentException()
        {
            Assert.Throws<ArgumentException>(() => Directory.SetCurrentDirectory(string.Empty));
        }

        [Fact]
        public void SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
        {
            Assert.Throws<DirectoryNotFoundException>(() => Directory.SetCurrentDirectory(GetTestFilePath()));
        }

        [Fact]
        public void SetToValidOtherDirectory()
        {
            RemoteInvoke(() =>
            {
                Directory.SetCurrentDirectory(TestDirectory);
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
                }
                return SuccessExitCode;
            }).Dispose();
        }
    }
}

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

using System.Diagnostics;
using System.Runtime.InteropServices;
using Xunit;

namespace System.IO.Tests
{
    public sealed class Directory_SetCurrentDirectory : RemoteExecutorTestBase
    {
        [Fact]
        public void Null_Path_Throws_ArgumentNullException()
        {
            Assert.Throws<ArgumentNullException>(() => Directory.SetCurrentDirectory(null));
        }

        [Fact]
        public void Empty_Path_Throws_ArgumentException()
        {
            Assert.Throws<ArgumentException>(() => Directory.SetCurrentDirectory(string.Empty));
        }

        [Fact]
        public void SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
        {
            Assert.Throws<DirectoryNotFoundException>(() => Directory.SetCurrentDirectory(GetTestFilePath()));
        }

        [Fact]
        public void SetToValidOtherDirectory()
        {
            RemoteInvoke(() =>
            {
                Directory.SetCurrentDirectory(TestDirectory);
                // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current
                // directory to a symlinked path will result in GetCurrentDirectory returning the absolute
                // path that followed the symlink.
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
                }
                return SuccessExitCode;
            }).Dispose();
        }
    }
}

Add comment for OSX specific FileSystem test


// 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;

namespace Openchain.Sqlite.Tests
{
    public class SqlServerStorageEngineTests : BaseStorageEngineTests
    {
        private readonly int instanceId;

        public SqlServerStorageEngineTests()
        {
            Random rnd = new Random();
            this.instanceId = rnd.Next(0, int.MaxValue);

            this.Store = CreateNewEngine();
        }

        protected override IStorageEngine CreateNewEngine()
        {
            SqlServerStorageEngine engine = new SqlServerStorageEngine("Data Source=.;Initial Catalog=Openchain;Integrated Security=True", this.instanceId, TimeSpan.FromSeconds(10));
            engine.OpenConnection().Wait();
            return engine;
        }
    }
}

Add unit tests for the SqlServerStorageEngine class


// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio.Lookups;

class Example
{
  static void Main(string[] args)
  {
    // Find your Account Sid and Auth Token at twilio.com/user/account
    const string accountSid = "{{ account_sid }}";
    const string authToken = "{{ auth_token }}";
    var lookupsClient = new LookupsClient(accountSid, authToken);

    // Look up a phone number in E.164 format
    var phoneNumber = lookupsClient.GetPhoneNumber("+15108675309", true);
    Console.WriteLine(phoneNumber.Carrier.Type);
    Console.WriteLine(phoneNumber.Carrier.Name);
  }
}

// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio.Lookups;

class Example
{
  static void Main(string[] args)
  {
    // Find your Account Sid and Auth Token at twilio.com/console
    const string accountSid = "{{ account_sid }}";
    const string authToken = "{{ auth_token }}";
    var lookupsClient = new LookupsClient(accountSid, authToken);

    // Look up a phone number in E.164 format
    var phoneNumber = lookupsClient.GetPhoneNumber("+15108675309", true);
    Console.WriteLine(phoneNumber.Carrier.Type);
    Console.WriteLine(phoneNumber.Carrier.Name);
  }
}

Change console URL for 1 code sample

Change console URL for 1 code sample


@model Orders.com.Web.MVC.ViewModels.OrderItemViewModel

@{
    ViewBag.Title = "Delete";
}

Delete Item

Are you sure you want to delete this?

        Category

            @Html.DisplayFor(model => model.AssociatedCategory.Name)

        Product

            @Html.DisplayFor(model => model.AssociatedProduct.Name)

        Price

            @Html.DisplayFor(model => model.Price)

        Quantity

            @Html.DisplayFor(model => model.Quantity)

        Amount

            @Html.DisplayFor(model => model.Amount)

        Status

            @Html.DisplayFor(model => model.Status)

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Edit", "Orders", new { id = Model.OrderID }, null)

    }

Add order item delete support

Add order item delete support


using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Configuration;

using Nohros.Resources;

namespace Nohros.Configuration
{
    /// <summary>
    /// Contains configuration informations for cache providers.
    /// </summary>
    public class CacheProviderNode : ProviderNode
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CacheProviderNode"/> class by using the specified
        /// provider name and type.
        /// </summary>
        /// <param name="name">The name of the provider.</param>
        /// <param name="type">The assembly-qualified name of the provider type.</param>
        public CacheProviderNode(string name, string type) : base(name, type) { }

        /// <summary>
        /// Parses a XML node that contains information about the provider.
        /// </summary>
        /// <param name="node">The XML node to parse.</param>
        /// <param name="config">A <see cref="NohrosConfiguration"/> object containing the provider configuration
        /// informations.</param>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">The <paramref name="node"/> is not a
        /// valid representation of a messenger provider.</exception>
        public override void Parse(XmlNode node, NohrosConfiguration config) {
            InternalParse(node, config);
        }
    }
}

Create a class that acts as a configuration node for cache providers


using System.Collections;
using System.Collections.Generic;
using Xe.Tools.Wpf.Models;

namespace OpenKh.Tools.Common.Models
{
    public class MyGenericListModel<T> : GenericListModel<T>, IEnumerable<T>
    {
        public MyGenericListModel(IEnumerable<T> list) : base(list)
        {
        }

        public IEnumerator<T> GetEnumerator() => Items.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => Items.GetEnumerator();
        protected override T OnNewItem() => throw new System.NotImplementedException();
    }
}

Add a more specific GenericListModel to reduce the amount of code


namespace FluentTc.Domain
{
    public class SourceBuildType
    {
        public override string ToString()
        {
            return "source-buildType";
        }

        public string Id { get; set; }
        public string Name { get; set; }
        public string ProjectName { get; set; }
        public string ProjectId { get; set; }
    }
}

Add build config info for ArtifactDependencies


// 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 osu.Game.Screens.Multi.Components;

namespace osu.Game.Tests.Visual.RealtimeMultiplayer
{
    public class TestSceneRealtimeMultiplayer : RealtimeMultiplayerTestScene
    {
        public TestSceneRealtimeMultiplayer()
        {
            var multi = new TestRealtimeMultiplayer();

            AddStep("show", () => LoadScreen(multi));
            AddUntilStep("wait for loaded", () => multi.IsLoaded);
        }

        private class TestRealtimeMultiplayer : Screens.Multi.RealtimeMultiplayer.RealtimeMultiplayer
        {
            protected override RoomManager CreateRoomManager() => new TestRealtimeRoomManager();
        }
    }
}

Add realtime multiplayer test scene

Add realtime multiplayer test scene


using Bugsnag.Payload;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace Bugsnag.Tests
{
  public class PayloadExtensionsTests
  {
    [Theory]
    [MemberData(nameof(PayloadTestData))]
    public void AddToPayloadTests(Dictionary<string, object> dictionary, string key, object value, object expectedValue)
    {
      dictionary.AddToPayload(key, value);

      if (expectedValue == null)
      {
        Assert.DoesNotContain(key, dictionary.Keys);
      }
      else
      {
        Assert.Equal(expectedValue, dictionary[key]);
      }
    }

    public static IEnumerable<object[]> PayloadTestData()
    {
      yield return new object[] { new Dictionary<string, object>(), "key", 1, 1 };
      yield return new object[] { new Dictionary<string, object>(), "key", null, null };
      yield return new object[] { new Dictionary<string, object>(), "key", "", null };
      yield return new object[] { new Dictionary<string, object>(), "key", "value", "value" };
      yield return new object[] { new Dictionary<string, object> { { "key", 1 } }, "key", null, null };
      yield return new object[] { new Dictionary<string, object> { { "key", 1 } }, "key", "", null };
    }

    [Fact]
    public void GetExistingKey()
    {
      var dictionary = new Dictionary<string, object> { { "key", "value" } };

      Assert.Equal("value", dictionary.Get("key"));
    }

    [Fact]
    public void GetNonExistentKeyReturnsNull()
    {
      var dictionary = new Dictionary<string, object>();

      Assert.Null(dictionary.Get("key"));
    }
  }
}

Add tests for Get & AddToPayload

Add tests for Get & AddToPayload


using Htc.Vita.Core.Util;
using Xunit;

namespace Htc.Vita.Core.Tests
{
    public class TypeRegistryTest
    {
        [Fact]
        public static void Default_0_RegisterDefault()
        {
            TypeRegistry.RegisterDefault<BaseClass, SubClass1>();
        }

        [Fact]
        public static void Default_1_Register()
        {
            TypeRegistry.RegisterDefault<BaseClass, SubClass1>();
            TypeRegistry.Register<BaseClass, SubClass2>();
        }

        [Fact]
        public static void Default_2_GetInstance()
        {
            TypeRegistry.RegisterDefault<BaseClass, SubClass1>();
            TypeRegistry.Register<BaseClass, SubClass2>();
            var obj = TypeRegistry.GetInstance<BaseClass>();
            Assert.False(obj is SubClass1);
            Assert.True(obj is SubClass2);
        }
    }

    public abstract class BaseClass
    {
    }

    public class SubClass1 : BaseClass
    {
    }

    public class SubClass2 : BaseClass
    {
    }
}

Add test case for TypeRegistry

Add test case for TypeRegistry


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

namespace Recipe.DebugAndException
{
    public static class ReflectException
    {
        public static void ReflectionException()
        {
            Type reflectedClass = typeof(ReflectException);

            try
            {
                MethodInfo methodToInvoke = reflectedClass.GetMethod("TestInvoke");
                methodToInvoke?.Invoke(null, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToShortDisplayString());
            }
        }

        public static void TestInvoke()
        {
            throw new Exception("Thrown from invoked method.");
        }
    }

    public static class ExceptionDisplayExtention
    {
        public static string ToShortDisplayString(this Exception ex)
        {
            StringBuilder displayText = new StringBuilder();
            WriteExceptionShortDetail(displayText, ex);
            foreach (Exception inner in ex.GetNestedExceptionList())
            {
                displayText.AppendFormat("**** INNEREXCEPTION START ****{0}", Environment.NewLine);
                WriteExceptionShortDetail(displayText, inner);
                displayText.AppendFormat("**** INNEREXCEPTION END ****{0}{0}", Environment.NewLine);
            }
            return displayText.ToString();
        }

        public static IEnumerable<Exception> GetNestedExceptionList(this Exception ex)
        {
            Exception current = ex;
            do
            {
                current = current.InnerException;
                if (current != null)
                {
                    yield return current;
                }
            } while (current != null);
        }

        public static void WriteExceptionShortDetail(StringBuilder builder, Exception ex)
        {
            builder.AppendFormat("Message:{0}{1}", ex.Message, Environment.NewLine);
            builder.AppendFormat("Type:{0}{1}", ex.GetType(), Environment.NewLine);
            builder.AppendFormat("Source:{0}{1}", ex.Source, Environment.NewLine);
            builder.AppendFormat("TargetSite:{0}{1}", ex.TargetSite, Environment.NewLine);
        }
    }
}

Add reflection exception log function

Add reflection exception log function


// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

using System.Diagnostics.CodeAnalysis;

[assembly: SuppressMessage("Reliability", "CA2007: Consider calling ConfigureAwait on the awaited task")]
[assembly: SuppressMessage("Design", "CA1062: Validate arguments of public methods")]
[assembly: SuppressMessage("Globalization", "CA1303: Do not pass literals as localized parameters")]

Create Global Supressions for CA warnings on THNETII.CommandLine.Hosting


// 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;
using osu.Framework.Testing;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Login;

namespace osu.Game.Tests.Visual.Menus
{
    [TestFixture]
    public class TestSceneLoginPanel : OsuManualInputManagerTestScene
    {
        private LoginPanel loginPanel;

        [SetUpSteps]
        public void SetUpSteps()
        {
            AddStep("create login dialog", () =>
            {
                Add(loginPanel = new LoginPanel
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Width = 0.5f,
                });
            });
        }

        [Test]
        public void TestBasicLogin()
        {
            AddStep("logout", () => API.Logout());

            AddStep("enter password", () => loginPanel.ChildrenOfType<OsuPasswordTextBox>().First().Text = "password");
            AddStep("submit", () => loginPanel.ChildrenOfType<OsuButton>().First(b => b.Text.ToString() == "Sign in").TriggerClick());
        }
    }
}

Add test coverage of login dialog

Add test coverage of login dialog