namespace Nancy.Json
{
    using System.Collections.Generic;
    using Converters;

    /// <summary>
    /// Json serializer settings
    /// </summary>
    public static class JsonSettings
    {
        /// <summary>
        /// Max length of json output
        /// </summary>
        public static int MaxJsonLength { get; set; }

        /// <summary>
        /// Maximum number of recursions
        /// </summary>
        public static int MaxRecursions { get; set; }

        /// <summary>
        /// Default charset for json responses.
        /// </summary>
        public static string DefaultCharset { get; set; }

        public static IList<JavaScriptConverter> Converters { get; set; }

        static JsonSettings()
        {
            MaxJsonLength = 102400;
            MaxRecursions = 100;
            DefaultCharset = "utf8";
            Converters = new List<JavaScriptConverter>
                             {
                                 new TimeSpanConverter(),
                             };
        }
    }
}

namespace Nancy.Json
{
    using System.Collections.Generic;
    using Converters;

    /// <summary>
    /// Json serializer settings
    /// </summary>
    public static class JsonSettings
    {
        /// <summary>
        /// Max length of json output
        /// </summary>
        public static int MaxJsonLength { get; set; }

        /// <summary>
        /// Maximum number of recursions
        /// </summary>
        public static int MaxRecursions { get; set; }

        /// <summary>
        /// Default charset for json responses.
        /// </summary>
        public static string DefaultCharset { get; set; }

        public static IList<JavaScriptConverter> Converters { get; set; }

        static JsonSettings()
        {
            MaxJsonLength = 102400;
            MaxRecursions = 100;
            DefaultCharset = "utf-8";
            Converters = new List<JavaScriptConverter>
                             {
                                 new TimeSpanConverter(),
                             };
        }
    }
}

Fix default JSON response charset

Fix default JSON response charset


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

namespace osu.Game.Online.API.Requests
{
    public class MarkChannelAsReadRequest : APIRequest
    {
        private readonly Channel channel;
        private readonly Message message;

        public MarkChannelAsReadRequest(Channel channel, Message message)
        {
            this.channel = channel;
            this.message = message;
        }

        protected override string Target => @"/chat/channels/{channel}/mark-as-read/{message}";
    }
}

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

namespace osu.Game.Online.API.Requests
{
    public class MarkChannelAsReadRequest : APIRequest
    {
        private readonly Channel channel;
        private readonly Message message;

        public MarkChannelAsReadRequest(Channel channel, Message message)
        {
            this.channel = channel;
            this.message = message;
        }

        protected override string Target => $"/chat/channels/{channel}/mark-as-read/{message}";
    }
}

Fix variables not being used inside target string


namespace Serilog.Exceptions.Core
{
    using System;
    using System.Collections.Generic;
    using Serilog.Exceptions.Filters;

    internal class ExceptionPropertiesBag : IExceptionPropertiesBag
    {
        private readonly Type exceptionType;
        private readonly IExceptionPropertyFilter filter;
        private readonly Dictionary<string, object> properties = new Dictionary<string, object>();
        private bool resultsCollected = false;

        public ExceptionPropertiesBag(Type exceptionType, IExceptionPropertyFilter filter = null)
        {
            this.exceptionType = exceptionType;
            this.filter = filter;
        }

        public IReadOnlyDictionary<string, object> GetResultDictionary()
        {
            this.resultsCollected = true;
            return this.properties;
        }

        public void AddProperty(string key, object value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key), "Cannot add exception property without a key");
            }

            if (this.resultsCollected)
            {
                throw new InvalidOperationException($"Cannot add exception property '{key}' to bag, after results were already collected");
            }

            if (this.filter != null)
            {
                if (this.filter.ShouldPropertyBeFiltered(this.exceptionType, key, value))
                {
                    return;
                }
            }

            this.properties.Add(key, value);
        }
    }
}

namespace Serilog.Exceptions.Core
{
    using System;
    using System.Collections.Generic;
    using Serilog.Exceptions.Filters;

    internal class ExceptionPropertiesBag : IExceptionPropertiesBag
    {
        private readonly Type exceptionType;
        private readonly IExceptionPropertyFilter filter;
        private readonly Dictionary<string, object> properties = new Dictionary<string, object>();

        // We keep a note on whether the results were collected to be sure that
        // after that there are no changes. This is the application of fail-fast principle.
        private bool resultsCollected = false;

        public ExceptionPropertiesBag(Type exceptionType, IExceptionPropertyFilter filter = null)
        {
            this.exceptionType = exceptionType;
            this.filter = filter;
        }

        public IReadOnlyDictionary<string, object> GetResultDictionary()
        {
            this.resultsCollected = true;
            return this.properties;
        }

        public void AddProperty(string key, object value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key), "Cannot add exception property without a key");
            }

            if (this.resultsCollected)
            {
                throw new InvalidOperationException($"Cannot add exception property '{key}' to bag, after results were already collected");
            }

            if (this.filter != null)
            {
                if (this.filter.ShouldPropertyBeFiltered(this.exceptionType, key, value))
                {
                    return;
                }
            }

            this.properties.Add(key, value);
        }
    }
}

Document fail-fast approach for exception bag property add after results collected


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

namespace kh.kh2.Messages
{
    public partial class MsgSerializer
    {
        public static string SerializeText(IEnumerable<MessageCommandModel> entries)
        {
            var sb = new StringBuilder();
            foreach (var entry in entries)
                sb.Append(SerializeToText(entry));
            return sb.ToString();
        }

        public static string SerializeToText(MessageCommandModel entry)
        {
            if (entry.Command == MessageCommand.PrintText)
                return entry.Text;
            if (entry.Command == MessageCommand.PrintComplex)
                return $"{{{entry.Text}}}";
            if (entry.Command == MessageCommand.NewLine)
                return "\n";
            if (entry.Command == MessageCommand.Tabulation)
                return "\t";

            if (!_serializer.TryGetValue(entry.Command, out var serializeModel))
                throw new NotImplementedException($"The command {entry.Command} serialization is not implemented yet.");

            return $"{{:{serializeModel.Name} {serializeModel.ValueGetter(entry)}}}";
        }
    }
}

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

namespace kh.kh2.Messages
{
    public partial class MsgSerializer
    {
        public static string SerializeText(IEnumerable<MessageCommandModel> entries)
        {
            var sb = new StringBuilder();
            foreach (var entry in entries)
                sb.Append(SerializeToText(entry));
            return sb.ToString();
        }

        public static string SerializeToText(MessageCommandModel entry)
        {
            if (entry.Command == MessageCommand.End)
                return string.Empty;
            if (entry.Command == MessageCommand.PrintText)
                return entry.Text;
            if (entry.Command == MessageCommand.PrintComplex)
                return $"{{{entry.Text}}}";
            if (entry.Command == MessageCommand.NewLine)
                return "\n";
            if (entry.Command == MessageCommand.Tabulation)
                return "\t";

            if (!_serializer.TryGetValue(entry.Command, out var serializeModel))
                throw new NotImplementedException($"The command {entry.Command} serialization is not implemented yet.");

            Debug.Assert(serializeModel != null, $"BUG: {nameof(serializeModel)} should never be null");

            if (serializeModel.ValueGetter != null)
                return $"{{:{serializeModel.Name} {serializeModel.ValueGetter(entry)}}}";
            return $"{{:{serializeModel.Name}}}";
        }
    }
}

Fix crash in Serializer on MessageCommand.End or empty getter


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

using System;

namespace osu.Framework.Graphics.Containers
{
    public class CircularContainer : Container
    {
        public override float CornerRadius
        {
            get
            {
                return Math.Min(DrawSize.X, DrawSize.Y) / 2f;
            }

            set
            {
                throw new InvalidOperationException($"Cannot manually set {nameof(CornerRadius)} of {nameof(CircularContainer)}.");
            }
        }
    }
}

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

using System;

namespace osu.Framework.Graphics.Containers
{
    /// <summary>
    /// A container which come with masking and automatic corner radius based on the smallest edge div 2.
    /// </summary>
    public class CircularContainer : Container
    {
        public CircularContainer()
        {
            Masking = true;
        }

        public override float CornerRadius
        {
            get
            {
                return Math.Min(DrawSize.X, DrawSize.Y) / 2f;
            }

            set
            {
                throw new InvalidOperationException($"Cannot manually set {nameof(CornerRadius)} of {nameof(CircularContainer)}.");
            }
        }
    }
}

Add comment and add masking back.

