using System;
using System.Collections.Generic;

namespace Chainey
{
    internal class SentenceConstruct
    {
        internal int WordCount
        {
            get { return Forwards.Count + Backwards.Count - order; }
        }

        internal string Sentence
        {
            get
            {
                var sen = new List<string>(Backwards);
                sen.RemoveRange(0, order);
                sen.Reverse();

                sen.AddRange(Forwards);

                return string.Join(" ", sen);
            }
        }

        internal string LatestForwardChain
        {
            get
            {
                int start = Forwards.Count - order;
                return string.Join(" ", Forwards, start, order);
            }
        }

        internal string LatestBackwardChain
        {
            get
            {
                int start = Backwards.Count - order;
                return string.Join(" ", Backwards, start, order);
            }
        }

        List<string> Forwards;
        List<string> Backwards;

        readonly int order;

        internal SentenceConstruct(string initialChain, int order)
        {
            string[] split = initialChain.Split(' ');
            Forwards = new List<string>(split);
            Backwards = new List<string>(split);
            Backwards.Reverse();

            this.order = order;
        }

        internal void Append(string word)
        {
            Forwards.Add(word);
        }

        internal void Prepend(string word)
        {
            Backwards.Add(word);
        }
    }
}

using System;
using System.Collections.Generic;

namespace Chainey
{
    internal class SentenceConstruct
    {
        internal int WordCount { get; private set; }

        internal string Sentence
        {
            get
            {
                var sen = new List<string>(Backwards);
                sen.RemoveRange(0, order);
                sen.Reverse();

                sen.AddRange(Forwards);

                return string.Join(" ", sen);
            }
        }

        internal string LatestForwardChain
        {
            get
            {
                var chain = new string[order];
                int start = Forwards.Count - order;
                Forwards.CopyTo(start, chain, 0, order);

                return string.Join(" ", Forwards, start, order);
            }
        }

        internal string LatestBackwardChain
        {
            get
            {
                var chain = new string[order];
                int start = Backwards.Count - order;
                Backwards.CopyTo(start, chain, 0, order);

                return string.Join(" ", Backwards, start, order);
            }
        }

        List<string> Forwards;
        List<string> Backwards;

        readonly int order;

        internal SentenceConstruct(string initialChain)
        {
            string[] split = initialChain.Split(' ');
            Forwards = new List<string>(split);
            Backwards = new List<string>(split);
            Backwards.Reverse();

            WordCount = split.Length;
            order = split.Length;
        }

        internal void Append(string word)
        {
            Forwards.Add(word);
            WordCount++;
        }

        internal void Prepend(string word)
        {
            Backwards.Add(word);
            WordCount++;
        }
    }
}

Fix latest chain properties, simplify WordCount property and make it deduce the order from the passed initial chain.


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("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]

// 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: AssemblyInformationalVersion("1.1.0.10-rc")]
[assembly: AssemblyFileVersion("1.0.0.0")]

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("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]

// 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: AssemblyInformationalVersion("1.1.0.10-rc2")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Update Nuget version of package to 1.1.0.10-rc


using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Migrator.Model;

namespace NUnit.Migrator.CodeActions
{
    internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator
    {
        private readonly ExceptionExpectancyAtAttributeLevel _attribute;

        public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator,
            ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator)
        {
            _attribute = attribute;
        }

        public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType)
        {
            var body = base.Create(method, assertedType);

            if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation))
                return body;

            var userMessageArgument = SyntaxFactory.Argument(
                SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                    SyntaxFactory.ParseToken($"\"{_attribute.UserMessage}\""))); // TODO: no need for full attribute, msg only

            var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument);

            return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList);
        }

        private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation)
        {
            invocation = null;

            if (block.Statements.Count == 0)
                return false;

            invocation = (block.Statements.First() as ExpressionStatementSyntax)?
                .Expression as InvocationExpressionSyntax;
            return invocation != null;
        }
    }
}

using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Migrator.Model;

namespace NUnit.Migrator.CodeActions
{
    internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator
    {
        private readonly string _userMessage;

        public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator,
            ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator)
        {
            if (attribute == null)
                throw new ArgumentNullException(nameof(attribute));

            _userMessage = attribute.UserMessage;
        }

        public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType)
        {
            var body = base.Create(method, assertedType);

            if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation))
                return body;

            var userMessageArgument = SyntaxFactory.Argument(
                SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
                    SyntaxFactory.ParseToken($"\"{_userMessage}\"")));

            var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument);

            return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList);
        }

        private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation)
        {
            invocation = null;

            if (block.Statements.Count == 0)
                return false;

            invocation = (block.Statements.First() as ExpressionStatementSyntax)?
                .Expression as InvocationExpressionSyntax;
            return invocation != null;
        }
    }
}

Refactor - UserMessage instead of attribute


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

namespace MFlow.Core.Internal
{
	/// <summary>
	///     An expression builder
	/// </summary>
	class ExpressionBuilder<T> : IExpressionBuilder<T>
	{
		static IDictionary<object, object> _expressions= new Dictionary<object, object>();
		static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>();

		/// <summary>
		///     Compiles the expression
		/// </summary>
		public Func<T, C> Compile<C>(Expression<Func<T, C>> expression)
		{
			if(_expressions.ContainsKey(expression))
				return (Func<T, C>)_expressions[expression];

			var compiled = expression.Compile();
			_expressions.Add(expression, compiled);
			return compiled;
		}

		/// <summary>
		///     Invokes the expression
		/// </summary>
		public C Invoke<C>(Func<T, C> compiled, T target)
		{
		   	return compiled.Invoke(target);
		}
	}

	class InvokeCacheKey
	{
		public object Target{get;set;}
		public object Func{get;set;}
	}
}

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

namespace MFlow.Core.Internal
{
	/// <summary>
	///     An expression builder
	/// </summary>
	class ExpressionBuilder<T> : IExpressionBuilder<T>
	{
		static IDictionary<object, object> _expressions= new Dictionary<object, object>();
		static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>();

		/// <summary>
		///     Compiles the expression
		/// </summary>
		public Func<T, C> Compile<C>(Expression<Func<T, C>> expression)
		{
			if(_expressions.ContainsKey(expression))
				return (Func<T, C>)_expressions[expression];

			var compiled = expression.Compile();
			_expressions.Add(expression, compiled);
			return compiled;
		}

		/// <summary>
		///     Invokes the expression
		/// </summary>
		public C Invoke<C>(Func<T, C> compiled, T target)
		{
		   	return compiled.Invoke(target);
		}
	}
}

Remove caching of invoked expressions as it is hard to do and adds little benefit


using SSMScripter.Integration;
using System;
using System.Data;

namespace SSMScripter.Scripter.Smo
{
    public class SmoObjectMetadata
    {
        public SmoObjectType Type { get; protected set; }
        public string Schema { get; protected set; }
        public string Name { get; protected set; }
        public string ParentSchema { get; protected set; }
        public string ParentName { get; protected set; }

        public bool? AnsiNullsStatus { get; set; }
        public bool? QuotedIdentifierStatus { get; set; }

        public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName)
        {
            Schema = schema;
            Name = name;
        }
    }
}

using SSMScripter.Integration;
using System;
using System.Data;

namespace SSMScripter.Scripter.Smo
{
    public class SmoObjectMetadata
    {
        public SmoObjectType Type { get; protected set; }
        public string Schema { get; protected set; }
        public string Name { get; protected set; }
        public string ParentSchema { get; protected set; }
        public string ParentName { get; protected set; }

        public bool? AnsiNullsStatus { get; set; }
        public bool? QuotedIdentifierStatus { get; set; }

        public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName)
        {
            Type = type;
            Schema = schema;
            Name = name;
            ParentSchema = parentSchema;
            ParentName = parentName;
        }
    }
}

Add missing ctor field initializations

Add missing ctor field initializations


@model SpaceBlog.Models.CommentViewModel

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Comment

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.ArticleId)
        @Html.HiddenFor(m => m.AuthorId)

            @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

@model SpaceBlog.Models.CommentViewModel

@{
    ViewBag.Title = "Edit";
    ViewBag.Message = "Comment";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

@ViewBag.Title

@ViewBag.Message

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.ArticleId)
        @Html.HiddenFor(m => m.AuthorId)

            @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })

                <input type="submit" value="Save" class="btn btn-success" />
                @Html.ActionLink("Back", "Index", new { @id = ""}, new { @class = "btn btn-primary" })

}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Change div class and change the position of button back


using System.Threading.Tasks;
using Xunit;
using YouTrackSharp.Issues;
using YouTrackSharp.Tests.Infrastructure;

