using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Web.Http;
using Microsoft.WindowsAzure.Mobile.Service;
using ZUMOAPPNAMEService.DataObjects;
using ZUMOAPPNAMEService.Models;

namespace ZUMOAPPNAMEService
{
    public static class WebApiConfig
    {
        public static void Register()
        {
            // Use this class to set configuration options for your mobile service
            ConfigOptions options = new ConfigOptions();

            // Use this class to set WebAPI configuration options
            HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

            // To display errors in the browser during development, uncomment the following
            // line. Comment it out again when you deploy your service for production use.
            // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            Database.SetInitializer(new ZUMOAPPNAMEInitializer());
        }
    }

    public class ZUMOAPPNAMEInitializer : ClearDatabaseSchemaIfModelChanges<ZUMOAPPNAMEContext>
    {
        protected override void Seed(ZUMOAPPNAMEContext context)
        {
            List<TodoItem> todoItems = new List<TodoItem>
            {
                new TodoItem { Id = Guid.NewGuid().ToString(), Text = "First item", Complete = false },
                new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Second item", Complete = false },
            };

            foreach (TodoItem todoItem in todoItems)
            {
                context.Set<TodoItem>().Add(todoItem);
            }

            base.Seed(context);
        }
    }
}

Add missing using directive in quickstart


// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using EndlessClient.ControlSets;
using EndlessClient.HUD.Controls;
using EOLib.Domain.Notifiers;

namespace EndlessClient.Rendering.NPC
{
    public class NPCAnimationActions : INPCAnimationNotifier
    {
        private readonly IHudControlProvider _hudControlProvider;
        private readonly INPCStateCache _npcStateCache;
        private readonly INPCRendererRepository _npcRendererRepository;

        public NPCAnimationActions(IHudControlProvider hudControlProvider,
                                   INPCStateCache npcStateCache,
                                   INPCRendererRepository npcRendererRepository)
        {
            _hudControlProvider = hudControlProvider;
            _npcStateCache = npcStateCache;
            _npcRendererRepository = npcRendererRepository;
        }

        public void StartNPCWalkAnimation(int npcIndex)
        {
            if (!_hudControlProvider.IsInGame)
                return;

            var npcAnimator = _hudControlProvider.GetComponent<INPCAnimator>(HudControlIdentifier.NPCAnimator);
            npcAnimator.StartWalkAnimation(npcIndex);
        }

        public void RemoveNPCFromView(int npcIndex, bool showDeathAnimation)
        {
            _npcStateCache.RemoveStateByIndex(npcIndex);

            if (!showDeathAnimation)
            {
                _npcRendererRepository.NPCRenderers[npcIndex].Dispose();
                _npcRendererRepository.NPCRenderers.Remove(npcIndex);
            }
            else
            {
                _npcRendererRepository.NPCRenderers[npcIndex].StartDying();
            }
        }
    }
}

// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

using EndlessClient.ControlSets;
using EndlessClient.HUD.Controls;
using EOLib.Domain.Notifiers;

namespace EndlessClient.Rendering.NPC
{
    public class NPCAnimationActions : INPCAnimationNotifier
    {
        private readonly IHudControlProvider _hudControlProvider;
        private readonly INPCStateCache _npcStateCache;
        private readonly INPCRendererRepository _npcRendererRepository;

        public NPCAnimationActions(IHudControlProvider hudControlProvider,
                                   INPCStateCache npcStateCache,
                                   INPCRendererRepository npcRendererRepository)
        {
            _hudControlProvider = hudControlProvider;
            _npcStateCache = npcStateCache;
            _npcRendererRepository = npcRendererRepository;
        }

        public void StartNPCWalkAnimation(int npcIndex)
        {
            if (!_hudControlProvider.IsInGame)
                return;

            var npcAnimator = _hudControlProvider.GetComponent<INPCAnimator>(HudControlIdentifier.NPCAnimator);
            npcAnimator.StartWalkAnimation(npcIndex);
        }

        public void RemoveNPCFromView(int npcIndex, bool showDeathAnimation)
        {
            if (!_hudControlProvider.IsInGame)
                return;

            _npcStateCache.RemoveStateByIndex(npcIndex);

            if (!showDeathAnimation)
            {
                _npcRendererRepository.NPCRenderers[npcIndex].Dispose();
                _npcRendererRepository.NPCRenderers.Remove(npcIndex);
            }
            else
            {
                _npcRendererRepository.NPCRenderers[npcIndex].StartDying();
            }
        }
    }
}

Fix crash when logging in

Fix crash when logging in

Crashing due to remove NPCs from view when HUD has not been constructed yet


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

namespace DerConverter
{
    internal static class QueueExtensions
    {
        public static IEnumerable<T> Dequeue<T>(this Queue<T> queue, int count)
        {
            for (int i = 0; i < count; i++) yield return queue.Dequeue();
        }

        public static IEnumerable<T> DequeueAll<T>(this Queue<T> queue)
        {
            while (queue.Any()) yield return queue.Dequeue();
        }
    }
}

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

namespace DerConverter
{
    internal static class QueueExtensions
    {
        public static IEnumerable<T> Dequeue<T>(this Queue<T> queue, long count)
        {
            for (long i = 0; i < count; i++) yield return queue.Dequeue();
        }

        public static IEnumerable<T> DequeueAll<T>(this Queue<T> queue)
        {
            while (queue.Any()) yield return queue.Dequeue();
        }
    }
}

Change int count to long count in Dequeue extension method


using NUnit.Framework;
using ZendeskApi_v2;

namespace Tests
{
    [TestFixture]
    public class LocaleTests
    {
        private ZendeskApi api = new ZendeskApi(Settings.Site, Settings.Email, Settings.Password);

        [Test]
        public void CanGetLocales()
        {
            var all = api.Locales.GetAllLocales();
            Assert.Greater(all.Count, 0);

            var agent = api.Locales.GetLocalesForAgents();
            Assert.Greater(agent.Count, 0);

            var specific = api.Locales.GetLocaleById(all.Locales[0].Id);
            Assert.AreEqual(specific.Locale.Id, all.Locales[0].Id);

            var current = api.Locales.GetCurrentLocale();
            Assert.Greater(current.Locale.Id, 0);
        }
    }
}

using NUnit.Framework;
using ZendeskApi_v2;

namespace Tests
{
    [TestFixture]
    public class LocaleTests
    {
        private ZendeskApi api = new ZendeskApi(Settings.Site, Settings.Email, Settings.Password);

        [Test]
        public void CanGetLocales()
        {
            var all = api.Locales.GetAllLocales();
            Assert.Greater(all.Count, 0);

            var agent = api.Locales.GetLocalesForAgents();
            Assert.Greater(agent.Count, 0);

            var specific = api.Locales.GetLocaleById(all.Locales[0].Id);
            Assert.AreEqual(specific.Locale.Id, all.Locales[0].Id);
            Assert.IsNull(specific.Locale.Translations);

            var specificWithTranslation = api.Locales.GetLocaleById(all.Locales[0].Id, true);
            Assert.AreEqual(specificWithTranslation.Locale.Id, all.Locales[0].Id);
            Assert.IsNotNull(specificWithTranslation.Locale.Translations);

            var current = api.Locales.GetCurrentLocale();
            Assert.Greater(current.Locale.Id, 0);
            Assert.IsNull(current.Locale.Translations);

            var currentWithTranslation = api.Locales.GetCurrentLocale(true);
            Assert.Greater(currentWithTranslation.Locale.Id, 0);
            Assert.IsNotNull(currentWithTranslation.Locale.Translations);
        }
    }
}

Add test case for fetch translation metadata capability when getting locales.


namespace Nett
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Util;

    internal static class UserTypeMetaData
    {
        private static readonly Dictionary<Type, MetaDataInfo> MetaData = new Dictionary<Type, MetaDataInfo>();

        public static bool IsPropertyIgnored(Type ownerType, PropertyInfo pi)
        {
            if (ownerType == null) { throw new ArgumentNullException(nameof(ownerType)); }
            if (pi == null) { throw new ArgumentNullException(nameof(pi)); }

            EnsureMetaDataInitialized(ownerType);

            return MetaData[ownerType].IgnoredProperties.Contains(pi.Name);
        }

        private static void EnsureMetaDataInitialized(Type t)
            => Extensions.DictionaryExtensions.AddIfNeeded(MetaData, t, () => ProcessType(t));

        private static MetaDataInfo ProcessType(Type t)
        {
            var ignored = ProcessIgnoredProperties(t);

            return new MetaDataInfo(ignored);
        }

        private static IEnumerable<string> ProcessIgnoredProperties(Type t)
        {
            var attributes = ReflectionUtil.GetPropertiesWithAttribute<TomlIgnoreAttribute>(t);
            return attributes.Select(pi => pi.Name);
        }

        private sealed class MetaDataInfo
        {
            public MetaDataInfo(IEnumerable<string> ignoredProperties)
            {
                this.IgnoredProperties = new HashSet<string>(ignoredProperties);
            }

            public HashSet<string> IgnoredProperties { get; }
        }
    }
}