Add comment and add masking back.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace KeepOn
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            bool hasUnknowArgs = false;
            foreach (string arg in args)
            {
                // /lang=zh_CN
                if (arg.StartsWith("/lang"))
                {
                    I18N.overrideLanguage = arg.Split('=')[1].Trim();
                }
                else
                    hasUnknowArgs = true;
            }
            if (hasUnknowArgs)
                MessageBox.Show(
@"/lang=zh_CN
/lang=en_US"
,
            "Available arguments");

            I18N.Init();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool createdNew;
            // To prevent the program to be started twice
            Mutex appMutex = new Mutex(true, Application.ProductName, out createdNew);
            if (createdNew)
            {
                Application.Run(new TrayApplicationContext());
                appMutex.ReleaseMutex();
            }
            else
            {
                string msg = string.Format(I18N.GetString("app.dupInstanceMsg"), Application.ProductName);
                MessageBox.Show(msg, Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace KeepOn
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            bool hasUnknowArgs = false;
            foreach (string arg in args)
            {
                try
                {
                    // /lang=zh_CN
                    if (arg.StartsWith("/lang"))
                    {
                        I18N.overrideLanguage = arg.Split('=')[1].Trim();
                    }
                    else
                        hasUnknowArgs = true;
                }
                catch
                {
                    hasUnknowArgs = true;
                }
            }
            if (hasUnknowArgs)
                MessageBox.Show(
@"Set UI language:
  /lang=zh_CN
  /lang=en_US"
,
            "Available arguments");

            I18N.Init();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool createdNew;
            // To prevent the program to be started twice
            Mutex appMutex = new Mutex(true, Application.ProductName, out createdNew);
            if (createdNew)
            {
                Application.Run(new TrayApplicationContext());
                appMutex.ReleaseMutex();
            }
            else
            {
                string msg = string.Format(I18N.GetString("app.dupInstanceMsg"), Application.ProductName);
                MessageBox.Show(msg, Application.ProductName,
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

Handle the exception when parsing the arguments


using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using SO115App.ExternalAPI.Client;
using SO115App.Models.Classi.ServiziEsterni.OPService;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.OPService;
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace SO115App.ExternalAPI.Fake.Servizi.OPService
{
    public class SetStatoSquadra : ISetStatoSquadra
    {
        private readonly HttpClient _client;
        private readonly IConfiguration _config;

        public SetStatoSquadra(HttpClient client, IConfiguration config)
        {
            _client = client;
            _config = config;
        }

        public async Task<HttpResponseMessage> SetStatoSquadraOPService(actionDTO action)
        {
            var json = JsonConvert.SerializeObject(action);
            var content = new StringContent(json);

            var baseurl = new Uri(_config.GetSection("UrlExternalApi").GetSection("OPService").Value);

            var url = new Uri(baseurl, "/api/v1/so-workshift/action");
            //var result = await _client.PostAsync(url, content);
            //return result;

            return null;
        }
    }
}

using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using SO115App.ExternalAPI.Client;
using SO115App.Models.Classi.ServiziEsterni.OPService;
using SO115App.Models.Servizi.Infrastruttura.SistemiEsterni.OPService;
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace SO115App.ExternalAPI.Fake.Servizi.OPService
{
    public class SetStatoSquadra : ISetStatoSquadra
    {
        private readonly HttpClient _client;
        private readonly IConfiguration _config;

        public SetStatoSquadra(HttpClient client, IConfiguration config)
        {
            _client = client;
            _config = config;
        }

        public async Task<HttpResponseMessage> SetStatoSquadraOPService(actionDTO action)
        {
            var json = JsonConvert.SerializeObject(action);
            var content = new StringContent(json);

            var baseurl = new Uri(_config.GetSection("UrlExternalApi").GetSection("OPService").Value);

            var url = new Uri(baseurl, "api/v1/so-workshift/action");
            var result = await _client.PostAsync(url, content);
            return result;

            //return null;
        }
    }
}

Set Stato Squadra - Abilitata la chiamata a OpService


using System;
using System.Linq;
using System.Net;

namespace BmpListener.Bgp
{
    public class IPAddrPrefix
    {
        public IPAddrPrefix(ArraySegment<byte> data, Bgp.AddressFamily afi = Bgp.AddressFamily.IP)
        {
            DecodeFromBytes(data, afi);
        }

        public byte Length { get; private set; }
        public IPAddress Prefix { get; private set; }

        public override string ToString()
        {
            return ($"{Prefix}/{Length}");
        }

        public void DecodeFromBytes(ArraySegment<byte> data, Bgp.AddressFamily afi)
        {
            //add length error check
            Length = data.ElementAt(0);
            var byteLength = (Length + 7) / 8;
            var ipBytes = afi == Bgp.AddressFamily.IP
                ? new byte[4]
                : new byte[16];
            if (Length <= 0) return;
            Buffer.BlockCopy(data.ToArray(), 1, ipBytes, 0, byteLength);
            Prefix = new IPAddress(ipBytes);
        }
    }
}

using System;
using System.Linq;
using System.Net;

namespace BmpListener.Bgp
{
    public class IPAddrPrefix
    {
        //TODO add offset to ctor
        public IPAddrPrefix(ArraySegment<byte> data, int offset = 0, AddressFamily afi = AddressFamily.IP)
        {
            DecodeFromBytes(data, afi);
        }

        public byte Length { get; private set; }
        public IPAddress Prefix { get; private set; }

        public override string ToString()
        {
            return ($"{Prefix}/{Length}");
        }

        public void DecodeFromBytes(ArraySegment<byte> data, Bgp.AddressFamily afi)
        {
            //add length error check
            Length = data.ElementAt(0);
            var byteLength = (Length + 7) / 8;
            var ipBytes = afi == Bgp.AddressFamily.IP
                ? new byte[4]
                : new byte[16];
            if (Length <= 0) return;
            Buffer.BlockCopy(data.ToArray(), 1, ipBytes, 0, byteLength);
            Prefix = new IPAddress(ipBytes);
        }
    }
}

Add offset as optional parameter

Add offset as optional parameter


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cats.Data.UnitWork;
using Ninject;
using Cats.Services.EarlyWarning;

namespace Cats.Infrastructure
{
    public class NinjectDependencyResolver : IDependencyResolver
    {
        private IKernel kernel;

        public NinjectDependencyResolver()
        {
            this.kernel = new StandardKernel();
            AddBindings();
        }

    public object GetService(Type serviceType)
        {
            return kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return kernel.GetAll(serviceType);
        }

        private void AddBindings()
        {
            kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
            kernel.Bind<IRegionalRequestService>().To<RegionalRequestService>();
            kernel.Bind<IFDPService>().To<FDPService>();
            kernel.Bind<IAdminUnitService>().To<AdminUnitService>();
            kernel.Bind<IProgramService>().To<ProgramService>();
            kernel.Bind<ICommodityService>().To<CommodityService>();
            kernel.Bind<IRegionalRequestDetailService>().To<RegionalRequestDetailService>();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cats.Data.UnitWork;
using Ninject;
using Cats.Services.EarlyWarning;

namespace Cats.Infrastructure
{
    public class NinjectDependencyResolver : IDependencyResolver
    {
        private IKernel kernel;

        public NinjectDependencyResolver()
        {
            this.kernel = new StandardKernel();
            AddBindings();
        }

    public object GetService(Type serviceType)
        {
            return kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return kernel.GetAll(serviceType);
        }

        private void AddBindings()
        {
            kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
            kernel.Bind<IRegionalRequestService>().To<RegionalRequestService>();
            kernel.Bind<IFDPService>().To<FDPService>();
            kernel.Bind<IAdminUnitService>().To<AdminUnitService>();
            kernel.Bind<IProgramService>().To<ProgramService>();
            kernel.Bind<ICommodityService>().To<CommodityService>();
            kernel.Bind<IRegionalRequestDetailService>().To<RegionalRequestDetailService>();
            kernel.Bind<IReliefRequisitionService>().To<ReliefRequisitionService>();
            kernel.Bind<IReliefRequisitionDetailService>().To<ReliefRequisitionDetailService>();
        }
    }
}

Update Dependency Resolver to include Requisition Service


using System.Collections.Generic;
using JetBrains.Application.UI.Controls.GotoByName;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features.CodeInsights.Providers;
using JetBrains.Rider.Model;

namespace JetBrains.ReSharper.Plugins.Unity.Rider.CodeInsights
{

    [SolutionComponent]
    public class UnityCodeInsightProvider : AbstractUnityCodeInsightProvider
    {
        public override string ProviderId => "Unity implicit usage";
        public override string DisplayName => "Unity implicit usage";
        public override CodeLensAnchorKind DefaultAnchor => CodeLensAnchorKind.Top;

        public override ICollection<CodeLensRelativeOrdering> RelativeOrderings =>  new[] { new CodeLensRelativeOrderingBefore(ReferencesCodeInsightsProvider.Id)};

        public UnityCodeInsightProvider(UnityHost host,BulbMenuComponent bulbMenu)
            : base(host, bulbMenu)
        {
        }

    }
}

using System.Collections.Generic;
using JetBrains.Application.UI.Controls.GotoByName;
using JetBrains.Platform.RdFramework.Util;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features.CodeInsights.Providers;
using JetBrains.Rider.Model;

namespace JetBrains.ReSharper.Plugins.Unity.Rider.CodeInsights
{
    [SolutionComponent]
    public class UnityCodeInsightProvider : AbstractUnityCodeInsightProvider
    {
        public override string ProviderId => "Unity implicit usage";
        public override string DisplayName => "Unity implicit usage";
        public override CodeLensAnchorKind DefaultAnchor => CodeLensAnchorKind.Top;

        public override ICollection<CodeLensRelativeOrdering> RelativeOrderings { get; }

        public UnityCodeInsightProvider(UnityHost host, BulbMenuComponent bulbMenu, UnitySolutionTracker tracker)
            : base(host, bulbMenu)
        {
            RelativeOrderings = tracker.IsUnityProject.HasValue() && tracker.IsUnityProject.Value
                ? new CodeLensRelativeOrdering[] {new CodeLensRelativeOrderingBefore(ReferencesCodeInsightsProvider.Id)}
                : new CodeLensRelativeOrdering[] {new CodeLensRelativeOrderingLast()};
        }
    }
}

Fix code vision order in not-unity projects


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

using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;

namespace Microsoft.NET.TestFramework.Commands
{
    public class MSBuildTest
    {
        public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath);

        private string DotNetHostPath { get; }

        public MSBuildTest(string dotNetHostPath)
        {
            DotNetHostPath = dotNetHostPath;
        }

        public Command CreateCommandForTarget(string target, params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"/t:{target}");

            return CreateCommand(newArgs.ToArray());
        }

        private Command CreateCommand(params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"msbuild");

            return Command.Create(DotNetHostPath, newArgs);
        }
    }
}

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

using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;

namespace Microsoft.NET.TestFramework.Commands
{
    public class MSBuildTest
    {
        public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath);

        private string DotNetHostPath { get; }

        public MSBuildTest(string dotNetHostPath)
        {
            DotNetHostPath = dotNetHostPath;
        }

        public ICommand CreateCommandForTarget(string target, params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"/t:{target}");

            return CreateCommand(newArgs.ToArray());
        }

        private ICommand CreateCommand(params string[] args)
        {
            var newArgs = args.ToList();
            newArgs.Insert(0, $"msbuild");

            ICommand command = Command.Create(DotNetHostPath, newArgs);

            //  Set NUGET_PACKAGES environment variable to match value from build.ps1
            command = command.EnvironmentVariable("NUGET_PACKAGES", RepoInfo.PackagesPath);

            return command;
        }
    }
}

Set NUGET_PACKAGES environment variable when running MSBuild commands

This is needed for running tests from Visual Studio, where the build.ps1 script hasn't set this value


using System.Runtime.Serialization;
using Elasticsearch.Net;

namespace Nest
{
	[ReadAs(typeof(PutWatchResponse))]
	public class PutWatchResponse : ResponseBase
	{
		[DataMember(Name = "created")]
		public bool Created { get; internal set; }

		[DataMember(Name = "_id")]
		public string Id { get; internal set; }

		[DataMember(Name = "_version")]
		public int Version { get; internal set; }
	}
}

using System.Runtime.Serialization;
using Elasticsearch.Net;

namespace Nest
{
	public class PutWatchResponse : ResponseBase
	{
		[DataMember(Name = "created")]
		public bool Created { get; internal set; }

		[DataMember(Name = "_id")]
		public string Id { get; internal set; }

		[DataMember(Name = "_version")]
		public int Version { get; internal set; }

		[DataMember(Name = "_seq_no")]
		public long SequenceNumber { get; internal set; }

		[DataMember(Name = "_primary_term")]
		public long PrimaryTerm { get; internal set; }
	}
}

Remove ReadAsAttribute from concrete response


namespace Stripe
{
    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class StripeBalanceTransaction : StripeEntityWithId
    {
        [JsonProperty("object")]
        public string Object { get; set; }

        [JsonProperty("amount")]
        public int Amount { get; set; }

        [JsonProperty("available_on")]
        [JsonConverter(typeof(StripeDateTimeConverter))]
        public DateTime AvailableOn { get; set; }

        [JsonProperty("created")]
        [JsonConverter(typeof(StripeDateTimeConverter))]
        public DateTime Created { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("fee")]
        public int Fee { get; set; }

        [JsonProperty("fee_details")]
        public List<StripeFee> FeeDetails { get; set; }

        [JsonProperty("net")]
        public int Net { get; set; }

        #region Expandable BalanceTransactionSource
        public string SourceId { get; set; }

        [JsonIgnore]
        public BalanceTransactionSource Source { get; set; }

        [JsonProperty("source")]
        internal object InternalSource
        {
            set
            {
                StringOrObject<BalanceTransactionSource>.Map(value, s => this.SourceId = s, o => this.Source = o);
            }
        }
        #endregion

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }
}

namespace Stripe
{
    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class StripeBalanceTransaction : StripeEntityWithId
    {
        [JsonProperty("object")]
        public string Object { get; set; }

        [JsonProperty("amount")]
        public int Amount { get; set; }

        [JsonProperty("available_on")]
        [JsonConverter(typeof(StripeDateTimeConverter))]
        public DateTime AvailableOn { get; set; }

        [JsonProperty("created")]
        [JsonConverter(typeof(StripeDateTimeConverter))]
        public DateTime Created { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("exchange_rate")]
        public decimal? ExchangeRate { get; set; }

        [JsonProperty("fee")]
        public int Fee { get; set; }

        [JsonProperty("fee_details")]
        public List<StripeFee> FeeDetails { get; set; }

        [JsonProperty("net")]
        public int Net { get; set; }

        #region Expandable BalanceTransactionSource
        public string SourceId { get; set; }

        [JsonIgnore]
        public BalanceTransactionSource Source { get; set; }

        [JsonProperty("source")]
        internal object InternalSource
        {
            set
            {
                StringOrObject<BalanceTransactionSource>.Map(value, s => this.SourceId = s, o => this.Source = o);
            }
        }
        #endregion

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }
}

Add exchange_rate to the Balance Transaction resource


using System.Collections.Generic;
using StressMeasurementSystem.Models;

namespace StressMeasurementSystem.ViewModels
{
    public class PatientViewModel
    {
        private Patient _patient;

        public PatientViewModel()
        {
            _patient = null;
        }

        public PatientViewModel(Patient patient)
        {
            _patient = patient;
        }
    }
}

using System.Collections.Generic;
using StressMeasurementSystem.Models;

namespace StressMeasurementSystem.ViewModels
{
    public class PatientViewModel
    {
        private Patient _patient;

        public PatientViewModel()
        {
            _patient = new Patient();
        }

        public PatientViewModel(Patient patient)
        {
            _patient = patient;
        }
    }
}

Fix null assignment in default constructor


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

namespace Archetype.Models
{
    [JsonObject]
    public class ArchetypeModel : IEnumerable<ArchetypeFieldsetModel>
    {
        [JsonProperty("fieldsets")]
        public IEnumerable<ArchetypeFieldsetModel> Fieldsets { get; set; }

        public ArchetypeModel()
        {
            Fieldsets = new List<ArchetypeFieldsetModel>();
        }

        public IEnumerator<ArchetypeFieldsetModel> GetEnumerator()
        {
            return this.Fieldsets.Where(f => f.Disabled == false).GetEnumerator();
        }

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

        public string SerializeForPersistence()
        {
            // clear the editor state before serializing (it's temporary state data)
            foreach(var property in Fieldsets.SelectMany(f => f.Properties.Where(p => p.EditorState != null)).ToList())
            {
                property.EditorState = null;
            }

            var json = JObject.Parse(JsonConvert.SerializeObject(this, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));

            var propertiesToRemove = new String[] { "propertyEditorAlias", "dataTypeId", "dataTypeGuid", "hostContentType" };

            json.Descendants().OfType<JProperty>()
              .Where(p => propertiesToRemove.Contains(p.Name))
              .ToList()
              .ForEach(x => x.Remove());

            return json.ToString(Formatting.None);
        }
    }
}

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

namespace Archetype.Models
{
    [JsonObject]
    public class ArchetypeModel : IEnumerable<ArchetypeFieldsetModel>
    {
        [JsonProperty("fieldsets")]
        public IEnumerable<ArchetypeFieldsetModel> Fieldsets { get; set; }

        public ArchetypeModel()
        {
            Fieldsets = new List<ArchetypeFieldsetModel>();
        }

        public IEnumerator<ArchetypeFieldsetModel> GetEnumerator()
        {
            return this.Fieldsets.Where(f => f.Disabled == false).GetEnumerator();
        }

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

        public string SerializeForPersistence()
        {
            var json = JObject.Parse(JsonConvert.SerializeObject(this, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));

            var propertiesToRemove = new String[] { "propertyEditorAlias", "dataTypeId", "dataTypeGuid", "hostContentType", "editorState" };

            json.Descendants().OfType<JProperty>()
              .Where(p => propertiesToRemove.Contains(p.Name))
              .ToList()
              .ForEach(x => x.Remove());

            return json.ToString(Formatting.None);
        }
    }
}

Remove editorState from model before persisting


using System.IO;
using System.Web.Optimization;

namespace Bundlr
{
    public static class BundleExtensions
    {
        public static TBundle IncludePath<TBundle>(this TBundle bundle, string root, params string[] files)
            where TBundle : Bundle
        {
            foreach (string file in files)
            {
                string path = Path.Combine(root, file);
                bundle.Include(path);
            }

            return bundle;
        }
    }
}

using System.IO;
using System.Web.Optimization;

namespace Bundlr
{
    public static class BundleExtensions
    {
        public static TBundle AddTo<TBundle>(this TBundle bundle, BundleCollection collection)
            where TBundle : Bundle
        {
            collection.Add(bundle);
            return bundle;
        }

        public static TBundle IncludePath<TBundle>(this TBundle bundle, string root, params string[] files)
            where TBundle : Bundle
        {
            foreach (string file in files)
            {
                string path = Path.Combine(root, file);
                bundle.Include(path);
            }

            return bundle;
        }
    }
}

Add extension method for adding bundle to bundle collection.


using System.Web.Optimization;

namespace Listy.Web
{
    public class BundleConfig
    {
        public class BootstrapResourcesTransform : IItemTransform
        {
            public string Process(string includedVirtualPath, string input)
            {
                return input.Replace(@"../fonts/", @"/Content/fonts/")
                    ;
            }
        }

        public static void Register(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle("~/bundles/css")
                            .Include("~/Content/bootstrap.css", new BootstrapResourcesTransform())
                            .Include("~/Content/toastr.css")
                            .IncludeDirectory("~/Content/Css/site/", "*.css", true));

            bundles.Add(new StyleBundle("~/bundles/css/"));

            // Remember order is important!
            bundles.Add(new ScriptBundle("~/bundles/js")
                            .Include("~/Scripts/jquery-2.0.3.js")
                            .Include("~/Scripts/jquery-ui-1.10.3.js")
                            .Include("~/Scripts/bootstrap.js")
                            .Include("~/Scripts/knockout-2.3.0.js")
                            .Include("~/Scripts/knockout.validation.js")
                            .Include("~/Scripts/toastr.js")
                            .Include("~/Scripts/knockout-sortable.js")
                            .IncludeDirectory("~/Scripts/extensions/", "*.js", true)
                            .IncludeDirectory("~/Scripts/site/", "*.js", true));

            bundles.Add(new ScriptBundle("~/bundles/html5shiv")
                            .Include("~/Scripts/html5shiv.js")
                            .Include("~/Scripts/respond.min.js"));
        }
    }
}

using System.Web.Optimization;

namespace Listy.Web
{
    public class BundleConfig
    {
        public class BootstrapResourcesTransform : IItemTransform
        {
            public string Process(string includedVirtualPath, string input)
            {
                return input.Replace(@"../fonts/", @"/Content/fonts/")
                    ;
            }
        }

        public static void Register(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle("~/bundles/css")
                            .Include("~/Content/bootstrap.css", new BootstrapResourcesTransform())
                            .Include("~/Content/toastr.css"));

            // Remember order is important!
            bundles.Add(new ScriptBundle("~/bundles/js")
                            .Include("~/Scripts/jquery-2.0.3.js")
                            .Include("~/Scripts/jquery-ui-1.10.3.js")
                            .Include("~/Scripts/bootstrap.js")
                            .Include("~/Scripts/knockout-2.3.0.js")
                            .Include("~/Scripts/knockout.validation.js")
                            .Include("~/Scripts/toastr.js")
                            .Include("~/Scripts/knockout-sortable.js")
                            .IncludeDirectory("~/Scripts/extensions/", "*.js", true)
                            .IncludeDirectory("~/Scripts/site/", "*.js", true));

            bundles.Add(new ScriptBundle("~/bundles/html5shiv")
                            .Include("~/Scripts/html5shiv.js")
                            .Include("~/Scripts/respond.min.js"));
        }
    }
}

