using System;
using System.Web.Mvc;

namespace NuGetGallery
{
    public class HttpHeaderValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            var request = controllerContext.RequestContext.HttpContext.Request;

            // Use this value provider only if a route is located under "API"
            if (request.Path.Contains("/api/"))
                return new HttpHeaderValueProvider(request, "ApiKey");
            return null;
        }
    }
}

using System;
using System.Web.Mvc;

namespace NuGetGallery
{
    public class HttpHeaderValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            var request = controllerContext.RequestContext.HttpContext.Request;

            // Use this value provider only if a route is located under "API"
            if (request.Path.TrimStart('/').StartsWith("api", StringComparison.OrdinalIgnoreCase))
                return new HttpHeaderValueProvider(request, "ApiKey");
            return null;
        }
    }
}

Revert "Fix issue with API header binding when running under a subdirectory"

This reverts commit d9e86ff97a08467c721955ca71a8ee2fda5ca9cd.


namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing
{
    using System;
#if !NET40
    using System.Diagnostics.Tracing;
#endif
    using System.Linq;
#if NET40
    using Microsoft.Diagnostics.Tracing;
#endif

    internal class DiagnosticsEventListener : EventListener
    {
        private const long AllKeyword = -1;
        private readonly EventLevel logLevel;
        private readonly DiagnosticsListener listener;

        public DiagnosticsEventListener(DiagnosticsListener listener, EventLevel logLevel)
        {
            this.listener = listener;
            this.logLevel = logLevel;
        }

        protected override void OnEventWritten(EventWrittenEventArgs eventSourceEvent)
        {
            var metadata = new EventMetaData
            {
                Keywords = (long)eventSourceEvent.Keywords,
                MessageFormat = eventSourceEvent.Message,
                EventId = eventSourceEvent.EventId,
                Level = eventSourceEvent.Level
            };

            var traceEvent = new TraceEvent
            {
                MetaData = metadata,
                Payload = eventSourceEvent.Payload != null ? eventSourceEvent.Payload.ToArray() : null
            };

            this.listener.WriteEvent(traceEvent);
        }

        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            if (eventSource.Name.StartsWith("Microsoft-ApplicationInsights-", StringComparison.Ordinal))
            {
                this.EnableEvents(eventSource, this.logLevel, (EventKeywords)AllKeyword);
            }

            base.OnEventSourceCreated(eventSource);
        }
    }
}

namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing
{
    using System;
#if !NET40
    using System.Diagnostics.Tracing;
#endif
    using System.Linq;
#if NET40
    using Microsoft.Diagnostics.Tracing;
#endif

    internal class DiagnosticsEventListener : EventListener
    {
        private const long AllKeyword = -1;
        private readonly EventLevel logLevel;
        private readonly DiagnosticsListener listener;

        public DiagnosticsEventListener(DiagnosticsListener listener, EventLevel logLevel)
        {
            this.listener = listener;
            this.logLevel = logLevel;
        }

        protected override void OnEventWritten(EventWrittenEventArgs eventSourceEvent)
        {
            if (eventSourceEvent == null)
            {
                return;
            }

            var metadata = new EventMetaData
            {
                Keywords = (long)eventSourceEvent.Keywords,
                MessageFormat = eventSourceEvent.Message,
                EventId = eventSourceEvent.EventId,
                Level = eventSourceEvent.Level
            };

            var traceEvent = new TraceEvent
            {
                MetaData = metadata,
                Payload = eventSourceEvent.Payload != null ? eventSourceEvent.Payload.ToArray() : null
            };

            this.listener.WriteEvent(traceEvent);
        }

        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            if (eventSource.Name.StartsWith("Microsoft-ApplicationInsights-", StringComparison.Ordinal))
            {
                this.EnableEvents(eventSource, this.logLevel, (EventKeywords)AllKeyword);
            }

            base.OnEventSourceCreated(eventSource);
        }
    }
}

Check if eventargs is null

Check if eventargs is null


//  Copyright (C) 2017, The Duplicati Team
//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library 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
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

namespace Duplicati.Library.Utility.Power
{
    public static class PowerSupply
    {
        public enum Source
        {
            AC,
            Battery,
            Unknown
        }
    }
}

//  Copyright (C) 2017, The Duplicati Team
//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library 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
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

namespace Duplicati.Library.Utility.Power
{
    public static class PowerSupply
    {
        public enum Source
        {
            AC,
            Battery,
            Unknown
        }

        public static Source GetSource()
        {
            IPowerSupplyState state;

            // Since IsClientLinux returns true when on Mac OS X, we need to check IsClientOSX first.
            if (Utility.IsClientOSX)
            {
                state = new DefaultPowerSupplyState();
            }
            else if (Utility.IsClientLinux)
            {
                state = new LinuxPowerSupplyState();
            }
            else
            {
                state = new DefaultPowerSupplyState();
            }

            return state.GetSource();
        }
    }
}

Add method to get current power source.

Add method to get current power source.


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

namespace com.techphernalia.MyPersonalAccounts.Model.Inventory
{
    public class StockItem
    {
        public int StockItemId { get; set; }
        public string StockItemName { get; set; }
        public int StockGroupId { get; set; }
        public int StockUnitId { get; set; }
        public decimal OpeningBalance { get; set; }
        public decimal OpeningRate { get; set; }
    }
}

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

namespace com.techphernalia.MyPersonalAccounts.Model.Inventory
{
    public class StockItem
    {
        public int StockItemId { get; set; }
        public string StockItemName { get; set; }
        public int StockGroupId { get; set; }
        public int StockUnitId { get; set; }
        public double OpeningBalance { get; set; }
        public double OpeningRate { get; set; }
    }
}

Change datatype for OpeningBalance and OpeningRate


using Foundatio.Repositories.Models;

namespace Exceptionless.Web.Models;

public class ViewToken : IIdentity, IHaveDates {
    public string Id { get; set; }
    public string OrganizationId { get; set; }
    public string ProjectId { get; set; }
    public string UserId { get; set; }
    public string DefaultProjectId { get; set; }
    public HashSet<string> Scopes { get; set; }
    public DateTime? ExpiresUtc { get; set; }
    public string Notes { get; set; }
    public bool IsDisabled { get; set; }
    public DateTime CreatedUtc { get; set; }
    public DateTime UpdatedUtc { get; set; }
}

using Foundatio.Repositories.Models;

namespace Exceptionless.Web.Models;

public class ViewToken : IIdentity, IHaveDates {
    public string Id { get; set; }
    public string OrganizationId { get; set; }
    public string ProjectId { get; set; }
    public string UserId { get; set; }
    public string DefaultProjectId { get; set; }
    public HashSet<string> Scopes { get; set; }
    public DateTime? ExpiresUtc { get; set; }
    public string Notes { get; set; }
    public bool IsDisabled { get; set; }
    public bool IsSuspended { get; set; }
    public DateTime CreatedUtc { get; set; }
    public DateTime UpdatedUtc { get; set; }
}

Add token issuspended to view model

Add token issuspended to view model


using System;
using Newtonsoft.Json;
using Oocx.ACME.Jose;
using Oocx.ACME.Protocol;
using Xunit;

namespace Oocx.ACME.Tests
{
    public class RegistrationTests
    {
        [Fact]
        public void Can_serialize()
        {
            var request = new NewRegistrationRequest
            {
                Contact = new[]
                {
                    "mailto:cert-admin@example.com",
                    "tel:+12025551212"
                },
                Key = new JsonWebKey
                {
                    Algorithm = "none"
                },
                Agreement = "https://example.com/acme/terms",
                Authorizations = "https://example.com/acme/reg/1/authz",
                Certificates = "https://example.com/acme/reg/1/cert",

            };

            var json = JsonConvert.SerializeObject(request, Formatting.Indented, new JsonSerializerSettings {
                DefaultValueHandling = DefaultValueHandling.Ignore
            });

            Assert.Equal(@"{
  ""resource"": ""new-reg"",
  ""jwk"": {
    ""alg"": ""none""
  },
  ""contact"": [
    ""mailto:cert-admin@example.com"",
    ""tel:+12025551212""
  ],
  ""agreement"": ""https://example.com/acme/terms"",
  ""authorizations"": ""https://example.com/acme/reg/1/authz"",
  ""certificates"": ""https://example.com/acme/reg/1/cert""
}", json);

        }
    }
}

using System;
using Newtonsoft.Json;
using Oocx.ACME.Jose;
using Oocx.ACME.Protocol;
using Xunit;

namespace Oocx.ACME.Tests
{
    public class RegistrationTests
    {
        [Fact]
        public void Can_serialize()
        {
            var request = new NewRegistrationRequest
            {
                Contact = new[]
                {
                    "mailto:cert-admin@example.com",
                    "tel:+12025551212"
                },
                Key = new JsonWebKey
                {
                    Algorithm = "none"
                },
                Agreement = "https://example.com/acme/terms",
                Authorizations = "https://example.com/acme/reg/1/authz",
                Certificates = "https://example.com/acme/reg/1/cert",

            };

            var json = JsonConvert.SerializeObject(request, Formatting.Indented, new JsonSerializerSettings {
                DefaultValueHandling = DefaultValueHandling.Ignore
            });

            Assert.Equal(@"{
  ""resource"": ""new-reg"",
  ""jwk"": {
    ""alg"": ""none""
  },
  ""contact"": [
    ""mailto:cert-admin@example.com"",
    ""tel:+12025551212""
  ],
  ""agreement"": ""https://example.com/acme/terms"",
  ""authorizations"": ""https://example.com/acme/reg/1/authz"",
  ""certificates"": ""https://example.com/acme/reg/1/cert""
}".Replace("\r\n", "\n"), json.Replace("\r\n", "\n"));

        }
    }
}