namespace YouTrackSharp.Tests.Integration.Issues
{
    public partial class IssuesServiceTests
    {
        public class GetIssuesInProject
        {
            [Fact]
            public async Task Valid_Connection_Returns_Issues()
            {
                // Arrange
                var connection = Connections.Demo1Token;
                var service = new IssuesService(connection);

                // Act
                var result = await service.GetIssuesInProject("DP1", filter: "assignee:me");

                // Assert
                Assert.NotNull(result);
                Assert.Collection(result, issue =>
                    Assert.Equal("DP1", ((dynamic)issue).ProjectShortName));
            }

            [Fact]
            public async Task Invalid_Connection_Throws_UnauthorizedConnectionException()
            {
                // Arrange
                var service = new IssuesService(Connections.UnauthorizedConnection);

                // Act & Assert
                await Assert.ThrowsAsync<UnauthorizedConnectionException>(
                    async () => await service.GetIssuesInProject("DP1"));
            }
        }
    }
}

using System.Threading.Tasks;
using Xunit;
using YouTrackSharp.Issues;
using YouTrackSharp.Tests.Infrastructure;

namespace YouTrackSharp.Tests.Integration.Issues
{
    public partial class IssuesServiceTests
    {
        public class GetIssuesInProject
        {
            [Fact]
            public async Task Valid_Connection_Returns_Issues()
            {
                // Arrange
                var connection = Connections.Demo1Token;
                var service = new IssuesService(connection);

                // Act
                var result = await service.GetIssuesInProject("DP1", filter: "assignee:me");

                // Assert
                Assert.NotNull(result);
                foreach (dynamic issue in result)
                {
                    Assert.Equal("DP1", issue.ProjectShortName);
                }
            }

            [Fact]
            public async Task Invalid_Connection_Throws_UnauthorizedConnectionException()
            {
                // Arrange
                var service = new IssuesService(Connections.UnauthorizedConnection);

                // Act & Assert
                await Assert.ThrowsAsync<UnauthorizedConnectionException>(
                    async () => await service.GetIssuesInProject("DP1"));
            }
        }
    }
}

Change assertion to support multiple issues in test


using Microsoft.AspNet.Builder;
using System;

namespace Glimpse.Host.Web.AspNet
{
    public static class GlimpseExtension
    {
        /// <summary>
        /// Adds a middleware that allows GLimpse to be registered into the system.
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app)
        {
            return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke);
        }
    }
}

using Glimpse.Web;
using Microsoft.AspNet.Builder;
using System;

namespace Glimpse.Host.Web.AspNet
{
    public static class GlimpseExtension
    {
        /// <summary>
        /// Adds a middleware that allows GLimpse to be registered into the system.
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app)
        {
            return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke);
        }

        public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app, Func<IHttpContext, bool> shouldRun)
        {
            return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices, shouldRun).Invoke);
        }
    }
}

Update aspnet middleware extension message to allow shouldRun to be passed in


using System;
using System.Threading;
using MbCacheTest.TestData;
using NUnit.Framework;
using SharpTestsEx;

namespace MbCacheTest.Logic.Concurrency
{
	public class SimultaneousCachePutTest : TestCase
	{
		public SimultaneousCachePutTest(Type proxyType) : base(proxyType)
		{
		}

		[Test]
		public void ShouldNotMakeTheSameCallMoreThanOnce()
		{
			CacheBuilder.For<ObjectWithCallCounter>()
				 .CacheMethod(c => c.Increment())
				 .PerInstance()
				 .As<IObjectWithCallCounter>();

			var factory = CacheBuilder.BuildFactory();

			10.Times(() =>
			{
				var instance = factory.Create<IObjectWithCallCounter>();

				var task1 = new Thread(() => instance.Increment());
				var task2 = new Thread(() => instance.Increment());
				var task3 = new Thread(() => instance.Increment());
				task1.Start();
				task2.Start();
				task3.Start();
				task1.Join();
				task2.Join();
				task3.Join();

				instance.Count.Should().Be(1);
			});
		}
	}
}

using System;
using System.Threading;
using MbCacheTest.TestData;
using NUnit.Framework;
using SharpTestsEx;

namespace MbCacheTest.Logic.Concurrency
{
	public class SimultaneousCachePutTest : TestCase
	{
		public SimultaneousCachePutTest(Type proxyType) : base(proxyType)
		{
		}

		[Test]
		public void ShouldNotMakeTheSameCallMoreThanOnce()
		{
			CacheBuilder.For<ObjectWithCallCounter>()
				 .CacheMethod(c => c.Increment())
				 .PerInstance()
				 .As<IObjectWithCallCounter>();

			var factory = CacheBuilder.BuildFactory();

			1000.Times(() =>
			{
				var instance = factory.Create<IObjectWithCallCounter>();

				var task1 = new Thread(() => instance.Increment());
				var task2 = new Thread(() => instance.Increment());
				var task3 = new Thread(() => instance.Increment());
				task1.Start();
				task2.Start();
				task3.Start();
				task1.Join();
				task2.Join();
				task3.Join();

				instance.Count.Should().Be(1);
			});
		}
	}
}

Make sure test fails more often if locks are removed


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

[assembly: AssemblyTitle("MigrateMSTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MigrateMSTest")]
[assembly: AssemblyCopyright("Copyright ©  2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")]

// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

#if LITE_EDITION
[assembly: InternalsVisibleTo("Telerik.JustMock")]
#endif

Make internals in MSTest2 visible for JustMock dll in lite version


namespace Fixie.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Threading;
    using Fixie.Execution;

    public static class TestExtensions
    {
        const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;

        public static MethodInfo GetInstanceMethod(this Type type, string methodName)
        {
            return type.GetMethod(methodName, InstanceMethods);
        }

        public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type)
        {
            return type.GetMethods(InstanceMethods);
        }

        public static IEnumerable<string> Lines(this RedirectedConsole console)
        {
            return console.Output.Lines();
        }

        public static IEnumerable<string> Lines(this string multiline)
        {
            var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();

            while (lines.Count > 0 && lines[lines.Count-1] == "")
                lines.RemoveAt(lines.Count-1);

            return lines;
        }

        public static string CleanStackTraceLineNumbers(this string stackTrace)
        {
            //Avoid brittle assertion introduced by stack trace line numbers.

            return Regex.Replace(stackTrace, @":line \d+", ":line #");
        }

        public static string CleanDuration(this string output)
        {
            //Avoid brittle assertion introduced by test duration.

            var decimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds");
        }
    }
}

namespace Fixie.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using Fixie.Execution;

    public static class TestExtensions
    {
        const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;

        public static MethodInfo GetInstanceMethod(this Type type, string methodName)
        {
            return type.GetMethod(methodName, InstanceMethods);
        }

        public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type)
        {
            return type.GetMethods(InstanceMethods);
        }

        public static IEnumerable<string> Lines(this RedirectedConsole console)
        {
            return console.Output.Lines();
        }

        public static IEnumerable<string> Lines(this string multiline)
        {
            var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();

            while (lines.Count > 0 && lines[lines.Count-1] == "")
                lines.RemoveAt(lines.Count-1);

            return lines;
        }

        public static string CleanStackTraceLineNumbers(this string stackTrace)
        {
            //Avoid brittle assertion introduced by stack trace line numbers.

            return Regex.Replace(stackTrace, @":line \d+", ":line #");
        }

        public static string CleanDuration(this string output)
        {
            //Avoid brittle assertion introduced by test duration.

            var decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds");
        }
    }
}

Rephrase culture-neutral number format helper so that it can successfully compile against both the full .NET Framework and .NET Core.


using MultiMiner.Engine.Configuration;
using System;
using System.IO;

namespace MultiMiner.Win
{
    public class ApplicationConfiguration
    {
        public ApplicationConfiguration()
        {
            this.StartupMiningDelay = 45;
        }

        public bool LaunchOnWindowsLogin { get; set; }
        public bool StartMiningOnStartup { get; set; }
        public int StartupMiningDelay { get; set; }
        public bool RestartCrashedMiners { get; set; }

        private static string AppDataPath()
        {
            string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            return Path.Combine(rootPath, "MultiMiner");
        }

        private static string DeviceConfigurationsFileName()
        {
            return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml");
        }

        public void SaveApplicationConfiguration()
        {
            ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName());
        }

        public void LoadApplicationConfiguration()
        {
            ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName());

            this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin;
            this.StartMiningOnStartup = tmp.StartMiningOnStartup;
            this.StartupMiningDelay = tmp.StartupMiningDelay;
            this.RestartCrashedMiners = tmp.RestartCrashedMiners;
        }
    }
}

using Microsoft.Win32;
using MultiMiner.Engine.Configuration;
using System;
using System.IO;
using System.Windows.Forms;

namespace MultiMiner.Win
{
    public class ApplicationConfiguration
    {
        public ApplicationConfiguration()
        {
            this.StartupMiningDelay = 45;
        }

        public bool LaunchOnWindowsLogin { get; set; }
        public bool StartMiningOnStartup { get; set; }
        public int StartupMiningDelay { get; set; }
        public bool RestartCrashedMiners { get; set; }