Remove a bundle directive which pointed to an empty folder (which blew up Azure)


using System;
using System.Collections.Generic;
using System.Linq;
using Trek.BalihooApiClient;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            // https://github.com/balihoo/local-connect-client

            var client = new BalihooApiClient();
            //client.GenerateClientApiKey("", "");

            // Not sure where this list of location Ids are supposed to come from
            var list = new List<int> { 85104, 1103020 };

            var result = client.GetCampaigns(list);

            var tactics = (from location in result
                           from campaign in location.Value
                           from tactic in campaign.Tactics
                           select tactic.Id).Distinct().ToList();

            foreach (var tacticId in tactics)
            {
                var tacticMetrics = client.GetTacticMetrics(list, tacticId);
            }

            Console.ReadLine();
        }
    }

}

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

namespace Trek.BalihooApiClient.Sample
{
    class Program
    {
        static void Main()
        {
            // https://github.com/balihoo/local-connect-client

            var client = new BalihooApiClient();
            //client.GenerateClientApiKey("", "");

            // Not sure where this list of location Ids are supposed to come from
            var list = new List<int> { 85104, 1103020 };

            var result = client.GetCampaigns(list);

            var tactics = (from location in result
                           from campaign in location.Value
                           from tactic in campaign.Tactics
                           select tactic.Id).Distinct().ToList();

            foreach (var tacticId in tactics)
            {
                var tacticMetrics = client.GetTacticMetrics(list, tacticId);
            }

            Console.ReadLine();
        }
    }

}