Fix failing test on Linux

Fix failing test on Linux


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.I2c;

namespace AM2320Demo
{
    public struct AM2320Data
    {
        public double Temperature;
        public double Humidity;
    }

    public class AM2320 : IDisposable
    {
        private I2cDevice sensor;

        private const byte AM2320_ADDR = 0x5C;

        /// <summary>
        /// Initialize
        /// </summary>
        public async Task InitializeAsync()
        {
            var settings = new I2cConnectionSettings(AM2320_ADDR);
            settings.BusSpeed = I2cBusSpeed.StandardMode;

            var controller = await I2cController.GetDefaultAsync();
            sensor = controller.GetDevice(settings);
        }

        public AM2320Data Read()
        {
            byte[] readBuf = new byte[4];

            sensor.WriteRead(new byte[] { 0x03, 0x00, 0x04 }, readBuf);

            double rawH = BitConverter.ToInt16(readBuf, 0);
            double rawT = BitConverter.ToInt16(readBuf, 2);

            AM2320Data data = new AM2320Data
            {
                Temperature = rawT / 10.0,
                Humidity = rawH / 10.0
            };

            return data;
        }

        public void Dispose()
        {
            sensor.Dispose();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.I2c;

namespace AM2320Demo
{
    public struct AM2320Data
    {
        public double Temperature;
        public double Humidity;
    }

    public class AM2320 : IDisposable
    {
        private I2cDevice sensor;

        private const byte AM2320_ADDR = 0x5C;

        /// <summary>
        /// Initialize
        /// </summary>
        public async Task InitializeAsync()
        {
            var settings = new I2cConnectionSettings(AM2320_ADDR);
            settings.BusSpeed = I2cBusSpeed.StandardMode;

            var controller = await I2cController.GetDefaultAsync();
            sensor = controller.GetDevice(settings);
        }

        public AM2320Data Read()
        {
            byte[] readBuf = new byte[4];

            sensor.WriteRead(new byte[] { 0x03, 0x00, 0x04 }, readBuf);

            double rawH = BitConverter.ToInt16(readBuf, 0);
            double rawT = BitConverter.ToInt16(readBuf, 2);

            AM2320Data data = new AM2320Data
            {
                Temperature = rawT / 10.0,
                Humidity = rawH / 10.0
            };

            return data;
        }

        public I2cDevice GetDevice()
        {
            return sensor;
        }

        public void Dispose()
        {
            sensor.Dispose();
        }
    }
}

Add Method to Get Device

Add Method to Get Device


using System;
using System.Collections.Generic;
using GitVersion.Logging;
using GitVersion.OutputVariables;

namespace GitVersion
{
    public abstract class BuildAgentBase : ICurrentBuildAgent
    {
        protected readonly ILog Log;
        protected IEnvironment Environment { get; }

        protected BuildAgentBase(IEnvironment environment, ILog log)
        {
            Log = log;
            Environment = environment;
        }

        protected abstract string EnvironmentVariable { get; }

        public abstract string GenerateSetVersionMessage(VersionVariables variables);
        public abstract string[] GenerateSetParameterMessage(string name, string value);

        public virtual bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable));

        public virtual string GetCurrentBranch(bool usingDynamicRepos) => null;

        public virtual bool PreventFetch() => true;
        public virtual bool ShouldCleanUpRemotes() => false;

        public virtual void WriteIntegration(Action<string> writer, VersionVariables variables, bool updateBuildNumber = true)
        {
            if (writer == null || !updateBuildNumber)
            {
                return;
            }

            writer($"Executing GenerateSetVersionMessage for '{GetType().Name}'.");
            writer(GenerateSetVersionMessage(variables));
            writer($"Executing GenerateBuildLogOutput for '{GetType().Name}'.");
            foreach (var buildParameter in GenerateBuildLogOutput(variables))
            {
                writer(buildParameter);
            }
        }

        protected IEnumerable<string> GenerateBuildLogOutput(VersionVariables variables)
        {
            var output = new List<string>();

            foreach (var variable in variables)
            {
                output.AddRange(GenerateSetParameterMessage(variable.Key, variable.Value));
            }

            return output;
        }
    }
}

using System;
using System.Collections.Generic;
using GitVersion.Logging;
using GitVersion.OutputVariables;

namespace GitVersion
{
    public abstract class BuildAgentBase : ICurrentBuildAgent
    {
        protected readonly ILog Log;
        protected IEnvironment Environment { get; }

        protected BuildAgentBase(IEnvironment environment, ILog log)
        {
            Log = log;
            Environment = environment;
        }

        protected abstract string EnvironmentVariable { get; }

        public abstract string GenerateSetVersionMessage(VersionVariables variables);
        public abstract string[] GenerateSetParameterMessage(string name, string value);

        public virtual bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable));

        public virtual string GetCurrentBranch(bool usingDynamicRepos) => null;

        public virtual bool PreventFetch() => true;
        public virtual bool ShouldCleanUpRemotes() => false;

        public virtual void WriteIntegration(Action<string> writer, VersionVariables variables, bool updateBuildNumber = true)
        {
            if (writer == null)
            {
                return;
            }

            if (updateBuildNumber)
            {
                writer($"Executing GenerateSetVersionMessage for '{GetType().Name}'.");
                writer(GenerateSetVersionMessage(variables));
            }
            writer($"Executing GenerateBuildLogOutput for '{GetType().Name}'.");
            foreach (var buildParameter in GenerateBuildLogOutput(variables))
            {
                writer(buildParameter);
            }
        }

        protected IEnumerable<string> GenerateBuildLogOutput(VersionVariables variables)
        {
            var output = new List<string>();

            foreach (var variable in variables)
            {
                output.AddRange(GenerateSetParameterMessage(variable.Key, variable.Value));
            }

            return output;
        }
    }
}

Fix for the wrong updateBuildNumber behavior

When `updateBuildNumber` is set to false the Build Number is still be overwritten.


using System;

namespace FluentConsole.Library
{
    /// <summary>
    /// Optionial configuration for FluentConsole
    /// </summary>
    public class FluentConsoleSettings
    {
        /// <summary>
        /// Gets or sets a value indicating how long lines of text should be displayed in the console window.
        /// </summary>
        public static LineWrapOption LineWrapOption { get; set; } = LineWrapOption.Auto;

        /// <summary>
        /// Gets or sets the line width used for wrapping long lines of text. Note: This value is ignored
        /// unless 'LineWrapOption' is set to 'Manual'. The default width is the value of the
        /// 'Console.BufferWidth' property.
        /// </summary>
        public static int LineWrapWidth { get; set; } = ConsoleWrapper.BufferWidth;

    }
}

using System;

namespace FluentConsole.Library
{
    /// <summary>
    /// Optionial configuration for FluentConsole
    /// </summary>
    public class FluentConsoleSettings
    {
        /// <summary>
        /// Gets or sets a value indicating how long lines of text should be displayed in the console window.
        /// </summary>
        public static LineWrapOption LineWrapOption { get; set; } = LineWrapOption.Auto;

        /// <summary>
        /// Gets or sets the line width used for wrapping long lines of text. Note: This value is ignored
        /// unless 'LineWrapOption' is set to 'Manual'. The default width is the value of the
        /// 'Console.BufferWidth' property.
        /// </summary>
        public static int LineWrapWidth { get; set; } = ConsoleWrapper.BufferWidth;

        /// <summary>
        /// Gets or sets the delimter used when wrapping long lines of text. The default is a space character. Note: This value is ignored if
        /// 'LineWrapOption' is set to 'Off'.
        /// </summary>
        public static char WordDelimiter { get; set; } = ' ';
    }
}

Allow word boundary delimiter to be set by user


