using System.Web.Http;
using WTM.Core.Services;
using WTM.Crawler;
using WTM.Crawler.Services;
using WTM.Domain;

namespace WTM.Api.Controllers
{
    public class UserController : ApiController
    {
        private readonly IUserService userService;

        public UserController()
        {
            var webClient = new WebClientWTM();
            var htmlParser = new HtmlParser();
            userService = new UserService(webClient, htmlParser);
        }

        public UserController(IUserService userService)
        {
            this.userService = userService;
        }

        // GET api/User/Login?username={username}&password={password}
        [Route("api/User/Login")]
        [HttpGet]
        public User Login([FromUri]string username, [FromUri]string password)
        {
            return userService.Login(username, password);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WTM.Core.Services;
using WTM.Crawler;
using WTM.Crawler.Services;
using WTM.Domain;

namespace WTM.Api.Controllers
{
    public class UserController : ApiController
    {
        private readonly IUserService userService;

        public UserController()
        {
            var webClient = new WebClientWTM();
            var htmlParser = new HtmlParser();
            userService = new UserService(webClient, htmlParser);
        }

        public UserController(IUserService userService)
        {
            this.userService = userService;
        }

        // GET api/User/Login?username={username}&password={password}
        [Route("api/User/Login")]
        [HttpGet]
        public User Login([FromUri]string username, [FromUri]string password)
        {
            return userService.Login(username, password);
        }

        [Route("api/User/{username}")]
        [HttpGet]
        public User Get(string username)
        {
            return userService.GetByUsername(username);
        }

        //[Route("api/User/Search")]
        [HttpGet]
        public List<UserSummary> Search(string search, [FromUri]int? page = null)
        {
            return userService.Search(search, page).ToList();
        }
    }
}

Add methods intto User Api

Add methods intto User Api


namespace Parsley;

public static class ReadOnlySpanExtensions
{
    public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length)
        => length >= input.Length
            ? input.Slice(0)
            : input.Slice(0, length);

    public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length)
    {
        var traversed = input.Peek(length);

        input = input.Slice(traversed.Length);

        index += traversed.Length;
    }

    public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test)
    {
        int i = 0;

        while (i < input.Length && test(input[i]))
            i++;

        return input.Peek(i);
    }
}

namespace Parsley;

public static class ReadOnlySpanExtensions
{
    public static ReadOnlySpan<char> Peek(this ref ReadOnlySpan<char> input, int length)
        => length >= input.Length
            ? input.Slice(0)
            : input.Slice(0, length);

    public static void Advance(this ref ReadOnlySpan<char> input, ref int index, int length)
    {
        var traversed = length >= input.Length
            ? input.Length
            : length;

        input = input.Slice(traversed);

        index += traversed;
    }

    public static ReadOnlySpan<char> TakeWhile(this ref ReadOnlySpan<char> input, Predicate<char> test)
    {
        int i = 0;

        while (i < input.Length && test(input[i]))
            i++;

        return input.Peek(i);
    }
}

Reduce the number of slice operations performed during an Advance, when those slices were used only for their length.


using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;

namespace Glimpse.Agent.Web
{
    public class DefaultRequestIgnorerManager : IRequestIgnorerManager
    {
        public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
        {
            RequestIgnorers = requestIgnorerProvider.Instances;
            HttpContextAccessor = httpContextAccessor;
        }

        private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }

        private IHttpContextAccessor HttpContextAccessor { get; }

        public bool ShouldIgnore()
        {
            return ShouldIgnore(HttpContextAccessor.HttpContext);
        }

        public bool ShouldIgnore(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (RequestIgnorers.Any())
            {
                foreach (var policy in RequestIgnorers)
                {
                    if (policy.ShouldIgnore(context))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.JsonPatch.Helpers;

namespace Glimpse.Agent.Web
{
    public class DefaultRequestIgnorerManager : IRequestIgnorerManager
    {
        public DefaultRequestIgnorerManager(IExtensionProvider<IRequestIgnorer> requestIgnorerProvider, IHttpContextAccessor httpContextAccessor)
        {
            RequestIgnorers = requestIgnorerProvider.Instances;
            HttpContextAccessor = httpContextAccessor;
        }

        private IEnumerable<IRequestIgnorer> RequestIgnorers { get; }

        private IHttpContextAccessor HttpContextAccessor { get; }

        public bool ShouldIgnore()
        {
            return ShouldIgnore(HttpContextAccessor.HttpContext);
        }

        public bool ShouldIgnore(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var result = GetCachedResult(context);
            if (result == null)
            {
                if (RequestIgnorers.Any())
                {
                    foreach (var policy in RequestIgnorers)
                    {
                        if (policy.ShouldIgnore(context))
                        {
                            result = true;
                            break;
                        }
                    }
                }

                if (!result.HasValue)
                {
                    result = false;
                }

                SetCachedResult(context, result);
            }

            return result.Value;
        }

        private bool? GetCachedResult(HttpContext context)
        {
            return context.Items["Glimpse.ShouldIgnoreRequest"] as bool?;
        }

        private void SetCachedResult(HttpContext context, bool? value)
        {
            context.Items["Glimpse.ShouldIgnoreRequest"] = value;
        }
    }
}

Introduce caching of ShouldIgnore request so that the ignorer pipeline is only executed once per request


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

namespace Akavache
{
    internal interface IWantsToRegisterStuff
    {
        void Register(IMutableDependencyResolver resolverToUse);
    }

    public static class DependencyResolverMixin
    {
        /// <summary>
        /// Initializes a ReactiveUI dependency resolver with classes that
        /// Akavache uses internally.
        /// </summary>
        public static void InitializeAkavache(this IMutableDependencyResolver This)
        {
            var namespaces = new[] {
                "Akavache",
                "Akavache.Mac",
                "Akavache.Mobile",
                "Akavache.Sqlite3",
            };

            var fdr = typeof(DependencyResolverMixin);

            var assmName = new AssemblyName(
                fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", ""));

            foreach (var ns in namespaces)
            {
                var targetType = ns + ".Registrations";
                string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns);

                var registerTypeClass = Type.GetType(fullName, false);
                if (registerTypeClass == null) continue;

                var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass);
                registerer.Register(This);
            };
        }
    }
}

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

namespace Akavache
{
    internal interface IWantsToRegisterStuff
    {
        void Register(IMutableDependencyResolver resolverToUse);
    }

    public static class DependencyResolverMixin
    {
        /// <summary>
        /// Initializes a ReactiveUI dependency resolver with classes that
        /// Akavache uses internally.
        /// </summary>
        public static void InitializeAkavache(this IMutableDependencyResolver This)
        {
            var namespaces = new[] {
                "Akavache",
                "Akavache.Mac",
                "Akavache.Deprecated",
                "Akavache.Mobile",
                "Akavache.Http",
                "Akavache.Sqlite3",
            };

            var fdr = typeof(DependencyResolverMixin);

            var assmName = new AssemblyName(
                fdr.AssemblyQualifiedName.Replace(fdr.FullName + ", ", ""));

            foreach (var ns in namespaces)
            {
                var targetType = ns + ".Registrations";
                string fullName = targetType + ", " + assmName.FullName.Replace(assmName.Name, ns);

                var registerTypeClass = Type.GetType(fullName, false);
                if (registerTypeClass == null) continue;

                var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass);
                registerer.Register(This);
            };
        }
    }
}

Make sure we register stuff

Make sure we register stuff


using System;
using System.ComponentModel;

namespace Krs.Ats.IBNet
{
    /// <summary>
    /// Contract Security Types
    /// </summary>
    [Serializable()]
    public enum SecurityType
    {
        /// <summary>
        /// Stock
        /// </summary>
        [Description("STK")] Stock,
        /// <summary>
        /// Option
        /// </summary>
        [Description("OPT")] Option,
        /// <summary>
        /// Future
        /// </summary>
        [Description("FUT")] Future,
        /// <summary>
        /// Indice
        /// </summary>
        [Description("IND")] Index,
        /// <summary>
        /// FOP = options on futures
        /// </summary>
        [Description("FOP")] FutureOption,
        /// <summary>
        /// Cash
        /// </summary>
        [Description("CASH")] Cash,
        /// <summary>
        /// For Combination Orders - must use combo leg details
        /// </summary>
        [Description("BAG")] Bag,
        /// <summary>
        /// Bond
        /// </summary>
        [Description("BOND")] Bond,
        /// <summary>
        /// Undefined Security Type
        /// </summary>
        [Description("")] Undefined
    }
}

using System;
using System.ComponentModel;

namespace Krs.Ats.IBNet
{
    /// <summary>
    /// Contract Security Types
    /// </summary>
    [Serializable()]
    public enum SecurityType
    {
        /// <summary>
        /// Stock
        /// </summary>
        [Description("STK")] Stock,
        /// <summary>
        /// Option
        /// </summary>
        [Description("OPT")] Option,
        /// <summary>
        /// Future
        /// </summary>
        [Description("FUT")] Future,
        /// <summary>
        /// Indice
        /// </summary>
        [Description("IND")] Index,
        /// <summary>
        /// FOP = options on futures
        /// </summary>
        [Description("FOP")] FutureOption,
        /// <summary>
        /// Cash
        /// </summary>
        [Description("CASH")] Cash,
        /// <summary>
        /// For Combination Orders - must use combo leg details
        /// </summary>
        [Description("BAG")] Bag,
        /// <summary>
        /// Bond
        /// </summary>
        [Description("BOND")] Bond,
        /// <summary>
        /// Warrant
        /// </summary>
        [Description("WAR")] Warrant,
        /// <summary>
        /// Undefined Security Type
        /// </summary>
        [Description("")] Undefined
    }
}

Add the warrant security type.

Add the warrant security type.


using Content.Shared.Maths;

namespace Content.Shared.Utility
{
    public static class TemperatureHelpers
    {
        public static float CelsiusToKelvin(float celsius)
        {
            return celsius + PhysicalConstants.ZERO_CELCIUS;
        }

        public static float KelvinToCelsius(float kelvin)
        {
            return kelvin - PhysicalConstants.ZERO_CELCIUS;
        }
    }
}

using Content.Shared.Maths;

namespace Content.Shared.Utility
{
    public static class TemperatureHelpers
    {
        public static float CelsiusToKelvin(float celsius)
        {
            return celsius + PhysicalConstants.ZERO_CELCIUS;
        }

        public static float CelsiusToFahrenheit(float celsius)
        {
            return celsius * 9 / 5 + 32;
        }

        public static float KelvinToCelsius(float kelvin)
        {
            return kelvin - PhysicalConstants.ZERO_CELCIUS;
        }

        public static float KelvinToFahrenheit(float kelvin)
        {
            var celsius = KelvinToCelsius(kelvin);
            return CelsiusToFahrenheit(celsius);
        }

        public static float FahrenheitToCelsius(float fahrenheit)
        {
            return (fahrenheit - 32) * 5 / 9;
        }

        public static float FahrenheitToKelvin(float fahrenheit)
        {
            var celsius = FahrenheitToCelsius(fahrenheit);
            return CelsiusToKelvin(celsius);
        }
    }
}

Add helpers for converting to and from Fahrenheit


using NUnit.Framework;
using SecretSplitting;

namespace ElectronicCash.Tests
{
    [TestFixture]
    class SecretSplittingTests
    {
        private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
        private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
        private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);

        [Test]
        public void OnSplit_OriginalMessageShouldBeRecoverable()
        {
            _splitter.SplitSecretBetweenTwoPeople();

            var r = _splitter.R;
            var s = _splitter.S;

            var m = Helpers.ExclusiveOr(r, s);

            Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
        }
    }
}

using NUnit.Framework;
using SecretSplitting;

namespace ElectronicCash.Tests
{
    [TestFixture]
    class SecretSplittingTests
    {
        private static readonly byte[] Message = Helpers.GetBytes("Supersecretmessage");
        private static readonly byte[] RandBytes = Helpers.GetRandomBytes(Helpers.GetString(Message).Length * sizeof(char));
        private readonly SecretSplittingProvider _splitter = new SecretSplittingProvider(Message, RandBytes);

