using System;
using System.Threading.Tasks;
using Bartender;
using ConsoleApplication.Registries;
using CoreApplication.Domain.Personne.Create;
using CoreApplication.Domain.Personne.Read;
using StructureMap;

namespace ConsoleApplication
{
    public class Program
    {
        static IContainer Container { get; set; }

        public static void Main(string[] args)
        {
            var registry = new Registry();
            registry.IncludeRegistry<InfrastructureRegistry>();
            Container = new Container(registry);

            Task t = RunAsync();
            t.Wait();
            Console.ReadKey();
        }

        static async Task RunAsync()
        {
            var createPersonCommandHandler = Container.GetInstance<IAsyncHandler<CreatePersonCommand>>();
            await createPersonCommandHandler.HandleAsync(new CreatePersonCommand());

            var getPersonQueryHandler = Container.GetInstance<IAsyncHandler<GetPersonQuery, GetPersonReadModel>>();
            var person = await getPersonQueryHandler.HandleAsync(new GetPersonQuery());

            Console.WriteLine($"Hello {person.Name} !");
        }
    }
}

using System;
using System.Threading.Tasks;
using Bartender;
using ConsoleApplication.Registries;
using CoreApplication.Domain.Personne.Create;
using CoreApplication.Domain.Personne.Read;
using StructureMap;

namespace ConsoleApplication
{
    public class Program
    {
        static IContainer Container { get; set; }

        public static void Main(string[] args)
        {
            var registry = new Registry();
            registry.IncludeRegistry<InfrastructureRegistry>();
            Container = new Container(registry);

            Task t = RunAsync();
            t.Wait();
            Console.ReadKey();
        }

        static async Task RunAsync()
        {
            var dispatcher = Container.GetInstance<IAsyncDispatcher>();
            await dispatcher.DispatchAsync(new CreatePersonCommand());

            var person = await dispatcher.DispatchAsync<GetPersonQuery, GetPersonReadModel>(new GetPersonQuery());

            Console.WriteLine($"Hello {person.Name} !");
        }
    }
}

Switch direct handling by a asyncrhonous dispatching in core sample


using System.IO;
using Microsoft.Extensions.Logging;
using OmniSharp.MSBuild.ProjectFile;
using TestUtility;
using Xunit;
using Xunit.Abstractions;

namespace OmniSharp.MSBuild.Tests
{
    public class ProjectFileInfoTests
    {
        private readonly TestAssets _testAssets;
        private readonly ILogger _logger;

        public ProjectFileInfoTests(ITestOutputHelper output)
        {
            this._testAssets = TestAssets.Instance;
            this._logger = new TestLogger(output);

            MSBuildEnvironment.Initialize(this._logger);
        }

        [Fact]
        public void Hello_world_has_correct_property_values()
        {
            var projectFolder = _testAssets.GetTestProjectFolder("HelloWorld");
            var projectFilePath = Path.Combine(projectFolder, "HelloWorld.csproj");

            var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger);

            Assert.NotNull(projectFileInfo);
            Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath);
            Assert.Equal(1, projectFileInfo.TargetFrameworks.Count);
            Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName);
        }
    }
}

using System.IO;
using Microsoft.Extensions.Logging;
using OmniSharp.MSBuild.ProjectFile;
using TestUtility;
using Xunit;
using Xunit.Abstractions;

namespace OmniSharp.MSBuild.Tests
{
    public class ProjectFileInfoTests
    {
        private readonly TestAssets _testAssets;
        private readonly ILogger _logger;

        public ProjectFileInfoTests(ITestOutputHelper output)
        {
            this._testAssets = TestAssets.Instance;
            this._logger = new TestLogger(output);

            MSBuildEnvironment.Initialize(this._logger);
        }

        [Fact]
        public void HelloWorld_has_correct_property_values()
        {
            var projectFolder = _testAssets.GetTestProjectFolder("HelloWorld");
            var projectFilePath = Path.Combine(projectFolder, "HelloWorld.csproj");

            var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger);

            Assert.NotNull(projectFileInfo);
            Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath);
            Assert.Equal(1, projectFileInfo.TargetFrameworks.Count);
            Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName);
        }

        [Fact]
        public void NetStandardAndNetCoreApp_has_correct_property_values()
        {
            var projectFolder = _testAssets.GetTestProjectFolder("NetStandardAndNetCoreApp");
            var projectFilePath = Path.Combine(projectFolder, "NetStandardAndNetCoreApp.csproj");

            var projectFileInfo = ProjectFileInfo.Create(projectFilePath, projectFolder, this._logger);

            Assert.NotNull(projectFileInfo);
            Assert.Equal(projectFilePath, projectFileInfo.ProjectFilePath);
            Assert.Equal(1, projectFileInfo.TargetFrameworks.Count);
            Assert.Equal(".NETCoreApp,Version=v1.0", projectFileInfo.TargetFrameworks[0].DotNetFrameworkName);
        }
    }
}

Add another unit test for an MSBuild project (currently failing)


using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ServiceBase.Configuration;
using System;
using System.IO;
using ServiceBase.Extensions;

namespace IdentityBase.Public
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var contentRoot = Directory.GetCurrentDirectory();
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            var configuration = ConfigurationSetup.Configure(contentRoot, environment, (confBuilder) =>
            {
                if ("Development".Equals(environment, StringComparison.OrdinalIgnoreCase))
                {
                    confBuilder.AddUserSecrets<Startup>();
                }

                confBuilder.AddCommandLine(args);
            });

            var configHost = configuration.GetSection("Host");
            var configLogging = configuration.GetSection("Logging");

            var hostBuilder = new WebHostBuilder()
                .UseKestrel()
                .UseUrls(configHost["Urls"])
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureLogging(f => f.AddConsole(configLogging))
                .UseStartup<Startup>();

            if (configHost["UseIISIntegration"].ToBoolean())
            {
                hostBuilder = hostBuilder.UseIISIntegration();
            }

            hostBuilder.Build().Run();
        }
    }
}

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ServiceBase.Configuration;
using ServiceBase.Extensions;
using System;
using System.IO;

namespace IdentityBase.Public
{
    public class Program
    {
        public static void Main(string[] args)
        {
            RunIdentityBase<Startup>(Directory.GetCurrentDirectory(), args);
        }

        public static void RunIdentityBase<TStartup>(string contentRoot, string[] args) where TStartup : Startup
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            var configuration = ConfigurationSetup.Configure(contentRoot, environment, (confBuilder) =>
            {
                if ("Development".Equals(environment, StringComparison.OrdinalIgnoreCase))
                {
                    confBuilder.AddUserSecrets<TStartup>();
                }

                confBuilder.AddCommandLine(args);
            });

            var configHost = configuration.GetSection("Host");
            var configLogging = configuration.GetSection("Logging");

            var hostBuilder = new WebHostBuilder()
                .UseKestrel()
                .UseUrls(configHost["Urls"])
                .UseContentRoot(contentRoot)
                .ConfigureLogging(f => f.AddConsole(configLogging))
                .UseStartup<TStartup>();

            if (configHost["UseIISIntegration"].ToBoolean())
            {
                hostBuilder = hostBuilder.UseIISIntegration();
            }

            hostBuilder.Build().Run();
        }
    }
}

Allow application startup with inherited startup class


using jab.Attributes;
using NSwag;
using Xunit;
using System.Linq;

namespace jab
{
    public class TestExample
    {
        [Theory, ParameterisedClassData(typeof(ApiOperations), "samples/example.json")]
        public void DeleteMethodsShouldNotTakeFormEncodedData(
            SwaggerService service,
            string path,
            SwaggerOperationMethod method,
            SwaggerOperation operation)
        {
            if (method == SwaggerOperationMethod.Delete)
            {
                Assert.Null(operation.ActualConsumes);
            } else
            {
                Assert.True(true);
            }
        }
    }
}

using jab.Attributes;
using NSwag;
using Xunit;
using System.Linq;

namespace jab
{
    public partial class TestExample
    {
        const string testDefinition = "samples/example.json";

        [Theory, ParameterisedClassData(typeof(ApiOperations), testDefinition)]
        public void DeleteMethodsShouldNotTakeFormEncodedData(
            SwaggerService service,
            string path,
            SwaggerOperationMethod method,
            SwaggerOperation operation)
        {
            if (method == SwaggerOperationMethod.Delete)
            {
                Assert.Null(operation.ActualConsumes);
            } else
            {
                Assert.True(true);
            }
        }

        /// <summary>
        /// You should not ask for api keys in query parameters.
        /// https://www.owasp.org/index.php/REST_Security_Cheat_Sheet#Authentication_and_session_management
        /// </summary>
        /// <param name="service"></param>
        /// <param name="path"></param>
        /// <param name="method"></param>
        /// <param name="operation"></param>
        [Theory, ParameterisedClassData(typeof(ApiOperations), testDefinition)]
        public void NoApiKeysInParameters(
            SwaggerService service,
            string path,
            SwaggerOperationMethod method,
            SwaggerOperation operation)
        {
            if (operation.ActualParameters.Count > 0)
            {
                Assert.False(
                    operation.Parameters.Count(
                        c => ((c.Name.ToLower() == "apikey") || (c.Name.ToLower() == "api_key"))
                            && c.Kind == SwaggerParameterKind.Query) > 0);
            }
            else
            {
                Assert.True(true);
            }
        }
    }
}

Add a check for api keys in query parameters.


using System.Windows.Input;

namespace clipman.Settings
{
    public static class Keyboard
    {
        public static Key ClearTextboxKey = Key.Escape;
    }
}

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Input;
using System.Windows.Interop;