using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace ConsoleWritePrettyOneDay
{
    public static class Spinner
    {
        private static char[] _chars = new[] { '|', '/', '-', '\\', '|', '/', '-', '\\' };

        public static void Wait(Action action, string message = null)
        {
            Wait(Task.Run(action), message);
        }

        public static void Wait(Task task, string message = null)
        {
            WaitAsync(task, message).Wait();
        }

        public static async Task WaitAsync(Task task, string message = null)
        {
            int index = 0;
            int max = _chars.Length;

            if (!string.IsNullOrWhiteSpace(message) && !message.EndsWith(" "))
            {
                message += " ";
            }

            var timer = new Stopwatch();
            timer.Start();
            while (!task.IsCompleted)
            {
                await Task.Delay(35);
                index = ++index % max;
                Console.Write($"\r{message}{_chars[index]}");
            }
            timer.Stop();
            Console.WriteLine($"\r{message}[{(timer.ElapsedMilliseconds / 1000m).ToString("0.0##")}s]");
        }
    }
}

using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace ConsoleWritePrettyOneDay
{
    public static class Spinner
    {
        private static char[] _chars = new[] { '|', '/', '-', '\\', '|', '/', '-', '\\' };

        /// <summary>
        /// Displays a spinner while the provided <paramref name="action"/> is performed.
        /// If provided, <paramref name="message"/> will be displayed along with the elapsed time in milliseconds.
        /// </summary>
        public static void Wait(Action action, string message = null)
        {
            Wait(Task.Run(action), message);
        }

        /// <summary>
        /// Displays a spinner while the provided <paramref name="task"/> is executed.
        /// If provided, <paramref name="message"/> will be displayed along with the elapsed time in milliseconds.
        /// </summary>
        public static void Wait(Task task, string message = null)
        {
            WaitAsync(task, message).Wait();
        }

        /// <summary>
        /// Displays a spinner while the provided <paramref name="task"/> is executed.
        /// If provided, <paramref name="message"/> will be displayed along with the elapsed time in milliseconds.
        /// </summary>
        /// <returns></returns>
        public static async Task WaitAsync(Task task, string message = null)
        {
            int index = 0;
            int max = _chars.Length;

            if (!string.IsNullOrWhiteSpace(message) && !message.EndsWith(" "))
            {
                message += " ";
            }

            var timer = new Stopwatch();
            timer.Start();
            while (!task.IsCompleted)
            {
                await Task.Delay(35);
                index = ++index % max;
                Console.Write($"\r{message}{_chars[index]}");
            }
            timer.Stop();
            Console.WriteLine($"\r{message}[{(timer.ElapsedMilliseconds / 1000m).ToString("0.0##")}s]");
        }
    }
}

Add comments to public methods

Add comments to public methods


//=================================================================================================
// Copyright 2013-2016 Dirk Lemstra <https://magick.codeplex.com/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   http://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//=================================================================================================

using System.Collections.Generic;

namespace ImageMagick
{
  internal sealed partial class PointInfoCollection
  {
    private PointInfoCollection(int count)
    {
      _NativeInstance = new NativePointInfoCollection(count);
      Count = count;
    }

    public PointInfoCollection(IList<PointD> coordinates)
      : this(coordinates.Count)
    {
      for (int i = 0; i < coordinates.Count; i++)
      {
        PointD point = coordinates[i];
        _NativeInstance.Set(i, point.X, point.Y);
      }
    }

    public int Count
    {
      get;
      private set;
    }

    public void Dispose()
    {
      if (_NativeInstance != null)
        _NativeInstance.Dispose();
    }
  }
}

//=================================================================================================
// Copyright 2013-2016 Dirk Lemstra <https://magick.codeplex.com/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
//   http://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//=================================================================================================

using System.Collections.Generic;
using System.Diagnostics;

namespace ImageMagick
{
  internal sealed partial class PointInfoCollection
  {
    private PointInfoCollection(int count)
    {
      _NativeInstance = new NativePointInfoCollection(count);
      Count = count;
    }

    public PointInfoCollection(IList<PointD> coordinates)
      : this(coordinates.Count)
    {
      for (int i = 0; i < coordinates.Count; i++)
      {
        PointD point = coordinates[i];
        _NativeInstance.Set(i, point.X, point.Y);
      }
    }

    public int Count
    {
      get;
      private set;
    }

    public void Dispose()
    {
      Debug.Assert(_NativeInstance != null);
      _NativeInstance.Dispose();
    }
  }
}

Use Assert instead of null check because this class is internal.


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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace Urho3DNet
{
    [System.Security.SuppressUnmanagedCodeSecurity]
    public partial class Urho3D
    {
        [DllImport("libUrho3D", EntryPoint="Urho3D_ParseArguments")]
        public static extern void ParseArguments(int argc,
            [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)]string[] argv);
    }
}

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace Urho3DNet
{
    [System.Security.SuppressUnmanagedCodeSecurity]
    public partial class Urho3D
    {
        [DllImport("Urho3D", EntryPoint="Urho3D_ParseArguments")]
        public static extern void ParseArguments(int argc,
            [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)]string[] argv);
    }
}

CSharp: Fix dllimport inconsistency and possibly being broken on windows.


using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;

namespace Avalonia.Xaml.Interactions.Custom;

/// <summary>
/// A behavior that allows to show control on double tapped event.
/// </summary>
public class ShowOnDoubleTappedBehavior : Behavior<Control>
{
    /// <summary>
    /// Identifies the <seealso cref="TargetControl"/> avalonia property.
    /// </summary>
    public static readonly StyledProperty<Control?> TargetControlProperty =
        AvaloniaProperty.Register<ShowOnDoubleTappedBehavior, Control?>(nameof(TargetControl));

    /// <summary>
    /// Gets or sets the target control. This is a avalonia property.
    /// </summary>
    public Control? TargetControl
    {
        get => GetValue(TargetControlProperty);
        set => SetValue(TargetControlProperty, value);
    }

    /// <inheritdoc />
    protected override void OnAttachedToVisualTree()
    {
        AssociatedObject?.AddHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped, RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
    }

    /// <inheritdoc />
    protected override void OnDetachedFromVisualTree()
    {
        AssociatedObject?.RemoveHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped);
    }

    private void AssociatedObject_DoubleTapped(object? sender, RoutedEventArgs e)
    {
        if (TargetControl is { IsVisible: false })
        {
            TargetControl.IsVisible = true;
            TargetControl.Focus();
        }
    }
}

using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;

namespace Avalonia.Xaml.Interactions.Custom;

/// <summary>
/// A behavior that allows to show control on double tapped event.
/// </summary>
public class ShowOnDoubleTappedBehavior : Behavior<Control>
{
    /// <summary>
    /// Identifies the <seealso cref="TargetControl"/> avalonia property.
    /// </summary>
    public static readonly StyledProperty<Control?> TargetControlProperty =
        AvaloniaProperty.Register<ShowOnDoubleTappedBehavior, Control?>(nameof(TargetControl));

    /// <summary>
    /// Gets or sets the target control. This is a avalonia property.
    /// </summary>
    [ResolveByName]
    public Control? TargetControl
    {
        get => GetValue(TargetControlProperty);
        set => SetValue(TargetControlProperty, value);
    }

    /// <inheritdoc />
    protected override void OnAttachedToVisualTree()
    {
        AssociatedObject?.AddHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped, RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
    }

    /// <inheritdoc />
    protected override void OnDetachedFromVisualTree()
    {
        AssociatedObject?.RemoveHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped);
    }

    private void AssociatedObject_DoubleTapped(object? sender, RoutedEventArgs e)
    {
        if (TargetControl is { IsVisible: false })
        {
            TargetControl.IsVisible = true;
            TargetControl.Focus();
        }
    }
}

Add ResolveByName attribute to TargetControl property


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;

namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
    public class GlowPiece : Container
    {
        public GlowPiece()
        {
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
            RelativeSizeAxes = Axes.Both;
        }

        [BackgroundDependencyLoader]
        private void load(TextureStore textures)
        {
            Child = new Sprite
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Texture = textures.Get("ring-glow"),
                Blending = BlendingParameters.Additive,
                Alpha = 0.5f
            };
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;

namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
    public class GlowPiece : Container
    {
        public GlowPiece()
        {
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
            RelativeSizeAxes = Axes.Both;
        }

        [BackgroundDependencyLoader]
        private void load(TextureStore textures)
        {
            Child = new Sprite
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Texture = textures.Get("Gameplay/osu/ring-glow"),
                Blending = BlendingParameters.Additive,
                Alpha = 0.5f
            };
        }
    }
}

Fix ring glow lookup being incorrect

Fix ring glow lookup being incorrect


using System;

namespace XamarinLifeGameXAML.Logic
{
    public class CellUtils
    {
        public static int GetIndex(Tuple<int, int> point)
        {
            return GetIndex(point.Item1, point.Item2);
        }

        public static int GetIndex(int x, int y)
        {
            return (y + x * CellSize);
        }

        public static Tuple<int, int> GetPoint(int index)
        {
            var y = index % CellSize;
            var x = (index - y) / CellSize;

            return Tuple.Create(x, y);
        }

        public static int CellSize => 9;

        public static int ArraySize => CellSize * CellSize;
    }
}

using System;

namespace XamarinLifeGameXAML.Logic
{
    public class CellUtils
    {
        public static int GetIndex(Tuple<int, int> point)
        {
            return GetIndex(point.Item1, point.Item2);
        }

        public static int GetIndex(int x, int y)
        {
            return (y + x * CellSize);
        }

        public static Tuple<int, int> GetPoint(int index)
        {
            var y = index % CellSize;
            var x = (index - y) / CellSize;

            return Tuple.Create(x, y);
        }

        public static int CellSize => 7;

        public static int ArraySize => CellSize * CellSize;
    }
}

Change number of cells. ( 9 => 7 )

Change number of cells. ( 9 => 7 )


namespace Iterator.Performance.Tests.NotConst
{
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Attributes.Columns;
    using RangeIt.Iterators;
    using System;
    using System.Collections;

    [MinColumn, MaxColumn]
    public class ArrayList_Iterator_Vs_Enumerator_Tests
    {
        private readonly ArrayList _arrayListInts = new ArrayList();
        private readonly ArrayList _arrayListStrings = new ArrayList();
        private readonly Random _random = new Random();

        [Setup]
        public void Setup()
        {
            var max = Constants.MAX_ITEMS;

            for (int i = 0; i < max; i++)
                _arrayListInts.Add(_random.Next(max));

            for (int i = 0; i < max; i++)
                _arrayListStrings.Add(_random.Next(max).ToString());
        }