namespace Nett
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Util;

    internal static class UserTypeMetaData
    {
        private static readonly ConcurrentDictionary<Type, MetaDataInfo> MetaData = new ConcurrentDictionary<Type, MetaDataInfo>();

        public static bool IsPropertyIgnored(Type ownerType, PropertyInfo pi)
        {
            if (ownerType == null) { throw new ArgumentNullException(nameof(ownerType)); }
            if (pi == null) { throw new ArgumentNullException(nameof(pi)); }

            EnsureMetaDataInitialized(ownerType);

            return MetaData[ownerType].IgnoredProperties.Contains(pi.Name);
        }

        private static void EnsureMetaDataInitialized(Type t)
            => Extensions.DictionaryExtensions.AddIfNeeded(MetaData, t, () => ProcessType(t));

        private static MetaDataInfo ProcessType(Type t)
        {
            var ignored = ProcessIgnoredProperties(t);

            return new MetaDataInfo(ignored);
        }

        private static IEnumerable<string> ProcessIgnoredProperties(Type t)
        {
            var attributes = ReflectionUtil.GetPropertiesWithAttribute<TomlIgnoreAttribute>(t);
            return attributes.Select(pi => pi.Name);
        }

        private sealed class MetaDataInfo
        {
            public MetaDataInfo(IEnumerable<string> ignoredProperties)
            {
                this.IgnoredProperties = new HashSet<string>(ignoredProperties);
            }

            public HashSet<string> IgnoredProperties { get; }
        }
    }
}

Fix flaky unit test caused by concurrency issue


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

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

namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets
{
    // TODO: Come up with some options
    public class SocketTransportOptions
    {

    }
}

Add copyright header to TransportSocketOptions.cs.


// 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.Graphics.UserInterface;
using osu.Game.Tournament.IO;

namespace osu.Game.Tournament.Screens.Setup
{
    internal class TournamentSwitcher : ActionableInfo
    {
        private OsuDropdown<string> dropdown;
        private OsuButton folderButton;

        [Resolved]
        private TournamentGameBase game { get; set; }

        [BackgroundDependencyLoader]
        private void load(TournamentStorage storage)
        {
            string startupTournament = storage.CurrentTournament.Value;

            dropdown.Current = storage.CurrentTournament;
            dropdown.Items = storage.ListTournaments();
            dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);

            Action = () => game.GracefullyExit();
            folderButton.Action = storage.PresentExternally;

            ButtonText = "Close osu!";
        }

        protected override Drawable CreateComponent()
        {
            var drawable = base.CreateComponent();

            FlowContainer.Insert(-1, dropdown = new OsuDropdown<string>
            {
                Width = 510
            });

            FlowContainer.Insert(-2, folderButton = new TriangleButton
            {
                Text = "Open folder",
                Width = 100
            });

            return drawable;
        }
    }
}

// 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.Graphics.UserInterface;
using osu.Game.Tournament.IO;

namespace osu.Game.Tournament.Screens.Setup
{
    internal class TournamentSwitcher : ActionableInfo
    {
        private OsuDropdown<string> dropdown;
        private OsuButton folderButton;

        [Resolved]
        private TournamentGameBase game { get; set; }

        [BackgroundDependencyLoader]
        private void load(TournamentStorage storage)
        {
            string startupTournament = storage.CurrentTournament.Value;

            dropdown.Current = storage.CurrentTournament;
            dropdown.Items = storage.ListTournaments();
            dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);

            Action = () => game.GracefullyExit();
            folderButton.Action = storage.PresentExternally;

            ButtonText = "Close osu!";
        }

        protected override Drawable CreateComponent()
        {
            var drawable = base.CreateComponent();

            FlowContainer.Insert(-1, folderButton = new TriangleButton
            {
                Text = "Open folder",
                Width = 100
            });

            FlowContainer.Insert(-2, dropdown = new OsuDropdown<string>
            {
                Width = 510
            });

            return drawable;
        }
    }
}

Change button location to the right side of dropdown


using System;
using System.Collections.Generic;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using Xunit;

namespace CSharpViaTest.Collections._20_YieldPractices
{
    [Medium]
    public class TakeUntilCatchingAnException
    {
        readonly int indexThatWillThrow = new Random().Next(2, 10);

        IEnumerable<int> GetSequenceOfData()
        {
            for (int i = 0;; ++i)
            {
                if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); }
                yield return i;
            }
        }

        #region Please modifies the code to pass the test

        static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence)
        {
            throw new NotImplementedException();
        }

        #endregion

        [Fact]
        public void should_get_sequence_until_an_exception_is_thrown()
        {
            IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData());
            Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using Xunit;

namespace CSharpViaTest.Collections._20_YieldPractices
{
    [Medium]
    public class TakeUntilCatchingAnException
    {
        readonly int indexThatWillThrow = new Random().Next(2, 10);

        IEnumerable<int> GetSequenceOfData()
        {
            for (int i = 0;; ++i)
            {
                if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); }
                yield return i;
            }
        }

        #region Please modifies the code to pass the test

        static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence)
        {
            throw new NotImplementedException();
        }

        #endregion

        [Fact]
        public void should_get_sequence_until_an_exception_is_thrown()
        {
            IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData());
            Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence);
        }

        [Fact]
        public void should_get_sequence_given_normal_collection()
        {
            var sequence = new[] { 1, 2, 3 };
            IEnumerable<int> result = TakeUntilError(sequence);
            Assert.Equal(sequence, result);
        }
    }
}

[liuxia] Add test to make sure normal collection works.


Coming soon

This service isn't available yet.

@section breadcrumb {

Back to homepage

}

Under development

This service is currently being developed and you don't yet have access.

@section breadcrumb {

Back to homepage

}

Update content for feature not enabled

Update content for feature not enabled


using System;
using System.Linq;
using NUnit.Framework;
using Shouldly;

namespace Nimbus.UnitTests.MulticastRequestResponseTests
{
    [TestFixture]
    internal class WhenTakingTwoResponses : GivenAWrapperWithTwoResponses
    {
        private readonly TimeSpan _timeout = TimeSpan.FromSeconds(1);

        private string[] _result;

        protected override void When()
        {
            _result = Subject.ReturnResponsesOpportunistically(_timeout).Take(2).ToArray();
        }

        [Test]
        public void TheElapsedTimeShouldBeLessThanTheTimeout()
        {
            ElapsedTime.ShouldBeLessThan(_timeout);
        }

        [Test]
        public void ThereShouldBeTwoResults()
        {
            _result.Count().ShouldBe(2);
        }
    }
}

using System;
using System.Linq;
using NUnit.Framework;
using Shouldly;

namespace Nimbus.UnitTests.MulticastRequestResponseTests
{
    [TestFixture]
    internal class WhenTakingTwoResponses : GivenAWrapperWithTwoResponses
    {
        private readonly TimeSpan _timeout = TimeSpan.FromSeconds(1.5);

        private string[] _result;

        protected override void When()
        {
            _result = Subject.ReturnResponsesOpportunistically(_timeout).Take(2).ToArray();
        }

        [Test]
        public void TheElapsedTimeShouldBeLessThanTheTimeout()
        {
            ElapsedTime.ShouldBeLessThan(_timeout);
        }

        [Test]
        public void ThereShouldBeTwoResults()
        {
            _result.Count().ShouldBe(2);
        }
    }
}

Increase timeout for running in container


using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace WootzJs.Mvc
{
    public class ControllerActionInvoker : IActionInvoker
    {
        public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action)
        {
            var parameters = action.GetParameters();
            var args = new object[parameters.Length];

            // If async
            if (action.ReturnType == typeof(Task<ActionResult>))
            {
                return (Task<ActionResult>)action.Invoke(context.Controller, args);
            }
            // If synchronous
            else
            {
                var actionResult = (ActionResult)action.Invoke(context.Controller, args);
                return Task.FromResult(actionResult);
            }
        }
    }
}

using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace WootzJs.Mvc
{
    public class ControllerActionInvoker : IActionInvoker
    {
        public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action)
        {
            var parameters = action.GetParameters();
            var args = new object[parameters.Length];
            for (var i = 0; i < parameters.Length; i++)
            {
                var value = context.Controller.RouteData[parameters[i].Name];
                args[i] = value;
            }

            // If async
            if (action.ReturnType == typeof(Task<ActionResult>))
            {
                return (Task<ActionResult>)action.Invoke(context.Controller, args);
            }
            // If synchronous
            else
            {
                var actionResult = (ActionResult)action.Invoke(context.Controller, args);
                return Task.FromResult(actionResult);
            }
        }
    }
}

Fix bug not properly propagating route arguments


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

namespace osu.Framework.Graphics
{
    public class ProxyDrawable : Drawable
    {
        public ProxyDrawable(Drawable original)
        {
            Original = original;
        }

        internal sealed override Drawable Original { get; }

        // We do not want to receive updates. That is the business
        // of the original drawable.
        public override bool IsPresent => false;
    }
}

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

namespace osu.Framework.Graphics
{
    public class ProxyDrawable : Drawable
    {
        public ProxyDrawable(Drawable original)
        {
            Original = original;
        }

        internal sealed override Drawable Original { get; }

        public override bool IsAlive => base.IsAlive && Original.IsAlive;

        // We do not want to receive updates. That is the business
        // of the original drawable.
        public override bool IsPresent => false;
    }
}

Fix proxied drawables never expiring.

Fix proxied drawables never expiring.


using Lykke.EmailSenderProducer.Interfaces;

namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
    public class BaseSettings
    {
        public AzureSettings Azure { get; set; }
        public AuthenticationSettings Authentication { get; set; }
        public NotificationsSettings Notifications { get; set; }

        public string EmailServiceBusSettingsUrl { get; set; }
    }

    public class AuthenticationSettings
    {
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string PostLogoutRedirectUri { get; set; }
        public string Authority { get; set; }
    }

    public class AzureSettings
    {
        public string StorageConnString { get; set; }
    }

    public class NotificationsSettings
    {
        public string EmailsQueueConnString { get; set; }
        public string SlackQueueConnString { get; set; }
    }

    public class EmailServiceBusSettings
    {
        public EmailServiceBus EmailServiceBus;
    }

    public class EmailServiceBus : IServiceBusEmailSettings
    {
        public string Key { get; set; }
        public string QueueName { get; set; }
        public string NamespaceUrl { get; set; }
        public string PolicyName { get; set; }
    }
}

using System.Collections.Generic;
using Lykke.EmailSenderProducer.Interfaces;

namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
    public class BaseSettings
    {
        public AzureSettings Azure { get; set; }
        public AuthenticationSettings Authentication { get; set; }
        public NotificationsSettings Notifications { get; set; }

        public string EmailServiceBusSettingsUrl { get; set; }

        public List<string> ProjectCreateNotificationReceiver { get; set; }
    }

    public class AuthenticationSettings
    {
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string PostLogoutRedirectUri { get; set; }
        public string Authority { get; set; }
    }

    public class AzureSettings
    {
        public string StorageConnString { get; set; }
    }

    public class NotificationsSettings
    {
        public string EmailsQueueConnString { get; set; }
        public string SlackQueueConnString { get; set; }
    }

    public class EmailServiceBusSettings
    {
        public EmailServiceBus EmailServiceBus;
    }

    public class EmailServiceBus : IServiceBusEmailSettings
    {
        public string Key { get; set; }
        public string QueueName { get; set; }
        public string NamespaceUrl { get; set; }
        public string PolicyName { get; set; }
    }
}

Add a list of notification receivers for project create.


using Mapsui.Geometries;
using Mapsui.GeometryLayer;
using Mapsui.Layers;
using Mapsui.Providers;
using NUnit.Framework;

namespace Mapsui.Tests.Layers
{
    [TestFixture]
    public class WritableLayerTests
    {
        [Test]
        public void DoNotCrashOnNullOrEmptyGeometries()
        {
            // arrange
            var writableLayer = new WritableLayer();
            writableLayer.Add(new GeometryFeature());
            writableLayer.Add(new GeometryFeature { Geometry = new Point() });
            writableLayer.Add(new GeometryFeature { Geometry = new LineString() });
            writableLayer.Add(new GeometryFeature { Geometry = new Polygon() });

            // act
            var extent = writableLayer.Extent;

            // assert
            Assert.IsNull(extent);
        }
    }
}

using Mapsui.Geometries;
using Mapsui.GeometryLayer;
using Mapsui.Layers;
using NUnit.Framework;

namespace Mapsui.Tests.Layers
{
    [TestFixture]
    public class WritableLayerTests
    {
        [Test]
        public void DoNotCrashOnNullOrEmptyGeometries()
        {
            // arrange
            var writableLayer = new WritableLayer();
            writableLayer.Add(new GeometryFeature());
            writableLayer.Add(new GeometryFeature(new Point()));
            writableLayer.Add(new GeometryFeature(new LineString()));
            writableLayer.Add(new GeometryFeature(new Polygon()));

            // act
            var extent = writableLayer.Extent;

            // assert
            Assert.IsNull(extent);
        }
    }
}

Add geometry in GeometryFeature constructor


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

namespace Mios.Swiftype {
	public class QuerySpecification {
		public string Q { get; set; }
		public int Page { get; set; }
		public int? PerPage { get; set; }
		public IDictionary<string, FilterCollection> Filters { get; set; }
		public IDictionary<string, IEnumerable<string>> SearchFields { get; set; }
		public IDictionary<string, IEnumerable<string>> FetchFields { get; set; }
		public QuerySpecification() {
			Page = 1;
			Filters = new Dictionary<string, FilterCollection>();
			SearchFields = new Dictionary<string, IEnumerable<string>>();
			FetchFields = new Dictionary<string, IEnumerable<string>>();
		}
	}
}

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

namespace Mios.Swiftype {
	public class QuerySpecification {
		public string Q { get; set; }
		public int Page { get; set; }
		public int? PerPage { get; set; }
		public string[] DocumentTypes { get; set; }
		public IDictionary<string, FilterCollection> Filters { get; set; }
		public IDictionary<string, IEnumerable<string>> SearchFields { get; set; }
		public IDictionary<string, IEnumerable<string>> FetchFields { get; set; }
		public QuerySpecification() {
			Page = 1;
			Filters = new Dictionary<string, FilterCollection>();
			SearchFields = new Dictionary<string, IEnumerable<string>>();
			FetchFields = new Dictionary<string, IEnumerable<string>>();
		}
	}
}

Allow specifying document types to search.


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

namespace Mycroft.Cmd.App
{
    class AppCommand : Command
    {
        /// <summary>
        /// Parses JSON into App command objects
        /// </summary>
        /// <param name="messageType">The message type that determines the command to create</param>
        /// <param name="json">The JSON body of the message</param>
        /// <returns>Returns a command object for the parsed message</returns>
        public static Command Parse(String type, String json, AppInstance instance)
        {
            switch (type)
            {
                case "APP_UP":
                    return new Up(json, instance);
                case "APP_DOWN":
                    return new DependencyChange(instance);
                case "APP_DESTROY":
                    return new Destroy(json, instance);
                case "APP_MANIFEST":
                    return Manifest.Parse(json, instance);
                default:
                    //data is incorrect - can't do anything with it
                    // TODO notify that is wrong
                    break;
            }
            return null ;
        }
    }
}

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

namespace Mycroft.Cmd.App
{
    class AppCommand : Command
    {
        /// <summary>
        /// Parses JSON into App command objects
        /// </summary>
        /// <param name="messageType">The message type that determines the command to create</param>
        /// <param name="json">The JSON body of the message</param>
        /// <returns>Returns a command object for the parsed message</returns>
        public static Command Parse(String type, String json, AppInstance instance)
        {
            switch (type)
            {
                case "APP_UP":
                case "APP_DOWN":
                    return new DependencyChange(instance);
                case "APP_DESTROY":
                    return new Destroy(json, instance);
                case "APP_MANIFEST":
                    return Manifest.Parse(json, instance);
                default:
                    //data is incorrect - can't do anything with it
                    // TODO notify that is wrong
                    break;
            }
            return null ;
        }
    }
}

Fix compile error from merging Up and Down


using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace WebSocketManager
{
    public class WebSocketManagerMiddleware
    {
        private readonly RequestDelegate _next;
        private WebSocketManager _webSocketManager { get; set; }
        private WebSocketMessageHandler _webSocketMessageHandler { get; set; }

        public WebSocketManagerMiddleware(RequestDelegate next,
                                          WebSocketManager webSocketManager,
                                          WebSocketMessageHandler webSocketMessageHandler)
        {
            _next = next;
            _webSocketManager = webSocketManager;
            _webSocketMessageHandler = webSocketMessageHandler;
        }

        public async Task Invoke(HttpContext context)
        {
            if(!context.WebSockets.IsWebSocketRequest)
                return;

            var socket = await context.WebSockets.AcceptWebSocketAsync();
            _webSocketManager.AddSocket(socket);

            await _webSocketMessageHandler.SendMessageAsync(socketId: "",
                                                            message: _webSocketManager.GetId(socket));

            await _next.Invoke(context);
        }
    }
}

using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace WebSocketManager
{
    public class WebSocketManagerMiddleware
    {
        private readonly RequestDelegate _next;
        private WebSocketManager _webSocketManager { get; set; }
        private WebSocketMessageHandler _webSocketMessageHandler { get; set; }

        public WebSocketManagerMiddleware(RequestDelegate next,
                                          WebSocketManager webSocketManager,
                                          WebSocketMessageHandler webSocketMessageHandler)
        {
            _next = next;
            _webSocketManager = webSocketManager;
            _webSocketMessageHandler = webSocketMessageHandler;
        }

        public async Task Invoke(HttpContext context)
        {
            if(!context.WebSockets.IsWebSocketRequest)
                return;

            var socket = await context.WebSockets.AcceptWebSocketAsync();
            _webSocketManager.AddSocket(socket);

            var socketId = _webSocketManager.GetId(socket);
            await _webSocketMessageHandler.SendMessageAsync(socketId: socketId,
                                                            message: $"SocketId: {_webSocketManager.GetId(socket)}");

            await _next.Invoke(context);
        }
    }
}

Send message to specific connection

Send message to specific connection


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

namespace osu.Framework.Graphics.Animations
{
    /// <summary>
    /// An animation / playback sequence.
    /// </summary>
    public interface IAnimation
    {
        /// <summary>
        /// The duration of the animation. Can only be queried after the decoder has started decoding has loaded. This value may be an estimate by FFmpeg, depending on the video loaded.
        /// </summary>
        public double Duration { get; }

        /// <summary>
        /// True if the animation has finished playing, false otherwise.
        /// </summary>
        public bool FinishedPlaying => !Loop && PlaybackPosition > Duration;

        /// <summary>
        /// True if the animation is playing, false otherwise. Starts true.
        /// </summary>
        bool IsPlaying { get; set; }

        /// <summary>
        /// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing.
        /// </summary>
        bool Loop { get; set; }