Change namespace to match project

Change namespace to match project


using NBi.Xml.Settings;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace NBi.Xml
{
    [XmlInclude(typeof(InstanceUnique))]
    public class InstanceSettlingXml
    {
        [XmlElement("local-variable")]
        public InstanceVariableXml Variable { get; set; }

        [XmlElement("category")]
        public List<string> Categories { get; set; } = new List<string>();

        [XmlElement("trait")]
        public List<TraitXml> Traits { get; set; } = new List<TraitXml>();

        private static InstanceSettlingXml _unique { get; set; }
        public static InstanceSettlingXml Unique
        {
            get
            {
                _unique = _unique ?? new InstanceUnique();
                return _unique;
            }
        }

        public class InstanceUnique : InstanceSettlingXml
        { }
    }
}

using NBi.Xml.Settings;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace NBi.Xml
{
    [XmlInclude(typeof(InstanceUnique))]
    public class InstanceSettlingXml
    {
        [XmlElement("local-variable")]
        public InstanceVariableXml Variable { get; set; }

        [XmlElement("category")]
        public List<string> Categories { get; set; } = new List<string>();

        [XmlElement("trait")]
        public List<TraitXml> Traits { get; set; } = new List<TraitXml>();

        public static InstanceSettlingXml Unique { get; } = new InstanceUnique();

        public class InstanceUnique : InstanceSettlingXml
        { }
    }
}

Improve handling of the singleton pattern of UniqueInstance


using Microsoft.MSBuildProjectBuilder;
using NUnit.Framework;
using Shouldly;

namespace MSBuildProjectBuilder.UnitTest
{
    [TestFixture]
    public class ProjectTest
    {
        private ProjectBuilder _project;

        [OneTimeSetUp]
        public void TestInitialize()
        {
            _project = new ProjectBuilder();
        }

        [Test]
        public void Create()
        {
            string expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
</Project>";
            _project.Create();
            _project.ProjectRoot.RawXml.Replace("\r\n", System.Environment.NewLine).ShouldBe(expectedOutput);

            expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""4.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" DefaultTargets=""TestDefaultTarget"" InitialTargets=""TestInitialTarget"" Label=""TestLabel"">
</Project>";
            _project.Create("test.csproj", "4.0", "TestDefaultTarget", "TestInitialTarget", "TestLabel");
            _project.ProjectRoot.RawXml.Replace("\r\n", System.Environment.NewLine).ShouldBe(expectedOutput);
        }
    }
}

using Microsoft.MSBuildProjectBuilder;
using NUnit.Framework;
using Shouldly;

namespace MSBuildProjectBuilder.UnitTest
{
    [TestFixture]
    public class ProjectTest
    {
        private ProjectBuilder _project;

        [OneTimeSetUp]
        public void TestInitialize()
        {
            _project = new ProjectBuilder();
        }

        [Test]
        public void Create()
        {
            string expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""14.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
</Project>".Replace("\r\n", string.Empty).Replace("\n", string.Empty);
            _project.Create();
            _project.ProjectRoot.RawXml.Replace("\r\n", string.Empty).Replace("\n", string.Empty);.ShouldBe(expectedOutput);

            expectedOutput =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""4.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" DefaultTargets=""TestDefaultTarget"" InitialTargets=""TestInitialTarget"" Label=""TestLabel"">
</Project>".Replace("\r\n", string.Empty).Replace("\n", string.Empty);
            _project.Create("test.csproj", "4.0", "TestDefaultTarget", "TestInitialTarget", "TestLabel");
            _project.ProjectRoot.RawXml.Replace("\r\n", string.Empty).Replace("\n", string.Empty);.ShouldBe(expectedOutput);
        }
    }
}

Test removing new lines for compare

Test removing new lines for compare


using System;
using Autofac.Core;
using Autofac.Core.Registration;
using Autofac.Features.Metadata;
using Autofac.Test.Features.Metadata.TestTypes;
using Autofac.Util;
using Xunit;

namespace Autofac.Test.Features.Metadata
{
    public class StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied
    {
        private IContainer _container;

        public StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<object>();
            _container = builder.Build();
        }

        [Fact]
        public void ResolvingStronglyTypedMetadataWithoutDefaultValueThrowsException()
        {
            var exception = Assert.Throws<DependencyResolutionException>(
                () => _container.Resolve<Meta<object, MyMeta>>());

            var propertyName = ReflectionExtensions.GetProperty<MyMeta, int>(x => x.TheInt).Name;
            var message = string.Format(MetadataViewProviderResources.MissingMetadata, propertyName);

            Assert.Equal(message, exception.Message);
        }

        [Fact]
        public void ResolvingStronglyTypedMetadataWithDefaultValueProvidesDefault()
        {
            var m = _container.Resolve<Meta<object, MyMetaWithDefault>>();
            Assert.Equal(42, m.Metadata.TheInt);
        }
    }
}

using Autofac.Core;
using Autofac.Features.Metadata;
using Autofac.Test.Features.Metadata.TestTypes;
using Autofac.Util;
using Xunit;