        [Test]
        public void OnSplit_OriginalMessageShouldBeRecoverable()
        {
            _splitter.SplitSecretBetweenTwoPeople();

            var r = _splitter.R;
            var s = _splitter.S;

            var m = Helpers.ExclusiveOr(r, s);

            Assert.AreEqual(Helpers.GetString(m), Helpers.GetString(Message));
        }

        [Test]
        public void OnSecretSplit_FlagsShouldBeTrue()
        {
            var splitter = new SecretSplittingProvider(Message, RandBytes);
            splitter.SplitSecretBetweenTwoPeople();

            Assert.IsTrue(splitter.IsRProtected);
            Assert.IsTrue(splitter.IsSProtected);
            Assert.IsTrue(splitter.IsSecretMessageProtected);
        }
    }
}

Write some more tests for secret splitting


#region

using System;
using System.Drawing;
using System.Windows.Forms;
using Tabster.Data;
using Tabster.Data.Processing;

#endregion

namespace RtfFile
{
    internal class RtfFileExporter : ITablatureFileExporter
    {
        private Font _font;
        private RichTextBox _rtb;

        #region Implementation of ITablatureFileExporter

        public FileType FileType { get; private set; }

        public Version Version
        {
            get { return new Version("1.0"); }
        }

        public void Export(ITablatureFile file, string fileName)
        {
            if (_font == null)
                _font = new Font("Courier New", 9F);

            if (_rtb == null)
                _rtb = new RichTextBox {Font = new Font("Courier New", 9F), Text = file.Contents};

            _rtb.SaveFile(fileName);
            _rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created
        }

        #endregion

        public RtfFileExporter()
        {
            FileType = new FileType("Rich Text Format File", ".rtf");
        }

        ~RtfFileExporter()
        {
            if (_font != null)
                _font.Dispose();

            if (_rtb != null && !_rtb.IsDisposed)
                _rtb.Dispose();
        }
    }
}

#region

using System;
using System.Drawing;
using System.Windows.Forms;
using Tabster.Data;
using Tabster.Data.Processing;

#endregion

namespace RtfFile
{
    internal class RtfFileExporter : ITablatureFileExporter
    {
        private RichTextBox _rtb;

        #region Implementation of ITablatureFileExporter

        public FileType FileType { get; private set; }

        public Version Version
        {
            get { return new Version("1.0"); }
        }

        public void Export(ITablatureFile file, string fileName, TablatureFileExportArguments args)
        {
            if (_rtb == null)
                _rtb = new RichTextBox {Font = args.Font, Text = file.Contents};

            _rtb.SaveFile(fileName);
            _rtb.SaveFile(fileName); //have to call method twice otherwise empty file is created
        }

        #endregion

        public RtfFileExporter()
        {
            FileType = new FileType("Rich Text Format File", ".rtf");
        }

        ~RtfFileExporter()
        {
            if (_rtb != null && !_rtb.IsDisposed)
                _rtb.Dispose();
        }
    }
}

Use specified font for RTF exporting

Use specified font for RTF exporting


using System;

namespace BuildingBlocks.CopyManagement
{
    public class SmartClientApplicationIdentity : IApplicationIdentity
    {
        private static readonly Lazy<IApplicationIdentity> _current;

        static SmartClientApplicationIdentity()
        {
            _current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
        }

        public static IApplicationIdentity Current
        {
            get { return _current.Value; }
        }

        private static readonly Guid _instanceId = Guid.NewGuid();
        private readonly string _applicationUid;
        private readonly string _mashineId;
        private readonly DateTime _instanceStartTime;

        private SmartClientApplicationIdentity()
        {
            _instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
            _applicationUid = ComputeApplicationId();
            _mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
        }

        public Guid InstanceId
        {
            get { return _instanceId; }
        }

        public string ApplicationUid
        {
            get { return _applicationUid; }
        }

        public string MashineId
        {
            get { return _mashineId; }
        }

        public DateTime InstanceStartTime
        {
            get { return _instanceStartTime; }
        }

        public string LicenceKey { get; private set; }

        private static string ComputeApplicationId()
        {
            var exeFileName = System.Reflection.Assembly.GetEntryAssembly().Location;
            var value = "EXE_PATH >> " + exeFileName + "\n" + ComputerId.Value;
            return value.ToFingerPrintMd5Hash();
        }
    }
}

using System;

namespace BuildingBlocks.CopyManagement
{
    public class SmartClientApplicationIdentity : IApplicationIdentity
    {
        private static readonly Lazy<IApplicationIdentity> _current;

        static SmartClientApplicationIdentity()
        {
            _current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
        }

        public static IApplicationIdentity Current
        {
            get { return _current.Value; }
        }

        private static readonly Guid _instanceId = Guid.NewGuid();
        private readonly string _applicationUid;
        private readonly string _mashineId;
        private readonly DateTime _instanceStartTime;

        private SmartClientApplicationIdentity()
        {
            _instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
            _applicationUid = ComputeApplicationId();
            _mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
        }

        public Guid InstanceId
        {
            get { return _instanceId; }
        }

        public string ApplicationUid
        {
            get { return _applicationUid; }
        }

        public string MashineId
        {
            get { return _mashineId; }
        }

        public DateTime InstanceStartTime
        {
            get { return _instanceStartTime; }
        }

        public string LicenceKey { get; private set; }

        private static string ComputeApplicationId()
        {
            return ComputerId.Value.ToFingerPrintMd5Hash();
        }
    }
}

Disable adding redundant arguments for getting machine id


using System;
using ChamberLib.Content;
using System.IO;

namespace ChamberLib.OpenTK
{
    public class GlslShaderImporter
    {
        public GlslShaderImporter(ShaderStageImporter next=null)
        {
            this.next = next;
        }

        readonly ShaderStageImporter next;

        public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
        {
            if (File.Exists(filename))
            {
            }
            else if (type == ShaderType.Vertex && File.Exists(filename + ".vert"))
            {
                filename += ".vert";
            }
            else if (type == ShaderType.Fragment && File.Exists(filename + ".frag"))
            {
                filename += ".frag";
            }
            else if (next != null)
            {
                return next(filename, type, importer);
            }
            else
            {
                throw new FileNotFoundException(
                    string.Format(
                        "The {0} shader file could not be found: {1}",
                        type,
                        filename),
                    filename);
            }

            var source = File.ReadAllText(filename);

            return new ShaderContent(
                vs: (type == ShaderType.Vertex ? source : null),
                fs: (type == ShaderType.Fragment ? source : null),
                name: filename,
                type: ShaderType.Vertex);
        }
    }
}

using System;
using ChamberLib.Content;
using System.IO;

namespace ChamberLib.OpenTK
{
    public class GlslShaderImporter
    {
        public GlslShaderImporter(ShaderStageImporter next=null)
        {
            this.next = next;
        }