        private static string AppDataPath()
        {
            string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            return Path.Combine(rootPath, "MultiMiner");
        }

        private static string DeviceConfigurationsFileName()
        {
            return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml");
        }

        public void SaveApplicationConfiguration()
        {
            ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName());
            ApplyLaunchOnWindowsStartup();
        }

        private void ApplyLaunchOnWindowsStartup()
        {
            RegistryKey registrykey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            if (LaunchOnWindowsLogin)
                registrykey.SetValue("MultiMiner", Application.ExecutablePath);
            else
                registrykey.DeleteValue("MultiMiner", false);
        }

        public void LoadApplicationConfiguration()
        {
            ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName());

            this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin;
            this.StartMiningOnStartup = tmp.StartMiningOnStartup;
            this.StartupMiningDelay = tmp.StartupMiningDelay;
            this.RestartCrashedMiners = tmp.RestartCrashedMiners;
        }
    }
}

Implement the option to start the app when logging into Windows


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

namespace Battlezeppelins.Models
{

    public class GameTable
    {
        public const int TABLE_ROWS = 10;
        public const int TABLE_COLS = 10;

        public Game.Role role { get; private set; }
        public List<OpenPoint> openPoints { get; private set; }
        public List<Zeppelin> zeppelins { get; private set; }

        public GameTable(Game.Role role)
        {
            this.role = role;

            this.openPoints = new List<OpenPoint>();
            this.zeppelins = new List<Zeppelin>();
        }

        public void removeZeppelins() {
            zeppelins = null;
        }

        public bool AddZeppelin(Zeppelin newZeppelin)
        {
            foreach (Zeppelin zeppelin in this.zeppelins)
            {
                // No multiple zeppelins of the same type
                if (zeppelin.type == newZeppelin.type)
                    return false;

                // No colliding zeppelins
                if (zeppelin.collides(newZeppelin))
                    return false;
            }

            if (newZeppelin.x < 0 ||
                newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 ||
                newZeppelin.y < 0 ||
                newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1)
            {
                return false;
            }

            this.zeppelins.Add(newZeppelin);

            return true;
        }
    }
}

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

namespace Battlezeppelins.Models
{

    public class GameTable
    {
        public const int TABLE_ROWS = 10;
        public const int TABLE_COLS = 10;

        public Game.Role role { get; private set; }
        public List<OpenPoint> openPoints { get; private set; }
        public List<Zeppelin> zeppelins { get; private set; }

        public GameTable() { }

        public GameTable(Game.Role role)
        {
            this.role = role;

            this.openPoints = new List<OpenPoint>();
            this.zeppelins = new List<Zeppelin>();
        }

        public void removeZeppelins() {
            zeppelins = null;
        }

        public bool AddZeppelin(Zeppelin newZeppelin)
        {
            foreach (Zeppelin zeppelin in this.zeppelins)
            {
                // No multiple zeppelins of the same type
                if (zeppelin.type == newZeppelin.type)
                    return false;

                // No colliding zeppelins
                if (zeppelin.collides(newZeppelin))
                    return false;
            }

            if (newZeppelin.x < 0 ||
                newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 ||
                newZeppelin.y < 0 ||
                newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1)
            {
                return false;
            }

            this.zeppelins.Add(newZeppelin);

            return true;
        }
    }
}

Add non-args constructor for serialization.


namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer
{
    using JustBehave;

    using NBench.VisualStudio.TestAdapter;
    using NBench.VisualStudio.TestAdapter.Helpers;

    using Ploeh.AutoFixture;
    using Ploeh.AutoFixture.AutoNSubstitute;

    using Xunit;

    public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer>
    {
        private INBenchFunctionalityWrapper functionalitywrapper;

        protected override NBenchTestDiscoverer CreateSystemUnderTest()
        {
            return new NBenchTestDiscoverer(this.functionalitywrapper);
        }

        protected override void CustomizeAutoFixture(IFixture fixture)
        {
            fixture.Customize(new AutoNSubstituteCustomization());
        }

        protected override void Given()
        {
            this.functionalitywrapper = null;
        }

        protected override void When()
        {
        }

        [Fact]
        public void TheNBenchTestDiscovererIsNotNull()
        {
            Assert.NotNull(this.SystemUnderTest);
        }
    }
}

namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer
{
    using JustBehave;

    using NBench.VisualStudio.TestAdapter;
    using NBench.VisualStudio.TestAdapter.Helpers;

    using Ploeh.AutoFixture;
    using Ploeh.AutoFixture.AutoNSubstitute;

    using Xunit;

    public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer>
    {
        private INBenchFunctionalityWrapper functionalitywrapper;

        protected override NBenchTestDiscoverer CreateSystemUnderTest()
        {
            return new NBenchTestDiscoverer(this.functionalitywrapper);
        }

        protected override void CustomizeAutoFixture(IFixture fixture)
        {
            fixture.Customize(new AutoNSubstituteCustomization());
        }

        protected override void Given()
        {
            this.functionalitywrapper = this.Fixture.Create<INBenchFunctionalityWrapper>();
        }

        protected override void When()
        {
        }

        [Fact]
        public void TheNBenchTestDiscovererIsNotNull()
        {
            Assert.NotNull(this.SystemUnderTest);
        }
    }
}

Create a non-null functionality wrapper in the required test.


using System;
using System.Diagnostics;
using System.Reflection;

namespace FonctionsUtiles.Fred.Csharp
{
  public class FunctionsWindows
  {
    public static bool IsInWinPath(string substring)
    {
      bool result = false;
      string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
      if (winPath != null) result = winPath.Contains(substring);
      return result;
    }

    public static string DisplayTitle()
    {
      Assembly assembly = Assembly.GetExecutingAssembly();
      FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
      return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}";
    }
  }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Principal;

namespace FonctionsUtiles.Fred.Csharp
{
  public class FunctionsWindows
  {
    public static bool IsInWinPath(string substring)
    {
      bool result = false;
      string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
      if (winPath != null) result = winPath.Contains(substring);
      return result;
    }

    public static string DisplayTitle()
    {
      Assembly assembly = Assembly.GetExecutingAssembly();
      FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
      return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}";
    }

    public static bool IsAdministrator()
    {
      WindowsIdentity identity = WindowsIdentity.GetCurrent();
      WindowsPrincipal principal = new WindowsPrincipal(identity);
      return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }

    public static bool IsAdmin()
    {
      return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
    }

    public static IEnumerable<Process> GetAllProcesses()
    {
      Process[] processlist = Process.GetProcesses();
      return processlist.ToList();
    }

    public static bool IsProcessRunningById(Process process)
    {
      try { Process.GetProcessById(process.Id); }
      catch (InvalidOperationException) { return false; }
      catch (ArgumentException) { return false; }
      return true;
    }

    public static bool IsProcessRunningByName(string processName)
    {
      try { Process.GetProcessesByName(processName); }
      catch (InvalidOperationException) { return false; }
      catch (ArgumentException) { return false; }
      return true;
    }

    public static Process GetProcessByName(string processName)
    {
      Process result = new Process();
      foreach (Process process in GetAllProcesses())
      {
        if (process.ProcessName == processName)
        {
          result = process;
          break;
        }
      }

      return result;
    }
  }
}

Add several methods for Windows: IsAdmin


using System.Globalization;
using System.Reflection;
using FluentAssertions;
using Microsoft.Office.Interop.Outlook;
using Moq;
using NUnit.Framework;
using OutlookMatters.Core.Settings;

namespace Test.OutlookMatters.Core.Settings
{
    [TestFixture]
    public class EnumMatchToBooleanConverterTest
    {
        [Test]
        [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)]
        [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)]
        [TestCase(null, MattermostVersion.ApiVersionThree, false)]
        [TestCase(MattermostVersion.ApiVersionOne, null, false)]
        public void Convert_ConvertsToExpectedResult(object parameter, object value,
            bool expectedResult)
        {
            var classUnderTest = new EnumMatchToBooleanConverter();

            var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>());

            Assert.That(result, Is.EqualTo(expectedResult));
        }
    }
}

using System.Globalization;
using System.Reflection;
using FluentAssertions;
using Microsoft.Office.Interop.Outlook;
using Moq;
using NUnit.Framework;
using OutlookMatters.Core.Settings;