        /// <summary>
        /// Seek the animation to a specific time value.
        /// </summary>
        /// <param name="time">The time value to seek to.</param>
        void Seek(double time);

        /// <summary>
        /// The current position of playback.
        /// </summary>
        public double PlaybackPosition { get; set; }
    }
}

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

namespace osu.Framework.Graphics.Animations
{
    /// <summary>
    /// An animation / playback sequence.
    /// </summary>
    public interface IAnimation
    {
        /// <summary>
        /// The duration of the animation.
        /// </summary>
        public double Duration { get; }

        /// <summary>
        /// True if the animation has finished playing, false otherwise.
        /// </summary>
        public bool FinishedPlaying => !Loop && PlaybackPosition > Duration;

        /// <summary>
        /// True if the animation is playing, false otherwise. Starts true.
        /// </summary>
        bool IsPlaying { get; set; }

        /// <summary>
        /// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing.
        /// </summary>
        bool Loop { get; set; }

        /// <summary>
        /// Seek the animation to a specific time value.
        /// </summary>
        /// <param name="time">The time value to seek to.</param>
        void Seek(double time);

        /// <summary>
        /// The current position of playback.
        /// </summary>
        public double PlaybackPosition { get; set; }
    }
}

Remove comment about ffmpeg from interface


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

namespace osu.Game.Scoring
{
    public enum ScoreRank
    {
        [Description(@"F")]
        F,

        [Description(@"F")]
        D,

        [Description(@"C")]
        C,

        [Description(@"B")]
        B,

        [Description(@"A")]
        A,

        [Description(@"S")]
        S,

        [Description(@"SPlus")]
        SH,

        [Description(@"SS")]
        X,

        [Description(@"SSPlus")]
        XH,
    }
}

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

namespace osu.Game.Scoring
{
    public enum ScoreRank
    {
        [Description(@"F")]
        F,

        [Description(@"F")]
        D,

        [Description(@"C")]
        C,

        [Description(@"B")]
        B,

        [Description(@"A")]
        A,

        [Description(@"S")]
        S,

        [Description(@"S+")]
        SH,

        [Description(@"SS")]
        X,

        [Description(@"SS+")]
        XH,
    }
}

Change + rank strings to be cleaner for the end-user


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

namespace GTPWrapperTest {
    public class Program {
        static void Main(string[] args) {
            Engine engine = new Engine();
            engine.NewCommand += engine_NewCommand;
            engine.ResponsePushed += engine_ResponsePushed;
            engine.ConnectionClosed += engine_ConnectionClosed;

            while (true) {
                string input = Console.ReadLine();
                engine.ParseString(input);
            }
        }

        static void engine_ConnectionClosed(object sender, EventArgs e) {
            Environment.Exit(0);
        }

        static void engine_NewCommand(object sender, CommandEventArgs e) {
            Engine engine = (Engine)sender;
            string response = e.Command.Name;

            if (e.Command.Name == "showboard") {
                response = new Board(19).ToString();
            }

            engine.PushResponse(new Response(e.Command, response, e.Command.Name == "error"));
        }

        static void engine_ResponsePushed(object sender, ResponseEventArgs e) {
            Console.Write(e.Response.ToString() + "\n\n");
        }
    }
}

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

namespace GTPWrapperTest {
    public class Program {
        static void Main(string[] args) {
            Engine engine = new Engine();
            engine.NewCommand += engine_NewCommand;
            engine.ResponsePushed += engine_ResponsePushed;
            engine.ConnectionClosed += engine_ConnectionClosed;

            engine.SupportedCommands.AddRange(new string[] { "showboard", "error" });

            while (true) {
                string input = Console.ReadLine();
                engine.ParseString(input);
            }
        }

        static void engine_ConnectionClosed(object sender, EventArgs e) {
            Environment.Exit(0);
        }

        static void engine_NewCommand(object sender, CommandEventArgs e) {
            Engine engine = (Engine)sender;
            string response = e.Command.Name;

            if (e.Command.Name == "showboard") {
                response = new Board(13).ToString();
            }

            engine.PushResponse(new Response(e.Command, response, e.Command.Name == "error"));
        }

        static void engine_ResponsePushed(object sender, ResponseEventArgs e) {
            Console.Write(e.Response.ToString() + "\n\n");
        }
    }
}

Add more supported commands to test

Add more supported commands to test


// 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.Threading;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Types;

namespace osu.Game.Rulesets.Catch.Objects
{
    public class BananaShower : CatchHitObject, IHasEndTime
    {
        public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana;

        public override bool LastInCombo => true;

        public override Judgement CreateJudgement() => new IgnoreJudgement();

        protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
        {
            base.CreateNestedHitObjects(cancellationToken);
            createBananas();
        }

        private void createBananas()
        {
            double spacing = Duration;
            while (spacing > 100)
                spacing /= 2;

            if (spacing <= 0)
                return;

            for (double i = StartTime; i <= EndTime; i += spacing)
            {
                AddNested(new Banana
                {
                    Samples = Samples,
                    StartTime = i
                });
            }
        }

        public double EndTime
        {
            get => StartTime + Duration;
            set => Duration = value - StartTime;
        }

        public double Duration { get; set; }
    }
}

// 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.Threading;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Types;

namespace osu.Game.Rulesets.Catch.Objects
{
    public class BananaShower : CatchHitObject, IHasEndTime
    {
        public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana;

        public override bool LastInCombo => true;

        public override Judgement CreateJudgement() => new IgnoreJudgement();

        protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
        {
            base.CreateNestedHitObjects(cancellationToken);
            createBananas(cancellationToken);
        }

        private void createBananas(CancellationToken cancellationToken)
        {
            double spacing = Duration;
            while (spacing > 100)
                spacing /= 2;

            if (spacing <= 0)
                return;

            for (double i = StartTime; i <= EndTime; i += spacing)
            {
                cancellationToken.ThrowIfCancellationRequested();

                AddNested(new Banana
                {
                    Samples = Samples,
                    StartTime = i
                });
            }
        }

        public double EndTime
        {
            get => StartTime + Duration;
            set => Duration = value - StartTime;
        }

        public double Duration { get; set; }
    }
}

Fix banana showers not using cancellation token


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

[assembly: AssemblyTitle("ScriptCs.Octokit")]
[assembly: AssemblyDescription("Octokit Script Pack for ScriptCs.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Henrik Andersson")]
[assembly: AssemblyProduct("ScriptCs.Octokit")]
[assembly: AssemblyCopyright("Copyright © Henrik Andersson")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("69341200-0230-4734-9F20-CE145B17043E")]

[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.14")]

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

[assembly: AssemblyTitle("ScriptCs.Octokit")]
[assembly: AssemblyDescription("Octokit Script Pack for ScriptCs.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Henrik Andersson")]
[assembly: AssemblyProduct("ScriptCs.Octokit")]
[assembly: AssemblyCopyright("Copyright © Henrik Andersson")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("69341200-0230-4734-9F20-CE145B17043E")]

[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.0-build14")]

Move to SemVer for packaging

Move to SemVer for packaging


using System.Collections;
using System.Reflection;
using Assets.Scripts.Props;

/// <summary>Commands for the alarm clock.</summary>
public static class AlarmClockCommands
{

	[Command(@"snooze")]
	public static IEnumerator Snooze(AlarmClock clock, string user, bool isWhisper)
	{
		var onField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance);
		if (TwitchPlaySettings.data.AllowSnoozeOnly && !TwitchPlaySettings.data.AnarchyMode && !(bool) onField.GetValue(clock))
			yield break;

		yield return null;
		clock.SnoozeButton.GetComponent<Selectable>().Trigger();
	}
}

using System.Collections;
using System.Reflection;
using Assets.Scripts.Props;

/// <summary>Commands for the alarm clock.</summary>
public static class AlarmClockCommands
{
	[Command("snooze")]
	public static IEnumerator Snooze(TwitchHoldable holdable, string user, bool isWhisper) =>
		holdable.RespondToCommand(user, "", isWhisper, Snooze(holdable.Holdable.GetComponent<AlarmClock>(), user, isWhisper));

	public static IEnumerator Snooze(AlarmClock clock, string user, bool isWhisper)
	{
		var onField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance);
		if(onField == null) yield break;

		if (TwitchPlaySettings.data.AllowSnoozeOnly && !TwitchPlaySettings.data.AnarchyMode && !(bool) onField.GetValue(clock))
			yield break;

		yield return null;
		clock.SnoozeButton.GetComponent<Selectable>().Trigger();
	}
}

Fix Alarm clock snooze command

Fix Alarm clock snooze command


namespace SCPI.Extensions
{
    public static class ValueTypeExtensions
    {
        /// <summary>
        /// Checks that the value is within specified range
        /// </summary>
        /// <param name="value">Value to check</param>
        /// <param name="minValue">The inclusive lower bound</param>
        /// <param name="maxValue">The inclusive upper bound</param>
        /// <returns>True if the value is within range otherwise false</returns>
        public static bool IsWithin(this int value, int minValue, int maxValue)
        {
            var ret = false;

            if (value >= minValue && value <= maxValue)
            {
                ret = true;
            }

            return ret;
        }
    }
}

using System.Globalization;