namespace Autofac.Test.Features.Metadata
{
    public class StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied
    {
        private readonly IContainer _container;

        public StronglyTypedMeta_WhenNoMatchingMetadataIsSupplied()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<object>();
            _container = builder.Build();
        }

        [Fact]
        public void ResolvingStronglyTypedMetadataWithoutDefaultValueThrowsException()
        {
            var exception = Assert.Throws<DependencyResolutionException>(
                () => _container.Resolve<Meta<object, MyMeta>>());

            var propertyName = ReflectionExtensions.GetProperty<MyMeta, int>(x => x.TheInt).Name;
            var message = string.Format(MetadataViewProviderResources.MissingMetadata, propertyName);

            Assert.Equal(message, exception.InnerException.Message);
        }

        [Fact]
        public void ResolvingStronglyTypedMetadataWithDefaultValueProvidesDefault()
        {
            var m = _container.Resolve<Meta<object, MyMetaWithDefault>>();
            Assert.Equal(42, m.Metadata.TheInt);
        }
    }
}

Fix broken metadata unit test

Fix broken metadata unit test


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

namespace Stripe
{
    public class StripeSubscriptionItem : StripeEntityWithId, ISupportMetadata
    {
        [JsonProperty("object")]
        public string Object { get; set; }

        [JsonProperty("created")]
        [JsonConverter(typeof(StripeDateTimeConverter))]
        public DateTime Created { get; set; }

        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }

        [JsonProperty("plan")]
        public StripePlan Plan { get; set; }

        [JsonProperty("quantity")]
        public int Quantity { get; set; }
    }
}

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

namespace Stripe
{
    public class StripeSubscriptionItem : StripeEntityWithId, ISupportMetadata
    {
        [JsonProperty("object")]
        public string Object { get; set; }

        [JsonProperty("created")]
        [JsonConverter(typeof(StripeDateTimeConverter))]
        public DateTime Created { get; set; }

        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }

        [JsonProperty("plan")]
        public StripePlan Plan { get; set; }

        [JsonProperty("quantity")]
        public int Quantity { get; set; }

        [JsonProperty("subscription")]
        public string Subscription { get; set; }
    }
}

Add subscription to the subscription item class


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using SimpleScale.HeadNode;

namespace TestApp
{
    public class Member {
        public string Name;
    }

    public class ValueMemberMapJob : IMapJob<Member>
    {
        public void DoWork(Job<Member> job)
        {
            MessageBox.Show("Processing member " + job.Info.Name);
            Thread.Sleep(1000);
            MessageBox.Show("Member " + job.Info.Name + " processed");
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var queueManager = new MemoryQueueManager<Member>();
            var mapService = new MapService<Member>(queueManager, new ValueMemberMapJob());

            queueManager.Add(GetJobs());
            mapService.Start();
        }

        public List<Job<Member>> GetJobs()
        {
            var job1 = new Job<Member>(0, new Member{ Name = "Tom"});
            var job2 = new Job<Member>(1, new Member{ Name = "Dick"});
            var job3 = new Job<Member>(2, new Member{ Name = "Harry"});

            return new List<Job<Member>>{
                job1, job2, job3
            };
        }

    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using SimpleScale.HeadNode;

namespace TestApp
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var queueManager = new MemoryQueueManager<Member>();
            var mapService = new MapService<Member>(queueManager, new ValueMemberMapJob());

            queueManager.Add(GetJobs());
            mapService.Start();
        }

        public List<Job<Member>> GetJobs()
        {
            var job1 = new Job<Member>(0, new Member{ Name = "Tom"});
            var job2 = new Job<Member>(1, new Member{ Name = "Dick"});
            var job3 = new Job<Member>(2, new Member{ Name = "Harry"});

            return new List<Job<Member>>{
                job1, job2, job3
            };
        }

    }
    public class Member {
        public string Name;
    }

    public class ValueMemberMapJob : IMapJob<Member>
    {
        public void DoWork(Job<Member> job)
        {
            MessageBox.Show("Processing member " + job.Info.Name);
            Thread.Sleep(1000);
            MessageBox.Show("Member " + job.Info.Name + " processed");
        }
    }
}

Rearrange class order so form designer works


using ChessDotNet;
using ChessDotNet.Variants.Crazyhouse;
using System.Collections.Generic;

namespace ChessVariantsTraining.Extensions
{
    public static class ChessGameExtensions
    {
        public static Dictionary<string, int> GenerateJsonPocket(this ChessGame game)
        {
            CrazyhouseChessGame zhCurrent = game as CrazyhouseChessGame;
            if (zhCurrent == null)
            {
                return null;
            }

            Dictionary<string, int> pocket = new Dictionary<string, int>();
            foreach (Piece p in zhCurrent.WhitePocket)
            {
                string key = "white-" + p.GetType().Name.ToLowerInvariant();
                if (!pocket.ContainsKey(key))
                {
                    pocket.Add(key, 1);
                }
                else
                {
                    pocket[key]++;
                }
            }

            foreach (Piece p in zhCurrent.BlackPocket)
            {
                string key = "black-" + p.GetType().Name.ToLowerInvariant();
                if (!pocket.ContainsKey(key))
                {
                    pocket.Add(key, 1);
                }
                else
                {
                    pocket[key]++;
                }
            }

            return pocket;
        }
    }
}

using ChessDotNet;
using ChessDotNet.Variants.Crazyhouse;
using System.Collections.Generic;

namespace ChessVariantsTraining.Extensions
{
    public static class ChessGameExtensions
    {
        public static Dictionary<string, int> GenerateJsonPocket(this ChessGame game)
        {
            CrazyhouseChessGame zhCurrent = game as CrazyhouseChessGame;
            if (zhCurrent == null)
            {
                return null;
            }

            Dictionary<string, int> pocket = new Dictionary<string, int>()
            {
                { "white-queen", 0 },
                { "white-rook", 0 },
                { "white-bishop", 0 },
                { "white-knight", 0 },
                { "white-pawn", 0 },
                { "black-queen", 0 },
                { "black-rook", 0 },
                { "black-bishop", 0 },
                { "black-knight", 0 },
                { "black-pawn", 0 }
            };
            foreach (Piece p in zhCurrent.WhitePocket)
            {
                string key = "white-" + p.GetType().Name.ToLowerInvariant();
                pocket[key]++;
            }

            foreach (Piece p in zhCurrent.BlackPocket)
            {
                string key = "black-" + p.GetType().Name.ToLowerInvariant();
                pocket[key]++;
            }

            return pocket;
        }
    }
}

Rewrite GenerateJsonPocket to complete output


using System;
using MonoTouch.ObjCRuntime;

[assembly: LinkWith ("libPayPalMobile.a",
                     LinkTarget.ArmV7 | LinkTarget.ArmV7s | LinkTarget.Simulator,
                     ForceLoad = true,
                     Frameworks="AVFoundation CoreMedia CoreVideo SystemConfiguration Security MessageUI OpenGLES MobileCoreServices",
                     LinkerFlags="-lz -lxml2 -lc++"
                     )]

using System;
using MonoTouch.ObjCRuntime;

[assembly: LinkWith ("libPayPalMobile.a",
                     LinkTarget.ArmV7 | LinkTarget.ArmV7s | LinkTarget.Simulator,
                     ForceLoad = true,
                     Frameworks="AVFoundation CoreMedia CoreVideo SystemConfiguration Security MessageUI OpenGLES MobileCoreServices",
                     LinkerFlags="-lz -lxml2 -lc++ -lstdc++"
                     )]

Fix linking errors when compiled for arm


using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace Totem.Runtime
{
  /// <summary>
  /// A user or process establishing a security context with a runtime service
  /// </summary>
  public class Client
  {
    public Client()
    {
      Id = Id.Unassigned;
      Principal = new ClaimsPrincipal();
    }

    public Client(Id id, ClaimsPrincipal principal)
    {
      Id = id;
      Principal = principal;
    }

    public Id Id { get; }
    public ClaimsPrincipal Principal { get; }

    public bool IsAuthenticated => Principal.Identity?.IsAuthenticated ?? false;
    public string Name => Principal.Identity?.Name ?? "";

    public override string ToString() => Name;
  }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace Totem.Runtime
{
  /// <summary>
  /// A user or process establishing a security context with a runtime service
  /// </summary>
  public class Client
  {
    public Client()
    {
      Id = Id.Unassigned;
      Principal = new ClaimsPrincipal();
    }

    public Client(Id id, ClaimsPrincipal principal)
    {
      Id = id;
      Principal = principal;
    }

    public Id Id { get; }
    public ClaimsPrincipal Principal { get; }

    public bool IsAnonymous => !Principal.Identity?.IsAuthenticated ?? true;
    public bool IsAuthenticated => Principal.Identity?.IsAuthenticated ?? false;
    public string Name => Principal.Identity?.Name ?? "";

    public override string ToString() => Name;
  }
}

Add check for anonymous clients

Add check for anonymous clients


namespace NEventSocket.Tests.Sockets
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    using Common.Logging;
    using Common.Logging.Simple;

    using Xunit;

    public class OutboundSocketTests
    {
        public OutboundSocketTests()
        {
            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(
                   LogLevel.All, true, true, true, "yyyy-MM-dd hh:mm:ss");
        }

        [Fact]
        public async Task On_calling_connect_it_should_populate_the_channel_data()
        {
            using (var listener = new OutboundListener(8084))
            {
                listener.Start();
                bool wasConnected = false;

                listener.Connections.Subscribe(
                    async (socket) =>
                    {
                        await socket.Connect();
                        wasConnected = socket.ChannelData != null;
                        await socket.SendCommandAsync("say hello!");
                    });

                var fakeSocket = new FakeFreeSwitchOutbound(8084);
                fakeSocket.MessagesReceived.Subscribe(x => Console.WriteLine(x));
                await fakeSocket.SendChannelDataEvent();

                Thread.Sleep(1000);
                Assert.True(wasConnected);
            }
        }
    }
}