namespace Test.OutlookMatters.Core.Settings
{
    [TestFixture]
    public class EnumMatchToBooleanConverterTest
    {
        [Test]
        [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)]
        [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)]
        [TestCase(null, MattermostVersion.ApiVersionThree, false)]
        [TestCase(MattermostVersion.ApiVersionOne, null, false)]
        public void Convert_ConvertsToExpectedResult(object parameter, object value,
            bool expectedResult)
        {
            var classUnderTest = new EnumMatchToBooleanConverter();

            var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>());

            Assert.That(result, Is.EqualTo(expectedResult));
        }

        [Test]
        [TestCase(true, "ApiVersionOne", MattermostVersion.ApiVersionOne)]
        [TestCase(false, "ApiVersionOne", null)]
        [TestCase(true, null, null)]
        [TestCase(null, "ApiVersionOne", null)]
        public void ConvertBack_ConvertsToExpectedResult(object value, object parameter, object expectedResult)
        {
            var classUnderTest = new EnumMatchToBooleanConverter();

            var result = classUnderTest.ConvertBack(value, typeof(MattermostVersion), parameter, It.IsAny<CultureInfo>());

            Assert.That(result, Is.EqualTo(expectedResult));
        }
    }
}

Add additional tests for EnumMatchToBooleanConverter


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChutesAndLadders.GamePlay;
using ChutesAndLadders.Entities;
using System.Diagnostics;

namespace Chute
{
    class Program
    {
        static void Main(string[] args)
        {
            var board = new GameBoard();

            #region Demo 1

            // board.Demo1a_GreedyAlgorithm();

            #endregion

            #region Demo 2

            // board.Demo2a_RulesEngine();
            // board.Demo2b_ImprovedLinear();

            #endregion

            #region Demo 3

            // Only do demo 3b unless there is time left over

            // board.Demo3a_GeneticAnalysis();
            // board.Demo3b_GeneticEvolution();
            // board.Demo3c_GeneticSuperiority();

            #endregion

            #region Demo 4

            // board.Demo4a_ShortestPath();

            #endregion

            #region Supplemental Demos

            // board.SupplementalDemo_SingleGame();
            // board.SupplementalDemo_Player1Advantage();

            board.GameActionOutput_SmallSample();

            #endregion
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChutesAndLadders.GamePlay;
using ChutesAndLadders.Entities;
using System.Diagnostics;

namespace Chute
{
    class Program
    {
        static void Main(string[] args)
        {
            var board = new GameBoard();

            #region Demo 1

            board.Demo1a_GreedyAlgorithm();

            #endregion

            #region Demo 2

            // board.Demo2a_RulesEngine();
            // board.Demo2b_ImprovedLinear();

            #endregion

            #region Demo 3

            // Only do demo 3b unless there is time left over

            // board.Demo3a_GeneticAnalysis();
            // board.Demo3b_GeneticEvolution();
            // board.Demo3c_GeneticSuperiority();

            #endregion

            #region Demo 4

            // board.Demo4a_ShortestPath();

            #endregion

            #region Supplemental Demos

            // board.SupplementalDemo_SingleGame();
            // board.SupplementalDemo_Player1Advantage();

            // board.GameActionOutput_SmallSample();

            #endregion
        }
    }
}

Reset Chutes & Ladders demos to run demo 1 by default


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bogus;
using Dexiom.EPPlusExporter;
using OfficeOpenXml;

namespace Dexiom.EPPlusExporterTests.Helpers
{
    public static class TestHelper
    {
        public static void OpenDocument(ExcelPackage excelPackage)
        {
            Console.WriteLine("Opening document");

            Directory.CreateDirectory("temp");
            var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx");
            excelPackage.SaveAs(fileInfo);
            Process.Start(fileInfo.FullName);
        }

        public static ExcelPackage FakeAnExistingDocument()
        {
            Console.WriteLine("FakeAnExistingDocument");

            var retVal = new ExcelPackage();
            var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet");
            worksheet.Cells[1, 1].Value = "I am a normal sheet";
            worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!";

            return retVal;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bogus;
using Dexiom.EPPlusExporter;
using OfficeOpenXml;

namespace Dexiom.EPPlusExporterTests.Helpers
{
    public static class TestHelper
    {
        public static void OpenDocument(ExcelPackage excelPackage)
        {
            Console.WriteLine("Opening document");

            Directory.CreateDirectory("temp");
            var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx");
            excelPackage.SaveAs(fileInfo);
            Process.Start(fileInfo.FullName);
        }

        public static ExcelPackage FakeAnExistingDocument()
        {
            var retVal = new ExcelPackage();
            var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet");
            worksheet.Cells[1, 1].Value = "I am a normal sheet";
            worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!";

            return retVal;
        }
    }
}

Remove output on some tests

Remove output on some tests


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

using osu.Game.Rulesets.Mania.Objects.Types;
using osu.Game.Rulesets.Objects;

namespace osu.Game.Rulesets.Mania.Objects
{
    public abstract class ManiaHitObject : HitObject, IHasColumn
    {
        public int Column { get; set; }
    }
}

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

using osu.Game.Rulesets.Mania.Objects.Types;
using osu.Game.Rulesets.Objects;

namespace osu.Game.Rulesets.Mania.Objects
{
    public abstract class ManiaHitObject : HitObject, IHasColumn
    {
        public int Column { get; set; }

        /// <summary>
        /// The number of other <see cref="ManiaHitObject"/> that start at
        /// the same time as this hit object.
        /// </summary>
        public int Siblings { get; set; }
    }
}

Add siblings, will be used in generator branches.


using LtiLibrary.Core.Common;
using Newtonsoft.Json;

namespace LtiLibrary.Core.Outcomes.v2
{
    /// <summary>
    /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources
    /// and from which they GET the list of LineItems associated with a a given learning context.
    /// </summary>
    public class LineItemContainer : JsonLdObject
    {
        public LineItemContainer()
        {
            Type = LtiConstants.LineItemContainerType;
        }

        /// <summary>
        /// Optional indication of which resource is the subject for the members of the container.
        /// </summary>
        [JsonProperty("membershipSubject")]
        public LineItemMembershipSubject LineItemMembershipSubject { get; set; }
    }
}

using LtiLibrary.Core.Common;
using Newtonsoft.Json;

namespace LtiLibrary.Core.Outcomes.v2
{
    /// <summary>
    /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources
    /// and from which they GET the list of LineItems associated with a a given learning context.
    /// </summary>
    public class LineItemContainer : JsonLdObject
    {
        public LineItemContainer()
        {
            Type = LtiConstants.LineItemContainerType;
        }

        /// <summary>
        /// Optional indication of which resource is the subject for the members of the container.
        /// </summary>
        [JsonProperty("membershipSubject")]
        public LineItemMembershipSubject MembershipSubject { get; set; }
    }
}

Simplify property name for LineItemMembershipSubject


using System.Collections.Generic;
using Nest.Domain;
using Newtonsoft.Json;
using System.Linq.Expressions;
using System;
using System.Linq;

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	public interface ISearchShardsResponse : IResponse
	{
		[JsonProperty("shards")]
		IEnumerable<IEnumerable<SearchShard>> Shards { get; }

		[JsonProperty("nodes")]
		IDictionary<string, SearchNode> Nodes { get; }
	}

	public class SearchShardsResponse : BaseResponse, ISearchShardsResponse
	{
		public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; }
		public IDictionary<string, SearchNode> Nodes { get; internal set; }
	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchNode
	{
		[JsonProperty("name")]
		public string Name { get; set; }
		[JsonProperty("transport_address")]
		public string TransportAddress { get; set; }

	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchShard
	{
		[JsonProperty("name")]
		public string State { get; set;}
		[JsonProperty("primary")]
		public bool Primary { get; set;}
		[JsonProperty("node")]
		public string Node { get; set;}
		[JsonProperty("relocating_node")]
		public string RelocatingNode { get; set;}
		[JsonProperty("shard")]
		public int Shard { get; set;}
		[JsonProperty("index")]
		public string Index { get; set;}
	}
}

using Nest.Domain;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	public interface ISearchShardsResponse : IResponse
	{
		[JsonProperty("shards")]
		IEnumerable<IEnumerable<SearchShard>> Shards { get; }

		[JsonProperty("nodes")]
		IDictionary<string, SearchNode> Nodes { get; }
	}

	public class SearchShardsResponse : BaseResponse, ISearchShardsResponse
	{
		public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; }

		public IDictionary<string, SearchNode> Nodes { get; internal set; }
	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchNode
	{
		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("transport_address")]
		public string TransportAddress { get; set; }
	}

	[JsonObject(MemberSerialization.OptIn)]
	public class SearchShard
	{
		[JsonProperty("state")]
		public string State { get; set; }

		[JsonProperty("primary")]
		public bool Primary { get; set; }

		[JsonProperty("node")]
		public string Node { get; set; }

		[JsonProperty("relocating_node")]
		public string RelocatingNode { get; set; }

		[JsonProperty("shard")]
		public int Shard { get; set; }

		[JsonProperty("index")]
		public string Index { get; set; }
	}
}

Fix wrong property mapping in SearchShard


using HotChocolate.Types;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual;
using Snowflake.Framework.Remoting.GraphQL.Schema;
using Snowflake.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem
{
    public class FilesystemQueries
       : ObjectTypeExtension
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.Name("Query");
            descriptor.Field("filesystem")
                .Argument("directoryPath", a => a.Type<OSDirectoryPathType>().Description("The path to explore."))
                .Resolver(context => {
                    var path = context.Argument<DirectoryInfo>("directoryPath");
                    if (path == null) return DriveInfo.GetDrives();
                    if (path.Exists) return path;
                    return null;
                })
                .Type<OSDirectoryContentsInterface>()
                .Description("Provides normalized OS-dependent filesystem access." +
                "Returns null if the specified path does not exist.");
        }
    }

}

using HotChocolate.Types;
using Microsoft.DotNet.PlatformAbstractions;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem;
using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual;
using Snowflake.Framework.Remoting.GraphQL.Schema;
using Snowflake.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem
{
    public class FilesystemQueries
       : ObjectTypeExtension
    {
        protected override void Configure(IObjectTypeDescriptor descriptor)
        {
            descriptor.Name("Query");
            descriptor.Field("filesystem")
                .Argument("directoryPath",
                    a => a.Type<OSDirectoryPathType>()
                    .Description("The path to explore. If this is null, returns a listing of drives on Windows, " +
                    "or the root directory on a Unix-like system."))
                .Resolver(context => {
                    var path = context.Argument<DirectoryInfo>("directoryPath");
                    if (path == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return DriveInfo.GetDrives();
                    if (path == null &&
                        (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                        || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                        || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) return new DirectoryInfo("/");

                    if (path?.Exists ?? false) return path;
                    return null;
                })
                .Type<OSDirectoryContentsInterface>()
                .Description("Provides normalized OS-dependent filesystem access." +
                "Returns null if the specified path does not exist.");
        }
    }

}

HC.filesystem: Clarify behaviour on non-Windows systems


using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("Tiny-JSON")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Robert Gering")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.1.2")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("Tiny-JSON")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Robert Gering")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.2.0")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

Increase assembly version to 1.2.0

Increase assembly version to 1.2.0


using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Utility.Extensions
{
    public static class ConcurrentDictionaryExtensions
    {
        public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key)
        {
            TValue value;
            return dictionary.TryRemove(key, out value);
        }

        /// <remarks>
        /// This is a hack but is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can (not 100%!)
        /// </remarks>
        public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value)
        {
            ICollection<KeyValuePair<TKey, TValue>> collection = dictionary;
            return collection.Remove(new KeyValuePair<TKey, TValue>(key, value));
        }
    }
}