namespace SCPI.Extensions
{
    public static class ValueTypeExtensions
    {
        /// <summary>
        /// Checks that the value is within specified range
        /// </summary>
        /// <param name="value">Value to check</param>
        /// <param name="minValue">The inclusive lower bound</param>
        /// <param name="maxValue">The inclusive upper bound</param>
        /// <returns>True if the value is within range otherwise false</returns>
        public static bool IsWithin(this int value, int minValue, int maxValue)
        {
            var ret = false;

            if (value >= minValue && value <= maxValue)
            {
                ret = true;
            }

            return ret;
        }

        /// <summary>
        /// Converts the string representation of a number to float
        /// </summary>
        /// <param name="value">A string representing a number to convert</param>
        /// <param name="result">When this method returns, contains the single-precision floating-point
        /// number equivalent to the numeric value or symbol contained in value, if the conversion succeeded</param>
        /// <returns>True if value was converted successfully; otherwise, false</returns>
        public static bool ScientificNotationStringToFloat(this string value, out float result)
        {
            if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out result))
            {
                return true;
            }

            return false;
        }
    }
}

Add method to convert scientific notation string to float


namespace HOLMS.Platform.Support.ReservationTags {
    class MigratedReservationTag : ReservationTagBase {
        protected override string[] GetDescriptorPartsAfterCategory() =>
            new string[] { };

        protected override string GetCategoryDescriptor() => MigratedBookingCategory;

        public override bool IsPermanent => true;
    }
}

namespace HOLMS.Platform.Support.ReservationTags {
    public class MigratedReservationTag : ReservationTagBase {
        protected override string[] GetDescriptorPartsAfterCategory() =>
            new string[] { };

        protected override string GetCategoryDescriptor() => MigratedBookingCategory;

        public override bool IsPermanent => true;
    }
}

Add public designator to tag

Add public designator to tag


#if NET471

namespace Fixie.Tests.Execution
{
    using System;
    using System.Configuration;
    using System.Linq;
    using System.Runtime.Versioning;
    using Assertions;

    public class ExecutionEnvironmentTests
    {
        public void ShouldEnableAccessToTestAssemblyConfigFile()
        {
            ConfigurationManager.AppSettings["CanAccessAppConfig"].ShouldEqual("true");
        }

        public void ShouldTargetFrameworkCompatibleWithQuirksModeStatus()
        {
            // Test frameworks which support both .NET 4.0 and 4.5 can encounter an issue
            // with their AppDomain setup in which test runner behavior can be negatively
            // impacted depending on whether code targets 4.0 or 4.5.  A test could fail,
            // for instance, even when the tested code is actually right.

            // Because Fixie targets a minimum of 4.5, it doesn't actually fall prey to
            // that issue. Fixie never needs to run in the presence of quirks mode.
            // However, we include this sanity check to avoid regressions.

            // See https://youtrack.jetbrains.com/issue/RSRP-412080

            var quirksAreEnabled = Uri.EscapeDataString("'") == "'";

            quirksAreEnabled.ShouldBeFalse();

            var targetFramework =
                typeof(ExecutionEnvironmentTests)
                    .Assembly
                    .GetCustomAttributes(typeof(TargetFrameworkAttribute), true)
                    .Cast<TargetFrameworkAttribute>()
                    .Single()
                    .FrameworkName;

            quirksAreEnabled.ShouldEqual(!targetFramework.Contains("4.5"));
        }
    }
}
#endif

#if NET471
namespace Fixie.Tests.Execution
{
    using System;
    using System.Configuration;
    using System.Linq;
    using System.Runtime.Versioning;
    using Assertions;

    public class ExecutionEnvironmentTests
    {
        public void ShouldEnableAccessToTestAssemblyConfigFile()
        {
            ConfigurationManager.AppSettings["CanAccessAppConfig"].ShouldEqual("true");
        }
    }
}
#endif

Remove deprecated "quirks mode" test coverage: although this concept has been an issue for test frameworks, it was never really an issue for Fixie as Fixie has always targeted net45 or higher, and the problem involved only applied to end users whose projects really targeted 4.0. Also, the test was meant to catch regressions in AppDomain setup, and Fixie no longer has any AppDomain concerns.


namespace SFA.DAS.EmployerUsers.Web.Models
{
    public class LoginViewModel
    {
        public string EmailAddress { get; set; }
        public string Password { get; set; }
        public string OriginatingAddress { get; set; }

        public bool InvalidLoginAttempt { get; set; }
        public string ReturnUrl { get; set; }
    }
}

namespace SFA.DAS.EmployerUsers.Web.Models
{
    public class LoginViewModel : ViewModelBase
    {
        public string EmailAddress { get; set; }
        public string Password { get; set; }
        public string OriginatingAddress { get; set; }

        public string ReturnUrl { get; set; }
        public string PasswordError => GetErrorMessage(nameof(Password));
        public string EmailAddressError => GetErrorMessage(nameof(EmailAddress));
    }
}

Add error messages to model

Add error messages to model

Implemented the ViewModelBase and added the Error Messags for the email
address and password.


using System;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using NinjaNye.SearchExtensions.Levenshtein;

namespace NinjaNye.SearchExtensions.Tests.LevenshteinTests
{
    [TestFixture]
    public class LevenshteinDistancePerformanceTests : BuildStringTestsBase
    {
        #if DEBUG
        // Performance test will always fail in debug mode
        [Ignore]
    	#endif
        [Test]
        public void ToLevenshteinDistance_CompareOneMillionStringsOfLength7_ExecutesInLessThanOneSecond()
        {
            //Arrange
            var words = this.BuildWords(1000000, 7, 7);
            var randomWord = this.BuildRandomWord(7,7);
            var stopwatch = new Stopwatch();
            //Act
            stopwatch.Start();
            var result = words.Select(w => LevenshteinProcessor.LevenshteinDistance(w, randomWord)).ToList();
            stopwatch.Stop();

            //Assert
            Console.WriteLine("Elapsed Time: {0}", stopwatch.Elapsed);
            Console.WriteLine("Total matching words: {0}", result.Count(i => i == 0));
            Console.WriteLine("Total words with distance of 1: {0}", result.Count(i => i == 1));
            Console.WriteLine("Total words with distance of 2: {0}", result.Count(i => i == 2));
            Console.WriteLine("Total words with distance of 3: {0}", result.Count(i => i == 3));
            Assert.IsTrue(stopwatch.Elapsed.TotalMilliseconds <= 1000);
        }
    }
}

using System;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using NinjaNye.SearchExtensions.Levenshtein;

namespace NinjaNye.SearchExtensions.Tests.LevenshteinTests
{
#if DEBUG
    // Performance test will always fail in debug mode
    [Ignore]
#endif
    [TestFixture]
    public class LevenshteinDistancePerformanceTests : BuildStringTestsBase
    {
        [TestCase(6)]
        [TestCase(7)]
        public void ToLevenshteinDistance_CompareOneMillionStringsOfLengthX_ExecutesInLessThanOneSecond(int length)
        {
            //Arrange
            var words = this.BuildWords(1000000, length, length);
            var randomWord = this.BuildRandomWord(length,length);
            var stopwatch = new Stopwatch();
            //Act
            stopwatch.Start();
            var result = words.Select(w => LevenshteinProcessor.LevenshteinDistance(w, randomWord)).ToList();
            stopwatch.Stop();

            //Assert
            Console.WriteLine("Elapsed Time: {0}", stopwatch.Elapsed);
            Console.WriteLine("Total matching words: {0}", result.Count(i => i == 0));
            Console.WriteLine("Total words with distance of 1: {0}", result.Count(i => i == 1));
            Console.WriteLine("Total words with distance of 2: {0}", result.Count(i => i == 2));
            Console.WriteLine("Total words with distance of 3: {0}", result.Count(i => i == 3));
            Assert.IsTrue(stopwatch.Elapsed.TotalMilliseconds <= 1000);
        }
    }
}

Update performance tests to use TestData attribute


using System;
using System.Reflection;

[assembly: AssemblyTitle("DoTheMath.Linear")]
[assembly: AssemblyDescription("A bunch of stuff for Linear Algebra.")]
[assembly: CLSCompliant(true)]

Mark assembly as CLS compliant

Mark assembly as CLS compliant

closes #3


using System;
using System.Threading;
using Leak.Client.Tracker;
using Leak.Common;
using Pargos;

namespace Leak.Announce
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            Options options = Argument.Parse<Options>(args);

            if (options.IsValid())
            {
                Uri tracker = new Uri(options.Tracker);
                TrackerLogger logger = new Logger();

                using (TrackerClient client = new TrackerClient(tracker, logger))
                {
                    foreach (string data in options.Hash)
                    {
                        FileHash hash = FileHash.Parse(data);

                        try
                        {
                            client.AnnounceAsync(hash);
                        }
                        catch (AggregateException ex)
                        {
                            Console.Error.WriteLine($"{hash}:{ex.InnerExceptions[0].Message}");
                        }
                        catch (Exception ex)
                        {
                            Console.Error.WriteLine($"{hash}:{ex.Message}");
                        }
                    }

                    Thread.Sleep(50000);
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Leak.Client.Tracker;
using Leak.Common;
using Pargos;

namespace Leak.Announce
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            Options options = Argument.Parse<Options>(args);
            List<Task<TrackerAnnounce>> tasks = new List<Task<TrackerAnnounce>>();

            if (options.IsValid())
            {
                Uri tracker = new Uri(options.Tracker);
                TrackerLogger logger = GetLogger(options);

                using (TrackerClient client = new TrackerClient(tracker, logger))
                {
                    foreach (string data in options.Hash)
                    {
                        FileHash hash = FileHash.Parse(data);
                        tasks.Add(client.AnnounceAsync(hash));
                    }

                    foreach (Task<TrackerAnnounce> task in tasks)
                    {
                        task.Wait();
                        Handle(options, task);
                    }
                }
            }
        }

        private static TrackerLogger GetLogger(Options options)
        {
            if (options.Analyze == "true")
            {
                return new Logger();
            }

            return null;
        }

        private static void Handle(Options options, Task<TrackerAnnounce> task)
        {
            if (options.Analyze != "true")
            {
                Console.WriteLine(task.Result.Hash);
                Console.WriteLine();

                foreach (PeerAddress peer in task.Result.Peers)
                {
                    Console.WriteLine($"  {peer}");
                }

                Console.WriteLine();
            }
        }
    }
}

