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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Threading;
using osu.Game.Graphics.Backgrounds;

namespace osu.Game.Screens.Backgrounds
{
    public class BackgroundScreenDefault : BackgroundScreen
    {
        private int currentDisplay;
        private const int background_count = 5;

        private string backgroundName => $@"Menu/menu-background-{currentDisplay % background_count + 1}";

        private Background current;

        [BackgroundDependencyLoader]
        private void load()
        {
            display(new Background(backgroundName));
        }

        private void display(Background newBackground)
        {
            current?.FadeOut(800, Easing.InOutSine);
            current?.Expire();

            Add(current = newBackground);
            currentDisplay++;
        }

        private ScheduledDelegate nextTask;

        public void Next()
        {
            nextTask?.Cancel();
            nextTask = Scheduler.AddDelayed(() =>
            {
                LoadComponentAsync(new Background(backgroundName) { Depth = currentDisplay }, display);
            }, 100);
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.MathUtils;
using osu.Framework.Threading;
using osu.Game.Graphics.Backgrounds;

namespace osu.Game.Screens.Backgrounds
{
    public class BackgroundScreenDefault : BackgroundScreen
    {
        private int currentDisplay;
        private const int background_count = 5;

        private string backgroundName => $@"Menu/menu-background-{currentDisplay % background_count + 1}";

        private Background current;

        [BackgroundDependencyLoader]
        private void load()
        {
            currentDisplay = RNG.Next(0, background_count);
            display(new Background(backgroundName));
        }

        private void display(Background newBackground)
        {
            current?.FadeOut(800, Easing.InOutSine);
            current?.Expire();

            Add(current = newBackground);
            currentDisplay++;
        }

        private ScheduledDelegate nextTask;

        public void Next()
        {
            nextTask?.Cancel();
            nextTask = Scheduler.AddDelayed(() =>
            {
                LoadComponentAsync(new Background(backgroundName) { Depth = currentDisplay }, display);
            }, 100);
        }
    }
}

Use random default background on starting the game


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using SylphyHorn.Services;

namespace SylphyHorn.UI.Controls
{
	public class UnlockImageConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			try
			{
				if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return null;

				using (var stream = new FileStream((string)value, FileMode.Open))
				{
					var decoder = BitmapDecoder.Create(
						stream,
						BitmapCreateOptions.None,
						BitmapCacheOption.OnLoad);

					var bitmap = new WriteableBitmap(decoder.Frames[0]);
					bitmap.Freeze();

					return bitmap;
				}
			}
			catch (Exception ex)
			{
				LoggingService.Instance.Register(ex);
				return null;
			}
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using SylphyHorn.Services;

namespace SylphyHorn.UI.Controls
{
	public class UnlockImageConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			try
			{
				if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return null;

				var filename = (string)value;
				if (string.IsNullOrEmpty(filename)) return null;

				using (var stream = new FileStream(filename, FileMode.Open))
				{
					var decoder = BitmapDecoder.Create(
						stream,
						BitmapCreateOptions.None,
						BitmapCacheOption.OnLoad);

					var bitmap = new WriteableBitmap(decoder.Frames[0]);
					bitmap.Freeze();

					return bitmap;
				}
			}
			catch (Exception ex)
			{
				LoggingService.Instance.Register(ex);
				return null;
			}
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}

Fix issue to throw exception when wallpaper isn't set.


using System.Text.RegularExpressions;

namespace Sep.Git.Tfs
{
    public static class GitTfsConstants
    {
        public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
        public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
        public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");

        public const string DefaultRepositoryId = "default";

        public const string GitTfsPrefix = "git-tfs";
        // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
        public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
        public static readonly Regex TfsCommitInfoRegex =
                new Regex("^\\s*" +
                          GitTfsPrefix +
                          "-id:\\s+" +
                          "\\[(?<url>.+)\\]" +
                          "(?<repository>.+);" +
                          "C(?<changeset>\\d+)" +
                          "\\s*$");
    }
}

using System.Text.RegularExpressions;

namespace Sep.Git.Tfs
{
    public static class GitTfsConstants
    {
        public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
        public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
        public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");

        public const string DefaultRepositoryId = "default";

        public const string GitTfsPrefix = "git-tfs";
        // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
        public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
        public static readonly Regex TfsCommitInfoRegex =
                new Regex("^\\s*" +
                          GitTfsPrefix +
                          "-id:\\s+" +
                          "\\[(?<url>.+)\\]" +
                          "(?<repository>.+);" +
                          "C(?<changeset>\\d+)" +
                          "\\s*$");
        // e.g. git-tfs-work-item: 24 associate
        public static readonly Regex TfsWorkItemRegex =
                new Regex(@"^\s*"+ GitTfsPrefix + @"-work-item:\s+(?<item_id>\d+)\s(?<action>.+)");
    }
}

Add regex for associating work items

Add regex for associating work items


using PKISharp.WACS.Services;

namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns
{
    class Manual : DnsValidation<ManualOptions, Manual>
    {
        private IInputService _input;

        public Manual(ILogService log, IInputService input, ManualOptions options, string identifier) :  base(log, options, identifier)
        {
            // Usually it's a big no-no to rely on user input in validation plugin
            // because this should be able to run unattended. This plugin is for testing
            // only and therefor we will allow it. Future versions might be more advanced,
            // e.g. shoot an email to an admin and complete the order later.
            _input = input;
        }

        public override void CreateRecord(string recordName, string token)
        {
            _log.Warning("Create record {recordName} for domain {identifier} with content {token}", recordName, _identifier, token);
            _input.Wait();
        }

        public override void DeleteRecord(string recordName, string token)
        {
            _log.Warning("Delete record {recordName} for domain {identifier}", recordName, _identifier);
            _input.Wait();
        }
    }
}

using PKISharp.WACS.Services;

namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns
{
    class Manual : DnsValidation<ManualOptions, Manual>
    {
        private IInputService _input;

        public Manual(ILogService log, IInputService input, ManualOptions options, string identifier) :  base(log, options, identifier)
        {
            // Usually it's a big no-no to rely on user input in validation plugin
            // because this should be able to run unattended. This plugin is for testing
            // only and therefor we will allow it. Future versions might be more advanced,
            // e.g. shoot an email to an admin and complete the order later.
            _input = input;
        }

        public override void CreateRecord(string recordName, string token)
        {
            _input.Wait($"Create record {recordName} for domain {_identifier} with content {token} and press enter to continue...");
        }

        public override void DeleteRecord(string recordName, string token)
        {
            _input.Wait($"Delete record {recordName} for domain {_identifier}");
        }
    }
}

Use proper input instead of log message to request manual DNS change


using System;

using NUnit.Framework;

namespace MongoDB.Driver.Connections
{
    [TestFixture]
    public class TestConnectionFactory
    {
        [TearDown]
        public void TearDown (){
            ConnectionFactory.Shutdown ();
        }

        [Test]
        public void TestGetConnection (){
            var connection1 = ConnectionFactory.GetConnection (string.Empty);
            var connection2 = ConnectionFactory.GetConnection (string.Empty);
            Assert.IsNotNull (connection1);
            Assert.IsNotNull (connection2);
            Assert.AreEqual (1, ConnectionFactory.PoolCount);
        }

        [Test]
        public void TestCreatePoolForEachUniqeConnectionString (){
            ConnectionFactory.GetConnection (string.Empty);
            ConnectionFactory.GetConnection (string.Empty);
            ConnectionFactory.GetConnection ("Username=test");
            ConnectionFactory.GetConnection ("Username=test");
            ConnectionFactory.GetConnection ("Server=localhost");
            Assert.AreEqual (3, ConnectionFactory.PoolCount);
        }

        [Test]
        public void TestGetInvalidConnection (){
            bool thrown = false;
            try{
                ConnectionFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10");
            }catch(ArgumentException){
                thrown = true;
            }catch(Exception){
                Assert.Fail("Wrong exception thrown");
            }
        }
    }
}

using System;

using NUnit.Framework;

namespace MongoDB.Driver.Connections
{
    [TestFixture]
    public class TestConnectionFactory
    {
        [TearDown]
        public void TearDown (){
            ConnectionFactory.Shutdown ();
        }

        [Test]
        public void TestGetConnection (){
            var connection1 = ConnectionFactory.GetConnection (string.Empty);
            var connection2 = ConnectionFactory.GetConnection (string.Empty);
            Assert.IsNotNull (connection1);
            Assert.IsNotNull (connection2);
            Assert.AreEqual (1, ConnectionFactory.PoolCount);
        }

        [Test]
        public void TestCreatePoolForEachUniqeConnectionString (){
            ConnectionFactory.GetConnection (string.Empty);
            ConnectionFactory.GetConnection (string.Empty);
            ConnectionFactory.GetConnection ("Username=test");
            ConnectionFactory.GetConnection ("Username=test");
            ConnectionFactory.GetConnection ("Server=localhost");
            Assert.AreEqual (3, ConnectionFactory.PoolCount);
        }

        [Test]
        public void TestExceptionWhenMinimumPoolSizeIsGreaterThenMaximumPoolSize (){
            try{
                ConnectionFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10");
            }catch(ArgumentException){
            }catch(Exception){
                Assert.Fail("Wrong exception thrown");
            }
        }
    }
}

Fix compiler warning and rename test to be more clear.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using OneWayMirror.Core;

namespace OneWayMirror
{
    internal sealed class ReportingConsoleHost : ConsoleHost
    {
        private readonly string _reportEmailAddress;

        internal ReportingConsoleHost(bool verbose, string reportEmailAddress) : base(verbose)
        {
            _reportEmailAddress = reportEmailAddress;
        }

        private void SendMail(string body)
        {
            using (var msg = new MailMessage())
            {
                msg.To.Add(new MailAddress(_reportEmailAddress));
                msg.From = new MailAddress(Environment.UserDomainName + @"@microsoft.com");
                msg.IsBodyHtml = false;
                msg.Subject = "Git to TFS Mirror Error";
                msg.Body = body;

                var client = new SmtpClient("smtphost");
                client.UseDefaultCredentials = true;
                client.Send(msg);
            }
        }

        public override void Error(string format, params object[] args)
        {
            base.Error(format, args);
            SendMail(string.Format(format, args));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using OneWayMirror.Core;

namespace OneWayMirror
{
    internal sealed class ReportingConsoleHost : ConsoleHost
    {
        private readonly string _reportEmailAddress;

        internal ReportingConsoleHost(bool verbose, string reportEmailAddress) : base(verbose)
        {
            _reportEmailAddress = reportEmailAddress;
        }

        private void SendMail(string body)
        {
            using (var msg = new MailMessage())
            {
                msg.To.Add(new MailAddress(_reportEmailAddress));
                msg.From = new MailAddress(Environment.UserName + @"@microsoft.com");
                msg.IsBodyHtml = false;
                msg.Subject = "Git to TFS Mirror Error";
                msg.Body = body;

                var client = new SmtpClient("smtphost");
                client.UseDefaultCredentials = true;
                client.Send(msg);
            }
        }

        public override void Error(string format, params object[] args)
        {
            base.Error(format, args);
            SendMail(string.Format(format, args));
        }
    }
}

Use UserName instead of UserDomainName

Use UserName instead of UserDomainName


using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Fotografix
{
    public sealed class DelegateCommand : ICommand
    {
        private readonly Func<bool> canExecute;
        private readonly Func<Task> execute;
        private bool executing;

        public DelegateCommand(Action execute) : this(() => true, () => { execute(); return Task.CompletedTask; })
        {
        }

        public DelegateCommand(Func<Task> execute) : this(() => true, execute)
        {
        }

        public DelegateCommand(Func<bool> canExecute, Func<Task> execute)
        {
            this.canExecute = canExecute;
            this.execute = execute;
        }

        public event EventHandler CanExecuteChanged
        {
            add { }
            remove { }
        }

        public bool CanExecute(object parameter)
        {
            return canExecute();
        }

        public async void Execute(object parameter)
        {
            if (executing)
            {
                /*
                 * This scenario can occur in two situations:
                 * 1. The user invokes the command again before the previous async execution has completed.
                 * 2. A bug in the XAML framework that sometimes triggers a command twice when using a keyboard accelerator.
                 */
                Debug.WriteLine("Skipping command execution since previous execution has not completed yet");
                return;
            }

            try
            {
                this.executing = true;
                await execute();
            }
            finally
            {
                this.executing = false;
            }
        }
    }
}

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Fotografix
{
    public sealed class DelegateCommand : ICommand
    {
        private readonly Func<bool> canExecute;
        private readonly Func<Task> execute;
        private bool executing;

        public DelegateCommand(Action execute) : this(() => true, () => { execute(); return Task.CompletedTask; })
        {
        }

        public DelegateCommand(Func<Task> execute) : this(() => true, execute)
        {
        }

        public DelegateCommand(Func<bool> canExecute, Func<Task> execute)
        {
            this.canExecute = canExecute;
            this.execute = execute;
        }

        public bool IsExecuting
        {
            get => executing;

            private set
            {
                this.executing = value;
                RaiseCanExecuteChanged();
            }
        }

        public event EventHandler CanExecuteChanged;

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }

        public bool CanExecute(object parameter)
        {
            return !executing && canExecute();
        }

        public async void Execute(object parameter)
        {
            if (IsExecuting)
            {
                /*
                 * This scenario can occur in two situations:
                 * 1. The user invokes the command again before the previous async execution has completed.
                 * 2. A bug in the XAML framework that sometimes triggers a command twice when using a keyboard accelerator.
                 */
                Debug.WriteLine("Skipping command execution since previous execution has not completed yet");
                return;
            }

            try
            {
                this.IsExecuting = true;
                await execute();
            }
            finally
            {
                this.IsExecuting = false;
            }
        }
    }
}

Disable commands while they are executing


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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online;

namespace osu.Game.Overlays
{
    public abstract class OnlineOverlay<T> : FullscreenOverlay<T>
        where T : OverlayHeader
    {
        protected override Container<Drawable> Content => content;

        protected readonly OverlayScrollContainer ScrollFlow;
        protected readonly LoadingLayer Loading;
        private readonly Container content;

        protected OnlineOverlay(OverlayColourScheme colourScheme, bool requiresSignIn = true)
            : base(colourScheme)
        {
            var mainContent = requiresSignIn
                ? new OnlineViewContainer($"Sign in to view the {Header.Title.Title}")
                : new Container();

            mainContent.RelativeSizeAxes = Axes.Both;

            mainContent.AddRange(new Drawable[]
            {
                ScrollFlow = new OverlayScrollContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    ScrollbarVisible = false,
                    Child = new FillFlowContainer
                    {
                        AutoSizeAxes = Axes.Y,
                        RelativeSizeAxes = Axes.X,
                        Direction = FillDirection.Vertical,
                        Children = new Drawable[]
                        {
                            Header.With(h => h.Depth = float.MinValue),
                            content = new Container
                            {
                                RelativeSizeAxes = Axes.X,
                                AutoSizeAxes = Axes.Y
                            }
                        }
                    }
                },
                Loading = new LoadingLayer()
            });

            base.Content.Add(mainContent);
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online;

namespace osu.Game.Overlays
{
    public abstract class OnlineOverlay<T> : FullscreenOverlay<T>
        where T : OverlayHeader
    {
        protected override Container<Drawable> Content => content;

        protected readonly OverlayScrollContainer ScrollFlow;
        protected readonly LoadingLayer Loading;
        private readonly Container content;

        protected OnlineOverlay(OverlayColourScheme colourScheme, bool requiresSignIn = true)
            : base(colourScheme)
        {
            var mainContent = requiresSignIn
                ? new OnlineViewContainer($"Sign in to view the {Header.Title.Title}")
                : new Container();

            mainContent.RelativeSizeAxes = Axes.Both;

            mainContent.AddRange(new Drawable[]
            {
                ScrollFlow = new OverlayScrollContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    ScrollbarVisible = false,
                    Child = new FillFlowContainer
                    {
                        AutoSizeAxes = Axes.Y,
                        RelativeSizeAxes = Axes.X,
                        Direction = FillDirection.Vertical,
                        Children = new Drawable[]
                        {
                            Header.With(h => h.Depth = float.MinValue),
                            content = new Container
                            {
                                RelativeSizeAxes = Axes.X,
                                AutoSizeAxes = Axes.Y
                            }
                        }
                    }
                },
                Loading = new LoadingLayer(true)
            });

            base.Content.Add(mainContent);
        }
    }
}

Revert change to loading layer's default 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;
using osu.Framework.Extensions.TypeExtensions;

namespace osu.Framework.Localisation
{
    /// <summary>
    /// Indicates that the members of an enum can be localised.
    /// </summary>
    [AttributeUsage(AttributeTargets.Enum)]
    public sealed class LocalisableEnumAttribute : Attribute
    {
        /// <summary>
        /// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.
        /// </summary>
        public readonly Type MapperType;

        /// <summary>
        /// Creates a new <see cref="LocalisableEnumAttribute"/>.
        /// </summary>
        /// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param>
        public LocalisableEnumAttribute(Type mapperType)
        {
            MapperType = mapperType;

            if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType))
                throw new ArgumentException($"Type \"{mapperType.ReadableName()}\" must inherit from {nameof(EnumLocalisationMapper<Enum>)}.", nameof(mapperType));
        }
    }
}

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

using System;
using osu.Framework.Extensions;
using osu.Framework.Extensions.TypeExtensions;

namespace osu.Framework.Localisation
{
    /// <summary>
    /// Indicates that the values of an enum have <see cref="LocalisableString"/> descriptions.
    /// The descriptions can be returned through <see cref="ExtensionMethods.GetLocalisableDescription{T}"/>.
    /// </summary>
    [AttributeUsage(AttributeTargets.Enum)]
    public sealed class LocalisableEnumAttribute : Attribute
    {
        /// <summary>
        /// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.
        /// </summary>
        public readonly Type MapperType;

        /// <summary>
        /// Creates a new <see cref="LocalisableEnumAttribute"/>.
        /// </summary>
        /// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param>
        public LocalisableEnumAttribute(Type mapperType)
        {
            MapperType = mapperType;

            if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType))
                throw new ArgumentException($"Type \"{mapperType.ReadableName()}\" must inherit from {nameof(EnumLocalisationMapper<Enum>)}.", nameof(mapperType));
        }
    }
}

Add description indicating retrieval method


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Common;
using Hadouken.Hosting;

namespace Hadouken.Hosts.WindowsService
{
    public class HdknService : ServiceBase
    {
        private IHadoukenHost _host;

        public HdknService()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.AutoLog = true;
            this.ServiceName = "Hadouken";
        }

        protected override void OnStart(string[] args)
        {
            Task.Factory.StartNew(() =>
                {
                    _host = Kernel.Get<IHadoukenHost>();
                    _host.Load();
                });
        }

        protected override void OnStop()
        {
            if (_host != null)
                _host.Unload();
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Common;
using Hadouken.Hosting;
using System.Threading;

namespace Hadouken.Hosts.WindowsService
{
    public class HdknService : ServiceBase
    {
        private IHadoukenHost _host;

        public HdknService()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.AutoLog = true;
            this.ServiceName = "Hadouken";
        }

        protected override void OnStart(string[] args)
        {
            Load();
        }

        private void Load()
        {
            _host = Kernel.Get<IHadoukenHost>();
            _host.Load();
        }

        protected override void OnStop()
        {
            if (_host != null)
                _host.Unload();
        }
    }
}

Load the service in the main thread, once more.


using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Core.Common.Fields;

namespace Orchard.Core.Common.Drivers {
    [UsedImplicitly]
    public class TextFieldDriver : ContentFieldDriver<TextField> {
        public IOrchardServices Services { get; set; }
        private const string TemplateName = "Fields/Common.TextField";

        public TextFieldDriver(IOrchardServices services) {
            Services = services;
        }

        private static string GetPrefix(TextField field, ContentPart part) {
            return part.PartDefinition.Name + "." + field.Name;
        }

        protected override DriverResult Display(ContentPart part, TextField field, string displayType) {
            return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part));
        }

        protected override DriverResult Editor(ContentPart part, TextField field) {
            return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part)).Location("primary", "5");
        }