using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Utility.Extensions
{
    public static class ConcurrentDictionaryExtensions
    {
        public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key)
        {
            TValue value;
            return dictionary.TryRemove(key, out value);
        }

        /// <remarks>
        /// HACK: is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can.
        /// </remarks>
        public static bool TryRemove<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
        {
            return collection.Remove(new KeyValuePair<TKey, TValue>(key, value));
        }
    }
}

Change try remove key pair method semantics


using IdeaWeb.Controllers;
using Microsoft.AspNetCore.Mvc;
using NUnit.Framework;

namespace IdeaWeb.Test
{
    [TestFixture]
    public class HomeControllerTests
    {
        HomeController _controller;

        [SetUp]
        public void SetUp()
        {
            _controller = new HomeController();
        }

        [Test]
        public void IndexReturnsIdeasView()
        {
            IActionResult result = _controller.Index();

            Assert.That(result, Is.Not.Null);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdeaWeb.Controllers;
using IdeaWeb.Data;
using IdeaWeb.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;

namespace IdeaWeb.Test
{
    [TestFixture]
    public class HomeControllerTests
    {
        const int NUM_IDEAS = 10;

        HomeController _controller;

        [SetUp]
        public void SetUp()
        {
            // Create unique database names based on the test id
            var options = new DbContextOptionsBuilder<IdeaContext>()
                .UseInMemoryDatabase(TestContext.CurrentContext.Test.ID)
                .Options;

            // Seed the in-memory database
            using (var context = new IdeaContext(options))
            {
                for(int i = 1; i <= NUM_IDEAS; i++)
                {
                    context.Add(new Idea
                    {
                        Name = $"Idea name {i}",
                        Description = $"Description {i}",
                        Rating = i % 3 + 1
                    });
                }
                context.SaveChanges();
            }

            // Use a clean copy of the context within the tests
            _controller = new HomeController(new IdeaContext(options));
        }

        [Test]
        public async Task IndexReturnsListOfIdeas()
        {
            ViewResult result = await _controller.Index() as ViewResult;

            Assert.That(result?.Model, Is.Not.Null);
            Assert.That(result.Model, Has.Count.EqualTo(NUM_IDEAS));

            IEnumerable<Idea> ideas = result.Model as IEnumerable<Idea>;
            Idea idea = ideas?.FirstOrDefault();
            Assert.That(idea, Is.Not.Null);
            Assert.That(idea.Name, Is.EqualTo("Idea name 1"));
            Assert.That(idea.Description, Does.Contain("1"));
            Assert.That(idea.Rating, Is.EqualTo(2));
        }
    }
}

Use the in-memory database for testing the home controller


namespace DependencyInjection.Console
{
    internal class PatternApp
    {
        private readonly PatternWriter _patternWriter;
        private readonly PatternGenerator _patternGenerator;

        public PatternApp(bool useColours)
        {
            _patternWriter = new PatternWriter(useColours);
            _patternGenerator = new PatternGenerator();
        }

        public void Run()
        {
            var pattern = _patternGenerator.Generate(10, 10);
            _patternWriter.Write(pattern);
        }
    }
}

namespace DependencyInjection.Console
{
    internal class PatternApp
    {
        private readonly PatternWriter _patternWriter;
        private readonly PatternGenerator _patternGenerator;

        public PatternApp(bool useColours)
        {
            _patternWriter = new PatternWriter(useColours);
            _patternGenerator = new PatternGenerator();
        }

        public void Run()
        {
            var pattern = _patternGenerator.Generate(25, 15);
            _patternWriter.Write(pattern);
        }
    }
}

Adjust initial size to look nicer

Adjust initial size to look nicer


using Xunit;

namespace EmotionAPI.Tests
{
    public class EmotionAPIClientTests : EmotionAPITestsBase
    {
        [Fact]
        public void Can_Create_EmotionAPIClient_Controller()
        {
            var controller = new EmotionAPIClient(mockOcpApimSubscriptionKey);

            Assert.NotNull(controller);
            Assert.NotEmpty(controller.OcpApimSubscriptionKey);
        }

    }
}

using Xunit;

namespace EmotionAPI.Tests
{
    public class EmotionAPIClientTests : EmotionAPITestsBase
    {
        [Fact]
        public void Can_Create_EmotionAPIClient_Class()
        {
            var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey);

            Assert.NotNull(sut);
        }

        [Fact]
        public void OcpApimSubscriptionKey_Is_Being_Set()
        {
            var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey);

            Assert.NotEmpty(sut.OcpApimSubscriptionKey);
        }
    }
}

Split test into two separate tests

Split test into two separate tests


using System.Windows.Forms;
using CefSharp;

namespace TweetDuck.Core.Handling{
    class KeyboardHandlerBase : IKeyboardHandler{
        protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){
            return false;
        }

        bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){
            if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){
                return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers);
            }

            return false;
        }

        bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){
            return false;
        }
    }
}

using System.Windows.Forms;
using CefSharp;
using TweetDuck.Core.Controls;
using TweetDuck.Core.Other;
using TweetDuck.Core.Utils;

namespace TweetDuck.Core.Handling{
    class KeyboardHandlerBase : IKeyboardHandler{
        protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){
            if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I){
                if (BrowserUtils.HasDevTools){
                    browser.ShowDevTools();
                }
                else{
                    browserControl.AsControl().InvokeSafe(() => {
                        string extraMessage;

                        if (Program.IsPortable){
                            extraMessage = "Please download the portable installer, select the folder with your current installation of TweetDuck Portable, and tick 'Install dev tools' during the installation process.";
                        }
                        else{
                            extraMessage = "Please download the installer, and tick 'Install dev tools' during the installation process. The installer will automatically find and update your current installation of TweetDuck.";
                        }

                        FormMessage.Information("Dev Tools", "You do not have dev tools installed. "+extraMessage, FormMessage.OK);
                    });
                }

                return true;
            }

            return false;
        }

        bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){
            if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){
                return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers);
            }

            return false;
        }

        bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){
            return false;
        }
    }
}

Add keyboard shortcut to open dev tools (Ctrl+Shift+I)


using System;
using System.Web.Mvc;
using Orchard.Localization;
using Orchard.ContentManagement;
using Orchard.Pages.Services;
using Orchard.Pages.ViewModels;
using Orchard.Security;