namespace clipman.Settings
{
    public static class Keyboard
    {
        public static Key ClearTextboxKey = Key.Escape;
    }

    public class KeyboardMonitor : IDisposable
    {
        private bool disposed = false;

        private static class NativeMethods
        {
            [DllImport("User32.dll")]
            public static extern bool RegisterHotKey(
                [In] IntPtr hWnd,
                [In] int id,
                [In] uint fsModifiers,
                [In] uint vk
            );

            [DllImport("User32.dll")]
            public static extern bool UnregisterHotKey(
                [In] IntPtr hWnd,
                [In] int id
            );

            public const int WM_HOTKEY = 0x0312;

            /// <summary>
            /// To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function.
            /// </summary>
            public static IntPtr HWND_MESSAGE = new IntPtr(-3);
        }

        public class HotkeyEventArgs : EventArgs
        {
            public int HotkeyId
            {
                get;
                set;
            }
        }

        private HwndSource hwndSource = new HwndSource(0, 0, 0, 0, 0, 0, 0, null, NativeMethods.HWND_MESSAGE);

        private List<int> hotkeyIds = new List<int>();

        public KeyboardMonitor()
        {
            hwndSource.AddHook(WndProc);
        }

        public int AddHotkey(int modifier, int key)
        {
            int id = hotkeyIds.Count + 9000;
            hotkeyIds.Add(id);
            NativeMethods.RegisterHotKey(hwndSource.Handle, id, (uint)modifier, (uint)key);
            return id;
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == NativeMethods.WM_HOTKEY)
            {
                Utility.Logging.Log("WM_HOTKEY");
                if (hotkeyIds.Contains(wParam.ToInt32()))
                {
                    handled = true;
                    var args = new HotkeyEventArgs();
                    args.HotkeyId = wParam.ToInt32();
                    KeyPressed?.Invoke(this, args);
                }
            }
            return IntPtr.Zero;
        }

        public void Dispose()
        {
            if (!disposed)
            {
                foreach (var id in hotkeyIds) {
                    NativeMethods.UnregisterHotKey(hwndSource.Handle, id);
                }
            }
        }

        public event EventHandler<HotkeyEventArgs> KeyPressed;
    }
}

Add global keyboard shortcut listener

Add global keyboard shortcut listener


// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

namespace StyleCop.Analyzers.Test
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CodeFixes;
    using StyleCop.Analyzers.ReadabilityRules;
    using Xunit;

    public class ExportCodeFixProviderAttributeNameTest
    {
        public static IEnumerable<object[]> CodeFixProviderTypeData
        {
            get
            {
                var codeFixProviders = typeof(SA1110OpeningParenthesisMustBeOnDeclarationLine)
                    .Assembly
                    .GetTypes()
                    .Where(t => typeof(CodeFixProvider).IsAssignableFrom(t));

                return codeFixProviders.Select(x => new[] { x });
            }
        }

        [Theory]
        [MemberData(nameof(CodeFixProviderTypeData))]
        public void TestExportCodeFixProviderAttribute(Type codeFixProvider)
        {
            var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes<ExportCodeFixProviderAttribute>(false).FirstOrDefault();

            Assert.NotNull(exportCodeFixProviderAttribute);
            Assert.Equal(codeFixProvider.Name, exportCodeFixProviderAttribute.Name);
            Assert.Equal(1, exportCodeFixProviderAttribute.Languages.Length);
            Assert.Equal(LanguageNames.CSharp, exportCodeFixProviderAttribute.Languages[0]);
        }
    }
}

// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

namespace StyleCop.Analyzers.Test
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Analyzers.SpacingRules;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CodeFixes;
    using Xunit;

    public class ExportCodeFixProviderAttributeNameTest
    {
        public static IEnumerable<object[]> CodeFixProviderTypeData
        {
            get
            {
                var codeFixProviders = typeof(TokenSpacingCodeFixProvider)
                    .Assembly
                    .GetTypes()
                    .Where(t => typeof(CodeFixProvider).IsAssignableFrom(t));

                return codeFixProviders.Select(x => new[] { x });
            }
        }

        [Theory]
        [MemberData(nameof(CodeFixProviderTypeData))]
        public void TestExportCodeFixProviderAttribute(Type codeFixProvider)
        {
            var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes<ExportCodeFixProviderAttribute>(false).FirstOrDefault();

            Assert.NotNull(exportCodeFixProviderAttribute);
            Assert.Equal(codeFixProvider.Name, exportCodeFixProviderAttribute.Name);
            Assert.Equal(1, exportCodeFixProviderAttribute.Languages.Length);
            Assert.Equal(LanguageNames.CSharp, exportCodeFixProviderAttribute.Languages[0]);
        }
    }
}

Fix test which relies on reflection over the code fixes assembly


using System;
using System.Threading;
using Xunit;
using Should;
using Timer = SlackConnector.Connections.Monitoring.Timer;

namespace SlackConnector.Tests.Unit.Connections.Monitoring
{
    public class TimerTests
    {
        [Fact]
        public void should_run_task_at_least_5_times()
        {
            // given
            var timer = new Timer();
            int calls = 0;
            DateTime timeout = DateTime.Now.AddSeconds(4);

            // when
            timer.RunEvery(() => calls++, TimeSpan.FromMilliseconds(1));

            while (calls < 5 && DateTime.Now < timeout)
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(5));
            }

            // then
            calls.ShouldBeGreaterThanOrEqualTo(5);
        }

        [Fact]
        public void should_throw_exception_if_a_second_timer_is_created()
        {
            // given
            var timer = new Timer();
            timer.RunEvery(() => { }, TimeSpan.FromMilliseconds(1));

            // when + then
            Assert.Throws<Timer.TimerAlreadyInitialisedException>(() => timer.RunEvery(() => { }, TimeSpan.FromMinutes(1)));
        }
    }
}

using System;
using System.Threading;
using Xunit;
using Should;
using Timer = SlackConnector.Connections.Monitoring.Timer;

namespace SlackConnector.Tests.Unit.Connections.Monitoring
{
    public class TimerTests
    {
        [Fact]
        public void should_run_task_at_least_5_times()
        {
            // given
            var timer = new Timer();
            int calls = 0;
            DateTime timeout = DateTime.Now.AddSeconds(20);

            // when
            timer.RunEvery(() => calls++, TimeSpan.FromMilliseconds(1));

            while (calls < 5 && DateTime.Now < timeout)
            {
                Thread.Sleep(TimeSpan.FromMilliseconds(5));
            }

            // then
            calls.ShouldBeGreaterThanOrEqualTo(5);
        }

        [Fact]
        public void should_throw_exception_if_a_second_timer_is_created()
        {
            // given
            var timer = new Timer();
            timer.RunEvery(() => { }, TimeSpan.FromMilliseconds(1));

            // when + then
            Assert.Throws<Timer.TimerAlreadyInitialisedException>(() => timer.RunEvery(() => { }, TimeSpan.FromMinutes(1)));
        }
    }
}

Increase timeout for Timer tests

Increase timeout for Timer tests


using System.Collections.Generic;
using System.Linq;
using TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers.Core;

namespace TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers
{
    public class RestMethodDoc
    {
        #region Variables

        public IReadOnlyList<RestResponse> Responses { get; }

        public IReadOnlyList<RestMethodParam> Params { get; }

        public string MethodType { get; }

        public RestTypeDoc Parent { get; }

        public string OperationId { get; }

        public string FullName { get; }

        public string Summary { get; }

        public string Name { get; }

        #endregion

        #region Constructor

        public RestMethodDoc(RestTypeDoc restTypeDoc, RestAction action)
        {
            OperationId = action.OperationId;
            FullName = $"http://app[x].timelog.com/[account name]{action.Name}";
            Name = action.OperationId.Replace($"{action.Tags[0]}_", "");
            Summary = action.Summary;
            MethodType = action.MethodType.ToUpper();
            Parent = restTypeDoc;
            Params = MapToMethodParam(action.Parameters);
            Responses = action.Responses.OrderBy(x => x.Code).ToList();
        }

        #endregion

        #region Internal and Private Implementations

        private IReadOnlyList<RestMethodParam> MapToMethodParam(IReadOnlyList<RestParameter> parameters)
        {
            return parameters
                .Select(x => new RestMethodParam(x.Name, x.Description, x.Type, x.SchemaRestRef))
                .ToList();
        }

        #endregion
    }
}

using System.Collections.Generic;
using System.Linq;
using TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers.Core;

namespace TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers
{
    public class RestMethodDoc
    {
        #region Variables

        public IReadOnlyList<RestResponse> Responses { get; }

        public IReadOnlyList<RestMethodParam> Params { get; }

        public string MethodType { get; }

        public RestTypeDoc Parent { get; }

        public string OperationId { get; }

        public string FullName { get; }

        public string Summary { get; }

        public string Name { get; }

        #endregion

        #region Constructor

        public RestMethodDoc(RestTypeDoc restTypeDoc, RestAction action)
        {
            OperationId = action.OperationId;
            FullName = $"https://app[x].timelog.com/[account name]/api{action.Name}";
            Name = action.OperationId.Replace($"{action.Tags[0]}_", "");
            Summary = action.Summary;
            MethodType = action.MethodType.ToUpper();
            Parent = restTypeDoc;
            Params = MapToMethodParam(action.Parameters);
            Responses = action.Responses.OrderBy(x => x.Code).ToList();
        }

        #endregion

        #region Internal and Private Implementations