        protected override DriverResult Editor(ContentPart part, TextField field, IUpdateModel updater) {
            updater.TryUpdateModel(field, GetPrefix(field, part), null, null);
            return Editor(part, field);
        }

    }
}

using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Core.Common.Fields;
using Orchard.Core.Common.Settings;

namespace Orchard.Core.Common.Drivers {
    [UsedImplicitly]
    public class TextFieldDriver : ContentFieldDriver<TextField> {
        public IOrchardServices Services { get; set; }
        private const string TemplateName = "Fields/Common.TextField";

        public TextFieldDriver(IOrchardServices services) {
            Services = services;
        }

        private static string GetPrefix(TextField field, ContentPart part) {
            return part.PartDefinition.Name + "." + field.Name;
        }

        protected override DriverResult Display(ContentPart part, TextField field, string displayType) {
            var locationSettings =
                field.PartFieldDefinition.Settings.GetModel<LocationSettings>("DisplayLocation") ??
                new LocationSettings { Zone = "primary", Position = "5" };

            return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part))
                .Location(locationSettings.Zone, locationSettings.Position);
        }

        protected override DriverResult Editor(ContentPart part, TextField field) {
            var locationSettings =
                field.PartFieldDefinition.Settings.GetModel<LocationSettings>("EditorLocation") ??
                new LocationSettings { Zone = "primary", Position = "5" };

            return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part))
                .Location(locationSettings.Zone, locationSettings.Position);
        }

        protected override DriverResult Editor(ContentPart part, TextField field, IUpdateModel updater) {
            updater.TryUpdateModel(field, GetPrefix(field, part), null, null);
            return Editor(part, field);
        }

    }
}