namespace NEventSocket.Tests.Sockets
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    using Common.Logging;
    using Common.Logging.Simple;

    using Xunit;

    public class OutboundSocketTests
    {
        public OutboundSocketTests()
        {
            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(
                   LogLevel.All, true, true, true, "yyyy-MM-dd hh:mm:ss");
        }

        [Fact(Timeout = 1000)]
        public async Task On_calling_connect_it_should_populate_the_channel_data()
        {
            using (var listener = new OutboundListener(8084))
            {
                listener.Start();
                bool gotChannelData = false;

                listener.Connections.Subscribe(
                    async (socket) =>
                    {
                        await socket.Connect();
                        gotChannelData = socket.ChannelData != null;
                    });

                var fakeSocket = new FakeFreeSwitchOutbound(8084);
                await fakeSocket.SendChannelDataEvent();

                Thread.Sleep(100);
                Assert.True(gotChannelData);
            }
        }
    }
}

Make ObservableSocket log using it's inherited type


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

using osu.Game.Overlays.Profile.Sections;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;

namespace osu.Game.Tests.Visual.Online
{
    public class TestSceneShowMoreButton : OsuTestScene
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(ShowMoreButton),
        };

        public TestSceneShowMoreButton()
        {
            ShowMoreButton button;

            Add(button = new ShowMoreButton
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
            });

            AddStep("switch loading state", () => button.IsLoading = !button.IsLoading);
        }
    }
}

// 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.Overlays.Profile.Sections;
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;

namespace osu.Game.Tests.Visual.Online
{
    public class TestSceneShowMoreButton : OsuTestScene
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(ShowMoreButton),
        };

        public TestSceneShowMoreButton()
        {
            ShowMoreButton button;

            Add(button = new ShowMoreButton
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Action = () => { }
            });

            AddStep("switch loading state", () => button.IsLoading = !button.IsLoading);
        }
    }
}

Add sample action to test so hover effect is visible


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

using System.Threading.Tasks;

namespace osu.Game.Online.RealtimeMultiplayer
{
    /// <summary>
    /// An interface defining a spectator client instance.
    /// </summary>
    public interface IMultiplayerClient
    {
        /// <summary>
        /// Signals that the room has changed state.
        /// </summary>
        /// <param name="state">The state of the room.</param>
        Task RoomStateChanged(MultiplayerRoomState state);
    }
}

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

using System.Threading.Tasks;

namespace osu.Game.Online.RealtimeMultiplayer
{
    /// <summary>
    /// An interface defining a spectator client instance.
    /// </summary>
    public interface IMultiplayerClient
    {
        /// <summary>
        /// Signals that the room has changed state.
        /// </summary>
        /// <param name="state">The state of the room.</param>
        Task RoomStateChanged(MultiplayerRoomState state);

        /// <summary>
        /// Signals that a user has joined the room.
        /// </summary>
        /// <param name="user">The user.</param>
        Task UserJoined(MultiplayerRoomUser user);

        /// <summary>
        /// Signals that a user has left the room.
        /// </summary>
        /// <param name="user">The user.</param>
        Task UserLeft(MultiplayerRoomUser user);
    }
}

Add callbacks for join/leave events to notify other room occupants


using System;
using System.Text.RegularExpressions;
using System.Web;

namespace Cassette.Aspnet
{
    public class RawFileRequestRewriter
    {
        readonly HttpContextBase context;
        readonly IFileAccessAuthorization fileAccessAuthorization;
        readonly HttpRequestBase request;

        public RawFileRequestRewriter(HttpContextBase context, IFileAccessAuthorization fileAccessAuthorization)
        {
            this.context = context;
            this.fileAccessAuthorization = fileAccessAuthorization;
            request = context.Request;
        }

        public void Rewrite()
        {
            if (!IsCassetteRequest()) return;

            string path;
            if (!TryGetFilePath(out path)) return;

            EnsureFileCanBeAccessed(path);

            SetFarFutureExpiresHeader();
            context.RewritePath(path);
        }

        bool IsCassetteRequest()
        {
            return request.AppRelativeCurrentExecutionFilePath == "~/cassette.axd";
        }

        bool TryGetFilePath(out string path)
        {
            var match = Regex.Match(request.PathInfo, "/file/[^/]+/(.*)", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                path = "~/" + match.Groups[1].Value;
                return true;
            }

            path = null;
            return false;
        }

        void EnsureFileCanBeAccessed(string path)
        {
            if (!fileAccessAuthorization.CanAccess(path))
            {
                throw new HttpException(404, "File not found");
            }
        }

        void SetFarFutureExpiresHeader()
        {
            context.Response.Cache.SetExpires(DateTime.UtcNow.AddYears(1));
        }
    }
}

using System;
using System.Text.RegularExpressions;
using System.Web;

namespace Cassette.Aspnet
{
    public class RawFileRequestRewriter
    {
        readonly HttpContextBase context;
        readonly IFileAccessAuthorization fileAccessAuthorization;
        readonly HttpRequestBase request;

        public RawFileRequestRewriter(HttpContextBase context, IFileAccessAuthorization fileAccessAuthorization)
        {
            this.context = context;
            this.fileAccessAuthorization = fileAccessAuthorization;
            request = context.Request;
        }

        public void Rewrite()
        {
            if (!IsCassetteRequest()) return;

            string path;
            if (!TryGetFilePath(out path)) return;

            EnsureFileCanBeAccessed(path);

            SetFarFutureExpiresHeader();
            context.RewritePath(path);
        }

        bool IsCassetteRequest()
        {
            return request.AppRelativeCurrentExecutionFilePath.StartsWith("~/cassette.axd/file", StringComparison.OrdinalIgnoreCase);
        }

        bool TryGetFilePath(out string path)
        {
            var match = Regex.Match(request.AppRelativeCurrentExecutionFilePath, "/file/[^/]+/(.*)", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                path = "~/" + match.Groups[1].Value;
                return true;
            }

            path = null;
            return false;
        }

        void EnsureFileCanBeAccessed(string path)
        {
            if (!fileAccessAuthorization.CanAccess(path))
            {
                throw new HttpException(404, "File not found");
            }
        }

        void SetFarFutureExpiresHeader()
        {
            context.Response.Cache.SetExpires(DateTime.UtcNow.AddYears(1));
        }
    }
}

Change raw file request rewriter to use AppRelativeCurrentExecutionFilePath instead of PathInfo to determine the file path. When not running in IIS PathInfo seems to be empty at the point when the rewriter is called.


using System;

namespace Lime.Protocol.Network
{
    public class EnvelopeTooLargeException : Exception
    {
        public EnvelopeTooLargeException()
            : base()
        {
        }

        public EnvelopeTooLargeException(string message)
            : base(message)
        {
        }

        public EnvelopeTooLargeException(string message, Envelope envelope)
            : base(message)
        {
            AddEnvelopePropertiesToData(envelope);
        }

        public EnvelopeTooLargeException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        public EnvelopeTooLargeException(string message, Envelope envelope, Exception innerException)
            : base(message, innerException)
        {
            AddEnvelopePropertiesToData(envelope);
        }

        private void AddEnvelopePropertiesToData(Envelope envelope)
        {
            Data["EnvelopeType"] = envelope.GetType().Name;
            Data[nameof(envelope.Id)] = envelope.Id?.ToString();
            Data[nameof(envelope.To)] = envelope.To?.ToString();
            Data[nameof(envelope.From)] = envelope.From?.ToString();
            Data[nameof(envelope.Pp)] = envelope.Pp?.ToString();
            Data[nameof(envelope.Metadata)] = envelope.Metadata;
        }
    }
}

using System;

namespace Lime.Protocol.Network
{
    public class EnvelopeTooLargeException : Exception
    {
        public EnvelopeTooLargeException()
            : base()
        {
        }

        public EnvelopeTooLargeException(string message)
            : base(message)
        {
        }

        public EnvelopeTooLargeException(string message, Envelope envelope)
            : base(message)
        {
            AddEnvelopePropertiesToData(envelope);
        }

        public EnvelopeTooLargeException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        public EnvelopeTooLargeException(string message, Envelope envelope, Exception innerException)
            : base(message, innerException)
        {
            AddEnvelopePropertiesToData(envelope);
        }

        private void AddEnvelopePropertiesToData(Envelope envelope)
        {
            Data["EnvelopeType"] = envelope.GetType().Name;
            Data[nameof(envelope.Id)] = envelope.Id;
            Data[nameof(envelope.To)] = envelope.To?.ToString();
            Data[nameof(envelope.From)] = envelope.From?.ToString();
            Data[nameof(envelope.Pp)] = envelope.Pp?.ToString();
            Data[nameof(envelope.Metadata)] = envelope.Metadata;
        }
    }
}