        private IReadOnlyList<RestMethodParam> MapToMethodParam(IReadOnlyList<RestParameter> parameters)
        {
            return parameters
                .Select(x => new RestMethodParam(x.Name, x.Description, x.Type, x.SchemaRestRef))
                .ToList();
        }

        #endregion
    }
}

Fix REST API url in documentation

Fix REST API url in documentation


// 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.Graphics;
using osu.Framework.Graphics.Shapes;

namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations
{
    /// <summary>
    /// Represents a singular point on a timeline part.
    /// </summary>
    public class PointVisualisation : Box
    {
        public const float MAX_WIDTH = 4;

        public PointVisualisation(double startTime)
            : this()
        {
            X = (float)startTime;
        }

        public PointVisualisation()
        {
            Origin = Anchor.TopCentre;

            RelativePositionAxes = Axes.X;
            RelativeSizeAxes = Axes.Y;

            Anchor = Anchor.CentreLeft;
            Origin = Anchor.Centre;

            Width = MAX_WIDTH;
            Height = 0.75f;
        }
    }
}

// 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.Graphics;
using osu.Framework.Graphics.Shapes;

namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations
{
    /// <summary>
    /// Represents a singular point on a timeline part.
    /// </summary>
    public class PointVisualisation : Circle
    {
        public const float MAX_WIDTH = 4;

        public PointVisualisation(double startTime)
            : this()
        {
            X = (float)startTime;
        }

        public PointVisualisation()
        {
            Origin = Anchor.TopCentre;

            RelativePositionAxes = Axes.X;
            RelativeSizeAxes = Axes.Y;

            Anchor = Anchor.CentreLeft;
            Origin = Anchor.Centre;

            Width = MAX_WIDTH;
            Height = 0.75f;
        }
    }
}

Add rounded corners to timeline ticks display


using System;
using System.Buffers;

namespace Dbus
{
    internal static class ExtensionMethods
    {
        public static void Dump(this ReadOnlySequence<byte> buffers)
        {
            foreach (var segment in buffers)
            {
                var buffer = segment.Span;
                dump(buffer);
            }
            Console.WriteLine();
        }

        public static void Dump(this Span<byte> memory)
        {
            dump(memory);
            Console.WriteLine();
        }

        private static void dump(this ReadOnlySpan<byte> buffer)
        {
            for (var i = 0; i < buffer.Length; ++i)
            {
                var isDigitOrAsciiLetter = false;
                isDigitOrAsciiLetter |= 48 <= buffer[i] && buffer[i] <= 57;
                isDigitOrAsciiLetter |= 65 <= buffer[i] && buffer[i] <= 90;
                isDigitOrAsciiLetter |= 97 <= buffer[i] && buffer[i] <= 122;
                if (isDigitOrAsciiLetter)
                    Console.Write($"{(char)buffer[i]} ");
                else
                    Console.Write($"x{buffer[i]:X} ");
            }
        }
    }
}

using System;
using System.Buffers;

namespace Dbus
{
    internal static class ExtensionMethods
    {
        public static void Dump(this ReadOnlySequence<byte> buffers)
        {
            var counter = 0;
            foreach (var segment in buffers)
            {
                var buffer = segment.Span;
                dump(buffer, ref counter);
            }
            Console.WriteLine();
        }

        public static void Dump(this Span<byte> memory)
        {
            var counter = 0;
            dump(memory, ref counter);
            Console.WriteLine();
        }

        private static void dump(this ReadOnlySpan<byte> buffer, ref int counter)
        {
            for (var i = 0; i < buffer.Length; ++i)
            {
                var isDigitOrAsciiLetter = false;
                isDigitOrAsciiLetter |= 48 <= buffer[i] && buffer[i] <= 57;
                isDigitOrAsciiLetter |= 65 <= buffer[i] && buffer[i] <= 90;
                isDigitOrAsciiLetter |= 97 <= buffer[i] && buffer[i] <= 122;
                if (isDigitOrAsciiLetter)
                    Console.Write($"{(char)buffer[i]} ");
                else
                    Console.Write($"x{buffer[i]:X} ");

                counter += 1;
                if ((counter & 7) == 0)
                    Console.Write("| ");
            }
        }
    }
}

Mark the eight-byte-boundaries when dumping a message


/* Copyright 2015 Realm Inc - All Rights Reserved
 * Proprietary and Confidential
 */

using System.IO;
using NUnit.Framework;
using Realms;

namespace IntegrationTests.Shared
{
    [TestFixture]
    public class AccessTests
    {
        protected string _databasePath;
        protected Realm _realm;

        [SetUp]
        public void Setup()
        {
            _databasePath = Path.GetTempFileName();
            _realm = Realm.GetInstance(_databasePath);
        }

        [TearDown]
        public void TearDown()
        {
            _realm.Dispose();
        }

        [Test]
        public void SetValueAndReplaceWithNull()
        {
            AllTypesObject ato;
            using (var transaction = _realm.BeginWrite())
            {
                ato = _realm.CreateObject<AllTypesObject>();

                TestHelpers.SetPropertyValue(ato, "NullableBooleanProperty", true);
                transaction.Commit();
            }

            Assert.That(ato.NullableBooleanProperty, Is.EqualTo(true));

            using (var transaction = _realm.BeginWrite())
            {
                TestHelpers.SetPropertyValue(ato, "NullableBooleanProperty", null);
                transaction.Commit();
            }

            Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null));
        }
    }
}

/* Copyright 2015 Realm Inc - All Rights Reserved
 * Proprietary and Confidential
 */

using System.IO;
using NUnit.Framework;
using Realms;

namespace IntegrationTests.Shared
{
    [TestFixture]
    public class AccessTests
    {
        protected string _databasePath;
        protected Realm _realm;

        [SetUp]
        public void Setup()
        {
            _databasePath = Path.GetTempFileName();
            _realm = Realm.GetInstance(_databasePath);
        }

        [TearDown]
        public void TearDown()
        {
            _realm.Dispose();
        }

        [TestCase("NullableCharProperty", '0')]
        [TestCase("NullableByteProperty", (byte)100)]
        [TestCase("NullableInt16Property", (short)100)]
        [TestCase("NullableInt32Property", 100)]
        [TestCase("NullableInt64Property", 100L)]
        [TestCase("NullableSingleProperty", 123.123f)]
        [TestCase("NullableDoubleProperty", 123.123)]
        [TestCase("NullableBooleanProperty", true)]
        public void SetValueAndReplaceWithNull(string propertyName, object propertyValue)
        {
            AllTypesObject ato;
            using (var transaction = _realm.BeginWrite())
            {
                ato = _realm.CreateObject<AllTypesObject>();

                TestHelpers.SetPropertyValue(ato, propertyName, propertyValue);
                transaction.Commit();
            }

            Assert.That(TestHelpers.GetPropertyValue(ato, propertyName), Is.EqualTo(propertyValue));

            using (var transaction = _realm.BeginWrite())
            {
                TestHelpers.SetPropertyValue(ato, propertyName, null);
                transaction.Commit();
            }

            Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null));
        }
    }
}

Add access tests for all nullable types.


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

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class QuestionDisplayOptionsCustomOptions
    {
        public List<string> OptionSet { get; set; }
        public int StartingPosition { get; set; }
        public int StepSize { get; set; }
    }
}

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

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class QuestionDisplayOptionsCustomOptions
    {
        public List<string> OptionSet { get; set; }
        public int StartingPosition { get; set; }
        public int StepSize { get; set; }
        public string Color { get; set; }
    }
}

Add Color custom display option for star ratings


using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;

namespace Microsoft.PowerShell.EditorServices
{
    internal class PesterDocumentSymbolProvider : DocumentSymbolProvider
    {
        protected override bool CanProvideFor(ScriptFile scriptFile)
        {
            return scriptFile.FilePath.EndsWith("tests.ps1", StringComparison.OrdinalIgnoreCase);
        }

