using System.Threading.Tasks;

using Newtonsoft.Json;

namespace Audiotica.Core.Utils
{
    public static class StringExtensions
    {
        public static string CleanForFileName(this string str, string invalidMessage)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }

            /*
             * A filename cannot contain any of the following characters:
             * \ / : * ? " < > |
             */
            var name =
                str.Replace("\\", string.Empty)
                    .Replace("/", string.Empty)
                    .Replace(":", " ")
                    .Replace("*", string.Empty)
                    .Replace("?", string.Empty)
                    .Replace("\"", "'")
                    .Replace("<", string.Empty)
                    .Replace(">", string.Empty)
                    .Replace("|", " ");

            return string.IsNullOrEmpty(name) ? invalidMessage : name;
        }

        public static async Task<T> DeserializeAsync<T>(this string json)
        {
            return await Task.Factory.StartNew(
                () =>
                    {
                        try
                        {
                            return JsonConvert.DeserializeObject<T>(json);
                        }
                        catch
                        {
                            return default(T);
                        }
                    }).ConfigureAwait(false);
        }

        public static string StripHtmlTags(this string str)
        {
            return HtmlRemoval.StripTagsRegex(str);
        }
    }
}

using System.Threading.Tasks;

using Newtonsoft.Json;

namespace Audiotica.Core.Utils
{
    public static class StringExtensions
    {
        public static string CleanForFileName(this string str, string invalidMessage)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }

            if (str.Length > 35)
            {
                str = str.Substring(0, 35);
            }

            /*
             * A filename cannot contain any of the following characters:
             * \ / : * ? " < > |
             */
            var name =
                str.Replace("\\", string.Empty)
                    .Replace("/", string.Empty)
                    .Replace(":", " ")
                    .Replace("*", string.Empty)
                    .Replace("?", string.Empty)
                    .Replace("\"", "'")
                    .Replace("<", string.Empty)
                    .Replace(">", string.Empty)
                    .Replace("|", " ");

            return string.IsNullOrEmpty(name) ? invalidMessage : name;
        }

        public static async Task<T> DeserializeAsync<T>(this string json)
        {
            return await Task.Factory.StartNew(
                () =>
                    {
                        try
                        {
                            return JsonConvert.DeserializeObject<T>(json);
                        }
                        catch
                        {
                            return default(T);
                        }
                    }).ConfigureAwait(false);
        }

        public static string StripHtmlTags(this string str)
        {
            return HtmlRemoval.StripTagsRegex(str);
        }
    }
}

Fix path too long bug

Fix path too long bug


using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace IronAHK.Scripting
{
    partial class Script
    {
        public static void CreateTrayMenu()
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                return;

            var menu = new NotifyIcon { ContextMenu = new ContextMenu() };
            menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); }));
            menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); }));

            var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico");

            if (favicon != null)
            {
                menu.Icon = new Icon(favicon);
                menu.Visible = true;
            }
        }
    }
}

using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace IronAHK.Scripting
{
    partial class Script
    {
        public static void CreateTrayMenu()
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                return;

            var menu = new NotifyIcon { ContextMenu = new ContextMenu() };
            menu.ContextMenu.MenuItems.Add(new MenuItem("&Reload", delegate { Application.Restart(); }));
            menu.ContextMenu.MenuItems.Add(new MenuItem("&Exit", delegate { Environment.Exit(0); }));

            var favicon = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Script).FullName + ".favicon.ico");

            if (favicon != null)
            {
                menu.Icon = new Icon(favicon);
                menu.Visible = true;
            }

            ApplicationExit += delegate
            {
                menu.Visible = false;
                menu.Dispose();
            };
        }
    }
}

Remove tray icon on safe exit.

Remove tray icon on safe exit.


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

#nullable disable

using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;

namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
    /// <summary>
    /// Calculates the colour coefficient of taiko difficulty.
    /// </summary>
    public class Colour : StrainDecaySkill
    {
        protected override double SkillMultiplier => 1;
        protected override double StrainDecayBase => 0.4;

        public Colour(Mod[] mods)
            : base(mods)
        {
        }

        protected override double StrainValueOf(DifficultyHitObject current)
        {
            TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour;
            double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty;
            if (current != null && colour != null)
            {
                ColourEncoding[] payload = colour.Encoding.Payload;
                string payloadDisplay = "";
                for (int i = 0; i < payload.Length; ++i)
                {
                    payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})";
                }

                System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}");
            }

            return difficulty;
        }
    }
}

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

#nullable disable

using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;

namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
    /// <summary>
    /// Calculates the colour coefficient of taiko difficulty.
    /// </summary>
    public class Colour : StrainDecaySkill
    {
        protected override double SkillMultiplier => 1;
        protected override double StrainDecayBase => 0.4;

        public Colour(Mod[] mods)
            : base(mods)
        {
        }

        protected override double StrainValueOf(DifficultyHitObject current)
        {
            TaikoDifficultyHitObjectColour colour = ((TaikoDifficultyHitObject)current).Colour;
            double difficulty = colour == null ? 0 : colour.EvaluatedDifficulty;
            // if (current != null && colour != null)
            // {
            //     ColourEncoding[] payload = colour.Encoding.Payload;
            //     string payloadDisplay = "";
            //     for (int i = 0; i < payload.Length; ++i)
            //     {
            //         payloadDisplay += $",({payload[i].MonoRunLength},{payload[i].EncodingRunLength})";
            //     }

            //     System.Console.WriteLine($"{current.StartTime},{colour.RepetitionInterval},{colour.Encoding.RunLength}{payloadDisplay}");
            // }

            return difficulty;
        }
    }
}

Comment out logging for debugging purposes


using Xunit;

namespace Nett.UnitTests
{
    public class TomlConfigTests
    {
        [Fact]
        public void WhenConfigHasActivator_ActivatorGetsUsed()
        {
            // Arrange
            var config = TomlConfig.Create(cfg => cfg
                .ConfigureType<IFoo>(ct => ct
                    .CreateInstance(() => new Foo())
                )
            );
            string toml = @"[Foo]";

            // Act
            var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);

            // Assert
            Assert.IsType<Foo>(co.Foo);
        }

        [Fact(DisplayName = "External configuration batch code is executed when configuration is done")]
        public void WhenConfigShouldRunExtenralConfig_ThisConfigGetsExecuted()
        {
            // Arrange
            var config = TomlConfig.Create(cfg => cfg
                .Apply(ExternalConfigurationBatch)
            );
            string toml = @"[Foo]";

            // Act
            var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);

            // Assert
            Assert.IsType<Foo>(co.Foo);
        }

        private static void ExternalConfigurationBatch(TomlConfig.ITomlConfigBuilder builder)
        {
            builder
                .ConfigureType<IFoo>(ct => ct
                    .CreateInstance(() => new Foo())
                );
        }

        class ConfigObject
        {
            public TestStruct S { get; set; }
        }

        struct TestStruct
        {
            public int Value;
        }

        interface IFoo
        {

        }

        class Foo : IFoo
        {
        }

        class ConfigOjectWithInterface
        {
            public IFoo Foo { get; set; }
        }
    }
}

using Xunit;

namespace Nett.UnitTests
{
    public class TomlConfigTests
    {
        [Fact]
        public void WhenConfigHasActivator_ActivatorGetsUsed()
        {
            // Arrange
            var config = TomlConfig.Create(cfg => cfg
                .ConfigureType<IFoo>(ct => ct
                    .CreateInstance(() => new Foo())
                )
            );
            string toml = @"[Foo]";

            // Act
            var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);

            // Assert
            Assert.IsType<Foo>(co.Foo);
        }

        [Fact(DisplayName = "External configuration batch code is executed when configuration is done")]
        public void WhenConfigShouldRunExternalConfig_ThisConfigGetsExecuted()
        {
            // Arrange
            var config = TomlConfig.Create(cfg => cfg
                .Apply(ExternalConfigurationBatch)
            );
            string toml = @"[Foo]";

            // Act
            var co = Toml.ReadString<ConfigOjectWithInterface>(toml, config);

            // Assert
            Assert.IsType<Foo>(co.Foo);
        }

        private static void ExternalConfigurationBatch(TomlConfig.ITomlConfigBuilder builder)
        {
            builder
                .ConfigureType<IFoo>(ct => ct
                    .CreateInstance(() => new Foo())
                );
        }

        class ConfigObject
        {
            public TestStruct S { get; set; }
        }

        struct TestStruct
        {
            public int Value;
        }

        interface IFoo
        {

        }

        class Foo : IFoo
        {
        }

        class ConfigOjectWithInterface
        {
            public IFoo Foo { get; set; }
        }
    }
}

Fix typo in unit test name

Fix typo in unit test name


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

namespace osu.Framework.Audio.Sample
{
    /// <summary>
    /// A <see cref="SampleChannel"/> which explicitly plays no audio.
    /// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound.
    /// </summary>
    public sealed class SampleChannelVirtual : SampleChannel
    {
        public SampleChannelVirtual()
            : base(new SampleVirtual(), _ => { })
        {
        }

        public override bool Playing => false;

        protected override void UpdateState()
        {
            // empty override to avoid affecting sample channel count in frame statistics
        }

        private class SampleVirtual : Sample
        {
        }
    }
}

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