namespace Orchard.Pages.Controllers {
    [ValidateInput(false)]
    public class PageController : Controller, IUpdateModel {
        private readonly IPageService _pageService;
        private readonly ISlugConstraint _slugConstraint;

        public PageController(
            IOrchardServices services,
            IPageService pageService,
            ISlugConstraint slugConstraint) {
            Services = services;
            _pageService = pageService;
            _slugConstraint = slugConstraint;
            T = NullLocalizer.Instance;
        }

        public IOrchardServices Services { get; set; }
        private Localizer T { get; set; }

        public ActionResult Item(string slug) {
            if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page")))
                return new HttpUnauthorizedResult();

            if (slug == null) {
                throw new ArgumentNullException("slug");
            }

            //var correctedSlug = _slugConstraint.LookupPublishedSlug(pageSlug);

            var page = _pageService.Get(slug);

            var model = new PageViewModel {
                Page = Services.ContentManager.BuildDisplayModel(page, "Detail")
            };
            return View(model);
        }

        bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
            return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
        }
        void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) {
            ModelState.AddModelError(key, errorMessage.ToString());
        }
    }
}

using System;
using System.Web.Mvc;
using Orchard.Localization;
using Orchard.ContentManagement;
using Orchard.Mvc.Results;
using Orchard.Pages.Services;
using Orchard.Pages.ViewModels;
using Orchard.Security;

namespace Orchard.Pages.Controllers {
    [ValidateInput(false)]
    public class PageController : Controller {
        private readonly IPageService _pageService;
        private readonly ISlugConstraint _slugConstraint;

        public PageController(IOrchardServices services, IPageService pageService, ISlugConstraint slugConstraint) {
            Services = services;
            _pageService = pageService;
            _slugConstraint = slugConstraint;
            T = NullLocalizer.Instance;
        }

        public IOrchardServices Services { get; set; }
        private Localizer T { get; set; }

        public ActionResult Item(string slug) {
            if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page")))
                return new HttpUnauthorizedResult();

            var correctedSlug = _slugConstraint.LookupPublishedSlug(slug);
            if (correctedSlug == null)
                return new NotFoundResult();

            var page = _pageService.Get(correctedSlug);
            if (page == null)
                return new NotFoundResult();

            var model = new PageViewModel {
                Page = Services.ContentManager.BuildDisplayModel(page, "Detail")
            };
            return View(model);
        }
    }
}

Fix pages slug to not be case sensitive when used in url

There was one line of code left to be resurrected from the old cms pages module

--HG--
extra : convert_revision : svn%3A5ff7c347-ad56-4c35-b696-ccb81de16e03/trunk%4045978


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

using System;

namespace osu.Game.Screens.Play
{
    public static class GameplayClockExtensions
    {
        /// <summary>
        /// The rate of gameplay when playback is at 100%.
        /// This excludes any seeking / user adjustments.
        /// </summary>
        public static double GetTrueGameplayRate(this IGameplayClock clock)
        {
            // To handle rewind, we still want to maintain the same direction as the underlying clock.
            double rate = Math.Sign(clock.Rate);

            return rate
                   * clock.GameplayAdjustments.AggregateFrequency.Value
                   * clock.GameplayAdjustments.AggregateTempo.Value;
        }
    }
}

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

using System;

namespace osu.Game.Screens.Play
{
    public static class GameplayClockExtensions
    {
        /// <summary>
        /// The rate of gameplay when playback is at 100%.
        /// This excludes any seeking / user adjustments.
        /// </summary>
        public static double GetTrueGameplayRate(this IGameplayClock clock)
        {
            // To handle rewind, we still want to maintain the same direction as the underlying clock.
            double rate = clock.Rate == 0 ? 1 : Math.Sign(clock.Rate);

            return rate
                   * clock.GameplayAdjustments.AggregateFrequency.Value
                   * clock.GameplayAdjustments.AggregateTempo.Value;
        }
    }
}

Fix case of zero rate calculating a zero true gameplay rate


using OpenTK.Input;

namespace MonoHaven.Input
{
	public abstract class InputEvent
	{
		private readonly KeyModifiers mods;

		protected InputEvent()
		{
			mods = GetCurrentKeyModifiers();
		}

		public bool Handled
		{
			get;
			set;
		}

		public KeyModifiers Modifiers
		{
			get { return mods; }
		}

		private static KeyModifiers GetCurrentKeyModifiers()
		{
			var mods = (KeyModifiers)0;
			var keyboardState = Keyboard.GetState();

			if (keyboardState.IsKeyDown(Key.LShift) ||
				keyboardState.IsKeyDown(Key.RShift))
				mods |= KeyModifiers.Shift;

			if (keyboardState.IsKeyDown(Key.LAlt) ||
				keyboardState.IsKeyDown(Key.RAlt))
				mods |= KeyModifiers.Alt;

			if (keyboardState.IsKeyDown(Key.ControlLeft) ||
				keyboardState.IsKeyDown(Key.ControlRight))
				mods |= KeyModifiers.Control;

			return mods;
		}
	}
}

using System;
using OpenTK.Input;

namespace MonoHaven.Input
{
	public abstract class InputEvent : EventArgs
	{
		private readonly KeyModifiers mods;

		protected InputEvent()
		{
			mods = GetCurrentKeyModifiers();
		}

		public bool Handled
		{
			get;
			set;
		}

		public KeyModifiers Modifiers
		{
			get { return mods; }
		}

		private static KeyModifiers GetCurrentKeyModifiers()
		{
			var mods = (KeyModifiers)0;
			var keyboardState = Keyboard.GetState();

			if (keyboardState.IsKeyDown(Key.LShift) ||
				keyboardState.IsKeyDown(Key.RShift))
				mods |= KeyModifiers.Shift;

			if (keyboardState.IsKeyDown(Key.LAlt) ||
				keyboardState.IsKeyDown(Key.RAlt))
				mods |= KeyModifiers.Alt;

			if (keyboardState.IsKeyDown(Key.ControlLeft) ||
				keyboardState.IsKeyDown(Key.ControlRight))
				mods |= KeyModifiers.Control;

			return mods;
		}
	}
}

Allow to use input event arguments in the event handlers


using Newtonsoft.Json;
using ShopifySharp.Converters;
using System.Runtime.Serialization;

namespace ShopifySharp.Enums
{
    [JsonConverter(typeof(NullableEnumConverter<ShopifyAuthorizationScope>))]
    public enum ShopifyAuthorizationScope
    {
        [EnumMember(Value = "read_content")]
        ReadContent,

        [EnumMember(Value = "write_content")]
        WriteContent,

        [EnumMember(Value = "read_themes")]
        ReadThemes,

        [EnumMember(Value = "write_themes")]
        WriteThemes,

        [EnumMember(Value = "read_products")]
        ReadProducts,

        [EnumMember(Value = "write_products")]
        WriteProducts,

        [EnumMember(Value = "read_customers")]
        ReadCustomers,

        [EnumMember(Value = "write_customers")]
        WriteCustomers,

        [EnumMember(Value = "read_orders")]
        ReadOrders,

        [EnumMember(Value = "write_orders")]
        WriteOrders,

        [EnumMember(Value = "read_script_tags")]
        ReadScriptTags,

        [EnumMember(Value = "write_script_tags")]
        WriteScriptTags,

        [EnumMember(Value = "read_fulfillments")]
        ReadFulfillments,

        [EnumMember(Value = "write_fulfillments")]
        WriteFulfillments,

        [EnumMember(Value = "read_shipping")]
        ReadShipping,

        [EnumMember(Value = "write_shipping")]
        WriteShipping
    }
}

using Newtonsoft.Json;
using ShopifySharp.Converters;
using System.Runtime.Serialization;

namespace ShopifySharp.Enums
{
    [JsonConverter(typeof(NullableEnumConverter<ShopifyAuthorizationScope>))]
    public enum ShopifyAuthorizationScope
    {
        [EnumMember(Value = "read_content")]
        ReadContent,

        [EnumMember(Value = "write_content")]
        WriteContent,

        [EnumMember(Value = "read_themes")]
        ReadThemes,

        [EnumMember(Value = "write_themes")]
        WriteThemes,

        [EnumMember(Value = "read_products")]
        ReadProducts,

        [EnumMember(Value = "write_products")]
        WriteProducts,

        [EnumMember(Value = "read_customers")]
        ReadCustomers,

        [EnumMember(Value = "write_customers")]
        WriteCustomers,

        [EnumMember(Value = "read_orders")]
        ReadOrders,

        [EnumMember(Value = "write_orders")]
        WriteOrders,

        [EnumMember(Value = "read_script_tags")]
        ReadScriptTags,

        [EnumMember(Value = "write_script_tags")]
        WriteScriptTags,

        [EnumMember(Value = "read_fulfillments")]
        ReadFulfillments,

        [EnumMember(Value = "write_fulfillments")]
        WriteFulfillments,