        readonly ShaderStageImporter next;

        public ShaderContent ImportShaderStage(string filename, ShaderType type, IContentImporter importer)
        {
            if (File.Exists(filename))
            {
            }
            else if (type == ShaderType.Vertex && File.Exists(filename + ".vert"))
            {
                filename += ".vert";
            }
            else if (type == ShaderType.Fragment && File.Exists(filename + ".frag"))
            {
                filename += ".frag";
            }
            else if (next != null)
            {
                return next(filename, type, importer);
            }
            else
            {
                throw new FileNotFoundException(
                    string.Format(
                        "The {0} shader file could not be found: {1}",
                        type,
                        filename),
                    filename);
            }

            var source = File.ReadAllText(filename);

            return new ShaderContent(
                vs: (type == ShaderType.Vertex ? source : null),
                fs: (type == ShaderType.Fragment ? source : null),
                name: filename,
                type: type);
        }
    }
}

Set the right shader type.

Set the right shader type.


// 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.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Schedule;

namespace osu.Game.Tournament.Tests.Screens
{
    public class TestSceneScheduleScreen : TournamentTestScene
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both });
            Add(new ScheduleScreen());
        }
    }
}

// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Schedule;

namespace osu.Game.Tournament.Tests.Screens
{
    public class TestSceneScheduleScreen : TournamentTestScene
    {
        [BackgroundDependencyLoader]
        private void load()
        {
            Add(new TourneyVideo("main") { RelativeSizeAxes = Axes.Both });
            Add(new ScheduleScreen());
        }

        [Test]
        public void TestCurrentMatchTime()
        {
            setMatchDate(TimeSpan.FromDays(-1));
            setMatchDate(TimeSpan.FromSeconds(5));
            setMatchDate(TimeSpan.FromMinutes(4));
            setMatchDate(TimeSpan.FromHours(3));
        }

        private void setMatchDate(TimeSpan relativeTime)
            // Humanizer cannot handle negative timespans.
            => AddStep($"start time is {relativeTime}", () =>
            {
                var match = CreateSampleMatch();
                match.Date.Value = DateTimeOffset.Now + relativeTime;
                Ladder.CurrentMatch.Value = match;
            });
    }
}

Add tests for time display

Add tests for time display


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

using Umbraco.Cms.Core.Configuration;

namespace uSync.Core
{
    /// <summary>
    ///  a centralized way of telling if the current version of umbraco has
    ///  certain features or not.
    /// </summary>
    public class uSyncCapabilityChecker
    {
        private readonly IUmbracoVersion _version;
        public uSyncCapabilityChecker(IUmbracoVersion version)
        {
            _version = version;
        }

        /// <summary>
        ///  History cleanup was introduced in Umbraco 9.1
        /// </summary>
        /// <remarks>
        ///  anything above v9.1 has history cleanup.
        /// </remarks>
        public bool HasHistoryCleanup
            => _version.Version.Major != 9 || _version.Version.Minor >= 1;

        /// <summary>
        ///  Has a runtime mode introduced in v10.1
        /// </summary>
        /// <remarks>
        ///  Runtime mode of Production means you can't update views etc.
        /// </remarks>
        public bool HasRuntimeMode
            => _version.Version.Major > 10 ||
            _version.Version.Major == 10 && _version.Version.Minor > 1;
    }

}

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

using Umbraco.Cms.Core.Configuration;

namespace uSync.Core
{
    /// <summary>
    ///  a centralized way of telling if the current version of umbraco has
    ///  certain features or not.
    /// </summary>
    public class uSyncCapabilityChecker
    {
        private readonly IUmbracoVersion _version;
        public uSyncCapabilityChecker(IUmbracoVersion version)
        {
            _version = version;
        }

        /// <summary>
        ///  History cleanup was introduced in Umbraco 9.1
        /// </summary>
        /// <remarks>
        ///  anything above v9.1 has history cleanup.
        /// </remarks>
        public bool HasHistoryCleanup
            => _version.Version.Major != 9 || _version.Version.Minor >= 1;

        /// <summary>
        ///  Has a runtime mode introduced in v10.1
        /// </summary>
        /// <remarks>
        ///  Runtime mode of Production means you can't update views etc.
        /// </remarks>
        public bool HasRuntimeMode
            => _version.Version.Major > 10 ||
            _version.Version.Major == 10 && _version.Version.Minor > 1;

        /// <summary>
        ///  User groups has Language Permissions - introduced in Umbraco 10.2.0
        /// </summary>
        public bool HasGroupLanguagePermissions => _version.Version >= new Version(10, 2, 0);
    }

}

Update compatibility checks for user language permissions


@using System.Security.Principal

@if (User.IsSignedIn())
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()

                @Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Log off

    }
}
else
{

@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })

@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })

}

@using System.Security.Claims

@if (User.IsSignedIn())
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()

                @Html.ActionLink("Hello " + User.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Log off

    }
}
else
{

@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })

@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })

}

Correct namespace to fix failure

Correct namespace to fix failure


using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azuria.ErrorHandling;
using Azuria.Requests.Builder;

namespace Azuria.Middleware
{
    /// <summary>
    /// Adds some static headers to the request. They indicate things like application, version and api key used.
    /// </summary>
    public class StaticHeaderMiddleware : IMiddleware
    {
        private readonly IDictionary<string, string> _staticHeaders;

        /// <summary>
        ///
        /// </summary>
        /// <param name="staticHeaders"></param>
        public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders)
        {
            this._staticHeaders = staticHeaders;
        }

        /// <inheritdoc />
        public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next,
            CancellationToken cancellationToken = default)
        {
            return next(request.WithHeader(this._staticHeaders), cancellationToken);
        }

        /// <inheritdoc />
        public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request,
            MiddlewareAction<T> next, CancellationToken cancellationToken = default)
        {
            return next(request.WithHeader(this._staticHeaders), cancellationToken);
        }
    }
}

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azuria.ErrorHandling;
using Azuria.Requests.Builder;

namespace Azuria.Middleware
{
    /// <summary>
    /// Adds some static headers to the request. They indicate things like application, version and api key used.
    /// </summary>
    public class StaticHeaderMiddleware : IMiddleware
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="staticHeaders"></param>
        public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders)
        {
            this.Header = staticHeaders;
        }

        /// <summary>
        ///
        /// </summary>
        /// <value></value>
        public IDictionary<string, string> Header { get; }

        /// <inheritdoc />
        public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next,
            CancellationToken cancellationToken = default)
        {
            return next(request.WithHeader(this.Header), cancellationToken);
        }

        /// <inheritdoc />
        public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request,
            MiddlewareAction<T> next, CancellationToken cancellationToken = default)
        {
            return next(request.WithHeader(this.Header), cancellationToken);
        }
    }
}

Make header of header middleware publicly accessible


using System;
using System.Globalization;
using ContainerInstaller;
using SIM.Pipelines.Processors;

namespace SIM.Pipelines.Install.Containers
{
  public enum Topology
  {
    Xm1,
    Xp0,
    Xp1
  }

  public static class StringExtentions
  {
    public static Topology ToTopology(this string tpl)
    {
      if (tpl.Equals("xp0", StringComparison.InvariantCultureIgnoreCase))
      {
        return Topology.Xp0;
      }

      if (tpl.Equals("xp1", StringComparison.InvariantCultureIgnoreCase))
      {
        return Topology.Xp1;
      }

      if (tpl.Equals("xm1", StringComparison.InvariantCultureIgnoreCase))
      {
        return Topology.Xm1;
      }

      throw new InvalidOperationException("Topology cannot be resolved from '" + tpl + "'");
    }
  }

  public class InstallContainerArgs : ProcessorArgs
  {

    public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology)
    {
      this.EnvModel = model;
      this.FilesRoot = filesRoot;
      this.Destination = destination;
      this.Topology = topology.ToTopology();
    }
    public EnvModel EnvModel { get; }
    public string Destination
    {
      get; set;
    }
    public Topology Topology { get; }
    public string FilesRoot
    {
      get;
    }
  }
}

using System;
using System.Globalization;
using ContainerInstaller;
using SIM.Pipelines.Processors;

namespace SIM.Pipelines.Install.Containers
{
  public enum Topology
  {
    Xm1,
    Xp0,
    Xp1
  }

  public class InstallContainerArgs : ProcessorArgs
  {

    public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology)
    {
      this.EnvModel = model;
      this.FilesRoot = filesRoot;
      this.Destination = destination;
      this.Topology = (Topology)Enum.Parse(typeof(Topology), topology, true);
    }
    public EnvModel EnvModel { get; }
    public string Destination
    {
      get; set;
    }
    public Topology Topology { get; }
    public string FilesRoot
    {
      get;
    }
  }
}

Simplify parsing string to Topology enum


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

namespace EDDiscovery.EliteDangerous.JournalEvents
{
    public class JournalFileHeader : JournalEntry
    {
        public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader)
        {

            GameVersion = Tools.GetStringDef(evt["gameversion"]);
            Build = Tools.GetStringDef(evt["build"]);
            Language = Tools.GetStringDef(evt["language"]);
        }

        public string GameVersion { get; set; }
        public string Build { get; set; }
        public string Language { get; set; }
    }
}

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