Use options to decide if analyze is enabled.


using System.ComponentModel;
using System.IO;

namespace Sakuno.IO
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class StreamExtensions
    {
        public static int FillBuffer(this Stream stream, byte[] buffer, int offset, int count)
        {
            var remaining = count;

            do
            {
                var length = stream.Read(buffer, offset, remaining);
                if (length == 0)
                    break;

                remaining -= length;
                offset += length;
            } while (remaining > 0);

            return count - remaining;
        }
    }
}

using System;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Sakuno.IO
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class StreamExtensions
    {
        public static int FillBuffer(this Stream stream, byte[] buffer, int offset, int count)
        {
            var remaining = count;

            do
            {
                var length = stream.Read(buffer, offset, remaining);
                if (length == 0)
                    break;

                remaining -= length;
                offset += length;
            } while (remaining > 0);

            return count - remaining;
        }

#if NETSTANDARD2_1
        public static async ValueTask<int> FillBuffer(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default)
        {
            var remaining = buffer.Length;
            var offset = 0;

            do
            {
                var length = await stream.ReadAsync(buffer, cancellationToken);
                if (length == 0)
                    break;

                remaining -= length;
                offset += length;
            } while (remaining > 0);

            return buffer.Length - remaining;
        }
#endif
    }
}

Add value task to FillBuffer()

Add value task to FillBuffer()


// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.Website
{
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;

    /// <summary>
    /// A class representing the startup logic for the application.
    /// </summary>
    public class Startup : StartupBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Startup"/> class.
        /// </summary>
        /// <param name="env">The <see cref="IHostingEnvironment"/> to use.</param>
        public Startup(IHostingEnvironment env)
            : base(env)
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

            bool isDevelopment = env.IsDevelopment();

            if (isDevelopment)
            {
                builder.AddUserSecrets("martincostello.com");
            }

            builder.AddApplicationInsightsSettings(developerMode: isDevelopment);

            Configuration = builder.Build();
        }
    }
}

// Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.Website
{
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;

    /// <summary>
    /// A class representing the startup logic for the application.
    /// </summary>
    public class Startup : StartupBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Startup"/> class.
        /// </summary>
        /// <param name="env">The <see cref="IHostingEnvironment"/> to use.</param>
        public Startup(IHostingEnvironment env)
            : base(env)
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

            bool isDevelopment = env.IsDevelopment();

            if (isDevelopment)
            {
                builder.AddUserSecrets<Startup>();
            }

            builder.AddApplicationInsightsSettings(developerMode: isDevelopment);

            Configuration = builder.Build();
        }
    }
}

Use type/attribute for user secrets

Use type/attribute for user secrets

Use type to configure user secrets instead of hard-coded string.


using System.IO;

namespace Microsoft.Diagnostics.Runtime
{
    /// <summary>
    /// Thrown when we fail to read memory from the target process.
    /// </summary>
    public class MemoryReadException : IOException
    {
        /// <summary>
        /// The address of memory that could not be read.
        /// </summary>
        public ulong Address { get; private set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="address">The address of memory that could not be read.</param>
        public MemoryReadException(ulong address)
            : base(string.Format("Could not read memory at {0:x}."))
        {
        }
    }
}

using System.IO;

namespace Microsoft.Diagnostics.Runtime
{
    /// <summary>
    /// Thrown when we fail to read memory from the target process.
    /// </summary>
    public class MemoryReadException : IOException
    {
        /// <summary>
        /// The address of memory that could not be read.
        /// </summary>
        public ulong Address { get; private set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="address">The address of memory that could not be read.</param>
        public MemoryReadException(ulong address)
            : base(string.Format("Could not read memory at {0:x}.", address))
        {
        }
    }
}

Fix missing string format parameter

Fix missing string format parameter


using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;

namespace DotNetRu.Azure
{
    [Route("diagnostics")]
    public class DiagnosticsController : ControllerBase
    {
        private readonly ILogger logger;

        public DiagnosticsController(
            ILogger<DiagnosticsController> logger)
        {
            this.logger = logger;
        }