        [Benchmark]
        public void ArrayList_Integer_Iterator()
        {
            var it = _arrayListInts.ConstBegin();
            while (it++) { }
        }

        [Benchmark]
        public void ArrayList_Integer_Enumerator()
        {
            foreach (var i in _arrayListInts) { }
        }

        [Benchmark]
        public void ArrayList_String_Iterator()
        {
            var it = _arrayListStrings.ConstBegin();
            while (it++) { }
        }

        [Benchmark]
        public void ArrayList_String_Enumerator()
        {
            foreach (var s in _arrayListStrings) { }
        }
    }
}

namespace Iterator.Performance.Tests.NotConst
{
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Attributes.Columns;
    using RangeIt.Iterators;
    using System;
    using System.Collections;

    [MinColumn, MaxColumn]
    public class ArrayList_Iterator_Vs_Enumerator_Tests
    {
        private readonly ArrayList _arrayListInts = new ArrayList();
        private readonly ArrayList _arrayListStrings = new ArrayList();
        private readonly Random _random = new Random();

        [Setup]
        public void Setup()
        {
            var max = Constants.MAX_ITEMS;

            for (int i = 0; i < max; i++)
                _arrayListInts.Add(_random.Next(max));

            for (int i = 0; i < max; i++)
                _arrayListStrings.Add(_random.Next(max).ToString());
        }

        [Benchmark]
        public void ArrayList_Integer_Iterator()
        {
            var it = _arrayListInts.Begin();
            while (it++) { }
        }

        [Benchmark]
        public void ArrayList_Integer_Enumerator()
        {
            foreach (var i in _arrayListInts) { }
        }

        [Benchmark]
        public void ArrayList_String_Iterator()
        {
            var it = _arrayListStrings.Begin();
            while (it++) { }
        }

        [Benchmark]
        public void ArrayList_String_Enumerator()
        {
            foreach (var s in _arrayListStrings) { }
        }
    }
}

Fix benchmark for arraylist iterator

Fix benchmark for arraylist iterator


using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;

namespace SolidworksAddinFramework
{
    public static class DisposableExtensions
    {
        public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
        {
            return new CompositeDisposable(d);
        }

        public static void DisposeWith(this IDisposable disposable, CompositeDisposable container)
        {
            container.Add(disposable);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;

namespace SolidworksAddinFramework
{
    public static class DisposableExtensions
    {
        public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
        {
            return new CompositeDisposable(d);
        }

        public static T DisposeWith<T>(this T disposable, CompositeDisposable container)
            where T : IDisposable
        {
            container.Add(disposable);
            return disposable;
        }
    }
}

Return added disposable from `DisposeWith`


using System.Collections.Generic;

namespace Ploeh.AutoFixture.Xunit
{
    internal class CustomizeAttributeComparer : Comparer<CustomizeAttribute>
    {
        public override int Compare(CustomizeAttribute x, CustomizeAttribute y)
        {
            if (x is FrozenAttribute && !(y is FrozenAttribute))
            {
                return 1;
            }

            if (y is FrozenAttribute && !(x is FrozenAttribute))
            {
                return -1;
            }

            return 0;
        }
    }
}

using System.Collections.Generic;

namespace Ploeh.AutoFixture.Xunit
{
    internal class CustomizeAttributeComparer : Comparer<CustomizeAttribute>
    {
        public override int Compare(CustomizeAttribute x, CustomizeAttribute y)
        {
            var xfrozen = x is FrozenAttribute;
            var yfrozen = y is FrozenAttribute;

            if (xfrozen && !yfrozen)
            {
                return 1;
            }

            if (yfrozen && !xfrozen)
            {
                return -1;
            }

            return 0;
        }
    }
}

Introduce variables to avoid multiple type casting


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TOTD.Mailer.Html")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCulture("")]

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

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TOTD.Mailer.Templates")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCulture("")]

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

Fix project name in assembly info

Fix project name in assembly info


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

namespace Consul.Test
{
    [TestClass]
    public class CoordinateTest
    {
        [TestMethod]
        public void TestCoordinate_Datacenters()
        {
            var client = new Client();

            var datacenters = client.Coordinate.Datacenters();

            Assert.IsNotNull(datacenters.Response);
            Assert.IsTrue(datacenters.Response.Length > 0);
        }

        [TestMethod]
        public void TestCoordinate_Nodes()
        {
            var client = new Client();

            var nodes = client.Coordinate.Nodes();

            Assert.IsNotNull(nodes.Response);
            Assert.IsTrue(nodes.Response.Length > 0);
        }
    }
}

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

namespace Consul.Test
{
    [TestClass]
    public class CoordinateTest
    {
        [TestMethod]
        public void TestCoordinate_Datacenters()
        {
            var client = new Client();

            var info = client.Agent.Self();

            if (!info.Response.ContainsKey("Coord"))
            {
                Assert.Inconclusive("This version of Consul does not support the coordinate API");
            }

            var datacenters = client.Coordinate.Datacenters();

            Assert.IsNotNull(datacenters.Response);
            Assert.IsTrue(datacenters.Response.Length > 0);
        }

        [TestMethod]
        public void TestCoordinate_Nodes()
        {
            var client = new Client();

            var info = client.Agent.Self();

            if (!info.Response.ContainsKey("Coord"))
            {
                Assert.Inconclusive("This version of Consul does not support the coordinate API");
            }

            var nodes = client.Coordinate.Nodes();

            Assert.IsNotNull(nodes.Response);
            Assert.IsTrue(nodes.Response.Length > 0);
        }
    }
}

Add test skipping for 0.5.2

Add test skipping for 0.5.2


// XMLDataSaver.cs
// <copyright file="XMLDataSaver.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace Todo_List
{
    /// <summary>
    /// A static class for reading and writing to XML files.
    /// </summary>
    public static class XMLDataSaver
    {
        /// <summary>
        /// Reads the xml file of information from the save location.
        /// </summary>
        public static void ReadXMLFile()
        {
        }

        /// <summary>
        /// Saves the xml file of information to the save location.
        /// </summary>
        public static void SaveXMLFile()
        {
        }
    }
}

// XMLDataSaver.cs
// <copyright file="XMLDataSaver.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace Todo_List
{
    /// <summary>
    /// A static class for reading and writing to XML files.
    /// </summary>
    public static class XMLDataSaver
    {
        /// <summary>
        /// Reads the xml file of information from the save location.
        /// </summary>
        public static void ReadXMLFile()
        {
            try
            {
                using (TextReader tr = new StreamReader("TodoListData.xml"))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(List<Note>));
                    NoteSorter.Notes = (List<Note>)xs.Deserialize(tr);
                }
            }
            catch (FileNotFoundException)
            {
                // File not found so don't read anything
            }
        }

        /// <summary>
        /// Saves the xml file of information to the save location.
        /// </summary>
        public static void SaveXMLFile()
        {
            using (TextWriter tw = new StreamWriter("TodoListData.xml"))
            {
                XmlSerializer xs = new XmlSerializer(typeof(List<Note>));
                xs.Serialize(tw, NoteSorter.Notes);
            }
        }
    }
}

Implement the read/write xml data

Implement the read/write xml data

This is done using the XML serializer class to automatically write and
read xml to a file, and back to the list of notes.


namespace TestAppUWP.Samples.Map
{
    public class MapServiceSettings
    {
        public static string Token="Pippo";
    }
}

namespace TestAppUWP.Samples.Map
{
    public class MapServiceSettings
    {
        public static string Token = string.Empty;
    }
}

Add bing map keys with fake default

Add bing map keys with fake default


using UnityEditor;

namespace SuperSystems.UnityBuild
{

[System.Serializable]
public class BuildLinux : BuildPlatform
{
    #region Constants

    private const string _name = "Linux";
    private const string _dataDirNameFormat = "{0}_Data";
    private const BuildTargetGroup _targetGroup = BuildTargetGroup.Standalone;

    #endregion

    public BuildLinux()
    {
        enabled = false;
        Init();
    }

    public override void Init()
    {
        platformName = _name;
        dataDirNameFormat = _dataDirNameFormat;
        targetGroup = _targetGroup;

        if (architectures == null || architectures.Length == 0)
        {
            architectures = new BuildArchitecture[] {
                new BuildArchitecture(BuildTarget.StandaloneLinuxUniversal, "Linux Universal", true, "{0}"),
                new BuildArchitecture(BuildTarget.StandaloneLinux, "Linux x86", false, "{0}.x86"),
                new BuildArchitecture(BuildTarget.StandaloneLinux64, "Linux x64", false, "{0}.x86_64")
            };

#if UNITY_2018_3_OR_NEWER
            architectures[0].enabled = false;
            architectures[2].enabled = true;
#endif
        }
    }
}

}

using UnityEditor;

namespace SuperSystems.UnityBuild
{

[System.Serializable]
public class BuildLinux : BuildPlatform
{
    #region Constants

    private const string _name = "Linux";
    private const string _dataDirNameFormat = "{0}_Data";
    private const BuildTargetGroup _targetGroup = BuildTargetGroup.Standalone;

    #endregion

    public BuildLinux()
    {
        enabled = false;
        Init();
    }