namespace EDDiscovery.EliteDangerous.JournalEvents
{
    public class JournalFileHeader : JournalEntry
    {
        public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader)
        {

            GameVersion = Tools.GetStringDef(evt["gameversion"]);
            Build = Tools.GetStringDef(evt["build"]);
            Language = Tools.GetStringDef(evt["language"]);
        }

        public string GameVersion { get; set; }
        public string Build { get; set; }
        public string Language { get; set; }

        public bool Beta
        {
            get
            {
                if (GameVersion.Contains("Beta"))
                    return true;

                if (GameVersion.Equals("2.2") && Build.Contains("r121645/r0"))
                    return true;

                return false;
            }
        }
    }
}

Add Beta property on FleaHeader event

Add Beta  property on FleaHeader event


using Ets.Mobile.ViewModel.Pages.Account;
using ReactiveUI;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;

namespace Ets.Mobile.Pages.Account
{
    public partial class LoginPage : IViewFor<LoginViewModel>
    {
        #region IViewFor<T>

        public LoginViewModel ViewModel
        {
            get { return (LoginViewModel)GetValue(ViewModelProperty); }
            set { SetValue(ViewModelProperty, value); }
        }
        public static readonly DependencyProperty ViewModelProperty =
            DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null));

        object IViewFor.ViewModel
        {
            get { return ViewModel; }
            set { ViewModel = (LoginViewModel)value; }
        }

        #endregion

        public LoginPage()
        {
            InitializeComponent();

            // When ViewModel is set
            this.WhenAnyValue(x => x.ViewModel)
                .Where(x => x != null)
                .Subscribe(x =>
                {
#if DEBUG
                    ViewModel.UserName = "";
                    ViewModel.Password = "";
#endif
                    Login.Click += (sender, arg) => { ErrorMessage.Visibility = Visibility.Collapsed; };
                });

            // Error Handling
            UserError.RegisterHandler(ue =>
            {
                ErrorMessage.Text = ue.ErrorMessage;
                ErrorMessage.Visibility = Visibility.Visible;

                return Observable.Return(RecoveryOptionResult.CancelOperation);
            });

            this.BindCommand(ViewModel, x => x.Login, x => x.Login);

            PartialInitialize();
        }

        partial void PartialInitialize();
    }
}

using Ets.Mobile.ViewModel.Pages.Account;
using ReactiveUI;
using System;
using System.Reactive.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace Ets.Mobile.Pages.Account
{
    public partial class LoginPage : IViewFor<LoginViewModel>
    {
        #region IViewFor<T>

        public LoginViewModel ViewModel
        {
            get { return (LoginViewModel)GetValue(ViewModelProperty); }
            set { SetValue(ViewModelProperty, value); }
        }
        public static readonly DependencyProperty ViewModelProperty =
            DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null));

        object IViewFor.ViewModel
        {
            get { return ViewModel; }
            set { ViewModel = (LoginViewModel)value; }
        }

        #endregion

        public LoginPage()
        {
            InitializeComponent();

            // When ViewModel is set
            this.WhenAnyValue(x => x.ViewModel)
                .Where(x => x != null)
                .Subscribe(x =>
                {
                    Login.Events().Click.Subscribe(arg => ErrorMessage.Visibility = Visibility.Collapsed);
                });

            // Error Handling
            UserError.RegisterHandler(ue =>
            {
                ErrorMessage.Text = ue.ErrorMessage;
                ErrorMessage.Visibility = Visibility.Visible;

                return Observable.Return(RecoveryOptionResult.CancelOperation);
            });

            PartialInitialize();
        }

        partial void PartialInitialize();
    }
}

Use ReactiveUI Events for Click Handler

Use ReactiveUI Events for Click Handler


using AllReady.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting.Internal;

namespace AllReady.UnitTest
{
  /// <summary>
  /// Inherit from this type to implement tests that
  /// have access to a service provider, empty in-memory
  /// database, and basic configuration.
  /// </summary>
  public abstract class TestBase
  {
    protected IServiceProvider ServiceProvider { get; private set; }

    public TestBase()
    {
      if (ServiceProvider == null)
      {
        var services = new ServiceCollection();

        // set up empty in-memory test db
        services.AddEntityFramework()
          .AddEntityFrameworkInMemoryDatabase()
          .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase());

        // add identity service
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AllReadyContext>();
        var context = new DefaultHttpContext();
        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
        services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });

        // Setup hosting environment
        IHostingEnvironment hostingEnvironment = new HostingEnvironment();
        hostingEnvironment.EnvironmentName = "Development";
        services.AddSingleton(x => hostingEnvironment);

        // set up service provider for tests
        ServiceProvider = services.BuildServiceProvider();
      }
    }
  }
}

using AllReady.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting.Internal;

namespace AllReady.UnitTest
{
  /// <summary>
  /// Inherit from this type to implement tests that
  /// have access to a service provider, empty in-memory
  /// database, and basic configuration.
  /// </summary>
  public abstract class TestBase
  {
    protected IServiceProvider ServiceProvider { get; private set; }

    public TestBase()
    {
      if (ServiceProvider == null)
      {
        var services = new ServiceCollection();

        // set up empty in-memory test db
        services
          .AddEntityFrameworkInMemoryDatabase()
          .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));

        // add identity service
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<AllReadyContext>();
        var context = new DefaultHttpContext();
        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
        services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });

        // Setup hosting environment
        IHostingEnvironment hostingEnvironment = new HostingEnvironment();
        hostingEnvironment.EnvironmentName = "Development";
        services.AddSingleton(x => hostingEnvironment);

        // set up service provider for tests
        ServiceProvider = services.BuildServiceProvider();
      }
    }
  }
}

Fix for EFCore using the same InMemoryDatabase Instance when running tests.


using System;
using Microsoft.AspNetCore.Http;

namespace Hellang.Middleware.SpaFallback
{
    public class SpaFallbackOptions
    {
        public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = _ => "/index.html";

        public bool AllowFileExtensions { get; set; } = false;

        public bool ThrowIfFallbackFails { get; set; } = true;
    }
}

using System;
using Microsoft.AspNetCore.Http;

namespace Hellang.Middleware.SpaFallback
{
    public class SpaFallbackOptions
    {
        private static readonly Func<HttpContext, PathString> DefaultFallbackPathFactory = _ => "/index.html";

        public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = DefaultFallbackPathFactory;

        public bool AllowFileExtensions { get; set; } = false;

        public bool ThrowIfFallbackFails { get; set; } = true;
    }
}

Make default fallback path factory static


using System;

using NHibernate.Cfg;

using NUnit.Framework;

namespace NHibernate.Test.CfgTest
{
	/// <summary>
	/// Summary description for ConfigurationFixture.
	/// </summary>
	[TestFixture]
	public class ConfigurationFixture
	{
		[SetUp]
		public void SetUp()
		{
			System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true);
		}

		[TearDown]
		public void TearDown()
		{
			System.IO.File.Delete("hibernate.cfg.xml");
		}

		/// <summary>
		/// Verify that NHibernate can read the configuration from a hibernate.cfg.xml
		/// file and that the values override what is in the app.config.
		/// </summary>
		[Test]
		public void ReadCfgXmlFromDefaultFile()
		{
			Configuration cfg = new Configuration();
			cfg.Configure();

			Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]);
			Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]);
		}
	}
}

using System;

using NHibernate.Cfg;

using NUnit.Framework;

namespace NHibernate.Test.CfgTest
{
	/// <summary>
	/// Summary description for ConfigurationFixture.
	/// </summary>
	[TestFixture]
	public class ConfigurationFixture
	{

		[SetUp]
		public void SetUp()
		{
			System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true);
		}

		[TearDown]
		public void TearDown()
		{
			System.IO.File.Delete("hibernate.cfg.xml");
		}

		/// <summary>
		/// Verify that NHibernate can read the configuration from a hibernate.cfg.xml
		/// file and that the values override what is in the app.config.
		/// </summary>
		[Test]
		public void ReadCfgXmlFromDefaultFile()
		{
			string origQuerySubst = Cfg.Environment.Properties[Cfg.Environment.QuerySubstitutions] as string;
			string origConnString = Cfg.Environment.Properties[Cfg.Environment.ConnectionString] as string;

			Configuration cfg = new Configuration();
			cfg.Configure();

			Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]);
			Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]);

			cfg.Properties[Cfg.Environment.QuerySubstitutions] = origQuerySubst;
			cfg.Properties[Cfg.Environment.ConnectionString] = origConnString;
		}
	}
}

Test now restores Environment properties back to their original values.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@707


@model List<Post>

Latest Posts

    @foreach (var post in Model.Take(4))
    {

        @Html.Partial("_HomePostCard", post)

    }

    @foreach (var post in Model.Skip(4))
    {

          @Html.Partial("_HomePostCard", post)

    }

Add medium breakpoint to home latests posts.


namespace GitTools.IssueTrackers.Jira
{
    public static class StringExtensions
    {
        public static string AddJiraFilter(this string value, string additionalValue, string joinText = "AND")
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                value += string.Format(" {0} ", joinText);
            }
            else
            {
                value = string.Empty;
            }

            value += additionalValue;

            return value;
        }
    }
}

namespace GitTools.IssueTrackers.Jira
{
    internal static class StringExtensions
    {
        public static string AddJiraFilter(this string value, string additionalValue, string joinText = "AND")
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                value += string.Format(" {0} ", joinText);
            }
            else
            {
                value = string.Empty;
            }

            value += additionalValue;

            return value;
        }
    }
}

Change class visibility from public to internal for Jira string extensions