        protected override IEnumerable<SymbolReference> GetSymbolsImpl(ScriptFile scriptFile, Version psVersion)
        {
            var commandAsts = scriptFile.ScriptAst.FindAll(ast =>
            {
                switch ((ast as CommandAst)?.GetCommandName().ToLower())
                {
                    case "describe":
                    case "context":
                    case "it":
                        return true;

                    case null:
                    default:
                        return false;
                }
            },
            true);

            return commandAsts.Select(ast => new SymbolReference(
                SymbolType.Function,
                ast.Extent,
                scriptFile.FilePath,
                scriptFile.GetLine(ast.Extent.StartLineNumber)));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;

namespace Microsoft.PowerShell.EditorServices
{
    internal class PesterDocumentSymbolProvider : DocumentSymbolProvider
    {
        protected override bool CanProvideFor(ScriptFile scriptFile)
        {
            return scriptFile.FilePath.EndsWith("tests.ps1", StringComparison.OrdinalIgnoreCase);
        }

        protected override IEnumerable<SymbolReference> GetSymbolsImpl(ScriptFile scriptFile, Version psVersion)
        {
            var commandAsts = scriptFile.ScriptAst.FindAll(ast =>
            {
                switch ((ast as CommandAst)?.GetCommandName().ToLower())
                {
                    case "describe":
                    case "context":
                    case "it":
                        return true;

                    default:
                        return false;
                }
            },
            true);

            return commandAsts.Select(ast => new SymbolReference(
                SymbolType.Function,
                ast.Extent,
                scriptFile.FilePath,
                scriptFile.GetLine(ast.Extent.StartLineNumber)));
        }
    }
}

Remove redundant case from switch statement


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

namespace SteamIrcBot
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main( string[] args )
        {
            AppDomain.CurrentDomain.UnhandledException += ( sender, e ) =>
            {
                Log.WriteError( "Program", "Unhandled exception (IsTerm: {0}): {1}", e.IsTerminating, e.ExceptionObject );
            };

            var service = new BotService();

#if SERVICE_BUILD
            ServiceBase.Run( service );
#else
            service.Start( args );
#endif
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Reflection;
using System.IO;

namespace SteamIrcBot
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main( string[] args )
        {
            string path = Assembly.GetExecutingAssembly().Location;
            path = Path.GetDirectoryName( path );
            Directory.SetCurrentDirectory( path );

            AppDomain.CurrentDomain.UnhandledException += ( sender, e ) =>
            {
                Log.WriteError( "Program", "Unhandled exception (IsTerm: {0}): {1}", e.IsTerminating, e.ExceptionObject );
            };

            var service = new BotService();

#if SERVICE_BUILD
            ServiceBase.Run( service );
#else
            service.Start( args );
#endif
        }
    }
}

Set current directory when running as a service.


using System;

namespace MK.Ext
{
	/// <summary>
	/// DateTime Json Extensions
	/// </summary>
	public static class DateTimeJsonExt
	{
		private static readonly DateTime D1970_01_01 = new DateTime(1970, 1, 1);
		public static string JsonValue(this DateTime d)
		{
			return "( new Date(" + System.Convert.ToInt64((d - D1970_01_01).TotalMilliseconds) + "))";
		}
	}
}

using System;

namespace MK.Ext
{
	/// <summary>
	/// DateTime Json Extensions
	/// </summary>
	public static class DateTimeJsonExt
	{
		private static readonly DateTime D1970_01_01 = new DateTime(1970, 1, 1);
		public static string JsonValue(this DateTime d)
		{
			return "( new Date(" + ((d.Ticks - D1970_01_01.Ticks) / 10000) + "))";
		}
	}
}

Fix datetime json ext - lost one millisecond


@{
    Layout = null;
}

<!DOCTYPE html>

    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">

Hello, world!

@{
    Layout = null;
}

<!DOCTYPE html>

    <title>Sweet Water Revolver</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">

Sweet Water Revolver

Change the page title and h1.

Change the page title and h1.


using AutoMapper;
using BusinessEntities;
using BusinessEntities.Dictionaries;
using DataModel;
using DataModel.Dictionaries;

namespace BLL.Mapping
{
	public class AutomapperProfile : Profile
	{
		public AutomapperProfile()
		{
			CreateMap<Animal, AnimalEntity>();
			CreateMap<Council, CouncilEntity>();
		}
	}
}

using AutoMapper;
using BusinessEntities;
using BusinessEntities.Dictionaries;
using DataModel;
using DataModel.Dictionaries;

namespace BLL.Mapping
{
	public class AutomapperProfile : Profile
	{
		public AutomapperProfile()
		{
			CreateMap<Animal, AnimalEntity>();
			CreateMap<Council, CouncilEntity>();
			CreateMap<ActivityType, ActivityTypeEntity>();
			CreateMap<Address, AddressEntity>();
			CreateMap<City, CityEntity>();
			CreateMap<CityType, CityTypeEntity>();
			CreateMap<Company, CompanyEntity>();
			CreateMap<Country, CountryEntity>();
			CreateMap<District, DistrictEntity>();
			CreateMap<DocumentType, DocumentTypeEntity>();
			CreateMap<EducationDegree, EducationDegreeEntity>();
			CreateMap<FamilyRelations, FamilyRelationsEntity>();
			CreateMap<FamilyStatus, FamilyStatusEntity>();
			CreateMap<Institution, InstitutionEntity>();
			CreateMap<Material, MaterialEntity>();
			CreateMap<Nationality, NationalityEntity>();
			CreateMap<PassAuthority, PassAuthorityEntity>();
			CreateMap<PensionType, PensionTypeEntity>();
			CreateMap<Person, PersonEntity>();
			CreateMap<Position, PositionEntity>();
			CreateMap<Region, RegionEntity>();
			CreateMap<Speciality, SpecialityEntity>();
			CreateMap<Street, StreetEntity>();
			CreateMap<StreetType, StreetType>();
			CreateMap<Catalog, CatalogEntity>();
			CreateMap<Document, DocumentEntity>();
			CreateMap<Education, EducationEntity>();
			CreateMap<Employment, EmploymentEntity>();
			CreateMap<House, HouseEntity>();
			CreateMap<People, PeopleEntity>();
			CreateMap<PersonDocument, PersonDocumentEntity>();
		}
	}
}

Add mapping for all entities

Add mapping for all entities


@using CarFuel.Models
@model Car

@Model.Make (@Model.Model)

    Average consumption is @(Model.AverageKmL?.ToString("n2")) km/L

@using CarFuel.Models
@model Car

@Model.Make (@Model.Model)

    @if (Model.AverageKmL == null)
    {

            Not has enough data to calculate consumption rate.
            Please add more fill up.

    }
    Average consumption is @(Model.AverageKmL?.ToString("n2")) km/L

Add Message if AvgKmL is null

Add Message if AvgKmL is null


using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PlanEatSave.Models;
using PlanEatSave.Utils;

namespace PlanEatSave.DataAceessLayer
{
    public class PantryService
    {
        private ApplicationDbContext _context;
        private IPlanEatSaveLogger _logger;

        public PantryService(ApplicationDbContext context, IPlanEatSaveLogger logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task<Pantry> GetPantryByUserIdAsync(string userId)
        {
            return await _context.Pantries
                                .Where(pantry => pantry.UserId == userId)
                                .Include(pantry => pantry.PantryItems).FirstOrDefaultAsync();
        }

        public async Task<bool> AddItem(string userId, PantryItem item)
        {
            var pantryDb = await _context.Pantries.Where(pantry => pantry.Id == item.PantryId).FirstOrDefaultAsync();
            if (pantryDb == null || pantryDb.UserId != userId)
            {
                return false;
            }

            _context.PantryItems.Add(item);
            await _context.SaveChangesAsync();
            return true;
        }
    }
}

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PlanEatSave.Models;
using PlanEatSave.Utils;

namespace PlanEatSave.DataAceessLayer
{
    public class PantryService
    {
        private ApplicationDbContext _context;
        private IPlanEatSaveLogger _logger;

        public PantryService(ApplicationDbContext context, IPlanEatSaveLogger logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task<Pantry> GetPantryByUserIdAsync(string userId)
        {
            var pantryFromDb = await _context.Pantries
                                .Where(pantry => pantry.UserId == userId)
                                .Include(pantry => pantry.PantryItems).FirstOrDefaultAsync();

            if (pantryFromDb != null)
            {
                return pantryFromDb;
            }

            var newPantry = new Pantry
            {
                UserId = userId
            };

            _context.Pantries.Add(newPantry);
            await _context.SaveChangesAsync();
            return newPantry;
        }

        public async Task<bool> AddItem(string userId, PantryItem item)
        {
            var pantryDb = await _context.Pantries.Where(pantry => pantry.Id == item.PantryId).FirstOrDefaultAsync();
            if (pantryDb == null || pantryDb.UserId != userId)
            {
                return false;
            }

            _context.PantryItems.Add(item);
            await _context.SaveChangesAsync();
            return true;
        }
    }
}

Add logic for creating a pantru for new users


namespace ElectronNET.API.Entities
{
    /// <summary>
    ///
    /// </summary>
    public class Data
    {
        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        /// <value>
        /// The text.
        /// </value>
        public string Text { get; set; }

        /// <summary>
        /// Gets or sets the HTML.
        /// </summary>
        /// <value>
        /// The HTML.
        /// </value>
        public string Html { get; set; }

        /// <summary>
        /// Gets or sets the RTF.
        /// </summary>
        /// <value>
        /// The RTF.
        /// </value>
        public string Rtf { get; set; }

        /// <summary>
        /// The title of the url at text.
        /// </summary>
        public string Bookmark { get; set; }
    }
}

namespace ElectronNET.API.Entities
{
    /// <summary>
    ///
    /// </summary>
    public class Data
    {
        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        /// <value>
        /// The text.
        /// </value>
        public string Text { get; set; }

        /// <summary>
        /// Gets or sets the HTML.
        /// </summary>
        /// <value>
        /// The HTML.
        /// </value>
        public string Html { get; set; }

        /// <summary>
        /// Gets or sets the RTF.
        /// </summary>
        /// <value>
        /// The RTF.
        /// </value>
        public string Rtf { get; set; }

        /// <summary>
        /// The title of the url at text.
        /// </summary>
        public string Bookmark { get; set; }

        public NativeImage? Image { get; set; }
    }
}

Add Image to clipboard data

Add Image to clipboard data


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

[CustomEditor(typeof(VRSubjectController))]
public class VRSubjectInspector : Editor
{
    VRSubjectController instance;