        [HttpPost]
        [Route("ping")]
        public async Task<IActionResult> Ping()
        {
            try
            {
                logger.LogInformation("Ping is requested");

                return new OkObjectResult("Success");
            }
            catch (Exception e)
            {
                logger.LogCritical(e, "Unhandled error while ping");
                return new ObjectResult(e) {
                    StatusCode = StatusCodes.Status500InternalServerError
                };
            }
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using DotNetRu.AzureService;

namespace DotNetRu.Azure
{
    [Route("diagnostics")]
    public class DiagnosticsController : ControllerBase
    {
        private readonly ILogger logger;

        private readonly RealmSettings realmSettings;
        private readonly TweetSettings tweetSettings;
        private readonly PushSettings pushSettings;
        private readonly VkontakteSettings vkontakteSettings;

        public DiagnosticsController(
            ILogger<DiagnosticsController> logger,
            RealmSettings realmSettings,
            TweetSettings tweetSettings,
            VkontakteSettings vkontakteSettings,
            PushSettings pushSettings)
        {
            this.logger = logger;
            this.realmSettings = realmSettings;
            this.tweetSettings = tweetSettings;
            this.vkontakteSettings = vkontakteSettings;
            this.pushSettings = pushSettings;
        }

        [HttpGet]
        [Route("settings")]
        public IActionResult Settings()
        {
            return new ObjectResult(new
            {
                RealmSettings = realmSettings,
                TweetSettings = tweetSettings,
                VkontakteSettings = vkontakteSettings,
                pushSettings = pushSettings
            });
        }
    }
}

Add method to get service settings

Add method to get service settings


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

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

[assembly: AssemblyTitle("UpdateVersion")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

[assembly: AssemblyVersion("1.0.*")]

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

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

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

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

[assembly: AssemblyTitle("UpdateVersion")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

[assembly: AssemblyVersion("2.0.0.7")]

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

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

Fix to avoid unwanted updates after builds


namespace TraktApiSharp.Objects.Get.People
{
    using Extensions;
    using Newtonsoft.Json;
    using System;

    public class TraktPerson
    {
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "ids")]
        public TraktPersonIds Ids { get; set; }

        [JsonProperty(PropertyName = "images")]
        public TraktPersonImages Images { get; set; }

        [JsonProperty(PropertyName = "biography")]
        public string Biography { get; set; }

        [JsonProperty(PropertyName = "birthday")]
        public DateTime? Birthday { get; set; }

        [JsonProperty(PropertyName = "death")]
        public DateTime? Death { get; set; }

        public int Age => Birthday.HasValue ? (Death.HasValue ? Birthday.YearsBetween(Death) : Birthday.YearsBetween(DateTime.Now)) : 0;

        [JsonProperty(PropertyName = "birthplace")]
        public string Birthplace { get; set; }

        [JsonProperty(PropertyName = "homepage")]
        public string Homepage { get; set; }
    }
}

namespace TraktApiSharp.Objects.Get.People
{
    using Extensions;
    using Newtonsoft.Json;
    using System;

    /// A Trakt person.
    public class TraktPerson
    {
        /// Gets or sets the person name.
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// Gets or sets the collection of ids for the person for various web services.
        [JsonProperty(PropertyName = "ids")]
        public TraktPersonIds Ids { get; set; }

        /// Gets or sets the collection of images and image sets for the person.
        [JsonProperty(PropertyName = "images")]
        public TraktPersonImages Images { get; set; }

        /// Gets or sets the biography of the person.
        [JsonProperty(PropertyName = "biography")]
        public string Biography { get; set; }

        /// Gets or sets the UTC datetime when the person was born.
        [JsonProperty(PropertyName = "birthday")]
        public DateTime? Birthday { get; set; }

        /// Gets or sets the UTC datetime when the person died.
        [JsonProperty(PropertyName = "death")]
        public DateTime? Death { get; set; }

        /// Returns the age of the person, if <see cref="Birthday" /> is set, otherwise zero.
        public int Age => Birthday.HasValue ? (Death.HasValue ? Birthday.YearsBetween(Death) : Birthday.YearsBetween(DateTime.Now)) : 0;

        /// Gets or sets the birthplace of the person.
        [JsonProperty(PropertyName = "birthplace")]
        public string Birthplace { get; set; }

        /// Gets or sets the web address of the homepage of the person.
        [JsonProperty(PropertyName = "homepage")]
        public string Homepage { get; set; }
    }
}

Add get best id method for person.

Add get best id method for person.


#pragma warning disable CA1304
#pragma warning disable MA0011
using System.Globalization;
using TestUtilities;
using Xunit;

namespace Meziantou.Framework.ResxSourceGenerator.GeneratorTests;

public class ResxGeneratorTests
{
    [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
    public void FormatString()
    {
        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
        Assert.Equal("Hello world!", Resource1.FormatHello("world"));

        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
        Assert.Equal("Bonjour le monde!", Resource1.FormatHello("le monde"));
    }

    [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
    public void StringValue()
    {
        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
        Assert.Equal("value", Resource1.Sample);

        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
        Assert.Equal("valeur", Resource1.Sample);
    }

    [Fact]
    public void TextFile()
    {
        Assert.Equal("test", Resource1.TextFile1);
    }

    [Fact]
    public void BinaryFile()
    {
        Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, Resource1.Image1![0..8]);
    }
}

#pragma warning disable CA1304
#pragma warning disable MA0011
using System.Globalization;
using TestUtilities;
using Xunit;

namespace Meziantou.Framework.ResxSourceGenerator.GeneratorTests;

public class ResxGeneratorTests
{
    [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
    public void FormatString()
    {
        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
        Assert.Equal("Hello world!", Resource1.FormatHello("world"));

        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
        Assert.Equal("Bonjour le monde!", Resource1.FormatHello("le monde"));
    }

    [RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
    public void StringValue()
    {
        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
        Assert.Equal("value", Resource1.Sample);

        CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
        Assert.Equal("valeur", Resource1.Sample);
    }

#nullable enable
    [Fact]
    public void GetStringWithDefaultValue()
    {
        // Ensure the value is not nullable
        Assert.Equal(3, Resource1.GetString("UnknownValue", defaultValue: "abc").Length);
    }
#nullable disable

    [Fact]
    public void TextFile()
    {
        Assert.Equal("test", Resource1.TextFile1);
    }

    [Fact]
    public void BinaryFile()
    {
        Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, Resource1.Image1![0..8]);
    }
}

Validate nullable attributes are set

Validate nullable attributes are set


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Diploms.Core;

namespace Diploms.WebUI.Controllers
{
    [Route("api/[controller]")]
    public class DepartmentsController : Controller
    {
        [HttpGet("")]
        public IEnumerable<Department> GetDepartments()
        {
            return new List<Department>{
                new Department {
                    Id = 1,
                    Name = "Информационных систем",
                    ShortName = "ИС"
                },
                new Department {
                    Id = 2,
                    Name = "Информационных технологий и компьютерных систем",
                    ShortName = "ИТиКС"
                },
                new Department {
                    Id = 3,
                    Name = "Управление в технических системах",
                    ShortName = "УВТ"
                }
            };
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Diploms.Core;

namespace Diploms.WebUI.Controllers
{
    [Route("api/[controller]")]
    public class DepartmentsController : Controller
    {
        private readonly IRepository<Department> _repository;

        public DepartmentsController(IRepository<Department> repository)
        {
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        }

        [HttpGet("")]
        public async Task<IActionResult> GetDepartments()
        {
            return Ok(await _repository.Get());
        }

        [HttpPut("add")]
        public async Task<IActionResult> AddDepartment([FromBody] DepartmentAddDto model)
        {
            var department = new Department
            {
                Name = model.Name,
                ShortName = model.ShortName,
                CreateDate = DateTime.UtcNow
            };
            try
            {
                _repository.Add(department);
                await _repository.SaveChanges();
                return Ok();
            }
            catch
            {
                return BadRequest();
            }
        }
    }

    public class DepartmentAddDto
    {
        public string Name { get; set; }
        public string ShortName { get; set; }
    }
}

Add possibility to add department and DepartmentAddDto


using System;

using NHibernate;

using NUnit.Framework;

namespace NHibernate.Test.TypesTest
{
	/// <summary>
	/// Summary description for BinaryBlobTypeFixture.
	/// </summary>
	[TestFixture]
	public class BinaryBlobTypeFixture : TypeFixtureBase
	{
		protected override string TypeName
		{
			get { return "BinaryBlob"; }
		}

		[Test]
		public void ReadWrite()
		{
			ISession s = OpenSession();
			BinaryBlobClass b = new BinaryBlobClass();
			b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz");
			s.Save(b);
			s.Flush();
			s.Close();

			s = OpenSession();
			b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id );
			ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz") , b.BinaryBlob );
			s.Delete( b );
			s.Flush();
			s.Close();
		}
	}
}

using System;

using NHibernate;

using NUnit.Framework;

namespace NHibernate.Test.TypesTest
{
	/// <summary>
	/// Summary description for BinaryBlobTypeFixture.
	/// </summary>
	[TestFixture]
	public class BinaryBlobTypeFixture : TypeFixtureBase
	{
		protected override string TypeName
		{
			get { return "BinaryBlob"; }
		}

		[Test]
		public void ReadWrite()
		{
			ISession s = OpenSession();
			BinaryBlobClass b = new BinaryBlobClass();
			b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz");
			s.Save(b);
			s.Flush();
			s.Close();

			s = OpenSession();
			b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id );
			ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz") , b.BinaryBlob );
			s.Delete( b );
			s.Flush();
			s.Close();
		}

		[Test]
		public void ReadWriteLargeBlob()
		{
			ISession s = OpenSession();
			BinaryBlobClass b = new BinaryBlobClass();
			b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes(new string('T', 10000));
			s.Save(b);
			s.Flush();
			s.Close();

			s = OpenSession();
			b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id );
			ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes(new string('T', 10000)) , b.BinaryBlob );
			s.Delete( b );
			s.Flush();
			s.Close();
		}
	}
}

Test for large binary blobs (more than 8000 bytes), just to be sure it works.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@2185


// 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.Runtime;
using osu.Framework.Caching;

namespace osu.Framework.Configuration
{
    public class FrameworkDebugConfigManager : IniConfigManager<DebugSetting>
    {
        protected override string Filename => null;

        public FrameworkDebugConfigManager()
            : base(null)
        {
        }

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

            Set(DebugSetting.ActiveGCMode, GCLatencyMode.SustainedLowLatency);
            Set(DebugSetting.BypassCaching, false).ValueChanged += delegate { StaticCached.BypassCache = Get<bool>(DebugSetting.BypassCaching); };
            Set(DebugSetting.FTBPass, false);
        }
    }

    public enum DebugSetting
    {
        ActiveGCMode,
        BypassCaching,
        FTBPass
    }
}

// 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.Runtime;
using osu.Framework.Caching;

namespace osu.Framework.Configuration
{
    public class FrameworkDebugConfigManager : IniConfigManager<DebugSetting>
    {
        protected override string Filename => null;

        public FrameworkDebugConfigManager()
            : base(null)
        {
        }

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

            Set(DebugSetting.ActiveGCMode, GCLatencyMode.SustainedLowLatency);
            Set(DebugSetting.BypassCaching, false).ValueChanged += delegate { StaticCached.BypassCache = Get<bool>(DebugSetting.BypassCaching); };
            Set(DebugSetting.FTBPass, true);
        }
    }

    public enum DebugSetting
    {
        ActiveGCMode,
        BypassCaching,
        FTBPass
    }
}

Set FTBPass to true by default

Set FTBPass to true by default


public static unsafe class Program
{
    public static extern void* malloc(ulong size);
    public static extern void free(void* data);
    public static extern int puts(byte* str);

    public static int Main()
    {
        byte* str = (byte*)malloc(3);
        *str = (byte)'h';
        *(str + 1) = (byte)'i';
        *(str + 2) = (byte)'\0';
        puts(str);
        free((void*)str);
        return 0;
    }
}

public static unsafe class Program
{
    public static extern void* malloc(ulong size);
    public static extern void free(void* data);
    public static extern int puts(byte* str);

    public static void FillString(byte* str)
    {
        *str = (byte)'h';
        *(str + 1) = (byte)'i';
        *(str + 2) = (byte)'\0';
    }

    public static int Main()
    {
        byte* str = (byte*)malloc(3);
        FillString(str);
        puts(str);
        free((void*)str);
        return 0;
    }
}

Tweak the hello world test

Tweak the hello world test


using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Errors;
using JetBrains.ReSharper.Plugins.Unity.Json.Psi.Resolve;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.JavaScript.LanguageImpl.JSon;
using JetBrains.ReSharper.Psi.Resolve;

namespace JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Stages.Resolve
{
    [Language(typeof(JsonLanguage))]
    public class UnresolvedReferenceErrorHandler : IResolveProblemHighlighter
    {
        public IHighlighting Run(IReference reference)
        {
            return new UnresolvedProjectReferenceError(reference);
        }

        public IEnumerable<ResolveErrorType> ErrorTypes => new[]
        {
            AsmDefResolveErrorType.ASMDEF_UNRESOLVED_REFERENCED_PROJECT_ERROR
        };
    }
}

using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Errors;
using JetBrains.ReSharper.Plugins.Unity.Json.Psi.Resolve;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.JavaScript.LanguageImpl.JSon;
using JetBrains.ReSharper.Psi.Resolve;

namespace JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Stages.Resolve
{
    [Language(typeof(JsonLanguage))]
    public class UnresolvedReferenceErrorHandler : IResolveProblemHighlighter
    {
        public IHighlighting Run(IReference reference)
        {
            // Don't show the error highlight for now - there are too many false positive hits due to references to
            // assembly definitions in .asmdef files that are not part of the solution. These files need to be added
            // into a custom PSI module to make this work properly. This is a quick fix
            // return new UnresolvedProjectReferenceError(reference);
            return null;
        }