// 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Objects.Drawables;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Osu.Skinning.Argon
{
    public class ArgonSliderScorePoint : CircularContainer
    {
        private Bindable<Color4> accentColour = null!;

        private const float size = 12;

        [BackgroundDependencyLoader]
        private void load(DrawableHitObject hitObject)
        {
            Masking = true;
            Origin = Anchor.Centre;
            Size = new Vector2(size);
            BorderThickness = 3;
            BorderColour = Color4.White;
            Child = new Box
            {
                RelativeSizeAxes = Axes.Both,
                AlwaysPresent = true,
                Alpha = 0,
            };

            accentColour = hitObject.AccentColour.GetBoundCopy();
            accentColour.BindValueChanged(accent => BorderColour = accent.NewValue);
        }
    }
}

// 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.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Objects.Drawables;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Osu.Skinning.Argon
{
    public class ArgonSliderScorePoint : CircularContainer
    {
        private Bindable<Color4> accentColour = null!;

        private const float size = 12;

        [BackgroundDependencyLoader]
        private void load(DrawableHitObject hitObject)
        {
            Masking = true;
            Origin = Anchor.Centre;
            Size = new Vector2(size);
            BorderThickness = 3;
            BorderColour = Color4.White;
            Child = new Box
            {
                RelativeSizeAxes = Axes.Both,
                AlwaysPresent = true,
                Alpha = 0,
            };

            accentColour = hitObject.AccentColour.GetBoundCopy();
            accentColour.BindValueChanged(accent => BorderColour = accent.NewValue, true);
        }
    }
}

Fix slider tick colour not being applied properly


using System;
using Xunit;
using Zuehlke.Eacm.Web.Backend.CQRS;

namespace Zuehlke.Eacm.Web.Backend.Tests.DomainModel
{
    public class EventAggregatorExtensionsFixture
    {
        [Fact]
        public void PublishEvent_()
        {
            // arrange

            // act

            // assert
        }

        private class TestEvent : IEvent
        {
            public Guid CorrelationId
            {
                get
                {
                    throw new NotImplementedException();
                }

                set
                {
                    throw new NotImplementedException();
                }
            }

            public Guid Id
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            public Guid SourceId
            {
                get
                {
                    throw new NotImplementedException();
                }

                set
                {
                    throw new NotImplementedException();
                }
            }

            public DateTime Timestamp
            {
                get
                {
                    throw new NotImplementedException();
                }

                set
                {
                    throw new NotImplementedException();
                }
            }
        }
    }
}

using System;
using Xunit;
using Zuehlke.Eacm.Web.Backend.CQRS;
using Zuehlke.Eacm.Web.Backend.Utils.PubSubEvents;

namespace Zuehlke.Eacm.Web.Backend.Tests.DomainModel
{
    public class EventAggregatorExtensionsFixture
    {
        [Fact]
        public void PublishEvent_EventAggregatorIsNull_ThrowsException()
        {
            // arrange
            IEventAggregator eventAggegator = null;
            IEvent e = new TestEvent();

            // act
            Assert.ThrowsAny<ArgumentNullException>(() => CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e));
        }

        [Fact]
        public void PublishEvent_EventIsNull_ThrowsException()
        {
            // arrange
            IEventAggregator eventAggegator = new EventAggregator();
            IEvent e = null;

            // act
            Assert.ThrowsAny<ArgumentNullException>(() => CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e));
        }

        [Fact]
        public void PublishEvent_WithEventSubscription_HandlerGetsCalleds()
        {
            // arrange
            IEventAggregator eventAggegator = new EventAggregator();
            IEvent e = new TestEvent();

            bool executed = false;

            eventAggegator.Subscribe<TestEvent>(ev => executed = true);

            // act
            CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e);

            Assert.True(executed);
        }

        private class TestEvent : IEvent
        {
            public Guid CorrelationId
            {
                get
                {
                    throw new NotImplementedException();
                }

                set
                {
                    throw new NotImplementedException();
                }
            }

            public Guid Id
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            public Guid SourceId
            {
                get
                {
                    throw new NotImplementedException();
                }

                set
                {
                    throw new NotImplementedException();
                }
            }

            public DateTime Timestamp
            {
                get
                {
                    throw new NotImplementedException();
                }

                set
                {
                    throw new NotImplementedException();
                }
            }
        }
    }
}

refactor(configurationproject): Implement tests for the EventAggregatorExtensions class.


using Aurora.Profiles.Generic.GSI.Nodes;
using Aurora.Profiles.TModLoader.GSI.Nodes;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aurora.Profiles.TModLoader.GSI {
    public class GameState_TModLoader : GameState<GameState_TModLoader> {
        public ProviderNode Provider => NodeFor<ProviderNode>("provider");

        public WorldNode World => NodeFor<WorldNode>("world");

        public PlayerNode Player => NodeFor<PlayerNode>("player");

        public GameState_TModLoader() : base() { }

        /// <summary>
        /// Creates a GameState_Terraria instance based on the passed JSON data.
        /// </summary>
        /// <param name="JSONstring"></param>
        public GameState_TModLoader(string JSONstring) : base(JSONstring) { }
    }
}

using Aurora.Profiles.Generic.GSI.Nodes;
using Aurora.Profiles.TModLoader.GSI.Nodes;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aurora.Profiles.TModLoader.GSI {
    public class GameState_TModLoader : GameState {
        public ProviderNode Provider => NodeFor<ProviderNode>("provider");

        public WorldNode World => NodeFor<WorldNode>("world");

        public PlayerNode Player => NodeFor<PlayerNode>("player");

        public GameState_TModLoader() : base() { }

        /// <summary>
        /// Creates a GameState_Terraria instance based on the passed JSON data.
        /// </summary>
        /// <param name="JSONstring"></param>
        public GameState_TModLoader(string JSONstring) : base(JSONstring) { }
    }
}

Fix error with merge on TModLoader GameState.


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace TechProFantasySoccer
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            /*var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);*/
            //Commenting the above code and using the below line gets rid of the master mobile site.
            routes.EnableFriendlyUrls();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace TechProFantasySoccer
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
            //Commenting the above code and using the below line gets rid of the master mobile site.
            //routes.EnableFriendlyUrls();
        }
    }
}

Switch the settings back for the mobile site. Fix this later


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

public class SimpleLinkedList<T> : IEnumerable<T>
{
    public SimpleLinkedList(T value) :
        this(new[] { value })
    {
    }

    public SimpleLinkedList(IEnumerable<T> values)
    {
        var array = values.ToArray();

        if (array.Length == 0)
        {
            throw new ArgumentException("Cannot create tree from empty list");
        }

        Value = array[0];
        Next = null;

        foreach (var value in array.Skip(1))
        {
            Add(value);
        }
    }

    public T Value { get; }

    public SimpleLinkedList<T> Next { get; private set; }

    public SimpleLinkedList<T> Add(T value)
    {
        var last = this;

        while (last.Next != null)
        {
            last = last.Next;
        }

        last.Next = new SimpleLinkedList<T>(value);

        return this;
    }

    public SimpleLinkedList<T> Reverse()
    {
        return new SimpleLinkedList<T>(this.AsEnumerable().Reverse());
    }

    public IEnumerator<T> GetEnumerator()
    {
        yield return Value;

        foreach (var next in Next?.AsEnumerable() ?? Enumerable.Empty<T>())
        {
            yield return next;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

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

public class SimpleLinkedList<T> : IEnumerable<T>
{
    public SimpleLinkedList(T value) :
        this(new[] { value })
    {
    }

    public SimpleLinkedList(IEnumerable<T> values)
    {
        var array = values.ToArray();

        if (array.Length == 0)
        {
            throw new ArgumentException("Cannot create tree from empty list");
        }

        Value = array[0];
        Next = null;

        foreach (var value in array.Skip(1))
        {
            Add(value);
        }
    }

    public T Value { get; }

    public SimpleLinkedList<T> Next { get; private set; }

    public SimpleLinkedList<T> Add(T value)
    {
        var last = this;

        while (last.Next != null)
        {
            last = last.Next;
        }

        last.Next = new SimpleLinkedList<T>(value);

        return this;
    }

    public IEnumerator<T> GetEnumerator()
    {
        yield return Value;

        foreach (var next in Next?.AsEnumerable() ?? Enumerable.Empty<T>())
        {
            yield return next;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Remove unnecessary Reverse() method in simple-linked-list


// 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 MessagePack;
using Newtonsoft.Json;

namespace osu.Game.Online.Rooms
{
    /// <summary>
    /// The local availability information about a certain beatmap for the client.
    /// </summary>
    [MessagePackObject]
    public class BeatmapAvailability : IEquatable<BeatmapAvailability>
    {
        /// <summary>
        /// The beatmap's availability state.
        /// </summary>
        [Key(0)]
        public readonly DownloadState State;

        /// <summary>
        /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
        /// </summary>
        public readonly float? DownloadProgress;

        [JsonConstructor]
        private BeatmapAvailability(DownloadState state, float? downloadProgress = null)
        {
            State = state;
            DownloadProgress = downloadProgress;
        }

        public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded);
        public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
        public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing);
        public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);

        public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;

        public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
    }
}

// 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 MessagePack;
using Newtonsoft.Json;

namespace osu.Game.Online.Rooms
{
    /// <summary>
    /// The local availability information about a certain beatmap for the client.
    /// </summary>
    [MessagePackObject]
    public class BeatmapAvailability : IEquatable<BeatmapAvailability>
    {
        /// <summary>
        /// The beatmap's availability state.
        /// </summary>
        [Key(0)]
        public readonly DownloadState State;

        /// <summary>
        /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
        /// </summary>
        [Key(1)]
        public readonly float? DownloadProgress;

        [JsonConstructor]
        private BeatmapAvailability(DownloadState state, float? downloadProgress = null)
        {
            State = state;
            DownloadProgress = downloadProgress;
        }

        public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded);
        public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
        public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing);
        public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);

        public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;

        public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
    }
}