    public override void OnInspectorGUI()
    {
        instance = target as VRSubjectController;

        base.OnInspectorGUI();

        GUILayout.BeginVertical();

        var availableBodyController = instance.GetComponents<IBodyMovementController>();
        var availableHeadController = instance.GetComponents<IHeadMovementController>();

        EditorGUILayout.LabelField("Available Head Controller");

        if (!availableHeadController.Any())
            EditorGUILayout.HelpBox("No Head Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);

        foreach (var headController in availableHeadController)
        {
            if (GUILayout.Button(headController.Identifier))
            {
                instance.ChangeHeadController(headController);
            }
        }

        EditorGUILayout.LabelField("Available Body Controller");

        if (!availableBodyController.Any())
            EditorGUILayout.HelpBox("No Body Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);

        foreach (var bodyController in availableBodyController)
        {
            if(GUILayout.Button(bodyController.Identifier))
                instance.ChangeBodyController(bodyController);
        }

        EditorGUILayout.Space();

        if (GUILayout.Button("Reset Controller"))
        {
            instance.ResetController();
        }

        GUILayout.EndVertical();

        instance.UseMonoscopigRendering = EditorGUILayout.Toggle("Monoscopic Rendering", instance.UseMonoscopigRendering);

        if (instance.UseMonoscopigRendering)
            instance.SetMonoscopic(instance.UseMonoscopigRendering);
    }
}

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

[CustomEditor(typeof(VRSubjectController))]
public class VRSubjectInspector : Editor
{
    VRSubjectController instance;

    public override void OnInspectorGUI()
    {
        instance = target as VRSubjectController;

        base.OnInspectorGUI();

        GUILayout.BeginVertical();

        var availableBodyController = instance.GetComponents<IBodyMovementController>();
        var availableHeadController = instance.GetComponents<IHeadMovementController>();

        EditorGUILayout.LabelField("Available Head Controller");

        if (!availableHeadController.Any())
            EditorGUILayout.HelpBox("No Head Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);

        foreach (var headController in availableHeadController)
        {
            if (GUILayout.Button(headController.Identifier))
            {
                instance.ChangeHeadController(headController);
            }
        }

        EditorGUILayout.LabelField("Available Body Controller");

        if (!availableBodyController.Any())
            EditorGUILayout.HelpBox("No Body Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);

        foreach (var bodyController in availableBodyController)
        {
            if(GUILayout.Button(bodyController.Identifier))
                instance.ChangeBodyController(bodyController);
        }

        EditorGUILayout.Space();

        if (GUILayout.Button("Reset Controller"))
        {
            instance.ResetController();
        }

        GUILayout.EndVertical();

    }
}

[FEATURE] Move the Recenter and Monoscoping Rendering feature to the Oculus Head Controller


using System.Text;

namespace TweetDck.Plugins{
    static class PluginScriptGenerator{
        public static string GenerateConfig(PluginConfig config){
            return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
        }

        public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
            StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);

            build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");

            build.Append("let tmp={");
            build.Append("id:\"").Append(pluginIdentifier).Append("\",");
            build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
            build.Append("};");

            build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
            build.Append("window.TD_PLUGINS.install(tmp);");

            build.Append("})(").Append(environment.GetScriptVariables()).Append(");");

            return build.ToString();
        }
    }
}

using System.Text;

namespace TweetDck.Plugins{
    static class PluginScriptGenerator{
        public static string GenerateConfig(PluginConfig config){
            return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
        }

        public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
            StringBuilder build = new StringBuilder(2*pluginIdentifier.Length+pluginContents.Length+165);

            build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");

            build.Append("let tmp={");
            build.Append("id:\"").Append(pluginIdentifier).Append("\",");
            build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
            build.Append("};");

            build.Append("tmp.obj.$id=\"").Append(pluginIdentifier).Append("\";");
            build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
            build.Append("window.TD_PLUGINS.install(tmp);");

            build.Append("})(").Append(environment.GetScriptVariables()).Append(");");

            return build.ToString();
        }
    }
}

Add plugin identifier to the object itself


@{
    ViewBag.Title = "Registreer je vandaag bij de Oogstplanner";
}

Registreer je vandaag bij de Oogstplanner

                    Inloggen

                @{ Html.RenderPartial("_RegisterForm"); }

Remove signupbox id from register bx since then it can be hidden by the zk.showLoginBox function


using UnityEngine;

namespace LiteNetLibManager
{
    [System.Serializable]
    public class LiteNetLibScene
    {
        [SerializeField]
        private Object sceneAsset;
        [SerializeField]
        private string sceneName = string.Empty;

        public string SceneName
        {
            get { return sceneName; }
            set { sceneName = value; }
        }

        public static implicit operator string(LiteNetLibScene unityScene)
        {
            return unityScene.SceneName;
        }

        public bool IsSet()
        {
            return !string.IsNullOrEmpty(sceneName);
        }
    }
}

using UnityEngine;

namespace LiteNetLibManager
{
    [System.Serializable]
    public struct LiteNetLibScene
    {
        [SerializeField]
        private Object sceneAsset;
        [SerializeField]
        private string sceneName;

        public string SceneName
        {
            get { return sceneName; }
            set { sceneName = value; }
        }

        public static implicit operator string(LiteNetLibScene unityScene)
        {
            return unityScene.SceneName;
        }

        public bool IsSet()
        {
            return !string.IsNullOrEmpty(sceneName);
        }
    }
}

Change unity scene type to struct

Change unity scene type to struct


using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Extensions;
using Abp.Authorization;
using Abp.Dependency;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Abp.AspNetCore.Mvc.Authorization
{
    public class AbpAuthorizationFilter : IAsyncAuthorizationFilter, ITransientDependency
    {
        private readonly IAuthorizationHelper _authorizationHelper;

        public AbpAuthorizationFilter(IAuthorizationHelper authorizationHelper)
        {
            _authorizationHelper = authorizationHelper;
        }

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            //Check IAllowAnonymous
            if (context.ActionDescriptor
                .GetMethodInfo()
                .GetCustomAttributes(true)
                .OfType<IAllowAnonymous>()
                .Any())
            {
                return;
            }

            await _authorizationHelper.AuthorizeAsync(context.ActionDescriptor.GetMethodInfo());
        }
    }
}

using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Extensions;
using Abp.Authorization;
using Abp.Dependency;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Abp.AspNetCore.Mvc.Authorization
{
    //TODO: Register only actions which define AbpMvcAuthorizeAttribute..?
    public class AbpAuthorizationFilter : IAsyncAuthorizationFilter, ITransientDependency
    {
        private readonly IAuthorizationHelper _authorizationHelper;

        public AbpAuthorizationFilter(IAuthorizationHelper authorizationHelper)
        {
            _authorizationHelper = authorizationHelper;
        }

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            await _authorizationHelper.AuthorizeAsync(context.ActionDescriptor.GetMethodInfo());
        }
    }
}

Check IAllowAnonymousFilter in a simpler way.


using System;
using Gtk;
using Castle.ActiveRecord.Framework.Config;
using Castle.ActiveRecord;
using HumanRightsTracker.Models;

namespace HumanRightsTracker
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			XmlConfigurationSource config = new XmlConfigurationSource("Config/ARConfig.xml");
			ActiveRecordStarter.Initialize(Models, config);

			Application.Init ();
			LoginWindow win = new LoginWindow ();
			win.Show ();
			Application.Run ();
		}
	}
}

using System;
using System.Reflection;
using Gtk;
using Castle.ActiveRecord.Framework.Config;
using Castle.ActiveRecord;
using HumanRightsTracker.Models;

namespace HumanRightsTracker
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			XmlConfigurationSource config = new XmlConfigurationSource("Config/ARConfig.xml");
			Assembly asm = Assembly.Load("Models");
			ActiveRecordStarter.Initialize(asm, config);

			Application.Init ();
			LoginWindow win = new LoginWindow ();
			win.Show ();
			Application.Run ();
		}
	}
}

Fix for initializing models from assembly.


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

using osu.Framework.Graphics;
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;

namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
    public class NoteMask : HitObjectMask
    {
        public NoteMask(DrawableNote note)
            : base(note)
        {
            Origin = Anchor.Centre;

            Position = note.Position;
            Size = note.Size;
            Scale = note.Scale;

            AddInternal(new NotePiece());

            note.HitObject.ColumnChanged += _ => Position = note.Position;
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            Colour = colours.Yellow;
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;

namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
    public class NoteMask : HitObjectMask
    {
        public NoteMask(DrawableNote note)
            : base(note)
        {
            Scale = note.Scale;

            AddInternal(new NotePiece());

            note.HitObject.ColumnChanged += _ => Position = note.Position;
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            Colour = colours.Yellow;
        }

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

            Size = HitObject.DrawSize;
            Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.BottomLeft);
        }
    }
}

Fix note masks not working

Fix note masks not working


using Autofac;
using Autofac.Integration.Mvc;
using Raven.Client;
using Raven.Client.Document;

namespace Compilify.Web.Infrastructure.DependencyInjection
{
    public class RavenDbModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register(c => new DocumentStore { ConnectionStringName = "RavenDB" }.Initialize())
                   .As<IDocumentStore>()
                   .SingleInstance();

            builder.Register(x => x.Resolve<IDocumentStore>().OpenSession())
                   .As<IDocumentSession>()
                   .InstancePerHttpRequest();

            builder.Register(x => x.Resolve<IDocumentStore>().OpenAsyncSession())
                   .As<IAsyncDocumentSession>()
                   .InstancePerHttpRequest();
        }
    }
}

using Autofac;
using Autofac.Integration.Mvc;
using Raven.Client;
using Raven.Client.Document;

namespace Compilify.Web.Infrastructure.DependencyInjection
{
    public class RavenDbModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register(c => new DocumentStore { ConnectionStringName = "RAVENHQ_CONNECTION_STRING" }.Initialize())
                   .As<IDocumentStore>()
                   .SingleInstance();

            builder.Register(x => x.Resolve<IDocumentStore>().OpenSession())
                   .As<IDocumentSession>()
                   .InstancePerHttpRequest();

            builder.Register(x => x.Resolve<IDocumentStore>().OpenAsyncSession())
                   .As<IAsyncDocumentSession>()
                   .InstancePerHttpRequest();
        }
    }
}

Update RavenDB connection string name

Update RavenDB connection string name