        [EnumMember(Value = "read_shipping")]
        ReadShipping,

        [EnumMember(Value = "write_shipping")]
        WriteShipping,

        [EnumMember(Value = "read_analytics")]
        ReadAnalytics,

        [EnumMember(Value = "read_users")]
        ReadUsers,

        [EnumMember(Value = "write_users")]
        WriteUsers
    }
}

Add missing authorization scopes read_analytics, read_users and write_users


using SlugityLib.Configuration;

namespace SlugityLib.Tests
{
    public class CustomSlugityConfig : ISlugityConfig
    {
        public CustomSlugityConfig()
        {
            TextCase = TextCase.LowerCase;
            StripStopWords = false;
            MaxLength = 30;
            StringSeparator = ' ';
            ReplacementCharacters = new CharacterReplacement();
        }

        public TextCase TextCase { get; set; }

        public char StringSeparator { get; set; }

        public int? MaxLength { get; set; }

        public CharacterReplacement ReplacementCharacters { get; set; }

        public bool StripStopWords { get; set; }
    }
}

Add vscode to git ignore

Add vscode to git ignore


Error!

            Uh, I can explain...

Fix error dialog close button not working


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;

namespace Firehose.Web.Authors
{
    public class ChristianHoejsager : IFilterMyBlogPosts, IAmACommunityMember
    {
        public string FirstName => "Christian";
        public string LastName => "Hoejsager";
        public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast";
        public string StateOrRegion => "Denmark";
        public string EmailAddress => "christian@scriptingchris.tech";
        public string TwitterHandle => "_ScriptingChris";
        public string GitHubHandle => "ScriptingChris";
        public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1";
        public GeoPosition Position => new GeoPosition(55.709830, 9.536208);
        public Uri WebSite => new Uri("https://scriptingchris.tech/");
        public IEnumerable<Uri> FeedUris
        {
            get { yield return new Uri("https://scriptingchris.tech/feed"); }
        }
        public bool Filter(SyndicationItem item)
        {
            return item.Categories?.Any(c => c.Name.ToLowerInvariant().Contains("powershell")) ?? false;
        }
        public string FeedLanguageCode => "en";
    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;

namespace Firehose.Web.Authors
{
    public class ChristianHoejsager : IAmACommunityMember
    {
        public string FirstName => "Christian";
        public string LastName => "Hoejsager";
        public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast";
        public string StateOrRegion => "Denmark";
        public string EmailAddress => "christian@scriptingchris.tech";
        public string TwitterHandle => "_ScriptingChris";
        public string GitHubHandle => "ScriptingChris";
        public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1";
        public GeoPosition Position => new GeoPosition(55.709830, 9.536208);
        public Uri WebSite => new Uri("https://scriptingchris.tech/");
        public IEnumerable<Uri> FeedUris
        {
            get { yield return new Uri("https://scriptingchris.tech/feed"); }
        }
        public string FeedLanguageCode => "en";
    }

}

Remove filter (default will work)

Remove filter (default will work)


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

namespace SharpRaven.Utilities {
    public class CircularBuffer<T>
    {
        private readonly int size;
        private readonly Queue<T> queue;

        public CircularBuffer(int size = 100)
        {
            this.size = size;
            queue = new Queue<T>();
        }

        public List<T> ToList()
        {
            return queue.ToList();
        }

        public void Clear()
        {
            queue.Clear();
        }

        public void Add(T item) {
            if (queue.Count >= size)
                queue.Dequeue();

            queue.Enqueue(item);
        }

        public bool IsEmpty()
        {
            return queue.Count <= 0;
        }
    }
}

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

namespace SharpRaven.Utilities {
    public class CircularBuffer<T>
    {
        private readonly int size;
        private ConcurrentQueue<T> queue;

        public CircularBuffer(int size = 100)
        {
            this.size = size;
            queue = new ConcurrentQueue<T>();
        }

        public List<T> ToList()
        {
            var listReturn = this.queue.ToList();

            return listReturn.Skip(Math.Max(0, listReturn.Count - size)).ToList();
        }

        public void Clear()
        {
            queue = new ConcurrentQueue<T>();
        }

        public void Add(T item) {
            if (queue.Count >= size)
            {
                T result;
                this.queue.TryDequeue(out result);
            }

            queue.Enqueue(item);
        }

        public bool IsEmpty()
        {
            return queue.Count <= 0;
        }
    }
}

Refactor to a thread-safe queue.

Refactor to a thread-safe queue.


using System;
using Nancy.Helpers;

namespace Nancy.ViewEngines.Razor
{
    /// <summary>
    /// An html string that is encoded.
    /// </summary>
    public class EncodedHtmlString : IHtmlString
    {
        /// <summary>
        /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly.
        /// </summary>
        public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty);

        private readonly Lazy<string> encoderFactory;

        /// <summary>
        /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class.
        /// </summary>
        /// <param name="value">The value.</param>
        public EncodedHtmlString(string value)
        {
            encoderFactory = new Lazy<string>(() => HttpUtility.HtmlEncode(value));
        }

        /// <summary>
        /// Returns an HTML-encoded string.
        /// </summary>
        /// <returns>An HTML-encoded string.</returns>
        public string ToHtmlString()
        {
            return encoderFactory.Value;
        }

        public static implicit operator EncodedHtmlString(string value)
        {
            return new EncodedHtmlString(value);
        }
    }
}

namespace Nancy.ViewEngines.Razor
{
    using System;
    using Nancy.Helpers;

    /// <summary>
    /// An html string that is encoded.
    /// </summary>
    public class EncodedHtmlString : IHtmlString
    {
        /// <summary>
        /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly.
        /// </summary>
        public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty);

        private readonly string encodedValue;

        /// <summary>
        /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class.
        /// </summary>
        /// <param name="value">The encoded value.</param>
        public EncodedHtmlString(string value)
        {
            encodedValue = HttpUtility.HtmlEncode(value);
        }

        /// <summary>
        /// Returns an HTML-encoded string.
        /// </summary>
        /// <returns>An HTML-encoded string.</returns>
        public string ToHtmlString()
        {
            return encodedValue;
        }

        public static implicit operator EncodedHtmlString(string value)
        {
            return new EncodedHtmlString(value);
        }
    }
}

Move using-statements within namespace declaration.

Also update stored encoded-value type from Lazy<T> to string.
Previous pattern is an outlier (generating the encoded value multiple times from a view-helper) and not really worth the extra baggage.


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Vipr.Core;

namespace Vipr
{
    internal static class FileWriter
    {
        public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null)
        {
            if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath))
                Directory.CreateDirectory(outputDirectoryPath);

            var fileTasks = new List<Task>();

            foreach (var file in textFilesToWrite)
            {
                var filePath = file.RelativePath;

                if (!string.IsNullOrWhiteSpace(outputDirectoryPath))
                    filePath = Path.Combine(outputDirectoryPath, filePath);

                if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) &&
                    !Path.IsPathRooted(filePath))
                    filePath = Path.Combine(Environment.CurrentDirectory, filePath);

                if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));

                fileTasks.Add(WriteToDisk(filePath, file.Contents));
            }
            await Task.WhenAll(fileTasks);
        }

        public static async Task WriteToDisk(string filePath, string output)
        {
            StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8);
            await sw.WriteAsync(output);
            sw.Close();
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Vipr.Core;

namespace Vipr
{
    internal static class FileWriter
    {
        public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null)
        {
            if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath))
                Directory.CreateDirectory(outputDirectoryPath);

            var fileTasks = new List<Task>();

            foreach (var file in textFilesToWrite)
            {
                var filePath = file.RelativePath;

                if (!string.IsNullOrWhiteSpace(outputDirectoryPath))
                    filePath = Path.Combine(outputDirectoryPath, filePath);

                if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) &&
                    !Path.IsPathRooted(filePath))
                    filePath = Path.Combine(Environment.CurrentDirectory, filePath);

                if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));

                fileTasks.Add(WriteToDisk(filePath, file.Contents));
            }
            await Task.WhenAll(fileTasks);
        }

        /**
         * Write the file to disk. If the file is locked for editing,
         * sleep until available
         */
        public static async Task WriteToDisk(string filePath, string output)
        {
            for (int tries = 0; tries < 10; tries++)
            {
                StreamWriter sw = null;
                try
                {
                    using (sw = new StreamWriter(filePath, false, Encoding.UTF8))
                    {
                        await sw.WriteAsync(output);
                        break;
                    }
                }
                // If the file is currently locked for editing, sleep
                // This shouldn't be hit if the generator is running correctly,
                // however, files are currently being overwritten several times
                catch (IOException)
                {
                    Thread.Sleep(5);
                }
            }

        }
    }
}

Add case for locked files

Add case for locked files