Add signalr messagepack key attribute

Add signalr messagepack key attribute


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EpubSharp.Tests
{
    [TestClass]
    public class EpubWriterTests
    {
        [TestMethod]
        public void SaveTest()
        {
            var book = EpubReader.Read(@"../../Samples/epub-assorted/iOS Hackers Handbook.epub");
            var writer = new EpubWriter(book);
            writer.Save("saved.epub");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EpubSharp.Tests
{
    [TestClass]
    public class EpubWriterTests
    {
        [TestMethod]
        public void SaveTest()
        {
            var book = EpubReader.Read(@"../../Samples/epub-assorted/Inversions - Iain M. Banks.epub");
            var writer = new EpubWriter(book);
            writer.Save("saved.epub");
        }
    }
}

Use smaller epub for saving test, so that online validators accept the size.


using CefSharp.Internals;
using System.Collections.Generic;
using System.ServiceModel;

namespace CefSharp.BrowserSubprocess
{
    public class CefRenderProcess : CefSubProcess, IRenderProcess
    {
        private DuplexChannelFactory<IBrowserProcess> channelFactory;
        private CefBrowserBase browser;
        public CefBrowserBase Browser
        {
            get { return browser; }
        }

        public CefRenderProcess(IEnumerable<string> args)
            : base(args)
        {
        }

        protected override void DoDispose(bool isDisposing)
        {
            //DisposeMember(ref renderprocess);
            DisposeMember(ref browser);

            base.DoDispose(isDisposing);
        }

        public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper)
        {
            browser = cefBrowserWrapper;

            if (ParentProcessId == null)
            {
                return;
            }

            channelFactory = new DuplexChannelFactory<IBrowserProcess>(
                this,
                new NetNamedPipeBinding(),
                new EndpointAddress(RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId))
            );

            channelFactory.Open();

            Bind(CreateBrowserProxy().GetRegisteredJavascriptObjects());
        }

        public object EvaluateScript(int frameId, string script, double timeout)
        {
            var result = Browser.EvaluateScript(frameId, script, timeout);
            return result;
        }

        public override IBrowserProcess CreateBrowserProxy()
        {
            return channelFactory.CreateChannel();
        }
    }
}

using CefSharp.Internals;
using System.Collections.Generic;
using System.ServiceModel;

namespace CefSharp.BrowserSubprocess
{
    public class CefRenderProcess : CefSubProcess, IRenderProcess
    {
        private DuplexChannelFactory<IBrowserProcess> channelFactory;
        private CefBrowserBase browser;
        public CefBrowserBase Browser
        {
            get { return browser; }
        }

        public CefRenderProcess(IEnumerable<string> args)
            : base(args)
        {
        }

        protected override void DoDispose(bool isDisposing)
        {
            //DisposeMember(ref renderprocess);
            DisposeMember(ref browser);

            base.DoDispose(isDisposing);
        }

        public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper)
        {
            browser = cefBrowserWrapper;

            if (ParentProcessId == null)
            {
                return;
            }

            var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId);

            channelFactory = new DuplexChannelFactory<IBrowserProcess>(
                this,
                new NetNamedPipeBinding(),
                new EndpointAddress(serviceName)
            );

            channelFactory.Open();

            Bind(CreateBrowserProxy().GetRegisteredJavascriptObjects());
        }

        public object EvaluateScript(int frameId, string script, double timeout)
        {
            var result = Browser.EvaluateScript(frameId, script, timeout);
            return result;
        }

        public override IBrowserProcess CreateBrowserProxy()
        {
            return channelFactory.CreateChannel();
        }
    }
}

Move serviceName to variable - makes for easier debugging


using System;
using App.Services;
using App.Services.Contracts;
using App.ViewModels;
using App.ViewModels.Contracts;
using Microsoft.Practices.Unity;

namespace App.Infrastructure
{
    // ReSharper disable once InconsistentNaming
    public sealed class UWPBootstrapper : CaliburnBootstrapper
    {
        public UWPBootstrapper(Action createWindow) : base(createWindow)
        {
        }

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

            this.UnityContainer.RegisterType<IOpenFolderService, OpenFolderService>();
            this.UnityContainer.RegisterType<IShellViewModel, ShellViewModel>();
        }

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

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.SuppressFinalize(this);
        }
    }
}

using System;
using App.Services;
using App.Services.Contracts;
using App.ViewModels;
using App.ViewModels.Contracts;
using Microsoft.Practices.Unity;

namespace App.Infrastructure
{
    // ReSharper disable once InconsistentNaming
    public sealed class UWPBootstrapper : CaliburnBootstrapper
    {
        public UWPBootstrapper(Action createWindow) : base(createWindow)
        {
        }

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

            this.UnityContainer
                .RegisterType<IOpenFolderService, OpenFolderService>()
                .RegisterType<IShellViewModel, ShellViewModel>();
        }

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

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.SuppressFinalize(this);
        }
    }
}

Use the chain way for registering services and view models.


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

#if NET5_0
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
using OpenTabletDriver;
using osu.Framework.Input.Handlers.Tablet;

namespace osu.Framework.Benchmarks
{
    public class BenchmarkTabletDriver : BenchmarkTest
    {
        private TabletDriver driver;

        public override void SetUp()
        {
            var collection = new DriverServiceCollection()
                .AddTransient<TabletDriver>();

            var serviceProvider = collection.BuildServiceProvider();

            driver = serviceProvider.GetRequiredService<TabletDriver>();
        }

        [Benchmark]
        public void DetectBenchmark()
        {
            driver.Detect();
        }
    }
}
#endif

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

#if NET5_0
using BenchmarkDotNet.Attributes;
using osu.Framework.Input.Handlers.Tablet;

namespace osu.Framework.Benchmarks
{
    public class BenchmarkTabletDriver : BenchmarkTest
    {
        private TabletDriver driver;

        public override void SetUp()
        {
            driver = TabletDriver.Create();
        }

        [Benchmark]
        public void DetectBenchmark()
        {
            driver.Detect();
        }
    }
}
#endif

Fix remaining usage of DI instead of direct `Create()` call


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;

namespace osu.Game.Beatmaps.Drawables
{
    /// <summary>
    /// Display a baetmap background from a local source, but fallback to online source if not available.
    /// </summary>
    public class UpdateableBeatmapBackgroundSprite : ModelBackedDrawable<BeatmapInfo>
    {
        public readonly IBindable<BeatmapInfo> Beatmap = new Bindable<BeatmapInfo>();

        [Resolved]
        private BeatmapManager beatmaps { get; set; }

        public UpdateableBeatmapBackgroundSprite()
        {
            Beatmap.BindValueChanged(b => Model = b);
        }

        protected override Drawable CreateDrawable(BeatmapInfo model)
        {
            Drawable drawable;

            var localBeatmap = beatmaps.GetWorkingBeatmap(model);

            if (localBeatmap.BeatmapInfo.ID == 0 && model?.BeatmapSet?.OnlineInfo != null)
                drawable = new BeatmapSetCover(model.BeatmapSet);
            else
                drawable = new BeatmapBackgroundSprite(localBeatmap);

            drawable.RelativeSizeAxes = Axes.Both;
            drawable.Anchor = Anchor.Centre;
            drawable.Origin = Anchor.Centre;
            drawable.FillMode = FillMode.Fill;

            return drawable;
        }

        protected override double FadeDuration => 400;
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;

namespace osu.Game.Beatmaps.Drawables
{
    /// <summary>
    /// Display a baetmap background from a local source, but fallback to online source if not available.
    /// </summary>
    public class UpdateableBeatmapBackgroundSprite : ModelBackedDrawable<BeatmapInfo>
    {
        public readonly IBindable<BeatmapInfo> Beatmap = new Bindable<BeatmapInfo>();

        [Resolved]
        private BeatmapManager beatmaps { get; set; }

        public UpdateableBeatmapBackgroundSprite()
        {
            Beatmap.BindValueChanged(b => Model = b);
        }

        protected override Drawable CreateDrawable(BeatmapInfo model)
        {
            return new DelayedLoadUnloadWrapper(() => {
                Drawable drawable;

                var localBeatmap = beatmaps.GetWorkingBeatmap(model);

                if (localBeatmap.BeatmapInfo.ID == 0 && model?.BeatmapSet?.OnlineInfo != null)
                    drawable = new BeatmapSetCover(model.BeatmapSet);
                else
                    drawable = new BeatmapBackgroundSprite(localBeatmap);

                drawable.RelativeSizeAxes = Axes.Both;
                drawable.Anchor = Anchor.Centre;
                drawable.Origin = Anchor.Centre;
                drawable.FillMode = FillMode.Fill;
                drawable.OnLoadComplete = d => d.FadeInFromZero(400);

                return drawable;
            }, 500, 10000);
        }