using System.Web.Mvc;
using SFA.DAS.EmployerUsers.WebClientComponents;

namespace SFA.DAS.EmployerUsers.Web.Controllers
{
    public class HomeController : ControllerBase
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CatchAll(string path)
        {
            return RedirectToAction("NotFound", "Error", new {path});
        }

        [AuthoriseActiveUser]
        [Route("Login")]
        public ActionResult Login()
        {
            return RedirectToAction("Index");
        }
    }
}

using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Mvc;
using Microsoft.Azure;
using SFA.DAS.EmployerUsers.WebClientComponents;

namespace SFA.DAS.EmployerUsers.Web.Controllers
{
    public class HomeController : ControllerBase
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CatchAll(string path)
        {
            return RedirectToAction("NotFound", "Error", new { path });
        }

        [AuthoriseActiveUser]
        [Route("Login")]
        public ActionResult Login()
        {
            return RedirectToAction("Index");
        }

        public ActionResult CertTest()
        {
            var certificatePath = string.Format(@"{0}\bin\DasIDPCert.pfx", AppDomain.CurrentDomain.BaseDirectory);
            var codeCert = new X509Certificate2(certificatePath, "idsrv3test");

            X509Certificate2 storeCert;
            var store = new X509Store(StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            try
            {
                var thumbprint = CloudConfigurationManager.GetSetting("TokenCertificateThumbprint");
                var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                storeCert = certificates.Count > 0 ? certificates[0] : null;

                if (storeCert == null)
                {
                    return Content($"Failed to load cert with thumbprint {thumbprint} from store");
                }
            }
            finally
            {
                store.Close();
            }

            var details = new StringBuilder();
            details.AppendLine("Code cert");
            details.AppendLine("-------------------------");
            details.AppendLine($"FriendlyName: {codeCert.FriendlyName}");
            details.AppendLine($"PublicKey: {codeCert.GetPublicKeyString()}");
            details.AppendLine($"HasPrivateKey: {codeCert.HasPrivateKey}");
            details.AppendLine($"Thumbprint: {codeCert.Thumbprint}");

            details.AppendLine();

            details.AppendLine("Store cert");
            details.AppendLine("-------------------------");
            details.AppendLine($"FriendlyName: {storeCert.FriendlyName}");
            details.AppendLine($"PublicKey: {storeCert.GetPublicKeyString()}");
            details.AppendLine($"HasPrivateKey: {storeCert.HasPrivateKey}");
            details.AppendLine($"Thumbprint: {storeCert.Thumbprint}");

            return Content(details.ToString(), "text/plain");
        }
    }
}

Add cert-test action to help diagnose issues in azure


using System;

namespace HelloServer
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
		}
	}
}

using System;
using System.Threading.Tasks;
using Grpc.Core;
using Hello;

namespace HelloServer
{
	class HelloServerImpl : HelloService.HelloServiceBase
	{
		// Server side handler of the SayHello RPC
		public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context)
		{
			return Task.FromResult(new HelloResp { Result = "Hello " + request.Name });
		}
	}

	class Program
	{
		const int Port = 50051;

		public static void Main(string[] args)
		{

			Server server = new Server
			{
				Services = { HelloService.BindService(new HelloServerImpl()) },
				Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
			};
			server.Start();

			Console.WriteLine("Greeter server listening on port " + Port);
			Console.WriteLine("Press any key to stop the server...");
			Console.ReadKey();

			server.ShutdownAsync().Wait();
		}
	}
}

Add basic hello server version

Add basic hello server version


using PluginContracts;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace LAN
{
    public class LANInterface : IPluginV1
    {
        public string Name { get; } = "LAN";

        public string Description { get; } = "LAN communication interface for oscilloscopes such as Rigol DS1054Z";

        public IPEndPoint IPEndPoint { get; set; }

        public int ReadTimeout { get; set; } = 500;

        public async Task<byte[]> SendReceiveAsync(string command)
        {
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(IPEndPoint.Address, IPEndPoint.Port);

                using (var stream = client.GetStream())
                {
                    stream.ReadTimeout = ReadTimeout;

                    var writer = new BinaryWriter(stream);
                    writer.Write(command + "\n");
                    writer.Flush();

                    using (var ms = new MemoryStream())
                    {
                        try
                        {
                            var reader = new BinaryReader(stream);

                            do
                            {
                                var value = reader.ReadByte();
                                ms.WriteByte(value);

                                while (client.Available != 0)
                                {
                                    var values = reader.ReadBytes(client.Available);
                                    ms.Write(values, 0, values.Length);
                                }
                            } while (true);
                        }
                        catch (Exception ex) when (ex.InnerException.GetType() == typeof(SocketException))
                        {
                            // ReadByte() method will eventually timeout ...
                        }

                        return ms.ToArray();
                    }
                }
            }
        }
    }
}

using PluginContracts;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace LAN
{
    public class LANInterface : IPluginV1
    {
        public string Name { get; } = "LAN";

        public string Description { get; } = "LAN communication interface for oscilloscopes such as Rigol DS1054Z";

        public IPEndPoint IPEndPoint { get; set; }

        public int ReadTimeout { get; set; } = 500;

        public async Task<byte[]> SendReceiveAsync(string command)
        {
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(IPEndPoint.Address, IPEndPoint.Port);

                using (var stream = client.GetStream())
                {
                    stream.ReadTimeout = ReadTimeout;

                    var data = Encoding.UTF8.GetBytes(command + "\n");
                    await stream.WriteAsync(data, 0, data.Length);

                    using (var ms = new MemoryStream())
                    {
                        try
                        {
                            var reader = new BinaryReader(stream);

                            do
                            {
                                var value = reader.ReadByte();
                                ms.WriteByte(value);

                                while (client.Available != 0)
                                {
                                    var values = reader.ReadBytes(client.Available);
                                    ms.Write(values, 0, values.Length);
                                }
                            } while (true);
                        }
                        catch (Exception ex) when (ex.InnerException.GetType() == typeof(SocketException))
                        {
                            // ReadByte() method will eventually timeout ...
                        }

                        return ms.ToArray();
                    }
                }
            }
        }
    }
}

Use stream writer instead of BinaryWriter


using System;
using System.IO;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Hosting;
using Newtonsoft.Json;

namespace DotVVM.Framework.ResourceManagement
{
    /// <summary>
    /// CSS in header. It's perfect for critical CSS.
    /// </summary>
    public class InlineStylesheetResource : ResourceBase
    {
        private string code;
        private readonly ILocalResourceLocation resourceLocation;

        [JsonConstructor]
        public InlineStylesheetResource(ILocalResourceLocation resourceLocation) : base(ResourceRenderPosition.Head)
        {
            this.resourceLocation = resourceLocation;
        }

        /// <inheritdoc/>
        public override void Render(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName)
        {
            if (code == null)
            {
                using (var resourceStream = resourceLocation.LoadResource(context))
                {
                    code = new StreamReader(resourceStream).ReadToEnd();
                }
            }

            if (!string.IsNullOrWhiteSpace(code))
            {
                writer.RenderBeginTag("style");
                writer.WriteUnencodedText(code);
                writer.RenderEndTag();
            }
        }
    }
}

using System;
using System.IO;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Hosting;
using Newtonsoft.Json;

namespace DotVVM.Framework.ResourceManagement
{
    /// <summary>
    /// CSS in header. It's perfect for small css. For example critical CSS.
    /// </summary>
    public class InlineStylesheetResource : ResourceBase
    {
        private string code;
        private readonly ILocalResourceLocation resourceLocation;

        [JsonConstructor]
        public InlineStylesheetResource(ILocalResourceLocation resourceLocation) : base(ResourceRenderPosition.Head)
        {
            this.resourceLocation = resourceLocation;
        }