    public override void Init()
    {
        platformName = _name;
        dataDirNameFormat = _dataDirNameFormat;
        targetGroup = _targetGroup;

        if (architectures == null || architectures.Length == 0)
        {
            architectures = new BuildArchitecture[] {
                new BuildArchitecture(BuildTarget.StandaloneLinux64, "Linux x64", false, "{0}.x86_64"),
#if !UNITY_2019_2_OR_NEWER
                new BuildArchitecture(BuildTarget.StandaloneLinuxUniversal, "Linux Universal", true, "{0}"),
                new BuildArchitecture(BuildTarget.StandaloneLinux, "Linux x86", false, "{0}.x86"),
#endif
            };

#if UNITY_2018_3_OR_NEWER
            architectures[0].enabled = true;
#endif

#if UNITY_2018_3_OR_NEWER && !UNITY_2019_2_OR_NEWER
            architectures[1].enabled = false;
#endif
            }
        }
    }

}

Remove obsolete Linux build architectures on 2019.2+


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

namespace Wycademy
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

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

namespace Wycademy
{
    class Program
    {
        //Call Start() so that the bot runs in a non static method
        static void Main(string[] args) => new Program().Start();

        private DiscordClient _client;

        public void Start()
        {
            //Set basic settings
            _client = new DiscordClient(x =>
            {
                x.AppName = "Wycademy";
                x.LogLevel = LogSeverity.Info;
                x.LogHandler = Log;
            })
            .UsingCommands(x =>
            {
                x.PrefixChar = '<';
                x.HelpMode = HelpMode.Private;
            });

            //Set up message logging
            _client.MessageReceived += (s, e) =>
            {
                if (e.Message.IsAuthor)
                {
                    _client.Log.Info(">>Message", $"{((e.Server != null) ? e.Server.Name : "Private")}/#{((!e.Channel.IsPrivate) ? e.Channel.Name : "")} by {e.User.Name}");
                }
                else if (!e.Message.IsAuthor)
                {
                    _client.Log.Info("<<Message", $"{((e.Server != null) ? e.Server.Name : "Private")}/#{((!e.Channel.IsPrivate) ? e.Channel.Name : "")} by {e.User.Name}");
                }
            };

            //Bot token is stored in an environment variable so that nobody sees it when I push to GitHub :D
            string token = Environment.GetEnvironmentVariable("WYCADEMY_TOKEN", EnvironmentVariableTarget.User);

            //Connect to all guilds that the bot is part of and then block until the bot is manually exited.
            _client.ExecuteAndWait(async () =>
            {
                await _client.Connect(token);
            });
        }

        //Whenever we log data, this method is called.
        private void Log(object sender, LogMessageEventArgs e)
        {
            Console.WriteLine($"[{e.Severity}] [{e.Source}] {e.Message}");
        }
    }
}

Set up client, settings, logging, and connection


#region Usings

using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using ReactiveUI;

#endregion

namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
    public class InstallationItemParent : InstallationItem
    {
        public InstallationItemParent(string title, IEnumerable<InstallationItem> children)
        {
            Title = title;
            Children = children.ToList();

            Children.Select(x => x.ProgressObservable).Zip().Select(list => list.Average()).BindTo(this, x => x.Progress);
            Children.Select(x => x.IndeterminateObservable).Zip().Select(list => list.All(b => b)).BindTo(this, x => x.Indeterminate);

            OperationMessage = null;
            CancellationTokenSource = new CancellationTokenSource();
            CancellationTokenSource.Token.Register(() =>
            {
                foreach (var installationItem in Children.Where(installationItem => !installationItem.CancellationTokenSource.IsCancellationRequested)
                    )
                {
                    installationItem.CancellationTokenSource.Cancel();
                }
            });
        }

        public IEnumerable<InstallationItem> Children { get; private set; }

        #region Overrides of InstallationItem

        public override Task Install()
        {
            return Task.WhenAll(Children.Select(x => x.Install()));
        }

        #endregion
    }
}

#region Usings

using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using ReactiveUI;

#endregion

namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
    public class InstallationItemParent : InstallationItem
    {
        public InstallationItemParent(string title, IEnumerable<InstallationItem> children)
        {
            Title = title;
            Children = children.ToList();

            Children.Select(x => x.ProgressObservable).CombineLatest().Select(list => list.Average()).BindTo(this, x => x.Progress);
            Children.Select(x => x.IndeterminateObservable).CombineLatest().Select(list => list.All(b => b)).BindTo(this, x => x.Indeterminate);

            OperationMessage = null;
            CancellationTokenSource = new CancellationTokenSource();
            CancellationTokenSource.Token.Register(() =>
            {
                foreach (var installationItem in Children.Where(installationItem => !installationItem.CancellationTokenSource.IsCancellationRequested)
                    )
                {
                    installationItem.CancellationTokenSource.Cancel();
                }
            });
        }

        public IEnumerable<InstallationItem> Children { get; private set; }

        #region Overrides of InstallationItem

        public override Task Install()
        {
            return Task.WhenAll(Children.Select(x => x.Install()));
        }

        #endregion
    }
}

Use CombineLatest instead of Zip

Use CombineLatest instead of Zip


using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities;
using Pomelo.EntityFrameworkCore.MySql.Tests;
using Xunit;

namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
    public class TwoDatabasesMySqlTest : TwoDatabasesTestBase, IClassFixture<MySqlFixture>
    {
        public TwoDatabasesMySqlTest(MySqlFixture fixture)
            : base(fixture)
        {
        }

        protected new MySqlFixture Fixture
            => (MySqlFixture)base.Fixture;

        protected override DbContextOptionsBuilder CreateTestOptions(
            DbContextOptionsBuilder optionsBuilder, bool withConnectionString = false)
            => withConnectionString
                ? optionsBuilder.UseMySql(DummyConnectionString, AppConfig.ServerVersion)
                : optionsBuilder.UseMySql(AppConfig.ServerVersion);

        protected override TwoDatabasesWithDataContext CreateBackingContext(string databaseName)
            => new TwoDatabasesWithDataContext(Fixture.CreateOptions(MySqlTestStore.Create(databaseName)));

        protected override string DummyConnectionString { get; } = "Server=localhost;Database=DoesNotExist;AllowUserVariables=True;Use Affected Rows=False";
    }
}

using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities;
using Pomelo.EntityFrameworkCore.MySql.Tests;
using Xunit;

namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
    public class TwoDatabasesMySqlTest : TwoDatabasesTestBase, IClassFixture<MySqlFixture>
    {
        public TwoDatabasesMySqlTest(MySqlFixture fixture)
            : base(fixture)
        {
        }

        protected new MySqlFixture Fixture
            => (MySqlFixture)base.Fixture;

        protected override DbContextOptionsBuilder CreateTestOptions(
            DbContextOptionsBuilder optionsBuilder, bool withConnectionString = false)
            => withConnectionString
                ? optionsBuilder.UseMySql(DummyConnectionString, AppConfig.ServerVersion)
                : optionsBuilder.UseMySql(AppConfig.ServerVersion);

        protected override TwoDatabasesWithDataContext CreateBackingContext(string databaseName)
            => new TwoDatabasesWithDataContext(Fixture.CreateOptions(MySqlTestStore.Create(databaseName)));

        protected override string DummyConnectionString { get; } = "Server=localhost;Database=DoesNotExist;Allow User Variables=True;Use Affected Rows=False";
    }
}

Adjust tests to MySqlConnector 1.4.0-beta.4.


using System;
using System.IO;
using Arkivverket.Arkade.Core.Base;

namespace Arkivverket.Arkade.Core.Util
{
    public static class SystemInfo
    {
        public static long GetAvailableDiskSpaceInBytes()
        {
            return GetAvailableDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
        }

        public static long GetTotalDiskSpaceInBytes()
        {
            return GetTotalDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
        }

        public static long GetAvailableDiskSpaceInBytes(string directory)
        {
            return GetDirectoryDriveInfo(directory).AvailableFreeSpace;
        }

        public static long GetTotalDiskSpaceInBytes(string directory)
        {
            return GetDirectoryDriveInfo(directory).TotalSize;
        }

        public static string GetDotNetClrVersion()
        {
            return Environment.Version.ToString();
        }

        private static DriveInfo GetDirectoryDriveInfo(string directory)
        {
            string fullyQualifiedPath = Path.GetFullPath(directory);

            // TODO: Use below line when on .NET Standard 2.1 (reducing IO)
            //string fullyQualifiedPath = Path.IsPathFullyQualified(directory) ? directory : Path.GetFullPath(directory);

            string directoryPathRoot = Path.GetPathRoot(fullyQualifiedPath);

            return new DriveInfo(directoryPathRoot);
        }
    }
}

using System;
using System.IO;
using System.Linq;
using Arkivverket.Arkade.Core.Base;

namespace Arkivverket.Arkade.Core.Util
{
    public static class SystemInfo
    {
        public static long GetAvailableDiskSpaceInBytes()
        {
            return GetAvailableDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
        }

        public static long GetTotalDiskSpaceInBytes()
        {
            return GetTotalDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
        }

        public static long GetAvailableDiskSpaceInBytes(string directory)
        {
            return GetDirectoryDriveInfo(directory).AvailableFreeSpace;
        }

        public static long GetTotalDiskSpaceInBytes(string directory)
        {
            return GetDirectoryDriveInfo(directory).TotalSize;
        }

        public static string GetDotNetClrVersion()
        {
            return Environment.Version.ToString();
        }