namespace osu.Framework.Audio.Sample
{
    /// <summary>
    /// A <see cref="SampleChannel"/> which explicitly plays no audio.
    /// Aimed for scenarios in which a non-null <see cref="SampleChannel"/> is needed, but one that doesn't necessarily play any sound.
    /// </summary>
    public sealed class SampleChannelVirtual : SampleChannel
    {
        public SampleChannelVirtual()
            : base(new SampleVirtual(), _ => { })
        {
        }

        public override bool Playing => false;

        private class SampleVirtual : Sample
        {
        }
    }
}

Allow virtual SampleChannels to count towards statistics


using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

namespace PatchKit.Unity.Patcher.Licensing
{
    public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
    {
        private State _state = State.None;

        private KeyLicense _keyLicense;

        private Animator _animator;

        public InputField KeyInputField;

        public GameObject ErrorMessage;

        private void Awake()
        {
            _animator = GetComponent<Animator>();
        }

        private void Update()
        {
            _animator.SetBool("IsOpened", _state == State.Obtaining);

            ErrorMessage.SetActive(ShowError);
        }

        public void Cancel()
        {
            _state = State.Cancelled;
        }

        public void Confirm()
        {
            string key = KeyInputField.text;
            key = key.ToUpper().Trim();

            _keyLicense = new KeyLicense
            {
                Key = KeyInputField.text
            };

            _state = State.Confirmed;
        }

        public bool ShowError { get; set; }

        ILicense ILicenseObtainer.Obtain()
        {
            _state = State.Obtaining;

            while (_state != State.Confirmed && _state != State.Cancelled)
            {
                Thread.Sleep(10);
            }

            if (_state == State.Cancelled)
            {
                throw new OperationCanceledException();
            }

            return _keyLicense;
        }

        private enum State
        {
            None,
            Obtaining,
            Confirmed,
            Cancelled
        }
    }
}

using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

namespace PatchKit.Unity.Patcher.Licensing
{
    public class KeyLicenseObtainer : MonoBehaviour, ILicenseObtainer
    {
        private State _state = State.None;

        private KeyLicense _keyLicense;

        private Animator _animator;

        public InputField KeyInputField;

        public GameObject ErrorMessage;

        private void Awake()
        {
            _animator = GetComponent<Animator>();
        }

        private void Update()
        {
            _animator.SetBool("IsOpened", _state == State.Obtaining);

            ErrorMessage.SetActive(ShowError);
        }

        public void Cancel()
        {
            _state = State.Cancelled;
        }

        public void Confirm()
        {
            string key = KeyInputField.text;
            key = key.ToUpper().Trim();

            _keyLicense = new KeyLicense
            {
                Key = key
            };

            _state = State.Confirmed;
        }

        public bool ShowError { get; set; }

        ILicense ILicenseObtainer.Obtain()
        {
            _state = State.Obtaining;

            while (_state != State.Confirmed && _state != State.Cancelled)
            {
                Thread.Sleep(10);
            }

            if (_state == State.Cancelled)
            {
                throw new OperationCanceledException();
            }

            return _keyLicense;
        }

        private enum State
        {
            None,
            Obtaining,
            Confirmed,
            Cancelled
        }
    }
}

Fix problem with invalid whitespaces and lower characters in input license key code


/*
 * FSpot.Query.OrderByTime.cs
 *
 * Author(s):
 *	Stephane Delcroix <stephane@delcroix.org>
 *
 * This is free software. See COPYING for details.
 *
 */

using System;
using FSpot.Utils;

namespace FSpot.Query {
	public class OrderByTime : IQueryCondition, IOrderCondition
	{
		public static OrderByTime OrderByTimeAsc = new OrderByTime (true);
		public static OrderByTime OrderByTimeDesc = new OrderByTime (false);

		bool asc;
		public bool Asc {
			get { return asc; }
		}

		public OrderByTime (bool asc)
		{
			this.asc = asc;
		}

		public string SqlClause ()
		{
			return String.Format (" time {0}, filename {0} ", asc ? "ASC" : "DESC");
		}
	}
}

/*
 * FSpot.Query.OrderByTime.cs
 *
 * Author(s):
 *	Stephane Delcroix <stephane@delcroix.org>
 *
 * This is free software. See COPYING for details.
 *
 */

using System;
using FSpot.Utils;

namespace FSpot.Query {
	public class OrderByTime : IQueryCondition, IOrderCondition
	{
		public static OrderByTime OrderByTimeAsc = new OrderByTime (true);
		public static OrderByTime OrderByTimeDesc = new OrderByTime (false);

		bool asc;
		public bool Asc {
			get { return asc; }
		}

		public OrderByTime (bool asc)
		{
			this.asc = asc;
		}

		public string SqlClause ()
		{
			// filenames must always appear in alphabetical order if times are the same
			return String.Format (" time {0}, filename ASC ", asc ? "ASC" : "DESC");
		}
	}
}

Order by filename ASC, so that detached versions appear always after the original photo, even if Reverse Order is used


using System.Threading.Tasks;

namespace MetaMediaPlugin.Abstractions
{
    public interface IMediaService
    {
        bool IsCameraAvailable { get; }
        bool IsTakePhotoSupported { get; }
        bool IsPickPhotoSupported { get; }
        string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses
        Task<IMediaFile> PickPhotoAsync();
        Task<IMediaFile> TakePhotoAsync();
    }
}

using System.Threading.Tasks;

namespace MetaMediaPlugin.Abstractions
{
    public interface IMediaService
    {
        bool IsCameraAvailable { get; }
        bool IsTakePhotoSupported { get; }
        bool IsPickPhotoSupported { get; }

        /// <summary>
        /// Specify the photo directory to use for your app.
        /// In iOS, this has no effect.
        /// In Android, this will be the name of the subdirectory within the shared photos directory.
        /// </summary>
        /// <value>The photos directory.</value>
        string PhotosDirectory { get; set; } // this is only used in Android to specify the sub-directory in photos that your app uses
        Task<IMediaFile> PickPhotoAsync();
        Task<IMediaFile> TakePhotoAsync();
    }
}

Add some comments to the new PhotosDirectory field so users understand how it is used.


using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Logging.StructuredLogger;
using Microsoft.Build.Utilities;

namespace StructuredLogViewer
{
    public class HostedBuild
    {
        private string projectFilePath;

        public HostedBuild(string projectFilePath)
        {
            this.projectFilePath = projectFilePath;
        }

        public Task<Build> BuildAndGetResult(BuildProgress progress)
        {
            var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);
            var loggerDll = typeof(StructuredLogger).Assembly.Location;
            var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml";
            progress.MSBuildCommandLine = commandLine;
            StructuredLogger.SaveLogToDisk = false;

            return System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    var result = MSBuildApp.Execute(commandLine);
                    return StructuredLogger.CurrentBuild;
                }
                catch (Exception ex)
                {
                    var build = new Build();
                    build.Succeeded = false;
                    build.AddChild(new Message() { Text = "Exception occurred during build:" });
                    build.AddChild(new Error() { Text = ex.ToString() });
                    return build;
                }
            });
        }
    }
}

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Logging.StructuredLogger;
using Microsoft.Build.Utilities;

namespace StructuredLogViewer
{
    public class HostedBuild
    {
        private string projectFilePath;

        public HostedBuild(string projectFilePath)
        {
            this.projectFilePath = projectFilePath;
        }