Create Display/Editor location settings for Parts and Fields

--HG--
branch : dev


// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System.Reflection;

[assembly: AssemblyTitle("Perspex.Styling.UnitTests")]

// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System.Reflection;
using Xunit;

[assembly: AssemblyTitle("Perspex.Styling.UnitTests")]

// Don't run tests in parallel.
[assembly: CollectionBehavior(DisableTestParallelization = true)]

Fix intermittent Style unit test failures.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox.ModAPI;
using VRage.Game.Components;

namespace Torch.Mod
{
    [MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)]
    public class TorchModCore : MySessionComponentBase
    {
        public const ulong MOD_ID = 1406994352;
        private static bool _init;
        public static bool Debug;

        public override void UpdateAfterSimulation()
        {
            if (_init)
                return;

            _init = true;
            ModCommunication.Register();
            MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered;
        }

        private void Utilities_MessageEntered(string messageText, ref bool sendToOthers)
        {
            if (messageText == "@!debug")
            {
                Debug = !Debug;
                MyAPIGateway.Utilities.ShowMessage("Torch", $"Debug: {Debug}");
                sendToOthers = false;
            }
        }

        protected override void UnloadData()
        {
            try
            {
                ModCommunication.Unregister();
            }
            catch
            {
                //session unloading, don't care
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox.ModAPI;
using VRage.Game.Components;

namespace Torch.Mod
{
    [MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)]
    public class TorchModCore : MySessionComponentBase
    {
        public const ulong MOD_ID = 1406994352;
        private static bool _init;
        public static bool Debug;

        public override void UpdateAfterSimulation()
        {
            if (_init)
                return;

            _init = true;
            ModCommunication.Register();
            MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered;
        }

        private void Utilities_MessageEntered(string messageText, ref bool sendToOthers)
        {
            if (messageText == "@!debug")
            {
                Debug = !Debug;
                MyAPIGateway.Utilities.ShowMessage("Torch", $"Debug: {Debug}");
                sendToOthers = false;
            }
        }

        protected override void UnloadData()
        {
            try
            {
                MyAPIGateway.Utilities.MessageEntered -= Utilities_MessageEntered;
                ModCommunication.Unregister();
            }
            catch
            {
                //session unloading, don't care
            }
        }
    }
}

Fix dumb in torch mod

Fix dumb in torch mod


// 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Utils;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;

namespace osu.Game.Tests.Visual.Gameplay
{
    [TestFixture]
    public class TestSceneStarCounter : OsuTestScene
    {
        private readonly StarCounter starCounter;
        private readonly OsuSpriteText starsLabel;

        public TestSceneStarCounter()
        {
            starCounter = new StarCounter
            {
                Origin = Anchor.Centre,
                Anchor = Anchor.Centre,
            };

            Add(starCounter);

            starsLabel = new OsuSpriteText
            {
                Origin = Anchor.Centre,
                Anchor = Anchor.Centre,
                Scale = new Vector2(2),
                Y = 50,
            };

            Add(starsLabel);

            setStars(5);

            AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10);
            AddStep("stop animation", () => starCounter.StopAnimation());
            AddStep("reset", () => setStars(0));
        }

        private void setStars(float stars)
        {
            starCounter.Current = stars;
            starsLabel.Text = starCounter.Current.ToString("0.00");
        }
    }
}

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

using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Utils;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;

namespace osu.Game.Tests.Visual.Gameplay
{
    [TestFixture]
    public class TestSceneStarCounter : OsuTestScene
    {
        private readonly StarCounter starCounter;
        private readonly OsuSpriteText starsLabel;

        public TestSceneStarCounter()
        {
            starCounter = new StarCounter
            {
                Origin = Anchor.Centre,
                Anchor = Anchor.Centre,
            };

            Add(starCounter);

            starsLabel = new OsuSpriteText
            {
                Origin = Anchor.Centre,
                Anchor = Anchor.Centre,
                Scale = new Vector2(2),
                Y = 50,
            };

            Add(starsLabel);

            setStars(5);

            AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10);
            AddSliderStep("exact value", 0f, 10f, 5f, setStars);
            AddStep("stop animation", () => starCounter.StopAnimation());
            AddStep("reset", () => setStars(0));
        }

        private void setStars(float stars)
        {
            starCounter.Current = stars;
            starsLabel.Text = starCounter.Current.ToString("0.00");
        }
    }
}

Add slider test step for visual inspection purposes


using System;
using System.Runtime.InteropServices;
using System.Resources;
using System.IO;

namespace Win32
{
    public static class Winmm
    {
        public static void PlayMessageNotify()
        {
            if (_soundData == null)
            {
                using (UnmanagedMemoryStream sound = Toxy.Properties.Resources.Blop)
                {
                    _soundData = new byte[sound.Length];
                    sound.Read(_soundData, 0, (int)sound.Length);
                }
            }
            PlaySound(_soundData, IntPtr.Zero, SND_ASYNC | SND_MEMORY);
        }

        private static byte[] _soundData;
        private const UInt32 SND_ASYNC = 1;
        private const UInt32 SND_MEMORY = 4;
        [DllImport("Winmm.dll")]
        private static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
    }
}