        private static DriveInfo GetDirectoryDriveInfo(string directory)
        {
            string fullyQualifiedDirectoryPath = // TODO: Uncomment below line when on .NET Standard 2.1 (reducing IO)
                /*Path.IsPathFullyQualified(directory) ? directory :*/ Path.GetFullPath(directory);

            DriveInfo directoryDrive = DriveInfo.GetDrives()
                .OrderByDescending(drive => drive.Name.Length)
                .First(drive => fullyQualifiedDirectoryPath.StartsWith(drive.Name));

            return directoryDrive;
        }
    }
}

Fix cross plattform issue with drive info method

ARKADE-245


using System;
using System.Collections.Generic;
using anime_downloader.Models;
using anime_downloader.Models.Configurations;
using anime_downloader.Services.Interfaces;

namespace anime_downloader.Tests.Services
{
    public class MockXmlSettingsService: ISettingsService
    {
        public PathConfiguration PathConfig { get; set; } = new PathConfiguration();
        public FlagConfiguration FlagConfig { get; set; } = new FlagConfiguration();
        public MyAnimeListConfiguration MyAnimeListConfig { get; set; } = new MyAnimeListConfiguration();
        public string SortBy { get; set; } = "";
        public string FilterBy { get; set; } = "";
        public List<string> Subgroups { get; set; } = new List<string>();
        public List<Anime> Animes { get; set; } = new List<Anime>();
        public bool CrucialDirectoriesExist() => true;
        public void Save() {}
        public DateTime UpdateCheckDelay { get; set; }
    }
}

using System;
using System.Collections.Generic;
using anime_downloader.Models;
using anime_downloader.Models.Configurations;
using anime_downloader.Services.Interfaces;

namespace anime_downloader.Tests.Services
{
    public class MockXmlSettingsService: ISettingsService
    {
        public PathConfiguration PathConfig { get; set; } = new PathConfiguration();
        public FlagConfiguration FlagConfig { get; set; } = new FlagConfiguration();
        public MyAnimeListConfiguration MyAnimeListConfig { get; set; } = new MyAnimeListConfiguration();
        public VersionCheck Version { get; set; }
        public string SortBy { get; set; } = "";
        public string FilterBy { get; set; } = "";
        public List<string> Subgroups { get; set; } = new List<string>();
        public List<Anime> Animes { get; set; } = new List<Anime>();
        public bool CrucialDirectoriesExist() => true;
        public void Save() {}
        public DateTime UpdateCheckDelay { get; set; }
    }
}

Add version to test mock settings

Add version to test mock settings


namespace SFA.DAS.EmployerUsers.Web.Models
{
    public class RegisterViewModel :ViewModelBase
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string ConfirmPassword { get; set; }
        public bool HasAcceptedTermsAndConditions { get; set; }

        public string ReturnUrl { get; set; }

        public string GeneralError => GetErrorMessage("");
        public string FirstNameError => GetErrorMessage(nameof(FirstName));
        public string LastNameError => GetErrorMessage(nameof(LastName));
        public string EmailError => GetErrorMessage(nameof(Email));
        public string PasswordError => GetErrorMessage(nameof(Password));
        public string ConfirmPasswordError => GetErrorMessage(nameof(ConfirmPassword));
        public string HasAcceptedTermsAndConditionsError => GetErrorMessage(nameof(HasAcceptedTermsAndConditions));
    }
}

using System.Web.Mvc;

namespace SFA.DAS.EmployerUsers.Web.Models
{
    public class RegisterViewModel :ViewModelBase
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string Email { get; set; }
        [AllowHtml]
        public string Password { get; set; }
        [AllowHtml]
        public string ConfirmPassword { get; set; }
        public bool HasAcceptedTermsAndConditions { get; set; }

        public string ReturnUrl { get; set; }

        public string GeneralError => GetErrorMessage("");
        public string FirstNameError => GetErrorMessage(nameof(FirstName));
        public string LastNameError => GetErrorMessage(nameof(LastName));
        public string EmailError => GetErrorMessage(nameof(Email));
        public string PasswordError => GetErrorMessage(nameof(Password));
        public string ConfirmPasswordError => GetErrorMessage(nameof(ConfirmPassword));
        public string HasAcceptedTermsAndConditionsError => GetErrorMessage(nameof(HasAcceptedTermsAndConditions));
    }
}

Allow all characters for password fields

Added the allow html attributes to allow all characters to be used
within the password field


using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class LoadTest : MonoBehaviour
{
	public void SignInButtonClicked()
	{
		GameJolt.UI.Manager.Instance.ShowSignIn((bool success) => {
			if (success)
			{
				Debug.Log("Logged In");
			}
			else
			{
				Debug.Log("Dismissed");
			}
		});
	}

	public void IsSignedInButtonClicked() {
		bool isSignedIn = GameJolt.API.Manager.Instance.CurrentUser != null;
		if (isSignedIn) {
			Debug.Log("Signed In");
		}
		else {
			Debug.Log("Not Signed In");
		}
	}

	public void LoadSceneButtonClicked(string sceneName) {
		Debug.Log("Loading Scene " + sceneName);
		Application.LoadLevel(sceneName);
	}
}

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class LoadTest : MonoBehaviour
{
	public void SignInButtonClicked()
	{
		GameJolt.UI.Manager.Instance.ShowSignIn((bool success) => {
			if (success)
			{
				Debug.Log("Logged In");
			}
			else
			{
				Debug.Log("Dismissed");
			}
		});
	}

	public void IsSignedInButtonClicked() {
		bool isSignedIn = GameJolt.API.Manager.Instance.CurrentUser != null;
		if (isSignedIn) {
			Debug.Log("Signed In");
		}
		else {
			Debug.Log("Not Signed In");
		}
	}

	public void LoadSceneButtonClicked(string sceneName) {
		Debug.Log("Loading Scene " + sceneName);
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
		Application.LoadLevel(sceneName);
#else
		UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
#endif
	}
}

Load levels with SceneManager instead of Application for Unity 5.3+


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

using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;

namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting
{
    [DataContract]
    internal readonly struct UnitTestingPinnedSolutionInfoWrapper
    {
        [DataMember(Order = 0)]
        internal readonly PinnedSolutionInfo UnderlyingObject;

        public UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
            => UnderlyingObject = underlyingObject;

        public static implicit operator UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
            => new(info);
    }
}

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

using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;

namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
    [DataContract]
    internal readonly struct UnitTestingPinnedSolutionInfoWrapper
    {
        [DataMember(Order = 0)]
        internal readonly PinnedSolutionInfo UnderlyingObject;

        public UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
            => UnderlyingObject = underlyingObject;

        public static implicit operator UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
            => new(info);
    }
}

Fix namespace so that external access wrapper type can be accessed from UT.


using System.Threading.Tasks;
using SFA.DAS.EmployerUsers.Application.Validation;

namespace SFA.DAS.EmployerUsers.Application.Commands.RequestChangeEmail
{
    public class RequestChangeEmailCommandValidator : IValidator<RequestChangeEmailCommand>
    {
        public Task<ValidationResult> ValidateAsync(RequestChangeEmailCommand item)
        {
            var result = new ValidationResult();

            if (string.IsNullOrEmpty(item.UserId))
            {
                result.AddError(nameof(item.UserId));
            }

            if (string.IsNullOrEmpty(item.NewEmailAddress))
            {
                result.AddError(nameof(item.NewEmailAddress), "Enter a valid email address");
            }

            if (string.IsNullOrEmpty(item.ConfirmEmailAddress))
            {
                result.AddError(nameof(item.ConfirmEmailAddress), "Re-type email address");
            }

            if (!result.IsValid())
            {
                return Task.FromResult(result);
            }

            if (!item.NewEmailAddress.Equals(item.ConfirmEmailAddress, System.StringComparison.CurrentCultureIgnoreCase))
            {
                result.AddError(nameof(item.ConfirmEmailAddress), "Emails don't match");
            }

            return Task.FromResult(result);
        }
    }
}

using System.Threading.Tasks;
using SFA.DAS.EmployerUsers.Application.Validation;

namespace SFA.DAS.EmployerUsers.Application.Commands.RequestChangeEmail
{
    public class RequestChangeEmailCommandValidator : BaseValidator, IValidator<RequestChangeEmailCommand>
    {
        public Task<ValidationResult> ValidateAsync(RequestChangeEmailCommand item)
        {
            var result = new ValidationResult();

            if (string.IsNullOrEmpty(item.UserId))
            {
                result.AddError(nameof(item.UserId));
            }

            if (string.IsNullOrEmpty(item.NewEmailAddress) || !IsEmailValid(item.NewEmailAddress))
            {
                result.AddError(nameof(item.NewEmailAddress), "Enter a valid email address");
            }

            if (string.IsNullOrEmpty(item.ConfirmEmailAddress) || !IsEmailValid(item.ConfirmEmailAddress))
            {
                result.AddError(nameof(item.ConfirmEmailAddress), "Re-type email address");
            }

            if (!result.IsValid())
            {
                return Task.FromResult(result);
            }

            if (!item.NewEmailAddress.Equals(item.ConfirmEmailAddress, System.StringComparison.CurrentCultureIgnoreCase))
            {
                result.AddError(nameof(item.ConfirmEmailAddress), "Emails don't match");
            }

            return Task.FromResult(result);
        }
    }
}

Add email validity check to change email command


using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;