Remove unneed ToString (on string)

Remove unneed ToString (on string)


@model Devworx.CodePrettify.ViewModels.CodePrettifySettingsViewModel

<fieldset>
    <legend>@T("Code Prettify")</legend>

        @Html.EditorFor(m => m.PrettifySettingsPart.UseAutoLoader)
         m.PrettifySettingsPart.UseAutoLoader)" class="forcheckbox">@T("Use default async auto load script.")
        @Html.ValidationMessageFor(m => m.PrettifySettingsPart.UseAutoLoader)
        @T("If checked, will be loaded using the 'run_prettify.js' script from github asynchronously, and only themes available in the theme gallery are supported. You will also have to manually add the class=\"prettyprint\" to all <pre> and/or <code> tags that need to be prettyprint'd")

        @T("Theme")
        @Html.DropDownList("Theme", new[] {new SelectListItem {Text = T("").Text, Value = ""}}.Union(new SelectList(Model.Themes, "", "", Model.PrettifySettingsPart.Theme)))
        @Html.ValidationMessage("Theme", "*")

</fieldset>

@model Devworx.CodePrettify.ViewModels.CodePrettifySettingsViewModel

<fieldset>
    <legend>@T("Code Prettify")</legend>

        @Html.CheckBox("UseAutoLoader", Model.PrettifySettingsPart.UseAutoLoader)
        @T("Use default async auto load script.")
        @T("If checked, will be loaded using the 'run_prettify.js' script from github asynchronously, and only themes available in the theme gallery are supported. You will also have to manually add the class=\"prettyprint\" to all <pre> and/or <code> tags that need to be prettyprint'd")

        @T("Theme")
        @Html.DropDownList("Theme", new[] {new SelectListItem {Text = T("").Text, Value = ""}}.Union(new SelectList(Model.Themes, "", "", Model.PrettifySettingsPart.Theme)))
        @Html.ValidationMessage("Theme", "*")

</fieldset>

Fix change that broke updating the setting.


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

using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Edit;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Screens.Play.HUD;

namespace osu.Game.Skinning.Editor
{
    public class SkinBlueprintContainer : BlueprintContainer<ISkinnableComponent>
    {
        private readonly Drawable target;

        public SkinBlueprintContainer(Drawable target)
        {
            this.target = target;
        }

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

            ISkinnableComponent[] components = target.ChildrenOfType<ISkinnableComponent>().ToArray();

            foreach (var c in components) AddBlueprintFor(c);
        }

        protected override SelectionHandler<ISkinnableComponent> CreateSelectionHandler() => new SkinSelectionHandler();

        protected override SelectionBlueprint<ISkinnableComponent> CreateBlueprintFor(ISkinnableComponent component)
            => new SkinBlueprint(component);
    }
}

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

using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Edit;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Screens.Play.HUD;

namespace osu.Game.Skinning.Editor
{
    public class SkinBlueprintContainer : BlueprintContainer<ISkinnableComponent>
    {
        private readonly Drawable target;

        public SkinBlueprintContainer(Drawable target)
        {
            this.target = target;
        }

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

            checkForComponents();
        }

        private void checkForComponents()
        {
            foreach (var c in target.ChildrenOfType<ISkinnableComponent>().ToArray()) AddBlueprintFor(c);

            Scheduler.AddDelayed(checkForComponents, 1000);
        }

        protected override SelectionHandler<ISkinnableComponent> CreateSelectionHandler() => new SkinSelectionHandler();

        protected override SelectionBlueprint<ISkinnableComponent> CreateBlueprintFor(ISkinnableComponent component)
            => new SkinBlueprint(component);
    }
}

Check for new components every one second to handle late loaders


using System.Collections.Generic;
using System.Linq;
using Avalonia.VisualTree;

namespace Avalonia.Rendering
{
    /// <summary>
    /// An interface to allow non-templated controls to customize their hit-testing
    /// when using a renderer with a simple hit-testing algorithm without a scene graph,
    /// such as <see cref="ImmediateRenderer" />
    /// </summary>
    public interface ICustomSimpleHitTest
    {
        bool HitTest(Point point);
    }

    /// <summary>
    /// Allows customization of hit-testing for all renderers.
    /// </summary>
    /// <remarks>
    /// Note that this interface can only used to make a portion of a control non-hittable, it
    /// cannot expand the hittable area of a control.
    /// </remarks>
    public interface ICustomHitTest : ICustomSimpleHitTest
    {
    }

    public static class CustomSimpleHitTestExtensions
    {
        public static bool HitTestCustom(this IVisual visual, Point point)
            => (visual as ICustomSimpleHitTest)?.HitTest(point) ?? visual.TransformedBounds?.Contains(point) == true;

        public static bool HitTestCustom(this IEnumerable<IVisual> children, Point point)
            => children.Any(ctrl => ctrl.HitTestCustom(point));
    }
}

using System.Collections.Generic;
using System.Linq;
using Avalonia.VisualTree;

namespace Avalonia.Rendering
{
    /// <summary>
    /// An interface to allow non-templated controls to customize their hit-testing
    /// when using a renderer with a simple hit-testing algorithm without a scene graph,
    /// such as <see cref="ImmediateRenderer" />
    /// </summary>
    public interface ICustomSimpleHitTest
    {
        bool HitTest(Point point);
    }

    /// <summary>
    /// Allows customization of hit-testing for all renderers.
    /// </summary>
    public interface ICustomHitTest : ICustomSimpleHitTest
    {
    }

    public static class CustomSimpleHitTestExtensions
    {
        public static bool HitTestCustom(this IVisual visual, Point point)
            => (visual as ICustomSimpleHitTest)?.HitTest(point) ?? visual.TransformedBounds?.Contains(point) == true;

        public static bool HitTestCustom(this IEnumerable<IVisual> children, Point point)
            => children.Any(ctrl => ctrl.HitTestCustom(point));
    }
}

ICustomHitTest: Remove comment, expanding the hittable area is possible


//  https://leetcode.com/submissions/detail/52724586/
//
//
//  Submission Details
//  164 / 164 test cases passed.
//      Status: Accepted
//      Runtime: 160 ms
//
//          Submitted: 0 minutes ago
//

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode DeleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
        {
            return head;
        }

        head.next = DeleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
    }
}

//
//  Submission Details
//  164 / 164 test cases passed.
//      Status: Accepted
//      Runtime: 164 ms
//
//          Submitted: 0 minutes ago
//
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode DeleteDuplicates(ListNode head) {
        var dummy = new ListNode(int.MaxValue);
        var it = dummy;
        while (head != null)
        {
            var next = head.next;
            if (it.val != head.val)
            {
                it.next = head;
                it = it.next;
                it.next = null;
            }

            head = next;
        }

        return dummy.next;
    }
}

Remove duplicates from sorted list - slower lol


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

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

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

        public IPEndPoint IPEndPoint { get; set; }

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

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

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

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

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

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

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

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

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

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

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

        public IPEndPoint IPEndPoint { get; set; }

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

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

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

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

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

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

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

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

Read available data inside of while loop


using System;

namespace Evolve.Test.Utilities
{
    public class CassandraDockerContainer
    {
        private DockerContainer _container;

        public string Id => _container.Id;
        public string ExposedPort => "9042";
        public string HostPort => "9042";
        public string ClusterName => "evolve";
        public string DataCenter => "dc1";
        public TimeSpan DelayAfterStartup => TimeSpan.FromMinutes(1);

        public bool Start(bool fromScratch = false)
        {
            _container = new DockerContainerBuilder(new DockerContainerBuilderOptions
            {
                FromImage = "cassandra",
                Tag = "latest",
                Name = "cassandra-evolve",
                Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" },
                ExposedPort = $"{ExposedPort}/tcp",
                HostPort = HostPort,
                DelayAfterStartup = DelayAfterStartup,
                RemovePreviousContainer = fromScratch
            }).Build();

            return _container.Start();
        }
        public void Remove() => _container.Remove();
        public bool Stop() => _container.Stop();
        public void Dispose() => _container?.Dispose();
    }
}

using System;

namespace Evolve.Test.Utilities
{
    public class CassandraDockerContainer
    {
        private DockerContainer _container;

        public string Id => _container.Id;
        public string ExposedPort => "9042";
        public string HostPort => "9042";
        public string ClusterName => "evolve";
        public string DataCenter => "dc1";
        public TimeSpan DelayAfterStartup => TimeSpan.FromSeconds(90);

        public bool Start(bool fromScratch = false)
        {
            _container = new DockerContainerBuilder(new DockerContainerBuilderOptions
            {
                FromImage = "cassandra",
                Tag = "latest",
                Name = "cassandra-evolve",
                Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" },
                ExposedPort = $"{ExposedPort}/tcp",
                HostPort = HostPort,
                DelayAfterStartup = DelayAfterStartup,
                RemovePreviousContainer = fromScratch
            }).Build();

            return _container.Start();
        }
        public void Remove() => _container.Remove();
        public bool Stop() => _container.Stop();
        public void Dispose() => _container?.Dispose();
    }
}

Increase Cassandra delay after startup (90 sec)


using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Deployment.WindowsInstaller;