        protected override double FadeDuration => 0;
    }
}

Fix covers being loaded even when off-screen


using FluentAssertions;
using NUnit.Framework;

namespace Nerdle.AutoConfig.Tests.Integration
{
    [TestFixture]
    public class UsingDefaultConfigFilePath
    {
        [Test]
#if NETCOREAPP
        [Ignore("Buggy interaction between the test runner and System.Configuration.ConfigurationManager, see https://github.com/nunit/nunit3-vs-adapter/issues/356")]
#endif
        public void Mapping_from_the_default_file_path()
        {
            var foo = AutoConfig.Map<IFoo>();
            var bar = AutoConfig.Map<IFoo>("bar");

            foo.Should().NotBeNull();
            foo.Name.Should().Be("foo");

            bar.Should().NotBeNull();
            bar.Name.Should().Be("bar");
        }

        public interface IFoo
        {
            string Name { get; }
        }
    }
}

using FluentAssertions;
using NUnit.Framework;

namespace Nerdle.AutoConfig.Tests.Integration
{
    [TestFixture]
    public class UsingDefaultConfigFilePath
#if NETCOREAPP
        : System.IDisposable
    {
        private readonly string _configFilePath;

        // In order to workaround flaky interaction between the test runner and System.Configuration.ConfigurationManager
        // See https://github.com/nunit/nunit3-vs-adapter/issues/356#issuecomment-700754225
        public UsingDefaultConfigFilePath()
        {
            _configFilePath = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).FilePath;
            System.IO.File.Copy($"{System.Reflection.Assembly.GetExecutingAssembly().Location}.config", _configFilePath, overwrite: true);
        }

        public void Dispose()
        {
            System.IO.File.Delete(_configFilePath);
        }
#else
    {
#endif

        [Test]
        public void Mapping_from_the_default_file_path()
        {
            var foo = AutoConfig.Map<IFoo>();
            var bar = AutoConfig.Map<IFoo>("bar");

            foo.Should().NotBeNull();
            foo.Name.Should().Be("foo");

            bar.Should().NotBeNull();
            bar.Name.Should().Be("bar");
        }

        public interface IFoo
        {
            string Name { get; }
        }
    }
}

Use a workaround to make Mapping_from_the_default_file_path pass on .NET Core

See https://github.com/nunit/nunit3-vs-adapter/issues/356#issuecomment-700754225


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

namespace Rubberduck.Math
{
    public static class Calculator
    {
        public static int Evaluate(string expression)
        {
            var lexer = new BasicMathLexer(new AntlrInputStream(expression));
            lexer.RemoveErrorListeners();
            lexer.AddErrorListener(new ThrowExceptionErrorListener());

            var tokens = new CommonTokenStream(lexer);
            var parser = new BasicMathParser(tokens);

            var tree = parser.compileUnit();

            var visitor = new IntegerMathVisitor();

            return visitor.Visit(tree);
        }
    }
}

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

namespace Rubberduck.Math
{
    public static class Calculator
    {
        public static int Evaluate(string expression)
        {
            var lexer = new BasicMathLexer(new AntlrInputStream(expression));
            lexer.RemoveErrorListeners();
            lexer.AddErrorListener(new ThrowExceptionErrorListener());

            var tokens = new CommonTokenStream(lexer);
            var parser = new BasicMathParser(tokens);

            var tree = parser.compileUnit();

            var exprCount = tree.expression().Count;
            if (exprCount > 1)
            {
                throw new ArgumentException(String.Format("Too many expressions. Only one can be evaluated. {0} expressions were entered.", exprCount));
            }

            var visitor = new IntegerMathVisitor();

            return visitor.Visit(tree);
        }
    }
}

Throw exception if more than one expression is passed to Evaluate


using System.IO;
using UnityEditor;
using UnityEngine;

namespace DTCommandPalette {
    public abstract class GameObjectCommand : ICommand {
        // PRAGMA MARK - ICommand
        public string DisplayTitle {
            get {
                return _obj.name;
            }
        }

        public string DisplayDetailText {
            get {
                return _obj.FullName();
            }
        }

        public abstract Texture2D DisplayIcon {
            get;
        }

        public bool IsValid() {
            return _obj != null;
        }

        public abstract void Execute();

        // PRAGMA MARK - Constructors
        public GameObjectCommand(GameObject obj) {
            _obj = obj;
        }

        // PRAGMA MARK - Internal
        protected GameObject _obj;
    }
}

using System.IO;
using UnityEditor;
using UnityEngine;

namespace DTCommandPalette {
    public abstract class GameObjectCommand : ICommand {
        // PRAGMA MARK - ICommand
        public string DisplayTitle {
            get {
                if (!IsValid()) {
                    return "";
                }
                return _obj.name;
            }
        }

        public string DisplayDetailText {
            get {
                if (!IsValid()) {
                    return "";
                }
                return _obj.FullName();
            }
        }

        public abstract Texture2D DisplayIcon {
            get;
        }

        public bool IsValid() {
            return _obj != null;
        }

        public abstract void Execute();

        // PRAGMA MARK - Constructors
        public GameObjectCommand(GameObject obj) {
            _obj = obj;
        }

        // PRAGMA MARK - Internal
        protected GameObject _obj;
    }
}

Fix null references when game object is destroyed


using System;

namespace Pixie
{
    /// <summary>
    /// A base class for markup nodes: composable elements that can
    /// be rendered.
    /// </summary>
    public abstract class MarkupNode
    {
        /// <summary>
        /// Gets a fallback version of this node for when the renderer
        /// doesn't know how to render this node's type. Null is
        /// returned if no reasonable fallback can be provided.
        /// </summary>
        /// <returns>The node's fallback version, or <c>null</c>.</returns>
        public abstract MarkupNode Fallback { get; }

        /// <summary>
        /// Applies a mapping to this markup node's children and returns
        /// a new instance of this node's type that contains the modified
        /// children.
        /// </summary>
        /// <param name="mapping">A mapping function.</param>
        /// <returns>A new markup node.</returns>
        public abstract MarkupNode Map(Func<MarkupNode, MarkupNode> mapping);
    }
}

using System;
using Pixie.Markup;

namespace Pixie
{
    /// <summary>
    /// A base class for markup nodes: composable elements that can
    /// be rendered.
    /// </summary>
    public abstract class MarkupNode
    {
        /// <summary>
        /// Gets a fallback version of this node for when the renderer
        /// doesn't know how to render this node's type. Null is
        /// returned if no reasonable fallback can be provided.
        /// </summary>
        /// <returns>The node's fallback version, or <c>null</c>.</returns>
        public abstract MarkupNode Fallback { get; }

        /// <summary>
        /// Applies a mapping to this markup node's children and returns
        /// a new instance of this node's type that contains the modified
        /// children.
        /// </summary>
        /// <param name="mapping">A mapping function.</param>
        /// <returns>A new markup node.</returns>
        public abstract MarkupNode Map(Func<MarkupNode, MarkupNode> mapping);

        /// <summary>
        /// Creates a text markup node from a string of characters.
        /// </summary>
        /// <param name="text">
        /// The text to wrap in a text markup node.
        /// </param>
        public static implicit operator MarkupNode(string text)
        {
            return new Text(text);
        }
    }
}

Define an implicit conversion from strings to markup nodes


using System;
using System.Collections.Generic;
using Avalonia.Data;

namespace Avalonia
{
    internal static class ClassBindingManager
    {
        private static readonly Dictionary<string, AvaloniaProperty> s_RegisteredProperties =
            new Dictionary<string, AvaloniaProperty>();

        public static IDisposable Bind(IStyledElement target, string className, IBinding source, object anchor)
        {
            if (!s_RegisteredProperties.TryGetValue(className, out var prop))
                s_RegisteredProperties[className] = prop = RegisterClassProxyProperty(className);
            return target.Bind(prop, source, anchor);
        }

        private static AvaloniaProperty RegisterClassProxyProperty(string className)
        {
            var prop = AvaloniaProperty.Register<StyledElement, bool>("__AvaloniaReserved::Classes::" + className);
            prop.Changed.Subscribe(args =>
            {
                var enable = args.NewValue.GetValueOrDefault();
                var classes = ((IStyledElement)args.Sender).Classes;
                if (enable)
                {
                    if (!classes.Contains(className))
                        classes.Add(className);
                }
                else
                    classes.Remove(className);
            });

            return prop;
        }
    }
}

using System;
using System.Collections.Generic;
using Avalonia.Data;

namespace Avalonia
{
    internal static class ClassBindingManager
    {
        private static readonly Dictionary<string, AvaloniaProperty> s_RegisteredProperties =
            new Dictionary<string, AvaloniaProperty>();

        public static IDisposable Bind(IStyledElement target, string className, IBinding source, object anchor)
        {
            if (!s_RegisteredProperties.TryGetValue(className, out var prop))
                s_RegisteredProperties[className] = prop = RegisterClassProxyProperty(className);
            return target.Bind(prop, source, anchor);
        }