namespace KafkaHttp.Net
{
    public interface IKafkaProducer
    {
        Task CreateTopic(string name);
        void Publish(params Message<string>[] payload);
    }

    public class KafkaProducer : IKafkaProducer
    {
        private readonly Socket _socket;
        private readonly Json _json;

        public KafkaProducer(Socket socket)
        {
            _socket = socket;
            _json = new Json();
        }

        public Task CreateTopic(string name)
        {
            Trace.TraceInformation("Creating topic...");
            var waitHandle = new AutoResetEvent(false);

            _socket.On("topicCreated", o => waitHandle.Set());
            _socket.Emit("createTopic", name);

            return waitHandle.ToTask($"Failed to create topic {name}.", $"Created topic {name}.");
        }

        public void Publish(params Message<string>[] payload)
        {
            _socket.Emit("publish", _json.Serialize(payload));
        }
    }
}

using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;

namespace KafkaHttp.Net
{
    public interface IKafkaProducer
    {
        Task CreateTopic(string name);
        void Publish(params Message<string>[] payload);
    }

    public class KafkaProducer : IKafkaProducer
    {
        private readonly Socket _socket;
        private readonly Json _json;

        public KafkaProducer(Socket socket)
        {
            _socket = socket;
            _json = new Json();
        }

        public Task CreateTopic(string name)
        {
            Trace.TraceInformation($"Creating topic {name}...");

            var tcs = new TaskCompletionSource<object>();
            _socket.Emit(
                "createTopic",
                (e, d) =>
                {
                    if (e != null)
                    {
                        Trace.TraceError(e.ToString());
                        tcs.SetException(new Exception(e.ToString()));
                        return;
                    }

                    Trace.TraceInformation($"Topic {name} created.");
                    tcs.SetResult(true);
                }
                , name);

            return tcs.Task;
        }

        public void Publish(params Message<string>[] payload)
        {
            _socket.Emit("publish", _json.Serialize(payload));
        }
    }
}

Use acknowledgement callback to indicate whether createTopic event was successful


// 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 Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace osu.Game.Online.API.Requests.Responses
{
    public class APIChangelogBuild : IEquatable<APIChangelogBuild>
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("version")]
        public string Version { get; set; }

        [JsonProperty("display_version")]
        public string DisplayVersion { get; set; }

        [JsonProperty("users")]
        public long Users { get; set; }

        [JsonProperty("created_at")]
        public DateTimeOffset CreatedAt { get; set; }

        [JsonProperty("update_stream")]
        public APIUpdateStream UpdateStream { get; set; }

        [JsonProperty("changelog_entries")]
        public List<APIChangelogEntry> ChangelogEntries { get; set; }

        [JsonProperty("versions")]
        public VersionNatigation Versions { get; set; }

        public class VersionNatigation
        {
            [JsonProperty("next")]
            public APIChangelogBuild Next { get; set; }

            [JsonProperty("previous")]
            public APIChangelogBuild Previous { get; set; }
        }

        public bool Equals(APIChangelogBuild other) => Id == other?.Id;

        public override string ToString() => $"{UpdateStream.DisplayName} {DisplayVersion}";
    }
}

// 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 Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace osu.Game.Online.API.Requests.Responses
{
    public class APIChangelogBuild : IEquatable<APIChangelogBuild>
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("version")]
        public string Version { get; set; }

        [JsonProperty("display_version")]
        public string DisplayVersion { get; set; }

        [JsonProperty("users")]
        public long Users { get; set; }

        [JsonProperty("created_at")]
        public DateTimeOffset CreatedAt { get; set; }

        [JsonProperty("update_stream")]
        public APIUpdateStream UpdateStream { get; set; }

        [JsonProperty("changelog_entries")]
        public List<APIChangelogEntry> ChangelogEntries { get; set; }

        [JsonProperty("versions")]
        public VersionNavigation Versions { get; set; }

        public class VersionNavigation
        {
            [JsonProperty("next")]
            public APIChangelogBuild Next { get; set; }

            [JsonProperty("previous")]
            public APIChangelogBuild Previous { get; set; }
        }

        public bool Equals(APIChangelogBuild other) => Id == other?.Id;

        public override string ToString() => $"{UpdateStream.DisplayName} {DisplayVersion}";
    }
}

Fix typo in VersionNavigation class name


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

using System;

#nullable enable

namespace osu.Framework.Localisation
{
    public static class LocalisableStringExtensions
    {
        /// <summary>
        /// Returns a <see cref="LocalisableFormattableString"/> formatting the given <paramref name="value"/> with the specified <paramref name="format"/>.
        /// </summary>
        /// <param name="value">The value to format.</param>
        /// <param name="format">The format string.</param>
        public static LocalisableFormattableString ToLocalisableString(this IFormattable value, string? format)
            => new LocalisableFormattableString(value, format);
    }
}

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

using System;

#nullable enable

namespace osu.Framework.Localisation
{
    public static class LocalisableStringExtensions
    {
        /// <summary>
        /// Returns a <see cref="LocalisableFormattableString"/> formatting the given <paramref name="value"/> to a string, along with an optional <paramref name="format"/> string.
        /// </summary>
        /// <param name="value">The value to format.</param>
        /// <param name="format">The format string.</param>
        public static LocalisableFormattableString ToLocalisableString(this IFormattable value, string? format = null)
            => new LocalisableFormattableString(value, format);
    }
}

Allow using `ToLocalisableString` without a format string

Defaults to `null` which is what the number structs (`Double`, `Int32`,
etc.) use to format values without a format string.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;

namespace TOTD.EntityFramework
{
    public static class ConfigurationExtensions
    {
        public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
        }

        public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
        }

        public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
            {
                IsUnique = true
            }));
        }

        public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
            {
                IsUnique = true
            }));
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;

namespace TOTD.EntityFramework
{
    public static class ConfigurationExtensions
    {
        public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
        }

        public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
        }

        public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)));
        }

        public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
            {
                IsUnique = true
            }));
        }

        public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
        {
            return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
            {
                IsUnique = true
            }));
        }

        public static PrimitivePropertyConfiguration IsIdentity(this PrimitivePropertyConfiguration configuration)
        {
            return configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        }
    }
}

Add EF extensions for identity columns and index column order


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

using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Overlays.Changelog
{
    public class ChangelogUpdateStreamControl : OverlayStreamControl<APIUpdateStream>
    {
        protected override OverlayStreamItem<APIUpdateStream> CreateStreamItem(APIUpdateStream value) => new ChangelogUpdateStreamItem(value);

        protected override void LoadComplete()
        {
            // suppress base logic of immediately selecting first item if one exists
            // (we always want to start with no stream selected).
        }
    }
}

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

using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Overlays.Changelog
{
    public class ChangelogUpdateStreamControl : OverlayStreamControl<APIUpdateStream>
    {
        public ChangelogUpdateStreamControl()
        {
            SelectFirstTabByDefault = false;
        }

        protected override OverlayStreamItem<APIUpdateStream> CreateStreamItem(APIUpdateStream value) => new ChangelogUpdateStreamItem(value);
    }
}

Fix changelog header staying dimmed after build show


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

public class Herp
{
    public Herp(int X)
    {
        this.X = X;
    }

    public int X { get; private set; }
}

public static class HerpExtensions
{
    public static void PrintX(this Herp Value)
    {
        Console.WriteLine(Value.X);
    }
}

public static class Program
{
    public static void Main()
    {
        var herp = new Herp(20);
        herp.PrintX();

        var items = new List<int>();
        items.Add(10);
        items.Add(20);
        items.Add(30);
        // Note that ToArray<int> is actually a generic extension method:
        // Enumerable.ToArray<T>.
        foreach (var x in items.ToArray<int>())
        {
            Console.WriteLine(x);
        }
    }
}

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

public class Herp
{
    public Herp(int X)
    {
        this.X = X;
    }

    public int X { get; private set; }
}

public static class HerpExtensions
{
    public static void PrintX(this Herp Value)
    {
        Console.WriteLine(Value.X);
    }
}

public static class Program
{
    public static void Main()
    {
        var herp = new Herp(20);
        herp.PrintX();

        var items = new List<int>();
        items.Add(10);
        items.Add(20);
        items.Add(30);
        // Note that ToArray<int> is actually a generic extension method:
        // Enumerable.ToArray<T>.
        foreach (var x in items.ToArray<int>())
        {
            Console.WriteLine(x);
        }
        foreach (var x in items.Concat<int>(new int[] { 40, 50 }))
        {
            Console.WriteLine(x);
        }
    }
}

Extend the extension methods test case again


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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay.Match.Components;

namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
    public class CreateMultiplayerMatchButton : PurpleTriangleButton
    {
        private IBindable<bool> isConnected;
        private IBindable<bool> operationInProgress;

        [Resolved]
        private StatefulMultiplayerClient multiplayerClient { get; set; }

        [Resolved]
        private OngoingOperationTracker ongoingOperationTracker { get; set; }

        [BackgroundDependencyLoader]
        private void load()
        {
            Triangles.TriangleScale = 1.5f;

            Text = "Create room";

            isConnected = multiplayerClient.IsConnected.GetBoundCopy();
            isConnected.BindValueChanged(_ => updateState());

            operationInProgress = ongoingOperationTracker.InProgress.GetBoundCopy();
            operationInProgress.BindValueChanged(_ => updateState(), true);
        }

        private void updateState() => Enabled.Value = isConnected.Value && !operationInProgress.Value;
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay.Match.Components;

namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
    public class CreateMultiplayerMatchButton : PurpleTriangleButton
    {
        private IBindable<bool> isConnected;
        private IBindable<bool> operationInProgress;

        [Resolved]
        private StatefulMultiplayerClient multiplayerClient { get; set; }

        [Resolved]
        private OngoingOperationTracker ongoingOperationTracker { get; set; }

        [BackgroundDependencyLoader]
        private void load()
        {
            Triangles.TriangleScale = 1.5f;

            Text = "Create room";

            isConnected = multiplayerClient.IsConnected.GetBoundCopy();
            operationInProgress = ongoingOperationTracker.InProgress.GetBoundCopy();
        }

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

            isConnected.BindValueChanged(_ => updateState());
            operationInProgress.BindValueChanged(_ => updateState(), true);
        }

        private void updateState() => Enabled.Value = isConnected.Value && !operationInProgress.Value;
    }
}

Move BindValueChanged subscriptions to LoadComplete


using Newtonsoft.Json;

namespace BitFlyer.Apis
{
    public class SendChildOrderParameter
    {
        [JsonProperty("product_code")]
        public ProductCode ProductCode { get; set; }

        [JsonProperty("child_order_type")]
        public ChildOrderType ChildOrderType { get; set; }

        [JsonProperty("side")]
        public Side Side { get; set; }

        [JsonProperty("price")]
        public int Price { get; set; }

        [JsonProperty("size")]
        public double Size { get; set; }

        [JsonProperty("minute_to_expire")]
        public int MinuteToExpire { get; set; }

        [JsonProperty("time_in_force")]
        public TimeInForce TimeInForce { get; set; }

    }
}

using Newtonsoft.Json;

namespace BitFlyer.Apis
{
    public class SendChildOrderParameter
    {
        [JsonProperty("product_code")]
        public ProductCode ProductCode { get; set; }

        [JsonProperty("child_order_type")]
        public ChildOrderType ChildOrderType { get; set; }

        [JsonProperty("side")]
        public Side Side { get; set; }

        [JsonProperty("price")]
        public double Price { get; set; }

        [JsonProperty("size")]
        public double Size { get; set; }

        [JsonProperty("minute_to_expire")]
        public int MinuteToExpire { get; set; }

        [JsonProperty("time_in_force")]
        public TimeInForce TimeInForce { get; set; }

    }
}

Change Price type to double

Change Price type to double


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

namespace Sitecore.Linqpad.Server
{
    public class CookieAwareWebClient : WebClient
    {
        public CookieAwareWebClient(CookieContainer cookies = null)
        {
            this.Cookies = cookies ?? new CookieContainer();
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var webRequest = base.GetWebRequest(address);
            var request2 = webRequest as HttpWebRequest;
            if (request2 != null)
            {
                request2.CookieContainer = this.Cookies;
            }
            webRequest.Timeout = 300000;
            return webRequest;
        }

        public CookieContainer Cookies { get; private set; }
    }
}

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

namespace Sitecore.Linqpad.Server
{
    public class CookieAwareWebClient : WebClient
    {
        public CookieAwareWebClient(CookieContainer cookies = null)
        {
            this.Cookies = cookies ?? new CookieContainer();
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var webRequest = base.GetWebRequest(address);
            var request2 = webRequest as HttpWebRequest;
            if (request2 != null)
            {
                request2.CookieContainer = this.Cookies;
                request2.AllowAutoRedirect = false;
            }
            webRequest.Timeout = 300000;
            return webRequest;
        }

        public CookieContainer Cookies { get; private set; }
    }
}

Disable login redirect to dbbrowser.aspx forbidding redirects altogether


using System.Collections.Generic;

namespace Humanizer.Localisation.NumberToWords
{
    internal class FrenchNumberToWordsConverter : FrenchNumberToWordsConverterBase
    {
        protected override void CollectPartsUnderAHundred(ICollection<string> parts, ref int number, GrammaticalGender gender, bool pluralize)
        {
            if (number == 71)
                parts.Add("soixante et onze");
            else if (number == 80)
                parts.Add("quatre-vingt" + (pluralize ? "s" : string.Empty));
            else if (number >= 70)
            {
                var @base = number < 80 ? 60 : 80;
                int units = number - @base;
                var tens = @base / 10;
                parts.Add($"{GetTens(tens)}-{GetUnits(units, gender)}");
            }
            else
                base.CollectPartsUnderAHundred(parts, ref number, gender, pluralize);
        }

        protected override string GetTens(int tens) => tens == 8 ? "quatre-vingt" : base.GetTens(tens);
    }
}

using System.Collections.Generic;

namespace Humanizer.Localisation.NumberToWords
{
    internal class FrenchNumberToWordsConverter : FrenchNumberToWordsConverterBase
    {
        protected override void CollectPartsUnderAHundred(ICollection<string> parts, ref int number, GrammaticalGender gender, bool pluralize)
        {
            if (number == 71)
                parts.Add("soixante et onze");
            else if (number == 80)
                parts.Add(pluralize ? "quatre-vingts" : "quatre-vingt");
            else if (number >= 70)
            {
                var @base = number < 80 ? 60 : 80;
                int units = number - @base;
                var tens = @base/10;
                parts.Add(string.Format("{0}-{1}", GetTens(tens), GetUnits(units, gender)));
            }
            else
                base.CollectPartsUnderAHundred(parts, ref number, gender, pluralize);
        }

        protected override string GetTens(int tens)
        {
            if (tens == 8)
                return "quatre-vingt";

            return base.GetTens(tens);
        }
    }
}

Revert "clean code a bit"

Revert "clean code a bit"

This reverts commit eb110e56c72b3529cf9a7f649f499499315482a7.


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

namespace kynnaugh
{
    class StringUtils
    {
        // By Hans Passant
        // http://stackoverflow.com/a/10773988
        public static IntPtr NativeUtf8FromString(string managedString)
        {
            int len = Encoding.UTF8.GetByteCount(managedString);
            byte[] buffer = new byte[len + 1];
            Encoding.UTF8.GetBytes(managedString, 0, managedString.Length, buffer, 0);
            IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length);
            Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length);
            return nativeUtf8;
        }

        public static string StringFromNativeUtf8(IntPtr nativeUtf8)
        {
            int len = 0;
            while (Marshal.ReadByte(nativeUtf8, len) != 0) ++len;
            byte[] buffer = new byte[len];
            Marshal.Copy(nativeUtf8, buffer, 0, buffer.Length);
            return Encoding.UTF8.GetString(buffer);
        }
    }
}

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

namespace kynnaugh
{
    class StringUtils
    {
        // By Hans Passant
        // http://stackoverflow.com/a/10773988
        public static IntPtr NativeUtf8FromString(string managedString)
        {
            int len = (new UTF8Encoding(false)).GetByteCount(managedString);
            byte[] buffer = new byte[len + 1];
            (new UTF8Encoding(false)).GetBytes(managedString, 0, managedString.Length, buffer, 0);
            IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length);
            Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length);
            return nativeUtf8;
        }

        public static string StringFromNativeUtf8(IntPtr nativeUtf8)
        {
            int len = 0;
            while (Marshal.ReadByte(nativeUtf8, len) != 0) ++len;
            byte[] buffer = new byte[len];
            Marshal.Copy(nativeUtf8, buffer, 0, buffer.Length);
            return (new UTF8Encoding(false)).GetString(buffer);
        }
    }
}

Remove BOM from UTF8 encoder

Remove BOM from UTF8 encoder


using System.Collections.Generic;
using Squirrel.Nodes;

namespace Squirrel
{
    public class Environment
    {
        private readonly Environment _parent;
        private readonly Dictionary<string, INode> _definitions = new Dictionary<string, INode>();

        public Environment(Environment parent)
        {
            _parent = parent;
        }

        public Environment() : this(null)
        {
        }

        public void Put(string key, INode value) => _definitions.Add(key, value);

        public void PutOuter(string key, INode value) => _parent.Put(key, value);

        public INode Get(string key)
        {
            if (_parent == null)
            {
                return GetShallow(key);
            }
            return GetShallow(key) ?? _parent.Get(key);
        }

        private INode GetShallow(string key) => _definitions.ContainsKey(key) ? _definitions[key] : null;

        public void Extend(Environment env)
        {
            foreach (var definition in env._definitions)
            {
                Put(definition.Key, definition.Value);
            }
        }
    }
}

using System.Collections.Generic;
using Squirrel.Nodes;

namespace Squirrel
{
    public class Environment
    {
        private readonly Environment _parent;
        private readonly Dictionary<string, INode> _definitions = new Dictionary<string, INode>();

        public Environment(Environment parent)
        {
            _parent = parent;
        }

        public Environment() : this(null)
        {
        }

        public void Put(string key, INode value) => _definitions[key] = value;

        public void PutOuter(string key, INode value) => _parent.Put(key, value);

        public INode Get(string key)
        {
            if (_parent == null)
            {
                return GetShallow(key);
            }
            return GetShallow(key) ?? _parent.Get(key);
        }

        private INode GetShallow(string key) => _definitions.ContainsKey(key) ? _definitions[key] : null;

        public void Extend(Environment env)
        {
            foreach (var definition in env._definitions)
            {
                Put(definition.Key, definition.Value);
            }
        }
    }
}

Allow redefining already defined symbols