using System;
using System.Runtime.InteropServices;
using System.Resources;
using System.IO;

namespace Win32
{
    public static class Winmm
    {
        public static void PlayMessageNotify()
        {
            if (_soundData == null)
            {
                using (UnmanagedMemoryStream sound = Toxy.Properties.Resources.Blop)
                {
                    _soundData = new byte[sound.Length];
                    sound.Read(_soundData, 0, (int)sound.Length);
                }
            }
            if (_soundData != null)
            {
                PlaySound(_soundData, IntPtr.Zero, SND_ASYNC | SND_MEMORY);
            }
        }

        private static byte[] _soundData;
        private const UInt32 SND_ASYNC = 1;
        private const UInt32 SND_MEMORY = 4;
        [DllImport("Winmm.dll")]
        private static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
    }
}

Check if _soundData is null before attempting to play the sound


using System;

namespace Arkivverket.Arkade.Metadata
{
    public static class MetsTranslationHelper
    {
        public static bool IsValidSystemType(string systemType)
        {
            // TODO: Use Enum ExternalModels.Mets.type (not ExternalModels.Info.type) when/if supported in built in mets schema

            return Enum.IsDefined(typeof(ExternalModels.Info.type), systemType);
        }

        public static bool IsSystemTypeNoark5(string systemType)
        {
            // TODO: Use Enum ExternalModels.Mets.type (not ExternalModels.Info.type) when/if supported in built in mets schema

            ExternalModels.Info.type enumSystemType;

            bool isParsableSystemType = Enum.TryParse(systemType, out enumSystemType);

            return isParsableSystemType && enumSystemType == ExternalModels.Info.type.Noark5;
        }
    }
}

using System;
using Arkivverket.Arkade.Core;

namespace Arkivverket.Arkade.Metadata
{
    public static class MetsTranslationHelper
    {
        public static bool IsValidSystemType(string systemType)
        {
            return Enum.IsDefined(typeof(ArchiveType), systemType);
        }

        public static bool IsSystemTypeNoark5(string systemType)
        {
            ArchiveType archiveType;

            bool isParsableSystemType = Enum.TryParse(systemType, out archiveType);

            return isParsableSystemType && archiveType == ArchiveType.Noark5;
        }
    }
}

Use local definition of ArchiveTypes to validate metadata systemtypes


using System;
using System.Collections.Generic;
using System.ServiceModel;
using PS.Mothership.Core.Common.Dto;

namespace PS.Mothership.Core.Common.Contracts
{
    [ServiceContract(Name = "DiallerService")]
    public interface IDiallerService
    {
        [OperationContract]
        ValidUserInfoDto ValidateUser(Guid userGuid, Guid mothershipSessionGuid);

        [OperationContract]
        Guid LogDiallerSessionSubscribe(DiallerSessionSubscribeDto diallerSessionSubscribe);

        [OperationContract]
        Guid LogDiallerSessionUnsubscribe(DiallerSessionUnsubscribeDto diallerSessionUnsubscribe);

        [OperationContract]
        SipAccountDetailsDto GetSipAccountDetails(Guid userGuid);

        [OperationContract(IsOneWay = true)]
        List<InboundQueueDetailsDto> GetInboundQueueDetails();

        [OperationContract(IsOneWay = true)]
        List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd);

        [OperationContract]
        void UpdateRecorderCallIdForCallGuid(Guid callGuid, int recorderCallId, Guid userGuid);
    }
}

using System;
using System.Collections.Generic;
using System.ServiceModel;
using PS.Mothership.Core.Common.Dto;

namespace PS.Mothership.Core.Common.Contracts
{
    [ServiceContract(Name = "DiallerService")]
    public interface IDiallerService
    {
        [OperationContract]
        ValidUserInfoDto ValidateUser(Guid mothershipSessionGuid);

        [OperationContract]
        Guid LogDiallerSessionSubscribe(DiallerSessionSubscribeDto diallerSessionSubscribe);

        [OperationContract]
        Guid LogDiallerSessionUnsubscribe(DiallerSessionUnsubscribeDto diallerSessionUnsubscribe);

        [OperationContract]
        SipAccountDetailsDto GetSipAccountDetails(Guid userGuid);

        [OperationContract(IsOneWay = true)]
        List<InboundQueueDetailsDto> GetInboundQueueDetails();

        [OperationContract(IsOneWay = true)]
        List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd);

        [OperationContract]
        void UpdateRecorderCallIdForCallGuid(Guid callGuid, int recorderCallId, Guid userGuid);
    }
}

Remove userGuid on ValidateUser method

Remove userGuid on ValidateUser method

git-svn-id: 0f264f6d45e0d91283c3b90d5150277c66769c5f@230 0f896bb5-3ab0-2d4e-82a7-85ef10020915


using Elders.Cronus.Workflow;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;

namespace Elders.Cronus.MessageProcessing
{
    /// <summary>
    /// Work-flow which gets an object from the passed context and calls a method 'Handle' passing execution.Context.Message'
    /// <see cref="HandlerContext"/> should have 'HandlerInstance' and 'Message' already set
    /// </summary>
    public class DynamicMessageHandle : Workflow<HandlerContext>
    {
        protected override Task RunAsync(Execution<HandlerContext> execution)
        {
            dynamic handler = execution.Context.HandlerInstance;
            return handler.HandleAsync((dynamic)execution.Context.Message);
        }
    }

    public class LogExceptionOnHandleError : Workflow<ErrorContext>
    {
        private static readonly ILogger logger = CronusLogger.CreateLogger(typeof(LogExceptionOnHandleError));

        protected override async Task RunAsync(Execution<ErrorContext> execution)
        {
            var serializer = execution.Context.ServiceProvider.GetRequiredService<ISerializer>();

            string messageContent = await MessageAsStringAsync(serializer, execution.Context.Message).ConfigureAwait(false);
            logger.ErrorException(execution.Context.Error, () => $"There was an error in {execution.Context.HandlerType.Name} while handling message {messageContent}");
        }

        private Task<string> MessageAsStringAsync(ISerializer serializer, CronusMessage message)
        {
            using (var stream = new MemoryStream())
            using (StreamReader reader = new StreamReader(stream))
            {
                serializer.Serialize(stream, message);
                stream.Position = 0;
                return reader.ReadToEndAsync();
            }
        }
    }
}

using Elders.Cronus.Workflow;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;

namespace Elders.Cronus.MessageProcessing
{
    /// <summary>
    /// Work-flow which gets an object from the passed context and calls a method 'Handle' passing execution.Context.Message'
    /// <see cref="HandlerContext"/> should have 'HandlerInstance' and 'Message' already set
    /// </summary>
    public class DynamicMessageHandle : Workflow<HandlerContext>
    {
        protected override async Task RunAsync(Execution<HandlerContext> execution)
        {
            dynamic handler = execution.Context.HandlerInstance;
            await handler.HandleAsync((dynamic)execution.Context.Message);
        }
    }

    public class LogExceptionOnHandleError : Workflow<ErrorContext>
    {
        private static readonly ILogger logger = CronusLogger.CreateLogger(typeof(LogExceptionOnHandleError));

        protected override Task RunAsync(Execution<ErrorContext> execution)
        {
            var serializer = execution.Context.ServiceProvider.GetRequiredService<ISerializer>();
            logger.ErrorException(execution.Context.Error, () => $"There was an error in {execution.Context.HandlerType.Name} while handling message {MessageAsString(serializer, execution.Context.Message)}");
            return Task.CompletedTask;
        }

        private string MessageAsString(ISerializer serializer, CronusMessage message)
        {
            using (var stream = new MemoryStream())
            using (StreamReader reader = new StreamReader(stream))
            {
                serializer.Serialize(stream, message);
                stream.Position = 0;
                return reader.ReadToEnd();
            }
        }
    }
}

Revert "fix: Uses async to log an error message"

This reverts commit f1583924af8af681f8fca81ed13973996ec2b937.


@model IEnumerable<GiveCRM.Models.Donation>

@{
    Layout = null;
}

    Date	Amount

@foreach (var donation in Model)
{

        @donation.Date.ToLongDateString()
        @donation.Amount

}

@using System.Globalization
@model IEnumerable<GiveCRM.Models.Donation>

@{
    Layout = null;
}

    Date	Amount

@foreach (var donation in Model)
{

        @donation.Date.ToLongDateString()
        @donation.Amount.ToString("C2", NumberFormatInfo.CurrentInfo)

}

Fix a niggle from the wiki: display donation amounts to two decimal places. Also format them as a currency, and respect the current culture.


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

using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;

namespace System.Collections.ObjectModel.Tests
{
    public partial class KeyedCollection_Serialization
    {
        public static IEnumerable<object[]> SerializeDeserialize_Roundtrips_MemberData()
        {
            yield return new object[] { new TestCollection() };
            yield return new object[] { new TestCollection() { "hello" } };
            yield return new object[] { new TestCollection() { "hello", "world" } };
        }