namespace Gu.Analyzers.Benchmarks.Benchmarks
{
    using System.Collections.Immutable;
    using System.Threading;
    using System.Threading.Tasks;
    using BenchmarkDotNet.Attributes;
    using Microsoft.CodeAnalysis.Diagnostics;

    public abstract class Analyzer
    {
        private readonly CompilationWithAnalyzers compilation;

        protected Analyzer(DiagnosticAnalyzer analyzer)
        {
            var project = Factory.CreateProject(analyzer);
            this.compilation = project.GetCompilationAsync(CancellationToken.None)
                                      .Result
                                      .WithAnalyzers(
                                          ImmutableArray.Create(analyzer),
                                          project.AnalyzerOptions,
                                          CancellationToken.None);
        }

        [Benchmark]
        public async Task<object> GetAnalyzerDiagnosticsAsync()
        {
            return await this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None)
                             .ConfigureAwait(false);
        }
    }
}

namespace Gu.Analyzers.Benchmarks.Benchmarks
{
    using System.Collections.Immutable;
    using System.Threading;
    using BenchmarkDotNet.Attributes;
    using Microsoft.CodeAnalysis.Diagnostics;

    public abstract class Analyzer
    {
        private readonly CompilationWithAnalyzers compilation;

        protected Analyzer(DiagnosticAnalyzer analyzer)
        {
            var project = Factory.CreateProject(analyzer);
            this.compilation = project.GetCompilationAsync(CancellationToken.None)
                                      .Result
                                      .WithAnalyzers(
                                          ImmutableArray.Create(analyzer),
                                          project.AnalyzerOptions,
                                          CancellationToken.None);
        }

        [Benchmark]
        public object GetAnalyzerDiagnosticsAsync()
        {
            return this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None).Result;
        }
    }
}

Tweak benchmarks, still don't trust the results.


namespace InfinniPlatform.Sdk.Hosting
{
    /// <summary>
    ///     .
    /// </summary>
    public interface IHostAddressParser
    {
        /// <summary>
        /// ,    .
        /// </summary>
        /// <param name="hostNameOrAddress">    .</param>
        /// <returns> <c>true</c>,    ;   <c>false</c>.</returns>
        bool IsLocalAddress(string hostNameOrAddress);

        /// <summary>
        /// ,    .
        /// </summary>
        /// <param name="hostNameOrAddress">    .</param>
        /// <param name="normalizedAddress">  .</param>
        /// <returns> <c>true</c>,    ;   <c>false</c>.</returns>
        bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress);
    }
}

namespace InfinniPlatform.Sdk.Hosting
{
    /// <summary>
    /// Интерфейс для разбора адресов узлов.
    /// </summary>
    public interface IHostAddressParser
    {
        /// <summary>
        /// Определяет, является ли адрес локальным.
        /// </summary>
        /// <param name="hostNameOrAddress">Имя узла или его адрес.</param>
        /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns>
        bool IsLocalAddress(string hostNameOrAddress);

        /// <summary>
        /// Определяет, является ли адрес локальным.
        /// </summary>
        /// <param name="hostNameOrAddress">Имя узла или его адрес.</param>
        /// <param name="normalizedAddress">Нормализованный адрес узла.</param>
        /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns>
        bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress);
    }
}

Fix files encoding to UTF-8

MC-4363: Fix files encoding to UTF-8


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

namespace Mindscape.Raygun4Net
{
  public class RaygunBreadcrumb
  {
    public string Message { get; set; }
    public string Category { get; set; }
    public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info;
    public IDictionary CustomData { get; set; }

    public string ClassName { get; set; }
    public string MethodName { get; set; }
    public int LineNumber { get; set; }
  }
}

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

namespace Mindscape.Raygun4Net
{
  public class RaygunBreadcrumb
  {
    public string Message { get; set; }
    public string Category { get; set; }
    public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info;
    public IDictionary CustomData { get; set; }

    public string ClassName { get; set; }
    public string MethodName { get; set; }
    public int? LineNumber { get; set; }
  }
}

Change LineNumber to nullable so it does not get serialized unless set


using System.Collections;
using System.Reflection;
using Assets.Scripts.Props;
using UnityEngine;

public class AlarmClockHoldableHandler : HoldableHandler
{
	public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller)
	{
		clock = Holdable.GetComponentInChildren<AlarmClock>();
	}

	protected override IEnumerator RespondToCommandInternal(string command)
	{
		if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break;

		yield return null;
		yield return DoInteractionClick(clock.SnoozeButton);
	}

	static AlarmClockHoldableHandler()
	{
		_alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance);
	}

	private static FieldInfo _alarmClockOnField = null;
	private AlarmClock clock;
}

using System.Collections;
using System.Reflection;
using Assets.Scripts.Props;
using UnityEngine;

public class AlarmClockHoldableHandler : HoldableHandler
{
	public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller)
	{
		clock = Holdable.GetComponentInChildren<AlarmClock>();
		HelpMessage = "Snooze the alarm clock with !{0} snooze";
		HelpMessage += TwitchPlaySettings.data.AllowSnoozeOnly
			? " (Current Twitch play settings forbids turning the Alarm clock back on.)"
			: " Alarm clock may also be turned back on with !{0} snooze";
	}

	protected override IEnumerator RespondToCommandInternal(string command)
	{
		if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break;

		yield return null;
		yield return DoInteractionClick(clock.SnoozeButton);
	}

	static AlarmClockHoldableHandler()
	{
		_alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance);
	}

	private static FieldInfo _alarmClockOnField = null;
	private AlarmClock clock;
}

Add help message to !alarmclock

Add help message to !alarmclock


using System;

namespace EvilDICOM.Core.Helpers
{
    public class EnumHelper
    {
        public static T StringToEnum<T>(string name)
        {
            return (T) Enum.Parse(typeof (T), name);
        }
    }
}

using System;

namespace EvilDICOM.Core.Helpers
{
    public class EnumHelper
    {
        public static T StringToEnum<T>(string name)
        {
            return (T) Enum.Parse(typeof (T), name, false);
        }
    }
}

Use Enum.Parse overload available in PCL


using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGameUtils.UI.GameComponents
{
    /// <summary>
    /// Represents a rectangular button that can be clicked in a game.
    /// </summary>
    public class Button : DrawableGameComponent
    {
        public SpriteFont Font { get; set; }
        public Color TextColor { get; set; }
        public string Text { get; set; }
        public Rectangle Bounds { get; set; }
        public Color BackgroundColor { get; set; }

        private Texture2D ButtonTexture;

        private readonly SpriteBatch spriteBatch;

        public Button(Game game, SpriteFont font, Color textColor, string text,
                      Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game)
        {
            this.Font = font;
            this.TextColor = textColor;
            this.Text = text;
            this.Bounds = bounds;
            this.BackgroundColor = backgroundColor;
            this.spriteBatch = spriteBatch;
        }

        protected override void LoadContent()
        {
            this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1);
            this.ButtonTexture.SetData<Color>(new Color[] { Color.White });
        }

        public override void Draw(GameTime gameTime)
        {
            // Draw the button background.
            spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor);

            // Draw the button text.
            spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor);

            base.Draw(gameTime);
        }
    }
}

Tag release with updated version number.


using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NutzCode.Libraries.Web.StreamProvider;

namespace NutzCode.CloudFileSystem
{
    public class AuthorizationFactory
    {
        private static AuthorizationFactory _instance;
        public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory());

        [Import(typeof(IAppAuthorization))]
        public IAppAuthorization AuthorizationProvider { get; set; }

        public AuthorizationFactory(string dll=null)
        {
            Assembly assembly = Assembly.GetEntryAssembly();
            string codebase = assembly.CodeBase;
            UriBuilder uri = new UriBuilder(codebase);
            string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path).Replace("/", "\\"));
            if (dirname != null)
            {
                AggregateCatalog catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new AssemblyCatalog(assembly));
                if (dll!=null)
                    catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll));
                var container = new CompositionContainer(catalog);
                container.ComposeParts(this);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NutzCode.Libraries.Web.StreamProvider;

namespace NutzCode.CloudFileSystem
{
    public class AuthorizationFactory
    {
        private static AuthorizationFactory _instance;
        public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory());

        [Import(typeof(IAppAuthorization))]
        public IAppAuthorization AuthorizationProvider { get; set; }

        public AuthorizationFactory(string dll=null)
        {
            Assembly assembly = Assembly.GetEntryAssembly();
            string codebase = assembly.CodeBase;
            UriBuilder uri = new UriBuilder(codebase);
            string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path)
                .Replace("/", $"{System.IO.Path.DirectorySeparatorChar}"));
            if (dirname != null)
            {
                AggregateCatalog catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new AssemblyCatalog(assembly));
                if (dll!=null)
                    catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll));
                var container = new CompositionContainer(catalog);
                container.ComposeParts(this);
            }
        }
    }
}

Handle dir separator better for Mono

Handle dir separator better for Mono