        /// <inheritdoc/>
        public override void Render(IHtmlWriter writer, IDotvvmRequestContext context, string resourceName)
        {
            if (code == null)
            {
                using (var resourceStream = resourceLocation.LoadResource(context))
                {
                    using (var resourceStreamReader = new StreamReader(resourceStream))
                    {
                        code = resourceStreamReader.ReadToEnd();
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(code))
            {
                writer.RenderBeginTag("style");
                writer.WriteUnencodedText(code);
                writer.RenderEndTag();
            }
        }
    }
}

Put StreamReader into using blog

Put StreamReader into using blog


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace LearnosityDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace LearnosityDemo
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

[DOC] Add static to class definition because reasons.


using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace DesktopWidgets.WidgetBase.Settings
{
    public class WidgetClockSettingsBase : WidgetSettingsBase
    {
        protected WidgetClockSettingsBase()
        {
            Style.FontSettings.FontSize = 24;
        }

        [Category("General")]
        [DisplayName("Refresh Interval")]
        public int UpdateInterval { get; set; } = -1;

        [Category("Style")]
        [DisplayName("Time Format")]
        public List<string> DateTimeFormat { get; set; } = new List<string> {"{hh}:{mm} {tt}"};

        [Category("General")]
        [DisplayName("Time Offset")]
        public TimeSpan TimeOffset { get; set; }

        [Category("Behavior")]
        [DisplayName("Copy Time On Double Click")]
        public bool CopyTextOnDoubleClick { get; set; } = true;
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace DesktopWidgets.WidgetBase.Settings
{
    public class WidgetClockSettingsBase : WidgetSettingsBase
    {
        protected WidgetClockSettingsBase()
        {
            Style.FontSettings.FontSize = 24;
        }

        [Category("General")]
        [DisplayName("Update Interval")]
        public int UpdateInterval { get; set; } = -1;

        [Category("Style")]
        [DisplayName("Date/Time Format")]
        public List<string> DateTimeFormat { get; set; } = new List<string> {"{hh}:{mm} {tt}"};

        [Category("General")]
        [DisplayName("Date/Time Offset")]
        public TimeSpan TimeOffset { get; set; }

        [Category("Behavior")]
        [DisplayName("Copy Text On Double Click")]
        public bool CopyTextOnDoubleClick { get; set; } = true;
    }
}

Change some clock widget settings names

Change some clock widget settings names


using System;
using System.Collections.Generic;
using System.Net.Http;

namespace Octokit.Internal
{
    public class Request : IRequest
    {
        public Request()
        {
            Headers = new Dictionary<string, string>();
            Parameters = new Dictionary<string, string>();
            AllowAutoRedirect = true;
        }

        public object Body { get; set; }
        public Dictionary<string, string> Headers { get; private set; }
        public HttpMethod Method { get; set; }
        public Dictionary<string, string> Parameters { get; private set; }
        public Uri BaseAddress { get; set; }
        public Uri Endpoint { get; set; }
        public TimeSpan Timeout { get; set; }
        public string ContentType { get; set; }
        public bool AllowAutoRedirect { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Net.Http;

namespace Octokit.Internal
{
    public class Request : IRequest
    {
        public Request()
        {
            Headers = new Dictionary<string, string>();
            Parameters = new Dictionary<string, string>();
            AllowAutoRedirect = true;
            Timeout = TimeSpan.FromSeconds(100);
        }

        public object Body { get; set; }
        public Dictionary<string, string> Headers { get; private set; }
        public HttpMethod Method { get; set; }
        public Dictionary<string, string> Parameters { get; private set; }
        public Uri BaseAddress { get; set; }
        public Uri Endpoint { get; set; }
        public TimeSpan Timeout { get; set; }
        public string ContentType { get; set; }
        public bool AllowAutoRedirect { get; set; }
    }
}

Set default timeout to 100 seconds

Set default timeout to 100 seconds

This is the same as HttpClient.


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

namespace PROProtocol
{
    public class Language
    {
        private const string FileName = "Resources/Lang.xml";

        private Dictionary<string, string> _texts = new Dictionary<string, string>();

        public Language()
        {
            if (File.Exists(FileName))
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(FileName);
                LoadXmlDocument(xml);
            }
        }

        private void LoadXmlDocument(XmlDocument xml)
        {
            XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0];
            if (languageNode != null)
            {
                foreach (XmlElement textNode in languageNode)
                {
                    _texts.Add(textNode.GetAttribute("name"), textNode.InnerText);
                }
            }
        }

        public string GetText(string name)
        {
            return _texts[name];
        }

        public string Replace(string originalText)
        {
            if (originalText.IndexOf('$') != -1)
            {
                foreach (var text in _texts)
                {
                    originalText = originalText.Replace("$" + text.Key, text.Value);
                }
            }
            return originalText;
        }
    }
}

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

namespace PROProtocol
{
    public class Language
    {
        private class DescendingLengthComparer : IComparer<string>
        {
            public int Compare(string x, string y)
            {
                int result = y.Length.CompareTo(x.Length);
                return result != 0 ? result : x.CompareTo(y);
            }
        }

        private const string FileName = "Resources/Lang.xml";

        private SortedDictionary<string, string> _texts = new SortedDictionary<string, string>();

        public Language()
        {
            _texts = new SortedDictionary<string, string>(new DescendingLengthComparer());

            if (File.Exists(FileName))
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(FileName);
                LoadXmlDocument(xml);
            }
        }

        private void LoadXmlDocument(XmlDocument xml)
        {
            XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0];
            if (languageNode != null)
            {
                foreach (XmlElement textNode in languageNode)
                {
                    _texts.Add(textNode.GetAttribute("name"), textNode.InnerText);
                }
            }
        }

        public string GetText(string name)
        {
            return _texts[name];
        }

        public string Replace(string originalText)
        {
            if (originalText.IndexOf('$') != -1)
            {
                foreach (var text in _texts)
                {
                    originalText = originalText.Replace("$" + text.Key, text.Value);
                }
            }
            return originalText;
        }
    }
}

Sort the i18n keys by descending length Fix 'FullHP' getting overridden by 'Full'.


// 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.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;

namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
    public class ManiaSelectionBlueprint : OverlaySelectionBlueprint
    {
        public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject;

        [Resolved]
        private IScrollingInfo scrollingInfo { get; set; }

        [Resolved]
        private IManiaHitObjectComposer composer { get; set; }

        public ManiaSelectionBlueprint(DrawableHitObject drawableObject)
            : base(drawableObject)
        {
            RelativeSizeAxes = Axes.None;
        }

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

            Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero));
        }

        public override void Show()
        {
            DrawableObject.AlwaysAlive = true;
            base.Show();
        }

        public override void Hide()
        {
            DrawableObject.AlwaysAlive = false;
            base.Hide();
        }
    }
}

// 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.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;

namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
    public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint
    {
        public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject;

        [Resolved]
        private IScrollingInfo scrollingInfo { get; set; }

        [Resolved]
        private IManiaHitObjectComposer composer { get; set; }

        protected ManiaSelectionBlueprint(DrawableHitObject drawableObject)
            : base(drawableObject)
        {
            RelativeSizeAxes = Axes.None;
        }

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

            Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero));
        }

        public override void Show()
        {
            DrawableObject.AlwaysAlive = true;
            base.Show();
        }

        public override void Hide()
        {
            DrawableObject.AlwaysAlive = false;
            base.Hide();
        }
    }
}

Make mania selection blueprint abstract

Make mania selection blueprint abstract


using System;
using System.ComponentModel.Composition;
using System.Text;
using NVika.Abstractions;
using NVika.Parsers;

namespace NVika.BuildServers
{
    internal sealed class GitHub : BuildServerBase
    {
        private readonly IEnvironment _environment;

        [ImportingConstructor]
        internal GitHub(IEnvironment environment)
        {
            _environment = environment;
        }

        public override string Name => nameof(GitHub);

        public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS"));

        public override void WriteMessage(Issue issue)
        {
            var outputString = new StringBuilder();

            switch (issue.Severity)
            {
                case IssueSeverity.Error:
                    outputString.Append("::error ");
                    break;

                case IssueSeverity.Warning:
                    outputString.Append("::warning");
                    break;
            }

            if (issue.FilePath != null)
            {
                var file = issue.FilePath.Replace('\\', '/');
                outputString.Append($"file={file},");
            }

            if (issue.Offset != null)
                outputString.Append($"col={issue.Offset.Start},");

            outputString.Append($"line={issue.Line}::{issue.Message}");

            Console.WriteLine(outputString.ToString());
        }
    }
}

using System;
using System.ComponentModel.Composition;
using System.Text;
using NVika.Abstractions;
using NVika.Parsers;

namespace NVika.BuildServers
{
    internal sealed class GitHub : BuildServerBase
    {
        private readonly IEnvironment _environment;

        [ImportingConstructor]
        internal GitHub(IEnvironment environment)
        {
            _environment = environment;
        }

        public override string Name => nameof(GitHub);

        public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS"));

        public override void WriteMessage(Issue issue)
        {
            var outputString = new StringBuilder();

            switch (issue.Severity)
            {
                case IssueSeverity.Error:
                    outputString.Append("::error ");
                    break;

                case IssueSeverity.Warning:
                    outputString.Append("::warning");
                    break;
            }

            var details = issue.Message;

            if (issue.FilePath != null)
            {
                var absolutePath = issue.FilePath.Replace('\\', '/');
                var relativePath = issue.Project != null ? issue.FilePath.Replace($"{issue.Project.Replace('\\', '/')}/", string.Empty) : absolutePath;

                outputString.Append($"file={absolutePath},");
                details = $"{issue.Message} in {relativePath} on line {issue.Line}";
            }

            if (issue.Offset != null)
                outputString.Append($"col={issue.Offset.Start},");

            outputString.Append($"line={issue.Line}::{details}");

            Console.WriteLine(outputString.ToString());
        }
    }
}

Add path and line to GH console output

Add path and line to GH console output


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

namespace AppHarbor
{
	public class TypeNameMatcher<T>
	{
		private readonly IEnumerable<Type> _candidateTypes;

		public TypeNameMatcher(IEnumerable<Type> candidateTypes)
		{
			if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x)))
			{
				throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes");
			}
			_candidateTypes = candidateTypes;
		}

		public Type GetMatchedType(string commandName, string scope)
		{
			var scopedTypes = _candidateTypes.Where(x => x.Name.EndsWith(string.Concat(scope, "Command")));

			try
			{
				return scopedTypes.Single(x => x.Name.ToLower().StartsWith(commandName.ToLower()));
			}
			catch (InvalidOperationException)
			{
				throw new ArgumentException("No candidate type matches", "commandName");
			}
		}
	}
}

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

namespace AppHarbor
{
	public class TypeNameMatcher<T>
	{
		private readonly IEnumerable<Type> _candidateTypes;

		public TypeNameMatcher(IEnumerable<Type> candidateTypes)
		{
			if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x)))
			{
				throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes");
			}
			_candidateTypes = candidateTypes;
		}

		public Type GetMatchedType(string commandName, string scope)
		{
			var scopedTypes = _candidateTypes.Where(x => x.Name.EndsWith(string.Concat(scope, "Command")));

			try
			{
				return scopedTypes.Single(x => x.Name.ToLower().StartsWith(commandName.ToLower()));
			}
			catch (InvalidOperationException exception)
			{
				throw new ArgumentException("Error while matching type", "commandName", exception);
			}
		}
	}
}