        private static AvaloniaProperty RegisterClassProxyProperty(string className)
        {
            var prop = AvaloniaProperty.Register<StyledElement, bool>("__AvaloniaReserved::Classes::" + className);
            prop.Changed.Subscribe(args =>
            {
                var classes = ((IStyledElement)args.Sender).Classes;
                classes.Set(className, args.NewValue.GetValueOrDefault());
            });

            return prop;
        }
    }
}

Simplify the code a bit

Simplify the code a bit


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Plugin.Scraping.TheGamesDb;
using Snowflake.Scraping;
using Snowflake.Scraping.Extensibility;
using Xunit;

namespace Snowflake.Scraping.Tests
{
    public class ScraperIntegrationTests
    {
        [Fact]
        public async Task TGDBScraping_Test()
        {
            var tgdb = new TheGamesDbScraper();
            var scrapeJob = new ScrapeJob(new SeedContent[] {
                ("platform", "NINTENDO_NES"),
                ("search_title", "Super Mario Bros."),
            }, new[] { tgdb }, new ICuller[] { });
            while (await scrapeJob.Proceed());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Plugin.Scraping.TheGamesDb;
using Snowflake.Scraping;
using Snowflake.Scraping.Extensibility;
using Xunit;

namespace Snowflake.Scraping.Tests
{
    public class ScraperIntegrationTests
    {
        // [Fact]
        // public async Task TGDBScraping_Test()
        // {
        //     var tgdb = new TheGamesDbScraper();
        //     var scrapeJob = new ScrapeJob(new SeedContent[] {
        //         ("platform", "NINTENDO_NES"),
        //         ("search_title", "Super Mario Bros."),
        //     }, new[] { tgdb }, new ICuller[] { });
        //     while (await scrapeJob.Proceed());
        // }
    }
}

Disable TGDB Tests for now

Tests: Disable TGDB Tests for now


namespace alert_roster.web.Migrations
{
    using alert_roster.web.Models;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<alert_roster.web.Models.AlertRosterDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = false;
            ContextKey = "alert_roster.web.Models.AlertRosterDbContext";
        }

        protected override void Seed(alert_roster.web.Models.AlertRosterDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //context.Messages.AddOrUpdate(
            //    m => m.Content,
            //    new Message { PostedDate = DateTime.UtcNow, Content = "This is the initial, test message posting" }
            //    );
        }
    }
}

namespace alert_roster.web.Migrations
{
    using alert_roster.web.Models;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<alert_roster.web.Models.AlertRosterDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            ContextKey = "alert_roster.web.Models.AlertRosterDbContext";
        }

        protected override void Seed(alert_roster.web.Models.AlertRosterDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //context.Messages.AddOrUpdate(
            //    m => m.Content,
            //    new Message { PostedDate = DateTime.UtcNow, Content = "This is the initial, test message posting" }
            //    );
        }
    }
}

Allow dataloss... shouldn't be necesssary?


using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace VersionOne.Bugzilla.BugzillaAPI.Testss
{
    [TestClass()]
    public class given_a_Bug
    {
        private IBug _bug;
        private string _expectedReassignToPayload;

        [TestInitialize()]
        public void SetContext()
        {
            _bug = new Bug();

            _expectedReassignToPayload = "{\r\n  \"assigned_to\": \"denise@denise.com\",\r\n  \"status\": \"CONFIRMED\",\r\n  \"token\": \"terry.densmore@versionone.com\"\r\n}";
        }

        [TestMethod]
        public void it_should_give_appropriate_reassigneto_payloads()
        {
            var integrationUser = "terry.densmore@versionone.com";
            _bug.AssignedTo = "denise@denise.com";

            Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
        }

    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace VersionOne.Bugzilla.BugzillaAPI.Testss
{
    [TestClass()]
    public class given_a_Bug
    {
        private IBug _bug;
        private string _expectedReassignToPayload;

        [TestInitialize()]
        public void SetContext()
        {
            _bug = new Bug();

            _expectedReassignToPayload = "{\r\n  \"assigned_to\": \"denise@denise.com\",\r\n  \"status\": \"CONFIRMED\",\r\n  \"token\": \"terry.densmore@versionone.com\"\r\n}";
        }

        [TestMethod]
        public void it_should_give_appropriate_reassigneto_payloads()
        {
            var integrationUser = "terry.densmore@versionone.com";
            _bug.AssignedTo = "denise@denise.com";

            Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser));
        }

    }
}

Remove no longer needed usings

S-51801: Remove no longer needed usings


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Glimpse.Extensions;

namespace Glimpse.Internal
{
    public class DefaultMessageTypeProcessor : IMessageTypeProcessor
    {
        private readonly static Type[] _exclusions = { typeof(object) };

        public virtual IEnumerable<string> Derive(object payload)
        {
            var typeInfo = payload.GetType().GetTypeInfo();

            return typeInfo.BaseTypes(true)
                .Concat(typeInfo.ImplementedInterfaces)
                .Except(_exclusions)
                .Select(t => t.KebabCase());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Glimpse.Extensions;

namespace Glimpse.Internal
{
    public class DefaultMessageTypeProcessor : IMessageTypeProcessor
    {
        private readonly static Type[] _exclusions = { typeof(object) };

        public virtual IEnumerable<string> Derive(object payload)
        {
            var typeInfo = payload.GetType().GetTypeInfo();

            return typeInfo.BaseTypes(true)
                .Concat(typeInfo.ImplementedInterfaces)
                .Except(_exclusions)
                .Select(t =>
                {
                    var result = t.KebabCase();

                    if (result.EndsWith("-message"))
                        return result.Substring(0, result.Length - 8);

                    return result;
                });
        }
    }
}

Drop "-message" from all message names

Drop "-message" from all message names


@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
    ViewBag.PageID = "authorize-response";
    ViewBag.Title = "Please wait";
    ViewBag.HideSigninLink = "true";
    Layout = "~/Views/Shared/_Layout-NoBanner.cshtml";
}

You've logged in

<form id="mainForm" method="post" action="@Model.ResponseFormUri">

Please wait...

    @Html.Raw(Model.ResponseFormFields)

        <button type="submit" class="button" autofocus="autofocus">Continue</button>

</form>

@section scripts
{

}

@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel
@{
    ViewBag.PageID = "authorize-response";
    ViewBag.Title = "Please wait";
    ViewBag.HideSigninLink = "true";
    Layout = "~/Views/Shared/_Layout-NoBanner.cshtml";
}

@ViewBag.Title

<form id="mainForm" method="post" action="@Model.ResponseFormUri">

Please wait...

    @Html.Raw(Model.ResponseFormFields)

        <button type="submit" class="button" autofocus="autofocus">Continue</button>

</form>

@section scripts
{

}

Use the viewBag Title rather than the hard coded one.


// Copyright (c) Solal Pirelli 2014
// See License.txt file for more details

using ThinMvvm.WindowsPhone.SampleApp.Resources;
using ThinMvvm.WindowsPhone.SampleApp.ViewModels;

namespace ThinMvvm.WindowsPhone.SampleApp
{
    public sealed class App : AppBase
    {
        protected override string Language
        {
            get { return AppResources.ResourceLanguage; }
        }

        protected override string FlowDirection
        {
            get { return AppResources.ResourceFlowDirection; }
        }

        public App()
        {
            Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>();
            Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>();

            Container.Bind<ISettings, Settings>();
        }

        protected override void Start( AppDependencies dependencies, AppArguments arguments )
        {
            // simple app, no additional dependencies or arguments

            dependencies.NavigationService.Bind<MainViewModel>( "/Views/MainView.xaml" );
            dependencies.NavigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" );

            dependencies.NavigationService.NavigateTo<MainViewModel, int>( 42 );
        }
    }
}

// Copyright (c) Solal Pirelli 2014
// See License.txt file for more details

using ThinMvvm.WindowsPhone.SampleApp.Resources;
using ThinMvvm.WindowsPhone.SampleApp.ViewModels;

namespace ThinMvvm.WindowsPhone.SampleApp
{
    public sealed class App : AppBase
    {
        private readonly IWindowsPhoneNavigationService _navigationService;

        protected override string Language
        {
            get { return AppResources.ResourceLanguage; }
        }

        protected override string FlowDirection
        {
            get { return AppResources.ResourceFlowDirection; }
        }

        public App()
        {
            _navigationService = Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>();
            Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>();

            Container.Bind<ISettings, Settings>();
        }

        protected override void Start( AppArguments arguments )
        {
            // simple app, no additional dependencies or arguments

            _navigationService.Bind<MainViewModel>( "/Views/MainView.xaml" );
            _navigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" );

            _navigationService.NavigateTo<MainViewModel, int>( 42 );
        }
    }
}

Fix the sample app following previous changes.


namespace Bakery.Security
{
	using System;

	public static class RandomExtensions
	{
		public static Byte[] GetBytes(this IRandom random, Int32 count)
		{
			if (count <= 0)
				throw new ArgumentOutOfRangeException(nameof(count));

			var buffer = new Byte[count];

			for (var i = 0; i < count; i++)
				buffer[i] = random.GetByte();

			return buffer;
		}

		public static Int64 GetInt64(this IRandom random)
		{
			return BitConverter.ToInt64(random.GetBytes(8), 0);
		}
	}
}

namespace Bakery.Security
{
	using System;

	public static class RandomExtensions
	{
		public static Byte[] GetBytes(this IRandom random, Int32 count)
		{
			if (count <= 0)
				throw new ArgumentOutOfRangeException(nameof(count));

			var buffer = new Byte[count];

			for (var i = 0; i < count; i++)
				buffer[i] = random.GetByte();

			return buffer;
		}

		public static Int64 GetInt64(this IRandom random)
		{
			return BitConverter.ToInt64(random.GetBytes(8), 0);
		}

		public static UInt64 GetUInt64(this IRandom random)
		{
			return BitConverter.ToUInt64(random.GetBytes(8), 0);
		}
	}
}

Add extension method for IRandom to get an unsigned 64-bit integer.