namespace IndexerSetup.RegisterProperties
{
    public class RegisterAction
    {
        [CustomAction]
        public static ActionResult RegisterPropDescFile(Session session)
        {
            session.Log("Registering property description file...");

            string propdescPath = Path.Combine(session.GetTargetPath("INSTALLDIR"), "WordPerfectIndexer.propdesc");
            bool registerSucceeded = PSRegisterPropertySchema(propdescPath);

            if (registerSucceeded) return ActionResult.Success;
            else return ActionResult.Failure;
        }

        [DllImport("propsys.dll", CharSet = CharSet.Unicode)]
        public static extern bool PSRegisterPropertySchema(string propdescPath);
    }
}

using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Deployment.WindowsInstaller;

namespace IndexerSetup.RegisterProperties
{
    public class RegisterAction
    {
        [CustomAction]
        public static ActionResult RegisterPropDescFile(Session session)
        {
            session.Log("Registering property description file...");

            string propdescPath = Path.Combine(session.GetTargetPath("INSTALLFOLDER"), "WordPerfectIndexer.propdesc");
            bool registerSucceeded = PSRegisterPropertySchema(propdescPath);

            if (registerSucceeded) return ActionResult.Success;
            else return ActionResult.Failure;
        }

        [DllImport("propsys.dll", CharSet = CharSet.Unicode)]
        public static extern bool PSRegisterPropertySchema(string propdescPath);
    }
}

Fix error in custom action code

Fix error in custom action code

This was causing the install to fail silently with no error message.


namespace Stripe
{
    using Newtonsoft.Json;

    ///
    /// The optional arguments you can pass. Stripe Documentation.
    ///
    public class DisputeListOptions : ListOptionsWithCreated
    {
        ///
        /// Only return disputes that are associated with the Charge specified by this Charge ID.
        ///
        [JsonProperty("charge")]
        public string Charge { get; set; }
    }
}

namespace Stripe
{
    using Newtonsoft.Json;

    ///
    /// The optional arguments you can pass. Stripe Documentation.
    ///
    public class DisputeListOptions : ListOptionsWithCreated
    {
        ///
        /// Only return disputes that are associated with the Charge specified by this Charge ID.
        ///
        [JsonProperty("charge")]
        public string Charge { get; set; }

        ///
        /// Only return disputes that are associated with the PaymentIntent specified by this PaymentIntent ID.
        ///
        [JsonProperty("payment_intent")]
        public string PaymentIntent { get; set; }
    }
}

Add PaymentIntent to filter lists of Disputes


// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Platform;
using osu.Game.Database;

namespace osu.Game.IPC
{
    public class ArchiveImportIPCChannel : IpcChannel<ArchiveImportMessage>
    {
        private readonly ICanAcceptFiles importer;

        public ArchiveImportIPCChannel(IIpcHost host, ICanAcceptFiles importer = null)
            : base(host)
        {
            this.importer = importer;
            MessageReceived += msg =>
            {
                Debug.Assert(importer != null);
                ImportAsync(msg.Path).ContinueWith(t =>
                {
                    if (t.Exception != null) throw t.Exception;
                }, TaskContinuationOptions.OnlyOnFaulted);
            };
        }

        public async Task ImportAsync(string path)
        {
            if (importer == null)
            {
                // we want to contact a remote osu! to handle the import.
                await SendMessageAsync(new ArchiveImportMessage { Path = path }).ConfigureAwait(false);
                return;
            }

            if (importer.HandledExtensions.Contains(Path.GetExtension(path)?.ToLowerInvariant()))
                await importer.Import(path).ConfigureAwait(false);
        }
    }

    public class ArchiveImportMessage
    {
        public string Path;
    }
}

// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Platform;
using osu.Game.Database;

namespace osu.Game.IPC
{
    public class ArchiveImportIPCChannel : IpcChannel<ArchiveImportMessage>
    {
        private readonly ICanAcceptFiles importer;

        public ArchiveImportIPCChannel(IIpcHost host, ICanAcceptFiles importer = null)
            : base(host)
        {
            this.importer = importer;
            MessageReceived += msg =>
            {
                Debug.Assert(importer != null);
                ImportAsync(msg.Path).ContinueWith(t =>
                {
                    if (t.Exception != null) throw t.Exception;
                }, TaskContinuationOptions.OnlyOnFaulted);

                return null;
            };
        }

        public async Task ImportAsync(string path)
        {
            if (importer == null)
            {
                // we want to contact a remote osu! to handle the import.
                await SendMessageAsync(new ArchiveImportMessage { Path = path }).ConfigureAwait(false);
                return;
            }

            if (importer.HandledExtensions.Contains(Path.GetExtension(path)?.ToLowerInvariant()))
                await importer.Import(path).ConfigureAwait(false);
        }
    }

    public class ArchiveImportMessage
    {
        public string Path;
    }
}

Update IPC usage to return `null`

Update IPC usage to return `null`


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PracticeGit.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

// ADDED FIRST LINE

namespace PracticeGit.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }
}

Test Major/Minor versions - Commit 1

Test Major/Minor versions - Commit 1


using System;
using System.Diagnostics;

namespace Toppler.Tests.Integration.TestHelpers
{
    public class TestBase
    {
        private static Random Generator = new Random();

        protected string TestEventSource { get; private set; }
        protected string TestDimension { get; private set; }
        public TestBase()
        {
            this.TestEventSource = RandomEventSource();

            this.TestDimension = RandomDimension();
            this.TestDimension = "mydimension";
        }

        protected bool Reset()
        {
            return RedisServer.Reset();
        }

        #region Monitor
        private Process RedisCli;
        protected void StartMonitor()
        {
            if (RedisCli == null)
            {
                RedisCli = RedisServer.StartNewMonitor();
                RedisCli.BeginOutputReadLine();
                RedisCli.OutputDataReceived += (e, s) =>
                {
                    Trace.WriteLine(s.Data);
                };
            }
        }
        protected void StopMonitor()
        {
            if (RedisCli != null)
                RedisCli.Kill();
        }
        #endregion"

        public static int RandomHits()
        {
            return Generator.Next(1000);
        }

        public static string RandomEventSource()
        {
            return "es-" + Generator.Next(1000).ToString();
        }

        public static string RandomDimension()
        {
            return "dim-" + Generator.Next(1000).ToString();
        }
    }
}

using System;
using System.Diagnostics;

namespace Toppler.Tests.Integration.TestHelpers
{
    public class TestBase
    {
        private static Random Generator = new Random();

        protected string TestEventSource { get; private set; }
        protected string TestDimension { get; private set; }
        public TestBase()
        {
            this.TestEventSource = RandomEventSource();
            this.TestDimension = RandomDimension();
        }

        protected bool Reset()
        {
            return RedisServer.Reset();
        }

        #region Monitor
        private Process RedisCli;
        protected void StartMonitor()
        {
            if (RedisCli == null)
            {
                RedisCli = RedisServer.StartNewMonitor();
                RedisCli.BeginOutputReadLine();
                RedisCli.OutputDataReceived += (e, s) =>
                {
                    Trace.WriteLine(s.Data);
                };
            }
        }
        protected void StopMonitor()
        {
            if (RedisCli != null)
                RedisCli.Kill();
        }
        #endregion"

        public static int RandomHits()
        {
            return Generator.Next(1000);
        }

        public static string RandomEventSource()
        {
            return "es-" + Generator.Next(1000).ToString();
        }

        public static string RandomDimension()
        {
            return "dim-" + Generator.Next(1000).ToString();
        }
    }
}

Fix Dimension in integration tests

Fix Dimension in integration tests


using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using Palaso.IO;

namespace Palaso.UI.WindowsForms.ReleaseNotes
{
	/// <summary>
	/// Shows a dialog for release notes; accepts html and markdown
	/// </summary>
	public partial class ShowReleaseNotesDialog : Form
	{
		private readonly string _path;
		private TempFile _temp;

		public ShowReleaseNotesDialog(System.Drawing.Icon icon, string path)
		{
			_path = path;
			Icon = icon;
			InitializeComponent();
		}

		private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
		{
			string contents = File.ReadAllText(_path);

			var md = new Markdown();
			_temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp
			File.WriteAllText(_temp.Path, md.Transform(contents));
			_browser.Url = new Uri(_temp.Path);
		}
	}
}

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Palaso.IO;

namespace Palaso.UI.WindowsForms.ReleaseNotes
{
	/// <summary>
	/// Shows a dialog for release notes; accepts html and markdown
	/// </summary>
	public partial class ShowReleaseNotesDialog : Form
	{
		private readonly string _path;
		private TempFile _temp;
		private readonly Icon _icon;

		public ShowReleaseNotesDialog(Icon icon, string path)
		{
			_path = path;
			_icon = icon;
			InitializeComponent();
		}

		private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
		{
			string contents = File.ReadAllText(_path);

			var md = new Markdown();
			_temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp
			File.WriteAllText(_temp.Path, md.Transform(contents));
			_browser.Url = new Uri(_temp.Path);
		}

		protected override void OnHandleCreated(EventArgs e)
		{
			base.OnHandleCreated(e);

			// a bug in Mono requires us to wait to set Icon until handle created.
			Icon = _icon;
		}
	}
}

Set the icon for the release notes dialog so it displays correctly on Linux