Change exception message and pass innerexception to argumentexception


using System;
using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi;
using JetBrains.ReSharper.Psi;

namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.LiveTemplates.Scope
{
    public class InUnityShaderLabFile : InAnyLanguageFile, IMainScopePoint
    {
        private static readonly Guid DefaultUID = new Guid("ED25967E-EAEA-47CC-AB3C-C549C5F3F378");
        private static readonly Guid QuickUID = new Guid("1149A991-197E-468A-90E0-07700A01FBD3");

        public override Guid GetDefaultUID() => DefaultUID;
        public override PsiLanguageType RelatedLanguage => ShaderLabLanguage.Instance;
        public override string PresentableShortName => "ShaderLab (Unity)";

        protected override IEnumerable<string> GetExtensions()
        {
            yield return ShaderLabProjectFileType.SHADER_EXTENSION;
        }

        public override string ToString() => "ShaderLab (Unity)";

        public new string QuickListTitle => "Unity files";
        public new Guid QuickListUID => QuickUID;
    }
}

using System;
using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Scope;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi;
using JetBrains.ReSharper.Psi;

namespace JetBrains.ReSharper.Plugins.Unity.Feature.Services.LiveTemplates.Scope
{
    public class InUnityShaderLabFile : InAnyLanguageFile, IMainScopePoint
    {
        private static readonly Guid DefaultUID = new Guid("ED25967E-EAEA-47CC-AB3C-C549C5F3F378");
        private static readonly Guid QuickUID = new Guid("1149A991-197E-468A-90E0-07700A01FBD3");

        public override Guid GetDefaultUID() => DefaultUID;
        public override PsiLanguageType RelatedLanguage => ShaderLabLanguage.Instance;
        public override string PresentableShortName => "ShaderLab (Unity)";

        protected override IEnumerable<string> GetExtensions()
        {
            yield return ShaderLabProjectFileType.SHADERLAB_EXTENSION;
        }

        public override string ToString() => "ShaderLab (Unity)";

        public new string QuickListTitle => "Unity files";
        public new Guid QuickListUID => QuickUID;
    }
}

Fix compile issue from merge

Fix compile issue from merge


using System.Drawing;
using System.Globalization;

namespace ClosedXML.Utils
{
    internal static class ColorStringParser
    {
        public static Color ParseFromHtml(string htmlColor)
        {
            try
            {
                if (htmlColor[0] != '#')
                    htmlColor = '#' + htmlColor;

                return ColorTranslator.FromHtml(htmlColor);
            }
            catch
            {
                // https://github.com/ClosedXML/ClosedXML/issues/675
                // When regional settings list separator is # , the standard ColorTranslator.FromHtml fails
                return Color.FromArgb(int.Parse(htmlColor.Replace("#", ""), NumberStyles.AllowHexSpecifier));
            }
        }
    }
}

using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;

namespace ClosedXML.Utils
{
    internal static class ColorStringParser
    {
        public static Color ParseFromHtml(string htmlColor)
        {
            try
            {
                if (htmlColor[0] == '#' && (htmlColor.Length == 4 || htmlColor.Length == 7))
                {
                    if (htmlColor.Length == 4)
                    {
                        var r = ReadHex(htmlColor, 1, 1);
                        var g = ReadHex(htmlColor, 2, 1);
                        var b = ReadHex(htmlColor, 3, 1);
                        return Color.FromArgb(
                            (r << 4) | r,
                            (g << 4) | g,
                            (b << 4) | b);
                    }

                    return Color.FromArgb(
                        ReadHex(htmlColor, 1, 2),
                        ReadHex(htmlColor, 3, 2),
                        ReadHex(htmlColor, 5, 2));
                }

                return (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(htmlColor);
            }
            catch
            {
                // https://github.com/ClosedXML/ClosedXML/issues/675
                // When regional settings list separator is # , the standard ColorTranslator.FromHtml fails
                return Color.FromArgb(int.Parse(htmlColor.Replace("#", ""), NumberStyles.AllowHexSpecifier));
            }
        }

        private static int ReadHex(string text, int start, int length)
        {
            return Convert.ToInt32(text.Substring(start, length), 16);
        }
    }
}

Remove a dependency on System.Drawing.Common by using a compatible color parser.


using System;

namespace Glimpse.Agent.Web
{
    public interface IIgnoredRequestPolicy
    {
        bool ShouldIgnore(IContext context);
    }
}

using System;
using Glimpse.Web;

namespace Glimpse.Agent.Web
{
    public interface IIgnoredRequestPolicy
    {
        bool ShouldIgnore(IHttpContext context);
    }
}

Update context that is passed through

Update context that is passed through


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainCamera : MonoBehaviour {

	public GameObject cursor;
	private IEnumerator currentMove;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		//this.transform.position.z = -10; //NO
	}

	public void scootTo(Vector3 endpos) {
		if (currentMove != null) {
			//if we're moving, fuck that
			StopCoroutine (currentMove);
		}
		Debug.Log ("Scoot TO:"); Debug.Log(endpos);
		currentMove = SmoothMove (this.transform.position, endpos, 5.0);
		StartCoroutine (currentMove);
	}

	IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, double seconds) {
		double t = 0.0;
		endpos.z = this.transform.position.z; //NEVER move forward or backward (Hack because we are in 2D)
		while ( t <= 1.0 ) {
			//Debug.Log ("t=" + t);
			t += Time.deltaTime/seconds;
			transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep((float) 0.0, (float) 1.0, (float) t));
			//Debug.Log (transform.position);
			yield return null; //WHY
		}
	}
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainCamera : MonoBehaviour {

	public GameObject cursor;
	private IEnumerator currentMove;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		//this.transform.position.z = -10; //NO
	}

	public void scootTo(Vector3 endpos) {
		double time = .6;
		bool skipEaseIn = false;
		if (currentMove != null) {
			//if we're moving, fuck that
			StopCoroutine (currentMove);
			skipEaseIn = true;
		}
		Debug.Log ("Scoot TO:"); Debug.Log(endpos);
		currentMove = SmoothMove (this.transform.position, endpos, time, skipEaseIn);
		StartCoroutine (currentMove);
	}

	IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, double seconds, bool skipEaseIn = false) {
		double t = 0.0;
		if (skipEaseIn) {
			//DO SOMETHING???
			//t = 0.1;
		}

		endpos.z = this.transform.position.z; //NEVER move forward or backward (Hack because we are in 2D)
		while ( t <= 1.0 ) {
			t += Time.deltaTime/seconds;
			transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep((float) 0.0, (float) 1.0, (float) t));
			yield return null; //WHY
		}
	}
}

Add scaffolding for skipping ease-in

Add scaffolding for skipping ease-in

But it doesn't work yet. So we'll see if we bother with this one.


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

using System;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;
using CalDavSynchronizer.Implementation;
using CalDavSynchronizer.Ui;

namespace CalDavSynchronizer.Contracts
{
  public class EventMappingConfiguration : MappingConfigurationBase
  {
    public ReminderMapping MapReminder { get; set; }
    public bool MapAttendees { get; set; }
    public bool MapBody { get; set; }

    public EventMappingConfiguration ()
    {
      MapReminder =  ReminderMapping.@true;
      MapAttendees = true;
      MapBody = true;
    }

    public override IConfigurationForm<MappingConfigurationBase> CreateConfigurationForm (IConfigurationFormFactory factory)
    {
      return factory.Create (this);
    }
  }
}

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

using System;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Serialization;
using CalDavSynchronizer.Implementation;
using CalDavSynchronizer.Ui;

namespace CalDavSynchronizer.Contracts
{
  public class EventMappingConfiguration : MappingConfigurationBase
  {
    public ReminderMapping MapReminder { get; set; }
    public bool MapAttendees { get; set; }
    public bool MapBody { get; set; }

    public EventMappingConfiguration ()
    {
      MapReminder = ReminderMapping.JustUpcoming;
      MapAttendees = true;
      MapBody = true;
    }

    public override IConfigurationForm<MappingConfigurationBase> CreateConfigurationForm (IConfigurationFormFactory factory)
    {
      return factory.Create (this);
    }
  }
}

Set default for Reminder mapping to 'JustUpcoming'.


using UnityEngine;
using System.Collections;

public class GUIBehavior : MonoBehaviour {

	public Texture barTexture;
	public wolf wolfData;
	public int boxWidth = 34;
	public int boxHeight = 30;

	void OnGUI () {
		//Print the bar
		GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture);

		//Print the box
		GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), "");
	}

}

using UnityEngine;
using System.Collections;

public class GUIBehavior : MonoBehaviour {

	public Texture barTexture;
	public wolf wolfData;
	public int boxWidth = 34;
	public int boxHeight = 30;

	void OnGUI () {
		//Print the bar
		GUI.Box (new Rect(Screen.width - barTexture.width - 18,10,barTexture.width + 8, barTexture.height + 8),barTexture);

		//Print the box
		GUI.Box (new Rect(Screen.width - barTexture.width / 2 - 14 - boxWidth / 2 , 8f + .97f * barTexture.height * (100f - wolfData.GetTemp()) / 100f,boxWidth,boxHeight), "");
	}

	void Update () {

		if(Input.GetKey ("t")) {
			// TRIGGER THE WIN SCENE
			print ("STUFF");
		}

		else if (Input.GetKey ("g")) {

			// TRIGGER THE LOSE SCENE
			print ("LOSE");

		}
	}

}

Add Win/Lose Scene Transition Hooks

Add Win/Lose Scene Transition Hooks