        public Task<Build> BuildAndGetResult(BuildProgress progress)
        {
            var msbuildExe = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion);
            var loggerDll = typeof(StructuredLogger).Assembly.Location;
            var commandLine = $@"""{msbuildExe}"" ""{projectFilePath}"" /t:Rebuild /v:diag /noconlog /logger:{nameof(StructuredLogger)},""{loggerDll}"";BuildLog.xml";
            progress.MSBuildCommandLine = commandLine;
            StructuredLogger.SaveLogToDisk = false;

            return System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    var result = MSBuildApp.Execute(commandLine);
                    return StructuredLogger.CurrentBuild;
                }
                catch (Exception ex)
                {
                    var build = new Build();
                    build.Succeeded = false;
                    build.AddChild(new Message() { Text = "Exception occurred during build:" });
                    build.AddChild(new Error() { Text = ex.ToString() });
                    return build;
                }
            });
        }
    }
}

Set verbosity to diagnostic on hosted build.


namespace Grabacr07.KanColleWrapper.Translation
{
    public static class ItemTranslationHelper
    {
        public static string TranslateItemName(string name)
        {
            string stripped = TranslationHelper.StripInvalidCharacters(name);
            string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture));

            return (string.IsNullOrEmpty(translated) ? name : translated);
        }
    }
}

namespace Grabacr07.KanColleWrapper.Translation
{
    public static class ItemTranslationHelper
    {
        public static string TranslateItemName(string name)
        {
            string stripped = name;
            string translated = (string.IsNullOrEmpty(stripped) ? null : Equipment.Resources.ResourceManager.GetString(stripped, Equipment.Resources.Culture));

            return (string.IsNullOrEmpty(translated) ? name : translated);
        }
    }
}

Fix bug that was preventing transation of some items.


using System;
using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;

namespace Abp.Web.EntityHistory
{
    /// <summary>
    /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
    /// </summary>
    public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
    {
        [CanBeNull]
        public override string Reason
        {
            get
            {
                if (OverridedValue != null)
                {
                    return OverridedValue.Reason;
                }

                try
                {
                    return HttpContext.Current?.Request.Url.AbsoluteUri;
                }
                catch (Exception ex)
                {
                    Logger.Warn(ex.ToString(), ex);
                    return null;
                }
            }
        }

        public HttpRequestEntityChangeSetReasonProvider(
            IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
            ) : base(reasonOverrideScopeProvider)
        {
        }
    }
}

using Abp.Dependency;
using Abp.EntityHistory;
using Abp.Runtime;
using JetBrains.Annotations;
using System.Web;

namespace Abp.Web.EntityHistory
{
    /// <summary>
    /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request.
    /// </summary>
    public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency
    {
        [CanBeNull]
        public override string Reason
        {
            get
            {
                if (OverridedValue != null)
                {
                    return OverridedValue.Reason;
                }

                try
                {
                    return HttpContext.Current?.Request.Url.AbsoluteUri;
                }
                catch (HttpException ex)
                {
                    /* Workaround:
                     * Accessing HttpContext.Request during Application_Start or Application_End will throw exception.
                     * This behavior is intentional from microsoft
                     * See https://stackoverflow.com/questions/2518057/request-is-not-available-in-this-context/23908099#comment2514887_2518066
                     */
                    Logger.Warn("HttpContext.Request access when it is not suppose to", ex);
                    return null;
                }
            }
        }

        public HttpRequestEntityChangeSetReasonProvider(
            IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider
            ) : base(reasonOverrideScopeProvider)
        {
        }
    }
}

Handle HttpException explicitly and include comments for workaround


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Bari.Core.Generic;
using Bari.Core.Tools;
using Bari.Core.UI;

namespace Bari.Plugins.Gallio.Tools
{
    public class Gallio: DownloadablePackedExternalTool, IGallio
    {
        private readonly IFileSystemDirectory targetDir;

        public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters)
            : base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"),
                   @"bin\Gallio.Echo.exe", new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters)
        {
            this.targetDir = targetDir;
        }

        public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies)
        {
            List<string> ps = testAssemblies.Select(p => (string)p).ToList();
            ps.Add("/report-type:Xml");
            ps.Add("/report-directory:.");
            ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent");
            ps.Add("/report-name-format:test-report");
            return Run(targetDir, ps.ToArray());
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Bari.Core.Generic;
using Bari.Core.Tools;
using Bari.Core.UI;

namespace Bari.Plugins.Gallio.Tools
{
    public class Gallio: DownloadablePackedExternalTool, IGallio
    {
        private readonly IFileSystemDirectory targetDir;

        public Gallio([TargetRoot] IFileSystemDirectory targetDir, IParameters parameters)
            : base("Gallio", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "gallio"),
                   Path.Combine("bin", "Gallio.Echo.exe"), new Uri("http://mb-unit.googlecode.com/files/GallioBundle-3.4.14.0.zip"), true, parameters)
        {
            this.targetDir = targetDir;
        }

        public bool RunTests(IEnumerable<TargetRelativePath> testAssemblies)
        {
            List<string> ps = testAssemblies.Select(p => (string)p).ToList();
            ps.Add("/report-type:Xml");
            ps.Add("/report-directory:.");
            ps.Add("/report-formatter-property:AttachmentContentDisposition=Absent");
            ps.Add("/report-name-format:test-report");
            return Run(targetDir, ps.ToArray());
        }
    }
}

Fix for gallio on non-windows systems

Fix for gallio on non-windows systems


using System.Diagnostics;
using System.Threading;

static class DebugUtilities {
	public static void Burn(long ms) {
		Stopwatch stopwatch = Stopwatch.StartNew();
		while (stopwatch.ElapsedMilliseconds < ms) {
		}
	}

	public static void Sleep(long ms) {
		Stopwatch stopwatch = Stopwatch.StartNew();
		while (stopwatch.ElapsedMilliseconds < ms) {
			Thread.Yield();
		}
	}
}

using SharpDX;
using System;
using System.Diagnostics;
using System.Threading;

static class DebugUtilities {
	public static void Burn(long ms) {
		Stopwatch stopwatch = Stopwatch.StartNew();
		while (stopwatch.ElapsedMilliseconds < ms) {
		}
	}

	public static void Sleep(long ms) {
		Stopwatch stopwatch = Stopwatch.StartNew();
		while (stopwatch.ElapsedMilliseconds < ms) {
			Thread.Yield();
		}
	}

	[Conditional("DEBUG")]
	public static void AssertSamePosition(Vector3 v1, Vector3 v2) {
		float distance = Vector3.Distance(v1, v2);
		float denominator = (Vector3.Distance(v1, Vector3.Zero) + Vector3.Distance(v2, Vector3.Zero)) / 2 + 1e-1f;
		float relativeDistance = distance / denominator;
		Debug.Assert(relativeDistance < 1e-2, "not same position");
	}

	[Conditional("DEBUG")]
	public static void AssertSameDirection(Vector3 v1, Vector3 v2) {
		Vector3 u1 = Vector3.Normalize(v1);
		Vector3 u2 = Vector3.Normalize(v2);
		float dotProduct = Vector3.Dot(u1, u2);
		Debug.Assert(Math.Abs(dotProduct - 1) < 1e-2f, "not same direction");
	}
}

Add a couple of SharpDX Math related assertion helpers


using System;
using System.Linq;

namespace KornelijePetak.IncidentCS
{
	public static partial class Incident
	{
		internal static Random Rand { get; private set; }

		public static PrimitiveRandomizer Primitive { get; private set; }
		public static TextRandomizer Text { get; private set; }

		static Incident()
		{
			Rand = new Random();
			setupConcreteRandomizers();
		}

		public static int Seed
		{
			set
			{
				Rand = new Random(value);
			}
		}
	}
}

using System;
using System.Linq;

namespace KornelijePetak.IncidentCS
{
	public static partial class Incident
	{
		internal static Random Rand { get; private set; }

		public static IPrimitiveRandomizer Primitive { get; private set; }
		public static ITextRandomizer Text { get; private set; }

		static Incident()
		{
			Rand = new Random();
			setupConcreteRandomizers();
		}

		public static int Seed
		{
			set
			{
				Rand = new Random(value);
			}
		}
	}
}

Convert .Text and .Primitive to interfaces


using System.Linq;
using Microsoft.AspNetCore.Mvc;
using topicr.Models;

namespace topicr.Controllers.Api
{
    [Produces("application/json")]
    [Route("api/topics")]
    public class TopicController : Controller
    {
        private readonly TopicContext _db;

        public TopicController(TopicContext db)
        {
            _db = db;
        }

        [HttpGet]
        public IActionResult GetTopics()
        {
            return Json(_db.Topics
                           .Select(p => new
                                        {
                                            p.Id,
                                            p.Title,
                                            p.Description
                                        })
                           .ToList());
        }

        [HttpPost]
        [Route("new")]
        public IActionResult PostTopic(Topic topic)
        {
            _db.Topics.Add(topic);
            _db.SaveChanges();
            return Ok();
        }
    }
}

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using topicr.Models;

namespace topicr.Controllers.Api
{
    [Produces("application/json")]
    [Route("api/topics")]
    public class TopicController : Controller
    {
        private readonly TopicContext _db;

        public TopicController(TopicContext db)
        {
            _db = db;
        }

        [HttpGet]
        [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult GetTopics()
        {
            return Json(_db.Topics
                           .Select(p => new
                                        {
                                            p.Id,
                                            p.Title,
                                            p.Description
                                        })
                           .ToList());
        }

        [HttpPost]
        [Route("new")]
        public IActionResult PostTopic(Topic topic)
        {
            _db.Topics.Add(topic);
            _db.SaveChanges();
            return Ok();
        }

        [HttpGet]
        [Route("clear")]
        public IActionResult ClearTopics()
        {
            foreach (var topic in _db.Topics)
            {
                _db.Topics.Remove(topic);
            }
            _db.SaveChanges();
            return Ok();
        }
    }
}

Disable caching to force fetching of data when navigating backwards. Added api to clear db.


public static class Bob
{
    public static string Response(string statement)
    {
        if (IsSilence(statement))
            return "Fine. Be that way!";
        if (IsYelling(statement))
            return "Whoa, chill out!";
        if (IsQuestion(statement))
            return "Sure.";
        return "Whatever.";
    }

    private static bool IsSilence (string statement)
    {
        return statement.Trim() == "";
    }

    private static bool IsYelling (string statement)
    {
        return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+");
    }

    private static bool IsQuestion (string statement)
    {
        return statement.Trim().EndsWith("?");
    }
}

public static class Bob
{
    public static string Response(string statement)
    {
        if (IsSilence(statement))
            return "Fine. Be that way!";
        if (IsYelling(statement) && IsQuestion(statement))
            return "Calm down, I know what I'm doing!";
        if (IsYelling(statement))
            return "Whoa, chill out!";
        if (IsQuestion(statement))
            return "Sure.";
        return "Whatever.";
    }

    private static bool IsSilence (string statement)
    {
        return statement.Trim() == "";
    }

    private static bool IsYelling (string statement)
    {
        return statement.ToUpper() == statement && System.Text.RegularExpressions.Regex.IsMatch(statement, "[a-zA-Z]+");
    }

    private static bool IsQuestion (string statement)
    {
        return statement.Trim().EndsWith("?");
    }
}

Update example implementation for Bob exercise


using System;

namespace PalmDB
{
    /// <summary>
    /// Typical guard class that contains methods to validate method arguments.
    /// </summary>
    public static class Guard
    {
        /// <summary>
        /// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>.
        /// </summary>
        /// <param name="argument">The argument to check for null.</param>
        /// <param name="name">The name of the argument.</param>
        public static void NotNull(object argument, string name)
        {
            if (argument == null)
                throw new ArgumentNullException(name);
        }

        /// <summary>
        /// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0.
        /// </summary>
        /// <param name="argument">The argument.</param>
        /// <param name="name">The name.</param>
        public static void NotNegative(int argument, string name)
        {
            if (argument < 0)
                throw new ArgumentException($"{name} cannot be less than 0.", name);
        }
    }
}

using System;

namespace PalmDB
{
    /// <summary>
    /// Typical guard class that contains methods to validate method arguments.
    /// </summary>
    internal static class Guard
    {
        /// <summary>
        /// Throws a <see cref="ArgumentNullException"/> if the specified <paramref name="argument"/> is <c>null</c>.
        /// </summary>
        /// <param name="argument">The argument to check for null.</param>
        /// <param name="name">The name of the argument.</param>
        public static void NotNull(object argument, string name)
        {
            if (argument == null)
                throw new ArgumentNullException(name);
        }

        /// <summary>
        /// Throws a <see cref="ArgumentException"/> if the specified <paramref name="argument"/> is less than 0.
        /// </summary>
        /// <param name="argument">The argument.</param>
        /// <param name="name">The name.</param>
        public static void NotNegative(int argument, string name)
        {
            if (argument < 0)
                throw new ArgumentException($"{name} cannot be less than 0.", name);
        }
    }
}

Make the guard class internal

Make the guard class internal


using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core;
using NBi.Core.ResultSet;
using static NBi.Core.ResultSet.ResultSetBuilder;

namespace NBi.Xml.Items.ResultSet
{
    public class ResultSetXml : BaseItem
    {
        [XmlElement("row")]
        public List<RowXml> _rows { get; set; }

        public IList<IRow> Rows
        {
            get { return _rows.Cast<IRow>().ToList(); }
        }

        public IList<string> Columns
        {
            get
            {
                if (_rows.Count == 0)
                    return new List<string>();

                var names = new List<string>();
                var row = _rows[0];

                foreach (var cell in row.Cells)
                {
                    if (!string.IsNullOrEmpty(cell.ColumnName))
                        names.Add(cell.ColumnName);
                    else
                        names.Add(string.Empty);
                }
                return names;
            }
        }

        [XmlIgnore]
        public Content Content
        {
            get { return new Content(Rows, Columns); }
        }

        [XmlAttribute("file")]
        public string File { get; set; }

        public string GetFile()
        {
            var file = string.Empty;
            if (Path.IsPathRooted(File))
                file = File;
            else
                file = Settings.BasePath + File;

            return file;
        }

        public ResultSetXml()
        {
            _rows = new List<RowXml>();
        }

    }
}

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using NBi.Core;
using NBi.Core.ResultSet;

namespace NBi.Xml.Items.ResultSet
{
    public class ResultSetXml : BaseItem
    {
        [XmlElement("row")]
        public List<RowXml> _rows { get; set; }

        public IList<IRow> Rows
        {
            get { return _rows.Cast<IRow>().ToList(); }
        }

        public IList<string> Columns
        {
            get
            {
                if (_rows.Count == 0)
                    return new List<string>();

                var names = new List<string>();
                var row = _rows[0];

                foreach (var cell in row.Cells)
                {
                    if (!string.IsNullOrEmpty(cell.ColumnName))
                        names.Add(cell.ColumnName);
                    else
                        names.Add(string.Empty);
                }
                return names;
            }
        }

        [XmlIgnore]
        public ResultSetBuilder.Content Content
        {
            get { return new ResultSetBuilder.Content(Rows, Columns); }
        }

        [XmlAttribute("file")]
        public string File { get; set; }

        public string GetFile()
        {
            var file = string.Empty;
            if (Path.IsPathRooted(File))
                file = File;
            else
                file = Settings.BasePath + File;

            return file;
        }

        public ResultSetXml()
        {
            _rows = new List<RowXml>();
        }

    }
}

Fix (again) syntax issue with using static


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

namespace FightFleet
{
    public enum BoardCellStatus
    {
        Blank = 0,
        Ship = 1,
        Hit = 2
    }
}

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

namespace FightFleet
{
    public enum BoardCellStatus
    {
        Blank = 0,
        Ship = 1,
        Hit = 2,
        Miss = 3
    }
}

Add a 4th board cell status "Miss" to show that the user shoot to a blank spot.


using System.Reflection;
using JetBrains.ActionManagement;
using JetBrains.Application.PluginSupport;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("Reformatting Utilities")]
[assembly:
    AssemblyDescription(
        "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]

[assembly: AssemblyCompany("Øystein Krog")]
[assembly: AssemblyProduct("ReformatUtils")]
[assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.0.*")]
[assembly: AssemblyFileVersion("1.3.0.*")]

// The following information is displayed by ReSharper in the Plugins dialog

[assembly: PluginTitle("Reformatting Utilities")]
[assembly:
    PluginDescription(
        "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]
[assembly: PluginVendor("Øystein Krog")]

using System.Reflection;
using JetBrains.ActionManagement;
using JetBrains.Application.PluginSupport;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("Reformatting Utilities")]
[assembly:
    AssemblyDescription(
        "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]

[assembly: AssemblyCompany("Øystein Krog")]
[assembly: AssemblyProduct("ReformatUtils")]
[assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.0.*")]

// The following information is displayed by ReSharper in the Plugins dialog

[assembly: PluginTitle("Reformatting Utilities")]
[assembly:
    PluginDescription(
        "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)")
]
[assembly: PluginVendor("Øystein Krog")]

Fix bug in assembly file versioning ("*" was included in file version string)


using System;

class Protagonist {
	private static Protagonist INSTANCE;
	private static int MAX_MONEY = 99;

	private int balance;
	public int Balance {
		get { return balance; }
	}

	private Inventory inventory;
	public Inventory Inventory {
		get { return inventory; }
	}

	private Outfit outfit;

	private Protagonist() {
		balance = 99;
		outfit = new Outfit();
		inventory = new Inventory();
	}

	public static Protagonist GetInstance() {
		if (INSTANCE == null) {
			INSTANCE = new Protagonist();
		}

		return INSTANCE;
	}

	public bool modifyBalance(int difference) {
		if (difference + balance < 0) {
			return false;
		}

		balance = Math.Min(balance + difference, MAX_MONEY);
		return true;
	}

	public bool CanPurchase(int price) {
		return (price >= 0) && balance - price >= 0;
	}
}

using System;

class Protagonist {
	private static Protagonist INSTANCE;
	private static int MAX_MONEY = 99;

	private int balance;
	public int Balance {
		get { return balance; }
	}

	private Inventory inventory;
	public Inventory Inventory {
		get { return inventory; }
	}

	private Outfit outfit;

	private Protagonist() {
		balance = 0;
		outfit = new Outfit();
		inventory = new Inventory();
	}

	public static Protagonist GetInstance() {
		if (INSTANCE == null) {
			INSTANCE = new Protagonist();
		}

		return INSTANCE;
	}

	public bool modifyBalance(int difference) {
		if (difference + balance < 0) {
			return false;
		}

		balance = Math.Min(balance + difference, MAX_MONEY);
		return true;
	}

	public bool CanPurchase(int price) {
		return (price >= 0) && balance - price >= 0;
	}
}

Reset protagonist balance to 0

Reset protagonist balance to 0


using System;
using UnityEditor;
using UnityEngine;

namespace GitHub.Unity
{
    [Serializable]
    class AuthenticationWindow : BaseWindow
    {
        [SerializeField] private AuthenticationView authView;

        [MenuItem("GitHub/Authenticate")]
        public static void Launch()
        {
            Open();
        }

        public static IView Open(Action<bool> onClose = null)
        {
            AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>();
            if (onClose != null)
                authWindow.OnClose += onClose;
            authWindow.minSize = new Vector2(290, 290);
            authWindow.Show();
            return authWindow;
       }

        public override void OnGUI()
        {
            authView.OnGUI();
        }

        public override void Refresh()
        {
            authView.Refresh();
        }

        public override void OnEnable()
        {
            Utility.UnregisterReadyCallback(CreateViews);
            Utility.RegisterReadyCallback(CreateViews);

            Utility.UnregisterReadyCallback(ShowActiveView);
            Utility.RegisterReadyCallback(ShowActiveView);
        }

        private void CreateViews()
        {
            if (authView == null)
                authView = new AuthenticationView();
            authView.Initialize(this);
        }

        private void ShowActiveView()
        {
            authView.OnShow();
            Refresh();
        }

        public override void Finish(bool result)
        {
            Close();
            base.Finish(result);
        }
    }
}

using System;
using UnityEditor;
using UnityEngine;

namespace GitHub.Unity
{
    [Serializable]
    class AuthenticationWindow : BaseWindow
    {
        [SerializeField] private AuthenticationView authView;

        [MenuItem("GitHub/Authenticate")]
        public static void Launch()
        {
            Open();
        }

        public static IView Open(Action<bool> onClose = null)
        {
            AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>();
            if (onClose != null)
                authWindow.OnClose += onClose;
            authWindow.minSize = new Vector2(290, 290);
            authWindow.Show();
            return authWindow;
       }

        public override void OnGUI()
        {
            authView.OnGUI();
        }

        public override void Refresh()
        {
            authView.Refresh();
        }

        public override void OnEnable()
        {
            // Set window title
            titleContent = new GUIContent("Sign in", Styles.SmallLogo);

            Utility.UnregisterReadyCallback(CreateViews);
            Utility.RegisterReadyCallback(CreateViews);

            Utility.UnregisterReadyCallback(ShowActiveView);
            Utility.RegisterReadyCallback(ShowActiveView);
        }

        private void CreateViews()
        {
            if (authView == null)
                authView = new AuthenticationView();
            authView.Initialize(this);
        }

        private void ShowActiveView()
        {
            authView.OnShow();
            Refresh();
        }

        public override void Finish(bool result)
        {
            Close();
            base.Finish(result);
        }
    }
}

Set window title for authentication

Set window title for authentication


using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace twitch_tv_viewer.Models
{
    public class TwitchChannel : IComparable
    {
        public TwitchChannel()
        {
        }

        public TwitchChannel(JToken data)
        {
            var channel = data["channel"];
            Name = channel["display_name"]?.ToString() ?? "no name";
            Game = channel["game"]?.ToString() ?? "no game";
            Status = channel["status"]?.ToString().Trim() ?? "no status";
            Viewers = data["viewers"]?.ToString() ?? "???";
        }

        public string Name { get; set; }

        public string Game { get; set; }

        public string Status { get; set; }

        public string Viewers { get; set; }

        public int CompareTo(object obj)
        {
            var that = obj as TwitchChannel;
            if (that == null)
                return 0;
            return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal);
        }

        public async Task<string> StartStream()
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = "livestreamer",
                Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{Name} high",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            };

            var process = new Process
            {
                StartInfo = startInfo
            };

            process.Start();

            return await process.StandardOutput.ReadToEndAsync();
        }

        public void OpenChatroom() => Process.Start($"http://twitch.tv/{Name}/chat?popout=");
    }
}

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace twitch_tv_viewer.Models
{
    public class TwitchChannel : IComparable
    {
        public TwitchChannel()
        {
        }

        public TwitchChannel(JToken data)
        {
            var channel = data["channel"];
            Name = channel["display_name"]?.ToString() ?? "no name";
            Game = channel["game"]?.ToString() ?? "no game";
            Status = channel["status"]?.ToString().Trim() ?? "no status";
            Viewers = data["viewers"]?.ToString() ?? "???";
        }

        public string Name { get; set; }

        public string Game { get; set; }

        public string Status { get; set; }

        public string Viewers { get; set; }

        public int CompareTo(object obj)
        {
            var that = obj as TwitchChannel;
            if (that == null)
                return 0;
            return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal);
        }

    }
}

Remove unneeded methods from model

Remove unneeded methods from model


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Game;
using GnomeServer.Extensions;
using GnomeServer.Routing;

namespace GnomeServer.Controllers
{
    [Route("Game")]
    public sealed class GameController : ConventionRoutingController
    {
        [HttpGet]
        [Route("")]
        public IResponseFormatter Get(int speed)
        {
            GnomanEmpire.Instance.World.GameSpeed.Value = speed;
            String content = String.Format("Game Speed set to '{0}'", speed);
            return JsonResponse(content);
        }

        public IResponseFormatter Test()
        {
            BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;

            var fields = typeof(Character).GetFields(bindFlags);
            var behaviorTypeFields = fields.Where(obj => obj.FieldType == typeof(BehaviorType)).ToList();

            List<TestResponse> testResponses = new List<TestResponse>();

            var members = GnomanEmpire.Instance.GetGnomes();
            foreach (var characterKey in members)
            {
                var character = characterKey.Value;
                var name = character.NameAndTitle();

                foreach (var fieldInfo in behaviorTypeFields)
                {
                    var val = (BehaviorType)(fieldInfo.GetValue(character));
                    testResponses.Add(new TestResponse
                    {
                        Name = name,
                        Value = val.ToString(),
                    });
                }
            }
            return JsonResponse(testResponses);
        }

        private class TestResponse
        {
            public String Name { get; set; }
            public String Value { get; set; }
        }
    }
}

using System.Globalization;
using System.Net;
using Game;
using GnomeServer.Routing;

namespace GnomeServer.Controllers
{
    [Route("Game")]
    public sealed class GameController : ConventionRoutingController
    {
        [HttpGet]
        [Route("Speed")]
        public IResponseFormatter GetSpeed()
        {
            var world = GnomanEmpire.Instance.World;
            var speed = new
            {
                Speed = world.GameSpeed.Value.ToString(CultureInfo.InvariantCulture),
                IsPaused = world.Paused.Value.ToString(CultureInfo.InvariantCulture)
            };
            return JsonResponse(speed);
        }

        [HttpPost]
        [Route("Speed")]
        public IResponseFormatter PostSpeed(int speed)
        {
            GnomanEmpire.Instance.World.GameSpeed.Value = speed;
            return BlankResponse(HttpStatusCode.NoContent);
        }

        [HttpPost]
        [Route("Pause")]
        public IResponseFormatter PostPause()
        {
            GnomanEmpire.Instance.World.Paused.Value = true;
            return BlankResponse(HttpStatusCode.NoContent);
        }

        [HttpPost]
        [Route("Play")]
        public IResponseFormatter PostPlay()
        {
            GnomanEmpire.Instance.World.Paused.Value = false;
            return BlankResponse(HttpStatusCode.NoContent);
        }
    }
}

Add endpoints for controlling game speed.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Aspose.Cells.Examples.CSharp.Articles
{
    public class LoadWorkbookWithSpecificCultureInfoNumberFormat
    {
        public static void Run()
        {
            // ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat
            using (var inputStream = new MemoryStream())
            {
                using (var writer = new StreamWriter(inputStream))
                {
                    writer.WriteLine("<title>Test Culture</title>

1234,56

");
                    writer.Flush();

                    var culture = new CultureInfo("en-GB");
                    culture.NumberFormat.NumberDecimalSeparator = ",";
                    culture.DateTimeFormat.DateSeparator = "-";
                    culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";

                    LoadOptions options = new LoadOptions(LoadFormat.Html);
                    options.CultureInfo = culture;

                    using (var workbook = new Workbook(inputStream, options))
                    {
                        var cell = workbook.Worksheets[0].Cells["A1"];
                        Assert.AreEqual(CellValueType.IsNumeric, cell.Type);
                        Assert.AreEqual(1234.56, cell.DoubleValue);
                    }
                }
            }
            // ExEnd:LoadWorkbookWithSpecificCultureInfo
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Aspose.Cells.Examples.CSharp.Articles
{
    public class LoadWorkbookWithSpecificCultureInfoNumberFormat
    {
        public static void Run()
        {
            // ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat
            using (var inputStream = new MemoryStream())
            {
                using (var writer = new StreamWriter(inputStream))
                {
                    writer.WriteLine("<title>Test Culture</title>

1234,56

");
                    writer.Flush();

                    var culture = new CultureInfo("en-GB");
                    culture.NumberFormat.NumberDecimalSeparator = ",";
                    culture.DateTimeFormat.DateSeparator = "-";
                    culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";

                    LoadOptions options = new LoadOptions(LoadFormat.Html);
                    options.CultureInfo = culture;

                    using (var workbook = new Workbook(inputStream, options))
                    {
                        var cell = workbook.Worksheets[0].Cells["A1"];
                        Assert.AreEqual(CellValueType.IsNumeric, cell.Type);
                        Assert.AreEqual(1234.56, cell.DoubleValue);
                    }
                }
            }
            // ExEnd:LoadWorkbookWithSpecificCultureInfoNumberFormat
        }
    }
}

Correct the Example Name in Comment

Correct the Example Name in Comment


// 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.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using OpenTK.Graphics;

namespace osu.Game.Graphics.Backgrounds
{
    public class Background : BufferedContainer
    {
        public Sprite Sprite;

        private readonly string textureName;

        public Background(string textureName = @"")
        {
            CacheDrawnFrameBuffer = true;

            this.textureName = textureName;
            RelativeSizeAxes = Axes.Both;

            Add(Sprite = new Sprite
            {
                RelativeSizeAxes = Axes.Both,
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Colour = Color4.DarkGray,
                FillMode = FillMode.Fill,
            });
        }

        [BackgroundDependencyLoader]
        private void load(LargeTextureStore textures)
        {
            if (!string.IsNullOrEmpty(textureName))
                Sprite.Texture = textures.Get(textureName);
        }
    }
}

// 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.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;

namespace osu.Game.Graphics.Backgrounds
{
    public class Background : BufferedContainer
    {
        public Sprite Sprite;

        private readonly string textureName;

        public Background(string textureName = @"")
        {
            CacheDrawnFrameBuffer = true;

            this.textureName = textureName;
            RelativeSizeAxes = Axes.Both;

            Add(Sprite = new Sprite
            {
                RelativeSizeAxes = Axes.Both,
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                FillMode = FillMode.Fill,
            });
        }

        [BackgroundDependencyLoader]
        private void load(LargeTextureStore textures)
        {
            if (!string.IsNullOrEmpty(textureName))
                Sprite.Texture = textures.Get(textureName);
        }
    }
}

Fix background brightness being adjusted globally


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

namespace BatteryCommander.Web.Controllers
{
    public class ACFTController : Controller
    {
        private readonly Database db;

        public ACFTController(Database db)
        {
            this.db = db;
        }

        public async Task<IActionResult> Index()
        {
            return Content("Coming soon!");
        }
    }
}

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

namespace BatteryCommander.Web.Controllers
{
    public class ACFTController : Controller
    {
        private readonly Database db;

        public ACFTController(Database db)
        {
            this.db = db;
        }

        public async Task<IActionResult> Index()
        {
            return Content("Coming soon!");
        }

        public async Task<IActionResult> Details(int id)
        {
            return View(await Get(db, id));
        }

        public async Task<IActionResult> New(int soldier = 0)
        {
            ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL);

            return View(nameof(Edit), new APFT { SoldierId = soldier });
        }

        public async Task<IActionResult> Edit(int id)
        {
            ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL);

            return View(await Get(db, id));
        }

        [HttpPost, ValidateAntiForgeryToken]
        public async Task<IActionResult> Save(ACFT model)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL);

                return View("Edit", model);
            }

            if (await db.ACFTs.AnyAsync(apft => apft.Id == model.Id) == false)
            {
                db.ACFTs.Add(model);
            }
            else
            {
                db.ACFTs.Update(model);
            }

            await db.SaveChangesAsync();

            return RedirectToAction(nameof(Details), new { model.Id });
        }

        [HttpPost, ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            var test = await Get(db, id);

            db.ACFTs.Remove(test);

            await db.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        public static async Task<ACFT> Get(Database db, int id)
        {
            return
                await db
                .ACFTs
                .Include(_ => _.Soldier)
                .ThenInclude(_ => _.Unit)
                .Where(_ => _.Id == id)
                .SingleOrDefaultAsync();
        }
    }
}

Drop in other CRUD methods

Drop in other CRUD methods

For #403


using System;
using System.Linq;
using Newtonsoft.Json;

namespace Exceptional.Core
{
    public class ExceptionSummary
    {
        [JsonProperty(PropertyName = "occurred_at")]
        public DateTime OccurredAt { get; set; }

        [JsonProperty(PropertyName = "message")]
        public string Message { get; set; }

        [JsonProperty(PropertyName = "backtrace")]
        public string[] Backtrace { get; set; }

        [JsonProperty(PropertyName = "exception_class")]
        public string ExceptionClass { get; set; }

        public ExceptionSummary()
        {
            OccurredAt = DateTime.UtcNow;
        }

        public static ExceptionSummary CreateFromException(Exception ex)
        {
            var summary = new ExceptionSummary();
            summary.Message = ex.Message;
            summary.Backtrace = ex.StackTrace.Split('\r', '\n').Select(line => line.Trim()).ToArray();
            summary.ExceptionClass = ex.GetType().Name;
            return summary;
        }
    }
}

using System;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;

namespace Exceptional.Core
{
    public class ExceptionSummary
    {
        [JsonProperty(PropertyName = "occurred_at")]
        public string OccurredAt { get; set; }

        [JsonProperty(PropertyName = "message")]
        public string Message { get; set; }

        [JsonProperty(PropertyName = "backtrace")]
        public string[] Backtrace { get; set; }

        [JsonProperty(PropertyName = "exception_class")]
        public string ExceptionClass { get; set; }

        public ExceptionSummary()
        {
            OccurredAt = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
        }

        public static ExceptionSummary CreateFromException(Exception ex)
        {
            var summary = new ExceptionSummary();
            summary.Message = ex.Message;
            summary.Backtrace = ex.StackTrace.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries).Select(line => line.Trim()).ToArray();
            summary.ExceptionClass = ex.GetType().Name;
            return summary;
        }
    }
}

Use 'o' format for date. Fixed splitting problem with backtrace.


using System;
using System.Web.Routing;
using MvcContrib.TestHelper;
using SnittListan.Controllers;
using Xunit;

namespace SnittListan.Test
{
	public class RoutesTest : IDisposable
	{
		public RoutesTest()
		{
			new RouteConfigurator(RouteTable.Routes).Configure();
		}

		public void Dispose()
		{
			RouteTable.Routes.Clear();
		}

		[Fact]
		public void DefaultRoute()
		{
			"~/".ShouldMapTo<HomeController>(c => c.Index());
		}

		[Fact]
		public void LowerCaseRoutes()
		{
			"~/account/register".ShouldMapTo<AccountController>(c => c.Register());
		}

		[Fact]
		public void Shortcuts()
		{
			"~/register".ShouldMapTo<AccountController>(c => c.Register());
			"~/logon".ShouldMapTo<AccountController>(c => c.LogOn());
			"~/about".ShouldMapTo<HomeController>(c => c.About());
		}
	}
}

using System;
using System.Web.Routing;
using MvcContrib.TestHelper;
using SnittListan.Controllers;
using Xunit;
using System.Web.Mvc;

namespace SnittListan.Test
{
	public class RoutesTest : IDisposable
	{
		public RoutesTest()
		{
			new RouteConfigurator(RouteTable.Routes).Configure();
		}

		public void Dispose()
		{
			RouteTable.Routes.Clear();
		}

		[Fact]
		public void DefaultRoute()
		{
			"~/".ShouldMapTo<HomeController>(c => c.Index());
		}

		[Fact]
		public void LowerCaseRoutes()
		{
			"~/account/register".ShouldMapTo<AccountController>(c => c.Register());
		}

		[Fact]
		public void Shortcuts()
		{
			"~/register".ShouldMapTo<AccountController>(c => c.Register());
			"~/logon".ShouldMapTo<AccountController>(c => c.LogOn());
			"~/about".ShouldMapTo<HomeController>(c => c.About());
		}

		[Fact]
		public void Verify()
		{
			var verify = "~/verify".WithMethod(HttpVerbs.Post);
			var guid = Guid.NewGuid();
			verify.Values["activationKey"] = guid.ToString();
			verify.ShouldMapTo<AccountController>(c => c.Verify(guid));
		}
	}
}

Verify should accept a guid activationKey


// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License

using Microsoft.MixedReality.Toolkit.UI.Interaction;
using UnityEditor;

namespace Microsoft.MixedReality.Toolkit.Editor
{
    /// <summary>
    /// Custom inspector for an InteractiveElement.
    /// </summary>
    [CustomEditor(typeof(InteractiveElement))]
    public class InteractiveElementInspector : BaseInteractiveElementInspector
    {
        protected override void OnEnable()
        {
            base.OnEnable();
        }

        public override void OnInspectorGUI()
        {
            // Interactive Element is a place holder class
            base.OnInspectorGUI();
        }
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License

using Microsoft.MixedReality.Toolkit.UI.Interaction;
using UnityEditor;

namespace Microsoft.MixedReality.Toolkit.Editor
{
    /// <summary>
    /// Custom inspector for an InteractiveElement.
    /// </summary>
    [CustomEditor(typeof(InteractiveElement))]
    public class InteractiveElementInspector : BaseInteractiveElementInspector
    {
       // Interactive Element is a place holder class
    }
}

Remove override methods from Interactive Element Inspector


using System.IO;
using NClap.ConsoleInput;
using NClap.Utilities;

namespace NClap.Repl
{
    /// <summary>
    /// Parameters for constructing a loop with advanced line input.  The
    /// parameters indicate how the loop's textual input and output should
    /// be implemented.
    /// </summary>
    public class LoopInputOutputParameters
    {
        /// <summary>
        /// Writer to use for error output.
        /// </summary>
        public TextWriter ErrorWriter { get; set; }

        /// <summary>
        /// Line input object to use.
        /// </summary>
        public IConsoleLineInput LineInput { get; set; }

        /// <summary>
        /// The console input interface to use.
        /// </summary>
        public IConsoleInput ConsoleInput { get; set; }

        /// <summary>
        /// The console output interface to use.
        /// </summary>
        public IConsoleOutput ConsoleOutput { get; set; }

        /// <summary>
        /// Input prompt.
        /// </summary>
        public ColoredString Prompt { get; set; }
    }
}

using System.IO;
using NClap.ConsoleInput;
using NClap.Utilities;

namespace NClap.Repl
{
    /// <summary>
    /// Parameters for constructing a loop with advanced line input.  The
    /// parameters indicate how the loop's textual input and output should
    /// be implemented.
    /// </summary>
    public class LoopInputOutputParameters
    {
        /// <summary>
        /// Optionally provides a writer to use for error output.
        /// </summary>
        public TextWriter ErrorWriter { get; set; }

        /// <summary>
        /// Line input object to use, or null for a default one to be
        /// constructed.
        /// </summary>
        public IConsoleLineInput LineInput { get; set; }

        /// <summary>
        /// The console input interface to use, or null to use the default one.
        /// </summary>
        public IConsoleInput ConsoleInput { get; set; }

        /// <summary>
        /// The console output interface to use, or null to use the default one.
        /// </summary>
        public IConsoleOutput ConsoleOutput { get; set; }

        /// <summary>
        /// The console key binding set to use, or null to use the default one.
        /// </summary>
        public IReadOnlyConsoleKeyBindingSet KeyBindingSet { get; set; }

        /// <summary>
        /// Input prompt, or null to use the default one.
        /// </summary>
        public ColoredString Prompt { get; set; }
    }
}

Add key binding set to loop i/o params

Add key binding set to loop i/o params


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

using Xamarin.Forms;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms.Controls.Issues
{
    [Preserve(AllMembers = true)]
    [Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)]
    public partial class Bugzilla51642 : ContentPage
	{
		public Bugzilla51642 ()
		{
			InitializeComponent ();
            LoadDelayedVM();
			BoundPicker.SelectedIndexChanged += (s, e) =>
			{
				SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString();
			};
		}

        public async void LoadDelayedVM()
        {
            await Task.Delay(1000);
            Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM());
        }
	}

	[Preserve(AllMembers=true)]
    class Bz51642VM
    {
        public IList<string> Items {
            get {
                return new List<String> { "Foo", "Bar", "Baz" };
            }
        }
    }
}

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

using Xamarin.Forms;
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms.Controls.Issues
{
    [Preserve(AllMembers = true)]
    [Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)]
    public partial class Bugzilla51642 : ContentPage
	{
#if APP
		public Bugzilla51642 ()
		{
			InitializeComponent ();
            LoadDelayedVM();
			BoundPicker.SelectedIndexChanged += (s, e) =>
			{
				SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString();
			};
		}

        public async void LoadDelayedVM()
        {
            await Task.Delay(1000);
            Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM());
        }
#endif
	}

	[Preserve(AllMembers=true)]
    class Bz51642VM
    {
        public IList<string> Items {
            get {
                return new List<String> { "Foo", "Bar", "Baz" };
            }
        }
    }
}

Fix build of test case

[Controls] Fix build of test case


// Copyright 2017 Daniel Plemmons

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

public class BasicStageManagable : StageManagable{
  private bool hasInitialized = false;

  protected virtual void Awake()
  {
    Initialize();
  }

  protected virtual void Initialize()
  {
    if(hasInitialized)
    {
      return;
    }

    hasInitialized = true;
    gameObject.SetActive(false);
  }

  public override void Enter()
  {
    Initialize();
    StartEnter();
    gameObject.SetActive(true);
    CompleteEnter();
  }

  public override void Exit()
  {
    Initialize();
    StartExit();
    gameObject.SetActive(false);
    CompleteExit();
  }
}

// Copyright 2017 Daniel Plemmons

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

public class BasicStageManagable : StageManagable{
  private bool hasInitialized = false;

  protected virtual void Awake()
  {
    Initialize();
  }

  protected virtual void Initialize()
  {
    if(hasInitialized)
    {
      return;
    }

    hasInitialized = true;
    gameObject.SetActive(false);
  }

  public override void Enter()
  {
    Initialize();
    StartEnter();
    gameObject.SetActive(true);
    CompleteEnter();
  }

  public override void Exit()
  {
    Initialize();
    StartExit();
    gameObject.SetActive(false);
    CompleteExit();
  }
}

Remove some unused using statements

Remove some unused using statements


using System;
using System.Linq;

#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif

namespace SQLite.Tests
{
	[TestFixture]
	public class ScalarTest
	{
		class TestTable
		{
			[PrimaryKey, AutoIncrement]
			public int Id { get; set; }
			public int Two { get; set; }
		}

		const int Count = 100;

		SQLiteConnection CreateDb ()
		{
			var db = new TestDb ();
			db.CreateTable<TestTable> ();
			var items = from i in Enumerable.Range (0, Count)
				select new TestTable { Two = 2 };
			db.InsertAll (items);
			Assert.AreEqual (Count, db.Table<TestTable> ().Count ());
			return db;
		}

		[Test]
		public void Int32 ()
		{
			var db = CreateDb ();

			var r = db.ExecuteScalar<int> ("SELECT SUM(Two) FROM TestTable");

			Assert.AreEqual (Count * 2, r);
		}
	}
}

using System;
using System.Linq;

#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#else
using NUnit.Framework;
#endif

namespace SQLite.Tests
{
	[TestFixture]
	public class ScalarTest
	{
		class TestTable
		{
			[PrimaryKey, AutoIncrement]
			public int Id { get; set; }
			public int Two { get; set; }
		}

		const int Count = 100;

		SQLiteConnection CreateDb ()
		{
			var db = new TestDb ();
			db.CreateTable<TestTable> ();
			var items = from i in Enumerable.Range (0, Count)
				select new TestTable { Two = 2 };
			db.InsertAll (items);
			Assert.AreEqual (Count, db.Table<TestTable> ().Count ());
			return db;
		}

		[Test]
		public void Int32 ()
		{
			var db = CreateDb ();

			var r = db.ExecuteScalar<int> ("SELECT SUM(Two) FROM TestTable");

			Assert.AreEqual (Count * 2, r);
		}

		[Test]
		public void SelectSingleRowValue ()
		{
			var db = CreateDb ();

			var r = db.ExecuteScalar<int> ("SELECT Two FROM TestTable WHERE Id = 1 LIMIT 1");

			Assert.AreEqual (2, r);
		}
	}
}

Add test for scalar queries with 1 row

Add test for scalar queries with 1 row

Repro for #496


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.5")]
[assembly: AssemblyFileVersion("1.0.0.5")]

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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.5")]
[assembly: AssemblyFileVersion("1.0.0.6")]

Increment version number to sync up with NuGet


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TTMouseclickSimulator.Core.Environment;

namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.Fishing
{
    public class FishingSpotFlavor
    {
        public Coordinates Scan1 { get; }
        public Coordinates Scan2 { get; }
        public ScreenshotColor BubbleColor { get; }
        public int Tolerance { get; }

        public FishingSpotFlavor(Coordinates scan1, Coordinates scan2,
            ScreenshotColor bubbleColor, int tolerance)
        {
            this.Scan1 = scan1;
            this.Scan2 = scan2;
            this.BubbleColor = bubbleColor;
            this.Tolerance = tolerance;
        }

        // TODO: The Color value needs some adjustment!
        public static readonly FishingSpotFlavor PunchlinePlace =
            new FishingSpotFlavor(new Coordinates(260, 196), new Coordinates(1349, 626),
                new ScreenshotColor(24, 142, 118), 16);

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TTMouseclickSimulator.Core.Environment;

namespace TTMouseclickSimulator.Core.ToontownRewritten.Actions.Fishing
{
    public class FishingSpotFlavor
    {
        public Coordinates Scan1 { get; }
        public Coordinates Scan2 { get; }
        public ScreenshotColor BubbleColor { get; }
        public int Tolerance { get; }

        public FishingSpotFlavor(Coordinates scan1, Coordinates scan2,
            ScreenshotColor bubbleColor, int tolerance)
        {
            this.Scan1 = scan1;
            this.Scan2 = scan2;
            this.BubbleColor = bubbleColor;
            this.Tolerance = tolerance;
        }

        // TODO: The Color value needs some adjustment!
        public static readonly FishingSpotFlavor PunchlinePlace =
            new FishingSpotFlavor(new Coordinates(260, 196), new Coordinates(1349, 626),
                new ScreenshotColor(22, 140, 116), 13);

    }
}

Adjust the values for the Punchline Place fishing spot.


namespace Foo.Tests.Web.Controllers
{
	public class HomeControllerTest
	{
	}
}

using Foo.Web.Controllers;

namespace Foo.Tests.Web.Controllers
{
	public class HomeControllerTest
	{
		private readonly HomeController _controller;

		public HomeControllerTest()
		{
			_controller = new HomeController();
		}
	}
}

Initialize new home controller instance for test class


using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.IO;
using System.Reflection;
using System.Text;
using Glimpse.Server.Web;

namespace Glimpse.Agent.Browser.Resources
{
    public class BrowserAgent : IMiddlewareResourceComposer
    {
        public void Register(IApplicationBuilder appBuilder)
        {
            appBuilder.Map("/browser/agent", chuldApp => chuldApp.Run(async context =>
            {
                var response = context.Response;

                response.Headers.Set("Content-Type", "application/javascript");

                var assembly = typeof(BrowserAgent).GetTypeInfo().Assembly;

                var jqueryStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/jquery.jquery-2.1.1.js");
                var signalrStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/signalr/jquery.signalR-2.2.0.js");
                var agentStream = assembly.GetManifestResourceStream("Resources/Embed/scripts/BrowserAgent.js");

                using (var jqueryReader = new StreamReader(jqueryStream, Encoding.UTF8))
                using (var signalrReader = new StreamReader(signalrStream, Encoding.UTF8))
                using (var agentReader = new StreamReader(agentStream, Encoding.UTF8))
                {
                    // TODO: The worlds worst hack!!! Nik did this...
                    await response.WriteAsync(jqueryReader.ReadToEnd() + signalrReader.ReadToEnd() + agentReader.ReadToEnd());
                }
            }));
        }
    }
}

using Glimpse.Web;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.IO;
using System.Reflection;
using System.Text;
using Glimpse.Server.Web;

namespace Glimpse.Agent.Browser.Resources
{
    public class BrowserAgent : IMiddlewareResourceComposer
    {
        public void Register(IApplicationBuilder appBuilder)
        {
            appBuilder.Map("/browser/agent", chuldApp => chuldApp.Run(async context =>
            {
                var response = context.Response;

                response.Headers.Set("Content-Type", "application/javascript");

                var assembly = typeof(BrowserAgent).GetTypeInfo().Assembly;

                var jqueryStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.jquery.jquery-2.1.1.js");
                var signalrStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.signalr.jquery.signalR-2.2.0.js");
                var agentStream = assembly.GetManifestResourceStream("Glimpse.Agent.Browser.Resources.Embed.scripts.BrowserAgent.js");

                using (var jqueryReader = new StreamReader(jqueryStream, Encoding.UTF8))
                using (var signalrReader = new StreamReader(signalrStream, Encoding.UTF8))
                using (var agentReader = new StreamReader(agentStream, Encoding.UTF8))
                {
                    // TODO: The worlds worst hack!!! Nik did this...
                    await response.WriteAsync(jqueryReader.ReadToEnd() + signalrReader.ReadToEnd() + agentReader.ReadToEnd());
                }
            }));
        }
    }
}

Update find resource code post internal change


@{
    Layout = "master.cshtml";
}

        <form role="form" method="POST" target="/">

                Key
                <input type="password" class="form-control" id="key" name="key" placeholder="key">

                    Username
                    <input class="form-control" id="username" name="username" placeholder="username">

                    Password
                    <input type="password" class="form-control" id="password" name="password" placeholder="password">

            <button class="btn btn-danger btn-lg pull-right" type="submit">Install</button>
        </form>

@{
    Layout = "master.cshtml";
}

        <form role="form" method="POST">

                Key
                <input type="password" class="form-control" id="key" name="key" placeholder="key">

                    Username
                    <input class="form-control" id="username" name="username" placeholder="username">

                    Password
                    <input type="password" class="form-control" id="password" name="password" placeholder="password">

            <button class="btn btn-danger btn-lg pull-right" type="submit">Install</button>
        </form>

Fix target in installer form

Fix target in installer form


using System.Collections.Generic;
using System.Management.Automation.Runspaces;

using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;

namespace Aggregator.Core
{
    /// <summary>
    /// Invokes Powershell scripting engine
    /// </summary>
    public class PsScriptEngine : ScriptEngine
    {
        private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();

        public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
            : base(store, logger, debug)
        {
        }

        public override bool Load(string scriptName, string script)
        {
            this.scripts.Add(scriptName, script);
            return true;
        }

        public override bool LoadCompleted()
        {
            return true;
        }

        public override void Run(string scriptName, IWorkItem workItem)
        {
            string script = this.scripts[scriptName];

            var config = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(config))
            {
                runspace.Open();

                runspace.SessionStateProxy.SetVariable("self", workItem);
                runspace.SessionStateProxy.SetVariable("store", this.Store);

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                // execute
                var results = pipeline.Invoke();

                this.Logger.ResultsFromScriptRun(scriptName, results);
            }
        }
    }
}

using System.Collections.Generic;
using System.Management.Automation.Runspaces;

using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;

namespace Aggregator.Core
{
    /// <summary>
    /// Invokes Powershell scripting engine
    /// </summary>
    public class PsScriptEngine : ScriptEngine
    {
        private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();

        public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
            : base(store, logger, debug)
        {
        }

        public override bool Load(string scriptName, string script)
        {
            this.scripts.Add(scriptName, script);
            return true;
        }

        public override bool LoadCompleted()
        {
            return true;
        }

        public override void Run(string scriptName, IWorkItem workItem)
        {
            string script = this.scripts[scriptName];

            var config = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(config))
            {
                runspace.Open();

                runspace.SessionStateProxy.SetVariable("self", workItem);
                runspace.SessionStateProxy.SetVariable("store", this.Store);
                runspace.SessionStateProxy.SetVariable("logger", this.Logger);

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                // execute
                var results = pipeline.Invoke();

                this.Logger.ResultsFromScriptRun(scriptName, results);
            }
        }
    }
}

FIX logger variable in PS scripts

FIX logger variable in PS scripts


#region

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Interop;
using SteamAccountSwitcher.Properties;

#endregion

namespace SteamAccountSwitcher
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class SwitchWindow : Window
    {
        public SwitchWindow()
        {
            InitializeComponent();
            ReloadAccountListBinding();
        }

        public void ReloadAccountListBinding()
        {
            AccountView.DataContext = null;
            AccountView.DataContext = App.Accounts;
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (App.IsShuttingDown)
                return;
            if (Settings.Default.AlwaysOn)
            {
                e.Cancel = true;
                HideWindow();
                return;
            }
            AppHelper.ShutdownApplication();
        }

        public void HideWindow()
        {
            var visible = Visibility == Visibility.Visible;
            Hide();
            if (visible && Settings.Default.AlwaysOn)
                TrayIconHelper.ShowRunningInTrayBalloon();
        }

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

            var mainWindowPtr = new WindowInteropHelper(this).Handle;
            var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
            mainWindowSrc?.AddHook(SingleInstanceHelper.WndProc);
        }
    }
}

#region

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Interop;
using SteamAccountSwitcher.Properties;

#endregion

namespace SteamAccountSwitcher
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class SwitchWindow : Window
    {
        public SwitchWindow()
        {
            InitializeComponent();
            WindowStartupLocation = Settings.Default.SwitchWindowKeepCentered
                ? WindowStartupLocation.CenterScreen
                : WindowStartupLocation.Manual;
            ReloadAccountListBinding();
        }

        public void ReloadAccountListBinding()
        {
            AccountView.DataContext = null;
            AccountView.DataContext = App.Accounts;
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (App.IsShuttingDown)
                return;
            if (Settings.Default.AlwaysOn)
            {
                e.Cancel = true;
                HideWindow();
                return;
            }
            AppHelper.ShutdownApplication();
        }

        public void HideWindow()
        {
            var visible = Visibility == Visibility.Visible;
            Hide();
            if (visible && Settings.Default.AlwaysOn)
                TrayIconHelper.ShowRunningInTrayBalloon();
        }

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

            var mainWindowPtr = new WindowInteropHelper(this).Handle;
            var mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
            mainWindowSrc?.AddHook(SingleInstanceHelper.WndProc);
        }
    }
}

Fix "Keep Window Centered" option

Fix "Keep Window Centered" option


using System;
using System.Windows.Forms;
using GUI.Utils;

namespace GUI.Forms
{
    public partial class SettingsForm : Form
    {
        public SettingsForm()
        {
            InitializeComponent();
        }

        private void SettingsForm_Load(object sender, EventArgs e)
        {
            foreach (var path in Settings.GameSearchPaths)
            {
                gamePaths.Items.Add(path);
            }
        }

        private void GamePathRemoveClick(object sender, EventArgs e)
        {
            if (gamePaths.SelectedIndex < 0)
            {
                return;
            }

            Settings.GameSearchPaths.Remove((string)gamePaths.SelectedItem);
            Settings.Save();

            gamePaths.Items.RemoveAt(gamePaths.SelectedIndex);
        }

        private void GamePathAdd(object sender, EventArgs e)
        {
            using (var dlg = new FolderBrowserDialog())
            {
                dlg.Description = "Select a folder";
                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                if (Settings.GameSearchPaths.Contains(dlg.SelectedPath))
                {
                    return;
                }

                Settings.GameSearchPaths.Add(dlg.SelectedPath);
                Settings.Save();

                gamePaths.Items.Add(dlg.SelectedPath);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var colorPicker = new ColorDialog();
            colorPicker.Color = Settings.BackgroundColor;

            // Update the text box color if the user clicks OK
            if (colorPicker.ShowDialog() == DialogResult.OK)
            {
                Settings.BackgroundColor = colorPicker.Color;
            }
        }
    }
}

using System;
using System.Windows.Forms;
using GUI.Utils;

namespace GUI.Forms
{
    public partial class SettingsForm : Form
    {
        public SettingsForm()
        {
            InitializeComponent();
        }

        private void SettingsForm_Load(object sender, EventArgs e)
        {
            foreach (var path in Settings.GameSearchPaths)
            {
                gamePaths.Items.Add(path);
            }
        }

        private void GamePathRemoveClick(object sender, EventArgs e)
        {
            if (gamePaths.SelectedIndex < 0)
            {
                return;
            }

            Settings.GameSearchPaths.Remove((string)gamePaths.SelectedItem);
            Settings.Save();

            gamePaths.Items.RemoveAt(gamePaths.SelectedIndex);
        }

        private void GamePathAdd(object sender, EventArgs e)
        {
            using (var dlg = new OpenFileDialog())
            {
                dlg.Filter = "Valve Pak (*.vpk)|*.vpk|All files (*.*)|*.*";

                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                if (Settings.GameSearchPaths.Contains(dlg.FileName))
                {
                    return;
                }

                Settings.GameSearchPaths.Add(dlg.FileName);
                Settings.Save();

                gamePaths.Items.Add(dlg.FileName);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var colorPicker = new ColorDialog();
            colorPicker.Color = Settings.BackgroundColor;

            // Update the text box color if the user clicks OK
            if (colorPicker.ShowDialog() == DialogResult.OK)
            {
                Settings.BackgroundColor = colorPicker.Color;
            }
        }
    }
}

Allow selecting vpks in content search paths