        [ActiveIssue("https://github.com/dotnet/coreclr/pull/7966")]
        [Theory]
        [MemberData(nameof(SerializeDeserialize_Roundtrips_MemberData))]
        public void SerializeDeserialize_Roundtrips(TestCollection c)
        {
            TestCollection clone = BinaryFormatterHelpers.Clone(c);
            Assert.NotSame(c, clone);
            Assert.Equal(c, clone);
        }

        [Serializable]
        public sealed class TestCollection : KeyedCollection<string, string>
        {
            protected override string GetKeyForItem(string item) => item;
        }
    }
}

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

using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;

namespace System.Collections.ObjectModel.Tests
{
    public partial class KeyedCollection_Serialization
    {
        public static IEnumerable<object[]> SerializeDeserialize_Roundtrips_MemberData()
        {
            yield return new object[] { new TestCollection() };
            yield return new object[] { new TestCollection() { "hello" } };
            yield return new object[] { new TestCollection() { "hello", "world" } };
        }

        [Theory]
        [MemberData(nameof(SerializeDeserialize_Roundtrips_MemberData))]
        public void SerializeDeserialize_Roundtrips(TestCollection c)
        {
            TestCollection clone = BinaryFormatterHelpers.Clone(c);
            Assert.NotSame(c, clone);
            Assert.Equal(c, clone);
        }

        [Serializable]
        public sealed class TestCollection : KeyedCollection<string, string>
        {
            protected override string GetKeyForItem(string item) => item;
        }
    }
}

Remove CoreCLR pull 6423, run msbuild System.ObjectModel.Tests.csproj /t:BuildAndTest, succeeded.


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

namespace Contentful.Core.Models
{
    /// <summary>
    /// Represents a single asset of a <see cref="Space"/>.
    /// </summary>
    public class Asset : IContentfulResource
    {
        /// <summary>
        /// Common system managed metadata properties.
        /// </summary>
        [JsonProperty("sys")]
        public SystemProperties SystemProperties { get; set; }

        /// <summary>
        /// The description of the asset.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// The title of the asset.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Encapsulates information about the binary file of the asset.
        /// </summary>
        public File File { get; set; }

        /// <summary>
        /// The titles of the asset per locale.
        /// </summary>
        public Dictionary<string, string> TitleLocalized { get; set; }

        /// <summary>
        /// The descriptions of the asset per locale.
        /// </summary>
        public Dictionary<string, string> DescriptionLocalized { get; set; }

        /// <summary>
        /// Information about the file in respective language.
        /// </summary>
        [JsonProperty("file")]
        public Dictionary<string, File> FilesLocalized { get; set; }
    }
}

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

namespace Contentful.Core.Models
{
    /// <summary>
    /// Represents a single asset of a <see cref="Space"/>.
    /// </summary>
    public class Asset : IContentfulResource
    {
        /// <summary>
        /// Common system managed metadata properties.
        /// </summary>
        [JsonProperty("sys")]
        public SystemProperties SystemProperties { get; set; }

        /// <summary>
        /// The description of the asset.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// The title of the asset.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Encapsulates information about the binary file of the asset.
        /// </summary>
        public File File { get; set; }

        /// <summary>
        /// The titles of the asset per locale.
        /// </summary>
        public Dictionary<string, string> TitleLocalized { get; set; }

        /// <summary>
        /// The descriptions of the asset per locale.
        /// </summary>
        public Dictionary<string, string> DescriptionLocalized { get; set; }

        /// <summary>
        /// Information about the file in respective language.
        /// </summary>
        public Dictionary<string, File> FilesLocalized { get; set; }
    }
}

Remove JsonProperty Mapping for "file"

Remove JsonProperty Mapping for "file"

This is an inconsistency as you either have all the fields mapped to the localized models like the following:

```
    public class Asset : IContentfulResource
    {
        /// <summary>
        /// Common system managed metadata properties.
        /// </summary>
        [JsonProperty("sys")]
        public SystemProperties SystemProperties { get; set; }

        /// <summary>
        /// The description of the asset.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// The title of the asset.
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Encapsulates information about the binary file of the asset.
        /// </summary>
        public File File { get; set; }

        /// <summary>
        /// The titles of the asset per locale.
        /// </summary>
        [JsonProperty("title")]
        public Dictionary<string, string> TitleLocalized { get; set; }

        /// <summary>
        /// The descriptions of the asset per locale.
        /// </summary>
        [JsonProperty("description")]
        public Dictionary<string, string> DescriptionLocalized { get; set; }

        /// <summary>
        /// Information about the file in respective language.
        /// </summary>
        [JsonProperty("file")]
        public Dictionary<string, File> FilesLocalized { get; set; }
    }
```

As currently only file is mapped to the localization property which is not really consistent.


namespace CypherTwo.Core
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public class NeoClient : INeoClient
    {
        private readonly ISendRestCommandsToNeo neoApi;

        public NeoClient(string baseUrl) : this(new ApiClientFactory(baseUrl, new JsonHttpClientWrapper()))
        {
        }

        internal NeoClient(ISendRestCommandsToNeo neoApi)
        {
            this.neoApi = neoApi;
        }

        public async Task InitialiseAsync()
        {
            try
            {
                await this.neoApi.LoadServiceRootAsync();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }

        public async Task<ICypherDataReader> QueryAsync(string cypher)
        {
            var neoResponse = await this.neoApi.SendCommandAsync(cypher);
            if (neoResponse.errors != null && neoResponse.errors.Any())
            {
                throw new Exception(string.Join(Environment.NewLine, neoResponse.errors.Select(error => error.ToObject<string>())));
            }

            return new CypherDataReader(neoResponse);
        }

        public async Task ExecuteAsync(string cypher)
        {
            await this.neoApi.SendCommandAsync(cypher);
        }
    }
}

namespace CypherTwo.Core
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public class NeoClient : INeoClient
    {
        private readonly ISendRestCommandsToNeo neoApi;

        public NeoClient(string baseUrl) : this(new ApiClientFactory(baseUrl, new JsonHttpClientWrapper()))
        {
        }

        internal NeoClient(ISendRestCommandsToNeo neoApi)
        {
            this.neoApi = neoApi;
        }

        public async Task InitialiseAsync()
        {
            try
            {
                await this.neoApi.LoadServiceRootAsync();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }

        public async Task<ICypherDataReader> QueryAsync(string cypher)
        {
            var neoResponse = await this.ExecuteCore(cypher);

            return new CypherDataReader(neoResponse);
        }

        public async Task ExecuteAsync(string cypher)
        {
            await this.ExecuteCore(cypher);
        }

        private async Task<NeoResponse> ExecuteCore(string cypher)
        {
            var neoResponse = await this.neoApi.SendCommandAsync(cypher);
            if (neoResponse.errors != null && neoResponse.errors.Any())
            {
                throw new Exception(string.Join(Environment.NewLine, neoResponse.errors.Select(error => error.ToObject<string>())));
            }

            return neoResponse;
        }
    }
}

Add throw error on Neo exception in ExecuteCore


using System;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      Table table = new Table(2, 3);
      string output = table.Draw();

      Console.WriteLine(output);
    }
  }
}

using System;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      // Table table = new Table(2, 3);
      // string output = table.Draw();

      // Console.WriteLine(output);
    }
  }
}

Comment out the code in Hangman that uses Table

To focus on the development of game logic


// 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);

        /// <summary>
        /// Signals that the settings for this room have changed.
        /// </summary>
        /// <param name="newSettings">The updated room settings.</param>
        Task SettingsChanged(MultiplayerRoomSettings newSettings);
    }
}

// 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);

        /// <summary>
        /// Signal that the host of the room has changed.
        /// </summary>
        /// <param name="userId">The user ID of the new host.</param>
        Task HostChanged(long userId);

        /// <summary>
        /// Signals that the settings for this room have changed.
        /// </summary>
        /// <param name="newSettings">The updated room settings.</param>
        Task SettingsChanged(MultiplayerRoomSettings newSettings);
    }
}

Add client method for notifying about host changes


using System;
using System.Threading;
using Microsoft.SPOT;

namespace AgentIntervals
{
    public delegate void HeartBeatEventHandler(object sender, EventArgs e);

    public class HeartBeat
    {
        private Timer _timer;
        private int _period;

        public event HeartBeatEventHandler OnHeartBeat;

        public HeartBeat(int period)
        {
            _period = period;
        }

        private void TimerCallback(object state)
        {
            if (OnHeartBeat != null)
            {
                OnHeartBeat(this, new EventArgs());
            }
        }

        public void Start(int delay)
        {
            if (_timer != null) return;

            _timer = new Timer(TimerCallback, null, delay, _period);
        }

        public void Stop()
        {
            if (_timer == null) return;

            _timer.Dispose();
            _timer = null;
        }

        public bool Toggle(int delay)
        {
            bool started;
            if (_timer == null)
            {
                Start(delay);
                started = true;
            }
            else
            {
                Stop();
                started = false;
            }
            return started;
        }

        public void Reset()
        {
            Stop();
            Start(0);
        }

        public void ChangePeriod(int newPeriod)
        {
            _period = newPeriod;
        }
    }
}

using System;
using System.Threading;
using Microsoft.SPOT;