        public IEnumerable<ResolveErrorType> ErrorTypes => new[]
        {
            AsmDefResolveErrorType.ASMDEF_UNRESOLVED_REFERENCED_PROJECT_ERROR
        };
    }
}

Disable error for invalid asmdef reference

Fixes #647. Fixes RIDER-17700


using Newtonsoft.Json;

namespace Digirati.IIIF.Model.Types.ImageApi
{
    public class ImageServiceProfile : IProfile
    {
        [JsonProperty(Order = 1, PropertyName = "formats")]
        public string[] Formats { get; set; }

        [JsonProperty(Order = 2, PropertyName = "qualities")]
        public string[] Qualities { get; set; }

        [JsonProperty(Order = 3, PropertyName = "supports")]
        public string[] Supports { get; set; }
    }
}

using Newtonsoft.Json;

namespace Digirati.IIIF.Model.Types.ImageApi
{
    public class ImageServiceProfile : IProfile
    {
        [JsonProperty(Order = 1, PropertyName = "formats")]
        public string[] Formats { get; set; }

        [JsonProperty(Order = 2, PropertyName = "qualities")]
        public string[] Qualities { get; set; }

        [JsonProperty(Order = 3, PropertyName = "supports")]
        public string[] Supports { get; set; }

        // 2.1
        [JsonProperty(Order = 4, PropertyName = "maxWidth")]
        public int MaxWidth { get; set; }
    }
}

Add maxWidth Image API 2.1 property

Add maxWidth Image API 2.1 property


using System;
using JetBrains.Application;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.CSharp.FileLayout;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel;
using JetBrains.ReSharper.Psi.CSharp.CodeStyle;
using JetBrains.ReSharper.Psi.CSharp.Impl.CodeStyle.MemberReordering;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.Util.Logging;

namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.CodeStyle
{
    [ShellComponent]
    public class AdditionalFileLayoutPatternProvider : IAdditionalCSharpFileLayoutPatternProvider
    {
        public Patterns GetPattern(IContextBoundSettingsStore store, ICSharpTypeAndNamespaceHolderDeclaration declaration)
        {
            if (!declaration.GetSolution().HasUnityReference())
                return null;

            // TODO: This doesn't work with ReSharper - the resources haven't been added
            // If we add them, how do we edit them?

            try
            {
                var pattern = store.GetValue((AdditionalFileLayoutSettings s) => s.Pattern);
                return FileLayoutUtil.ParseFileLayoutPattern(pattern);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return null;
            }
        }
    }
}

using System;
using JetBrains.Application;
using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.CSharp.FileLayout;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel;
using JetBrains.ReSharper.Psi.CSharp.CodeStyle;
using JetBrains.ReSharper.Psi.CSharp.Impl.CodeStyle.MemberReordering;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.Util.Logging;

namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.CodeStyle
{
    [ShellComponent]
    public class AdditionalFileLayoutPatternProvider : IAdditionalCSharpFileLayoutPatternProvider
    {
        public Patterns GetPattern(IContextBoundSettingsStore store, ICSharpTypeAndNamespaceHolderDeclaration declaration)
        {
            var solution = declaration.GetSolution();
            if (!solution.HasUnityReference())
                return null;

            // TODO: This doesn't work with ReSharper - the resources haven't been added
            // If we add them, how do we edit them?

            try
            {
                var pattern = store.GetValue((AdditionalFileLayoutSettings s) => s.Pattern);
                return FileLayoutUtil.ParseFileLayoutPattern(solution, pattern);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return null;
            }
        }
    }
}

Fix unity plugin after CodeCleanupModel refactoring


using System;
using System.Linq;
using System.Net;
using AngleSharp.Dom;
using PreMailer.Net.Downloaders;

namespace PreMailer.Net.Sources
{
	public class LinkTagCssSource : ICssSource
	{
		private readonly Uri _downloadUri;
		private string _cssContents;

		public LinkTagCssSource(IElement node, Uri baseUri)
		{
			// There must be an href
			var href = node.Attributes.First(a => a.Name.Equals("href", StringComparison.OrdinalIgnoreCase)).Value;

			if (Uri.IsWellFormedUriString(href, UriKind.Relative) && baseUri != null)
			{
				_downloadUri = new Uri(baseUri, href);
			}
			else
			{
				// Assume absolute
				_downloadUri = new Uri(href);
			}
		}

		public string GetCss()
		{
			if (IsSupported(_downloadUri.Scheme))
			{
                try
                {
                    return _cssContents ?? (_cssContents = WebDownloader.SharedDownloader.DownloadString(_downloadUri));
                } catch (WebException)
                {
                    throw new WebException($"PreMailer.Net is unable to fetch the requested URL: {_downloadUri}");
                }
            }
			return string.Empty;
		}

		private static bool IsSupported(string scheme)
		{
			return
				scheme == "http" ||
				scheme == "https" ||
				scheme == "ftp" ||
				scheme == "file";
		}
	}
}

using System;
using System.Linq;
using System.Net;
using AngleSharp.Dom;
using PreMailer.Net.Downloaders;

namespace PreMailer.Net.Sources
{
	public class LinkTagCssSource : ICssSource
	{
		private readonly Uri _downloadUri;
		private string _cssContents;

		public LinkTagCssSource(IElement node, Uri baseUri)
		{
			// There must be an href
			var href = node.Attributes.First(a => a.Name.Equals("href", StringComparison.OrdinalIgnoreCase)).Value;

			if (Uri.IsWellFormedUriString(href, UriKind.Relative) && baseUri != null)
			{
				_downloadUri = new Uri(baseUri, href);
			}
			else
			{
				// Assume absolute
				_downloadUri = new Uri(href);
			}
		}

		public string GetCss()
		{
			Console.WriteLine($"GetCss scheme: {_downloadUri.Scheme}");

			if (IsSupported(_downloadUri.Scheme))
			{
                try
                {
					Console.WriteLine($"Will download from '{_downloadUri}' using {WebDownloader.SharedDownloader.GetType()}");

										return _cssContents ?? (_cssContents = WebDownloader.SharedDownloader.DownloadString(_downloadUri));
                } catch (WebException)
                {
                    throw new WebException($"PreMailer.Net is unable to fetch the requested URL: {_downloadUri}");
                }
            }
			return string.Empty;
		}

		private static bool IsSupported(string scheme)
		{
			return
				scheme == "http" ||
				scheme == "https" ||
				scheme == "ftp" ||
				scheme == "file";
		}
	}
}

Add debug info to troubleshoot failing test


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;

namespace Firehose.Web.Authors
{
    public class KevinMarquette : IAmAMicrosoftMVP
    {
        public string FirstName => "Kevin";
        public string LastName => "Marquette";
        public string ShortBioOrTagLine => "Sr. DevOps Engineer, 2018 PowerShell Community Hero, Microsoft MVP, and SoCal PowerShell UserGroup Organizer.";
        public string StateOrRegion => "Orange County, USA";
        public string EmailAddress => "kevmar@gmail.com";
        public string TwitterHandle => "kevinmarquette";
        public string GitHubHandle => "kevinmarquette";
        public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142";
        public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000);

        public Uri WebSite => new Uri("https://kevinmarquette.github.io");
        public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://kevinmarquette.github.io/feed.xml"); } }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;

namespace Firehose.Web.Authors
{
    public class KevinMarquette : IAmAMicrosoftMVP
    {
        public string FirstName => "Kevin";
        public string LastName => "Marquette";
        public string ShortBioOrTagLine => "Sr. DevOps Engineer, 2018 PowerShell Community Hero, Microsoft MVP, and SoCal PowerShell UserGroup Organizer.";
        public string StateOrRegion => "Orange County, USA";
        public string EmailAddress => "kevmar@gmail.com";
        public string TwitterHandle => "kevinmarquette";
        public string GitHubHandle => "kevinmarquette";
        public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142";
        public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000);

        public Uri WebSite => new Uri("https://PowerShellExplained.com");
        public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://powershellexplained.com/feed.xml"); } }
    }
}

Move Kevin's blog to his new domain at powershellexplained.com


using System;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using NLog;

namespace SFA.DAS.EmployerUsers.Web.Authentication
{
  public class IdsContext
    {
        public string ReturnUrl { get; set; }
        public string ClientId { get; set; }
        public static string CookieName => "IDS";

        public static IdsContext ReadFrom(string data)
        {
            try
            {
                var unEncData = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(data)));
                return JsonConvert.DeserializeObject<IdsContext>(unEncData);
            }
            catch (ArgumentException ex)
            {
                LogManager.GetCurrentClassLogger().Info(ex, ex.Message);
                return new IdsContext();
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                return new IdsContext();
            }

        }
    }
}

using System;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using NLog;

namespace SFA.DAS.EmployerUsers.Web.Authentication
{
  public class IdsContext
    {
        public string ReturnUrl { get; set; }
        public string ClientId { get; set; }
        public static string CookieName => "IDS";

        public static IdsContext ReadFrom(string data)
        {
            try
            {
                if (string.IsNullOrEmpty(data))
                {
                    return new IdsContext();
                }

                var unEncData = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(data)));
                return JsonConvert.DeserializeObject<IdsContext>(unEncData);
            }
            catch (ArgumentException ex)
            {
                LogManager.GetCurrentClassLogger().Info(ex, ex.Message);
                return new IdsContext();
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                return new IdsContext();
            }

        }
    }
}

Return new IDSContext if data is null

Return new IDSContext if data is null