namespace AgentIntervals
{
    public delegate void HeartBeatEventHandler(object sender, EventArgs e);

    public class HeartBeat
    {
        private Timer _timer;
        private int _period;

        public event HeartBeatEventHandler OnHeartBeat;

        public HeartBeat(int period)
        {
            _period = period;
        }

        private void TimerCallback(object state)
        {
            if (OnHeartBeat != null)
            {
                OnHeartBeat(this, new EventArgs());
            }
        }

        public void Start()
        {
            Start(0);
        }

        public void Start(int delay)
        {
            if (_timer != null) return;

            _timer = new Timer(TimerCallback, null, delay, _period);
        }

        public void Stop()
        {
            if (_timer == null) return;

            _timer.Dispose();
            _timer = null;
        }

        public bool Toggle()
        {
            return Toggle(0);
        }

        public bool Toggle(int delay)
        {
            bool started;
            if (_timer == null)
            {
                Start(delay);
                started = true;
            }
            else
            {
                Stop();
                started = false;
            }
            return started;
        }

        public void Reset()
        {
            Reset(0);
        }

        public void Reset(int delay)
        {
            Stop();
            Start(delay);
        }

        public void ChangePeriod(int newPeriod)
        {
            _period = newPeriod;
        }
    }
}

Add parameter-less defaults for Start, Toggle, Reset.


using System;
using System.Linq;

namespace FibCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var max = 50;
            Enumerable.Range(0, int.MaxValue)
                .Select(Fib)
                .TakeWhile(x => x <= 50)
                .ToList()
                .ForEach(Console.WriteLine);
        }

        static int Fib(int arg) =>
            arg == 0 ? 0
            : arg == 1 ? 1
            : Fib(arg - 2) + Fib(arg - 1);
    }
}

using System;
using System.Linq;

namespace FibCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var max = 50;
            Enumerable.Range(0, int.MaxValue)
                .Select(Fib)
                .TakeWhile(x => x <= max)
                .ToList()
                .ForEach(Console.WriteLine);
        }

        static int Fib(int arg) =>
            arg == 0 ? 0
            : arg == 1 ? 1
            : Fib(arg - 2) + Fib(arg - 1);
    }
}

Use the defined max value

Use the defined max value


using System;
using System.Collections.Generic;

namespace IvionSoft
{
    public class History<T>
    {
        int length;
        HashSet<T> hashes;
        Queue<T> queue;
        object _locker;

        public History(int length)
        {
            if (length < 1)
                throw new ArgumentException("Must be 1 or larger", "length");

            this.length = length;
            hashes = new HashSet<T>();
            queue = new Queue<T>(length + 1);

            _locker = new object();
        }

        public bool Contains(T item)
        {
            return hashes.Contains(item);
        }

        public bool Add(T item)
        {
            bool added;
            lock (_locker)
            {
                added = hashes.Add(item);

                if (added)
                {
                    queue.Enqueue(item);
                    if (queue.Count > length)
                    {
                        T toRemove = queue.Dequeue();
                        hashes.Remove(toRemove);
                    }
                }
            }

            return added;
        }
    }
}

using System;
using System.Collections.Generic;

namespace IvionSoft
{
    public class History<T>
    {
        public int Length { get; private set; }

        HashSet<T> hashes;
        Queue<T> queue;
        object _locker = new object();

        public History(int length) : this(length, null)
        {}

        public History(int length, IEqualityComparer<T> comparer)
        {
            if (length < 1)
                throw new ArgumentException("Must be 1 or larger", "length");

            Length = length;
            queue = new Queue<T>(length + 1);

            if (comparer != null)
                hashes = new HashSet<T>(comparer);
            else
                hashes = new HashSet<T>();
        }

        public bool Contains(T item)
        {
            return hashes.Contains(item);
        }

        public bool Add(T item)
        {
            bool added;
            lock (_locker)
            {
                added = hashes.Add(item);

                if (added)
                {
                    queue.Enqueue(item);
                    if (queue.Count > Length)
                    {
                        T toRemove = queue.Dequeue();
                        hashes.Remove(toRemove);
                    }
                }
            }

            return added;
        }
    }
}

Add the option of specifying a comparer.


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;

namespace osu.Game.Screens.OnlinePlay.Lounge.Components
{
    public class RoomSpecialCategoryPill : OnlinePlayComposite
    {
        private SpriteText text;

        public RoomSpecialCategoryPill()
        {
            AutoSizeAxes = Axes.Both;
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            InternalChild = new PillContainer
            {
                Background =
                {
                    Colour = colours.Pink,
                    Alpha = 1
                },
                Child = text = new OsuSpriteText
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 12),
                    Colour = Color4.Black
                }
            };
        }

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

            Category.BindValueChanged(c => text.Text = c.NewValue.ToString(), true);
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.Rooms;
using osuTK.Graphics;

namespace osu.Game.Screens.OnlinePlay.Lounge.Components
{
    public class RoomSpecialCategoryPill : OnlinePlayComposite
    {
        private SpriteText text;
        private PillContainer pill;

        [Resolved]
        private OsuColour colours { get; set; }

        public RoomSpecialCategoryPill()
        {
            AutoSizeAxes = Axes.Both;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            InternalChild = pill = new PillContainer
            {
                Background =
                {
                    Colour = colours.Pink,
                    Alpha = 1
                },
                Child = text = new OsuSpriteText
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 12),
                    Colour = Color4.Black
                }
            };
        }

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

            Category.BindValueChanged(c =>
            {
                text.Text = c.NewValue.GetLocalisableDescription();

                switch (c.NewValue)
                {
                    case RoomCategory.Spotlight:
                        pill.Background.Colour = colours.Green2;
                        break;

                    case RoomCategory.FeaturedArtist:
                        pill.Background.Colour = colours.Blue2;
                        break;
                }
            }, true);
        }
    }
}

Update colour of spotlights playlist to match new specs


namespace PegSharp.External
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class BlockChain
    {
        private List<BlockData> blocks = new List<BlockData>();
        private List<BlockData> others = new List<BlockData>();

        public long Height { get { return blocks.Count; } }

        public BlockData BestBlock
        {
            get
            {
                return this.blocks.Last();
            }
        }

        public bool Add(BlockData block)
        {
            if ((this.blocks.Count == 0 && block.Number == 0) || (this.blocks.Count > 0 && this.BestBlock.Hash.Equals(block.ParentHash)))
            {
                this.blocks.Add(block);

                var children = this.others.Where(b => b.ParentHash.Equals(block.Hash));

                foreach (var child in children) {
                    this.others.Remove(child);
                    this.Add(child);
                }

                return true;
            }

            others.Add(block);

            return false;
        }
    }
}

namespace PegSharp.External
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class BlockChain
    {
        private List<BlockData> blocks = new List<BlockData>();
        private List<BlockData> others = new List<BlockData>();

        public long Height { get { return blocks.Count; } }

        public BlockData BestBlock
        {
            get
            {
                return this.blocks.Last();
            }
        }

        public bool Add(BlockData block)
        {
            if ((this.blocks.Count == 0 && block.Number == 0) || (this.blocks.Count > 0 && this.BestBlock.Hash.Equals(block.ParentHash)))
            {
                this.blocks.Add(block);

                var children = this.others.Where(b => b.ParentHash.Equals(block.Hash)).ToList();

                foreach (var child in children) {
                    this.others.Remove(child);
                    this.Add(child);
                }

                return true;
            }

            others.Add(block);

            return false;
        }
    }
}

Add blocks not in order

Add blocks not in order


using System;

namespace BitCommitment
{
    /// <summary>
    /// A class to perform bit commitment. It does not care what the input is; it's just a
    /// facility for exchanging bit commitment messages.
    /// </summary>
    public class BitCommitmentEngine
    {
        #region properties

        public byte[] BobRandBytesR { get; set; }
        public byte[] AliceEncryptedMessage { get; set; }

        #endregion
    }
}

using System;

namespace BitCommitment
{
    /// <summary>
    /// A class to perform bit commitment. It does not care what the input is; it's just a
    /// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way
    /// function method for committing bits
    /// </summary>
    public class BitCommitmentEngine
    {
        public byte[] AliceRandBytes1 { get; set; }
        public byte[] AliceRandBytes2 { get; set; }
        public byte[] AliceMessageBytesBytes { get; set; }

        public BitCommitmentEngine(byte[] one, byte[] two, byte[] messageBytes)
        {
            AliceRandBytes1 = one;
            AliceRandBytes2 = two;
            AliceMessageBytesBytes = messageBytes;
        }

    }
}

Use one way function protocol for bit commitment


/*
 * Created by SharpDevelop.
 * User: Lars Magnus
 * Date: 12.06.2014
 * Time: 20:54
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Text;
using Nancy;
using SubmittedData;

namespace Modules
{
	/// <summary>
	/// Description of WebService.
	/// </summary>
	public class RootMenuModule : NancyModule
	{
		private ITournament _tournament;
		public RootMenuModule(ITournament tournament)
		{
			_tournament = tournament;

			var groups = new Groups() { Tournament = _tournament.GetName() };
			Get["/"] = _ => {
				return View["groups.sshtml", groups];
			};
		}

		private string PrintGroups()
		{
			StringBuilder s = new StringBuilder();
			s.AppendFormat("Welcome to {0} betting scores\n", _tournament.GetName());

			char gn = 'A';
			foreach (object[] group in _tournament.GetGroups())
			{
				s.AppendLine("Group " + gn);
				foreach (var team in group)
				{
					s.AppendLine(team.ToString());
				}
				gn++;
			}

			return s.ToString();
		}
	}

	class Groups
	{
		public string Tournament { get; set; }
	}
}

/*
 * Created by SharpDevelop.
 * User: Lars Magnus
 * Date: 12.06.2014
 * Time: 20:54
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Text;
using Nancy;
using SubmittedData;

namespace Modules
{
	/// <summary>
	/// Description of WebService.
	/// </summary>
	public class RootMenuModule : NancyModule
	{
		public RootMenuModule(ITournament tournament)
		{
			Get["/"] = _ => {
				return View["groups.sshtml", new GroupsViewModel(tournament)];
			};
		}
	}

	public class GroupsViewModel
	{
		public string Tournament
		{
			get { return _tournament.GetName(); }
		}

		ITournament _tournament;
		public GroupsViewModel(ITournament t)
		{
			_tournament = t;
		}

		private string PrintGroups()
		{
			StringBuilder s = new StringBuilder();
			s.AppendFormat("Welcome to {0} betting scores\n", _tournament.GetName());

			char gn = 'A';
			foreach (object[] group in _tournament.GetGroups())
			{
				s.AppendLine("Group " + gn);
				foreach (var team in group)
				{
					s.AppendLine(team.ToString());
				}
				gn++;
			}

			return s.ToString();
		}
	}
}

Make a proper view model

Make a proper view model


using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    [DisplayName("Intro Settings")]
    public class IntroData
    {
        [DisplayName("Duration")]
        public int Duration { get; set; } = -1;

        [DisplayName("Reversable")]
        public bool Reversable { get; set; } = false;

        [DisplayName("Activate")]
        public bool Activate { get; set; } = false;

        [DisplayName("Hide On Finish")]
        public bool HideOnFinish { get; set; } = true;

        [DisplayName("Execute Finish Action")]
        public bool ExecuteFinishAction { get; set; } = true;
    }
}

using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;

namespace DesktopWidgets.Classes
{
    [ExpandableObject]
    [DisplayName("Intro Settings")]
    public class IntroData
    {
        [DisplayName("Duration")]
        public int Duration { get; set; } = -1;

        [DisplayName("Reversable")]
        public bool Reversable { get; set; } = false;

        [DisplayName("Activate")]
        public bool Activate { get; set; } = false;

        [DisplayName("Hide On End")]
        public bool HideOnFinish { get; set; } = true;

        [DisplayName("Trigger End Event")]
        public bool ExecuteFinishAction { get; set; } = true;
    }
}

Change some intro settings property names


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalRDemo.Hubs
{
    public class Chat : Hub
    {
        public void SayHello()
        {
            while (true)
            {
                Clients.All.addMessage("Date time  : "+DateTime.Now);
                Thread.Sleep(500);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;
using Microsoft.AspNet.SignalR;
using Timer = System.Timers.Timer;

namespace SignalRDemo.Hubs
{
    public class Chat : Hub
    {
        static string messageToSend = DateTime.Now.ToString();
        Timer t = new Timer(500);

        public void SayHello()
        {
            t.Elapsed +=t_Elapsed;
            t.Start();
        }

        private void t_Elapsed(object sender, ElapsedEventArgs e)
        {
            Clients.All.addMessage("Date time  : " + messageToSend);
            messageToSend = DateTime.Now.ToString();
        }
    }
}

Use timer rather than blocking sleep

Use timer rather than blocking sleep


using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers.API
{
    public class EmbedsController : ApiController
    {
        public EmbedsController(Database db) : base(db)
        {
            // Nothing to do here
        }

        [HttpGet]
        public IEnumerable<Embed> List()
        {
            return db.Embeds.ToList();
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody]Embed embed)
        {
            db.Embeds.Add(embed);

            await db.SaveChangesAsync();

            return Ok();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            var embed = await db.Embeds.SingleOrDefaultAsync(_ => _.Id == id);

            db.Embeds.Remove(embed);

            await db.SaveChangesAsync();

            return Ok();
        }
    }
}

using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryCommander.Web.Controllers.API
{
    public class EmbedsController : ApiController
    {
        public EmbedsController(Database db) : base(db)
        {
            // Nothing to do here
        }

        [HttpGet]
        public async Task<IEnumerable<dynamic>> List()
        {
            return
                await db
                .Embeds
                .Select(embed => new
                {
                    embed.Id,
                    embed.UnitId,
                    embed.Name,
                    embed.Route,
                    embed.Source
                })
                .ToListAsync();
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody]Embed embed)
        {
            db.Embeds.Add(embed);

            await db.SaveChangesAsync();

            return Ok();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            var embed = await db.Embeds.SingleOrDefaultAsync(_ => _.Id == id);

            db.Embeds.Remove(embed);

            await db.SaveChangesAsync();

            return Ok();
        }
    }
}

Switch to not serialize the full embed object


using Roguelike.UI;
using System;

namespace Roguelike.Entities.Components
{
    public class FighterComponent : Component
    {
        public int MaximumHealth { get; set; }
        public int CurrentHealth { get; set; }
        public int Power { get; set; }
        public int Defense { get; set; }

        public Action<Entity> DeathFunction { get; set; }

        public void Damage(int amount)
        {
            CurrentHealth -= amount;

            if (CurrentHealth <= 0)
            {
                DeathFunction?.Invoke(Entity);
            }
        }

        public void Attack(Entity target)
        {
            if (target.GetComponent<FighterComponent>() == null)
            {
                return;
            }

            var damage = Power - target.GetComponent<FighterComponent>().Defense;

            if (damage > 0)
            {
                MessageLog.Add($"{Entity.Name} attacks {target.Name} for {damage} HP.");
                target.GetComponent<FighterComponent>().Damage(damage);
            }
            else
            {
                MessageLog.Add($"{Entity.Name} attacks {target.Name} but it has no effect!");
            }
        }
    }
}

using Roguelike.UI;
using System;

namespace Roguelike.Entities.Components
{
    public class FighterComponent : Component
    {
        public const float CriticalHitChance = 0.05f;

        public int MaximumHealth { get; set; }
        public int CurrentHealth { get; set; }
        public int Power { get; set; }
        public int Defense { get; set; }

        public Action<Entity> DeathFunction { get; set; }

        public void Damage(int amount)
        {
            CurrentHealth -= amount;

            if (CurrentHealth <= 0)
            {
                DeathFunction?.Invoke(Entity);
            }
        }

        public void Attack(Entity target)
        {
            if (target.GetComponent<FighterComponent>() == null)
            {
                return;
            }

            int damage = 0;

            if (Program.Random.NextDouble() < CriticalHitChance)
            {
                damage = Power;
            }
            else
            {
                damage = Power - target.GetComponent<FighterComponent>().Defense;
            }

            if (damage > 0)
            {
                MessageLog.Add($"{Entity.Name} attacks {target.Name} for {damage} HP.");
                target.GetComponent<FighterComponent>().Damage(damage);
            }
            else
            {
                MessageLog.Add($"{Entity.Name} attacks {target.Name} but it has no effect!");
            }
        }
    }
}

Add a 5% chance for attacks to be critical hits, which ignore defense.


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

namespace CodeFirstMigrations
{
    public class Address
    {
        public Int32 Id { get; set; }
        public Int32 HouseNumber { get; set; }
        public String Street { get; set; }
        public String City { get; set; }
    }
}

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

namespace CodeFirstMigrations
{
    public class Address
    {
        public Int32 Id { get; set; }
        public Int32 HouseNumber { get; set; }
        public String Street { get; set; }
        public String City { get; set; }
        public String Postcode { get; set; }
    }
}

Change model and EF errors with schema change


using BSParser.Data;
using CsvHelper;
using System.IO;
using System.Text;

namespace BSParser.Writers
{
    public class StrictCSVWriter : Writer
    {
        private string _fileName;

        public StrictCSVWriter(string fileName)
        {
            _fileName = fileName;
        }

        public override bool Write(StatementTable data)
        {
            using (var sw = new StreamWriter(_fileName, false, Encoding.UTF8))
            {
                var csv = new CsvWriter(sw);
                csv.Configuration.Delimiter = ";";
                csv.WriteRecords(data);
            }

            return true;
        }
    }
}

using BSParser.Data;
using CsvHelper;
using System.IO;
using System.Linq;
using System.Text;

namespace BSParser.Writers
{
    public class StrictCSVWriter : Writer
    {
        private string _fileName;

        public StrictCSVWriter(string fileName)
        {
            _fileName = fileName;
        }

        public override bool Write(StatementTable data)
        {
            if (!data.Any()) return false;

            var orderedData = data.Select(x => new
            {
                x.Category,
                x.RefNum,
                x.DocNum,
                x.Amount,
                x.Direction,
                x.RegisteredOn,
                x.Description,
                x.PayerINN,
                x.PayerName,
                x.ReceiverINN,
                x.ReceiverName
            });

            using (var sw = new StreamWriter(_fileName, false, Encoding.UTF8))
            {
                var csv = new CsvWriter(sw);
                csv.Configuration.Delimiter = ";";
                csv.WriteRecords(orderedData);
            }

            return true;
        }
    }
}

Change the order of the columns in CSV export


using CompatApiClient.Utils;
using DSharpPlus.Entities;
using IrdLibraryClient;
using IrdLibraryClient.POCOs;

namespace CompatBot.Utils.ResultFormatters
{
    public static class IrdSearchResultFormattercs
    {
        public static DiscordEmbedBuilder AsEmbed(this SearchResult searchResult)
        {
            var result = new DiscordEmbedBuilder
            {
                //Title = "IRD Library Search Result",
                Color = Config.Colors.DownloadLinks,
            };
            if (searchResult.Data.Count == 0)
            {
                result.Color = Config.Colors.LogResultFailed;
                result.Description = "No matches were found";
                return result;
            }

            foreach (var item in searchResult.Data)
            {
                var parts = item.Filename?.Split('-');
                if (parts == null)
                    parts = new string[] {null, null};
                else if (parts.Length == 1)
                    parts = new[] {null, item.Filename};
                result.AddField(
                    $"[{parts?[0]}] {item.Title?.Sanitize().Trim(EmbedPager.MaxFieldTitleLength)}",
                    $"⏬ [`{parts[1]?.Sanitize().Trim(200)}`]({IrdClient.GetDownloadLink(item.Filename)})　ℹ [Info]({IrdClient.GetInfoLink(item.Filename)})"
                );
            }
            return result;
        }
    }
}

using CompatApiClient.Utils;
using DSharpPlus.Entities;
using IrdLibraryClient;
using IrdLibraryClient.POCOs;

namespace CompatBot.Utils.ResultFormatters
{
    public static class IrdSearchResultFormattercs
    {
        public static DiscordEmbedBuilder AsEmbed(this SearchResult searchResult)
        {
            var result = new DiscordEmbedBuilder
            {
                //Title = "IRD Library Search Result",
                Color = Config.Colors.DownloadLinks,
            };
            if (searchResult.Data.Count == 0)
            {
                result.Color = Config.Colors.LogResultFailed;
                result.Description = "No matches were found";
                return result;
            }

            foreach (var item in searchResult.Data)
            {
                var parts = item.Filename?.Split('-');
                if (parts == null)
                    parts = new string[] {null, null};
                else if (parts.Length == 1)
                    parts = new[] {null, item.Filename};
                result.AddField(
                    $"[{parts?[0]} v{item.GameVersion}] {item.Title?.Sanitize().Trim(EmbedPager.MaxFieldTitleLength)}",
                    $"⏬ [`{parts[1]?.Sanitize().Trim(200)}`]({IrdClient.GetDownloadLink(item.Filename)})　ℹ [Info]({IrdClient.GetInfoLink(item.Filename)})"
                );
            }
            return result;
        }
    }
}

Add game version to the results (for e.g. heavy rain)


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

namespace LivrariaTest
{
    [TestClass]
    public class AutorTest
    {

        [TestMethod]
        public void TestProperties()
        {
            Autor autor = new Autor();

            autor.CodAutor = 999;
            autor.Nome = "George R. R. Martin";
            autor.Cpf = "012.345.678.90";
            autor.DtNascimento = new DateTime(1948, 9, 20);

            Assert.AreEqual(autor.CodAutor, 999);
            Assert.AreEqual(autor.Nome, "George R. R. Martin");
            Assert.AreEqual(autor.Cpf, "012.345.678.90");
            Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20));
        }

    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Livraria;
using System.Collections.Generic;

namespace LivrariaTest
{
    [TestClass]
    public class AutorTest
    {

        [TestMethod]
        public void TestProperties()
        {
            Autor autor = new Autor();

            autor.CodAutor = 999;
            autor.Nome = "George R. R. Martin";
            autor.Cpf = "012.345.678.90";
            autor.DtNascimento = new DateTime(1948, 9, 20);

            Assert.AreEqual(autor.CodAutor, 999);
            Assert.AreEqual(autor.Nome, "George R. R. Martin");
            Assert.AreEqual(autor.Cpf, "012.345.678.90");
            Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20));
        }

        [TestMethod]
        public void TestListaAutores()
        {
            Autor autor = new Autor();
            List<Autor> lstAutores = autor.ListaAutores();

            foreach (var aut in lstAutores)
            {
                Assert.IsInstanceOfType(aut, typeof(Autor));
            }
        }

    }
}

Add test for ListaAutores method

Add test for ListaAutores method


using System;

class Program {
	static void Main(string[] args)
	{
		Console.WriteLine("Hello World!");
		foreach (var arg in args)
		{
			Console.Write("Hello ");
			Console.Write(arg);
			Console.WriteLine("!");
		}
		Console.WriteLine("Press ENTER to exit ...");
		Console.ReadLine();
	}
}

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

using System;

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        foreach (var arg in args)
        {
            Console.Write("Hello ");
            Console.Write(arg);
            Console.WriteLine("!");
        }
        Console.WriteLine("Press ENTER to exit ...");
        Console.ReadLine();
    }
}

Make coding style consistent with corefx


// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;

namespace TiltBrushToolkit {

[InitializeOnLoad]
public class GammaSettings : EditorWindow {

  static ColorSpace m_LastColorSpace;

  static GammaSettings() {
    EditorApplication.update += OnUpdate;

    SetKeywords();
    m_LastColorSpace = PlayerSettings.colorSpace;
  }

  static void OnUpdate() {
    if (m_LastColorSpace != PlayerSettings.colorSpace) {
      SetKeywords();
      m_LastColorSpace = PlayerSettings.colorSpace;
    }

  }

  static void SetKeywords() {
    bool linear = PlayerSettings.colorSpace == ColorSpace.Linear;
    if (linear) {
      Shader.DisableKeyword("FORCE_SRGB");
    } else {
      Shader.EnableKeyword("FORCE_SRGB");
    }
  }

}
}

// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;

namespace TiltBrushToolkit {

[InitializeOnLoad]
public class GammaSettings : EditorWindow {

  static ColorSpace m_LastColorSpace;

  static GammaSettings() {
    EditorApplication.update += OnUpdate;

    SetKeywords();
    m_LastColorSpace = PlayerSettings.colorSpace;
  }

  static void OnUpdate() {
    if (m_LastColorSpace != PlayerSettings.colorSpace) {
      SetKeywords();
      m_LastColorSpace = PlayerSettings.colorSpace;
    }

  }

  static void SetKeywords() {
    bool linear = PlayerSettings.colorSpace == ColorSpace.Linear;
    if (linear) {
      Shader.EnableKeyword("TBT_LINEAR_TARGET");
    } else {
      Shader.DisableKeyword("TBT_LINEAR_TARGET");
    }
  }

}
}

Use correct TBT_LINEAR_TARGET shader feature keyword.

Change-Id: Iaa498426ff3ec9c678ca0e02e5c510121654eded


// 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 ManagedBass;
using System;
using System.Collections.Concurrent;

namespace osu.Framework.Audio.Sample
{
    internal class SampleBass : Sample, IBassAudio
    {
        private volatile int sampleId;

        public override bool IsLoaded => sampleId != 0;

        public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null)
        {
            if (customPendingActions != null)
                PendingActions = customPendingActions;

            PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default); });
        }

        protected override void Dispose(bool disposing)
        {
            Bass.SampleFree(sampleId);
            base.Dispose(disposing);
        }

        void IBassAudio.UpdateDevice(int deviceIndex)
        {
            if (IsLoaded)
                // counter-intuitively, this is the correct API to use to migrate a sample to a new device.
                Bass.ChannelSetDevice(sampleId, deviceIndex);
        }

        public int CreateChannel() => Bass.SampleGetChannel(sampleId);
    }
}

// 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 ManagedBass;
using System;
using System.Collections.Concurrent;

namespace osu.Framework.Audio.Sample
{
    internal class SampleBass : Sample, IBassAudio
    {
        private volatile int sampleId;

        public override bool IsLoaded => sampleId != 0;

        public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null)
        {
            if (customPendingActions != null)
                PendingActions = customPendingActions;

            PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default | BassFlags.SampleOverrideLongestPlaying); });
        }

        protected override void Dispose(bool disposing)
        {
            Bass.SampleFree(sampleId);
            base.Dispose(disposing);
        }

        void IBassAudio.UpdateDevice(int deviceIndex)
        {
            if (IsLoaded)
                // counter-intuitively, this is the correct API to use to migrate a sample to a new device.
                Bass.ChannelSetDevice(sampleId, deviceIndex);
        }

        public int CreateChannel() => Bass.SampleGetChannel(sampleId);
    }
}

Allow bass sample channels to overwrite older ones by default.