using System;
using System.Threading;

namespace Lurchsoft.ParallelWorkshop.Ex08DiyReaderWriterLock.PossibleSolution
{
    /// <summary>
    /// A scary low-level reader-writer lock implementation.
    /// <para>
    /// This one does not block, though it does yield. It will spin the CPU until the lock is available. However, by doing
    /// so, it avoids the cost of synchronisation and is much faster than a blocking lock.
    /// </para>
    /// </summary>
    public class InterlockedReaderWriterLock : IReaderWriterLock
    {
        private const int OneWriter = 1 << 16;

        private int counts;

        public void EnterReadLock()
        {
            while (true)
            {
                int cur = Interlocked.Increment(ref counts);
                if ((cur & 0xFFFF0000) == 0)
                {
                    return;
                }

                Interlocked.Decrement(ref counts);
                Thread.Yield();
            }
        }

        public void ExitReadLock()
        {
            Interlocked.Decrement(ref counts);
        }

        public void EnterWriteLock()
        {
            while (true)
            {
                int cur = Interlocked.Add(ref counts, OneWriter);
                if (cur == OneWriter)
                {
                    return;
                }

                Interlocked.Add(ref counts, -OneWriter);
                Thread.Yield();
            }
        }

        public void ExitWriteLock()
        {
            Interlocked.Add(ref counts, -OneWriter);
        }
    }
}

using System.Threading;

namespace Lurchsoft.ParallelWorkshop.Ex08DiyReaderWriterLock.PossibleSolution
{
    /// <summary>
    /// A scary low-level reader-writer lock implementation.
    /// <para>
    /// This one does not block, though it does yield. It will spin the CPU until the lock is available. However, by doing
    /// so, it avoids the cost of synchronisation and is much faster than a blocking lock.
    /// </para>
    /// </summary>
    public class InterlockedReaderWriterLock : IReaderWriterLock
    {
        private const int OneWriter = 1 << 28;

        private int counts;

        public void EnterReadLock()
        {
            while (true)
            {
                int cur = Interlocked.Increment(ref counts);
                if ((cur & 0xF0000000) == 0)
                {
                    return;
                }

                Interlocked.Decrement(ref counts);
                Thread.Yield();
            }
        }

        public void ExitReadLock()
        {
            Interlocked.Decrement(ref counts);
        }

        public void EnterWriteLock()
        {
            while (true)
            {
                int cur = Interlocked.Add(ref counts, OneWriter);
                if (cur == OneWriter)
                {
                    return;
                }

                Interlocked.Add(ref counts, -OneWriter);
                Thread.Yield();
            }
        }

        public void ExitWriteLock()
        {
            Interlocked.Add(ref counts, -OneWriter);
        }
    }
}

Allow more of the word for the reader count, as the writer count will always be v small


using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(GridLayoutGroup))]
public class TabletUI : MonoBehaviour, ITablet
{
    public ITabletCell TopLeft { get { return topLeft; } set { topLeft.SetState(value); } }
    public ITabletCell TopRight { get { return topRight; } set { topRight.SetState(value); } }
    public ITabletCell BottomLeft { get { return bottomLeft; } set { bottomLeft.SetState(value); } }
    public ITabletCell BottomRight { get { return bottomRight; } set { bottomRight.SetState(value); } }

    private TabletCellUI topLeft;
    private TabletCellUI topRight;
    private TabletCellUI bottomLeft;
    private TabletCellUI bottomRight;

    void Start() {
        GetComponent<GridLayoutGroup>().startCorner = GridLayoutGroup.Corner.UpperLeft;
        GetComponent<GridLayoutGroup>().startAxis = GridLayoutGroup.Axis.Horizontal;

        TabletCellUI[] cells = GetComponentsInChildren<TabletCellUI>();
        if (cells.Length != 4)
            throw new Exception("Expected 4 TabletCellUI components in children, but found " + cells.Length);
        topLeft = cells[0];
        topRight = cells[1];
        bottomLeft = cells[2];
        bottomRight = cells[3];

        topLeft.parent = this;
        topRight.parent = this;
        bottomLeft.parent = this;
        bottomRight.parent = this;
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(GridLayoutGroup))]
public class TabletUI : MonoBehaviour, ITablet
{
    public ITabletCell TopLeft { get { return topLeft; } set { topLeft.SetState(value); } }
    public ITabletCell TopRight { get { return topRight; } set { topRight.SetState(value); } }
    public ITabletCell BottomLeft { get { return bottomLeft; } set { bottomLeft.SetState(value); } }
    public ITabletCell BottomRight { get { return bottomRight; } set { bottomRight.SetState(value); } }

    private TabletCellUI topLeft;
    private TabletCellUI topRight;
    private TabletCellUI bottomLeft;
    private TabletCellUI bottomRight;

    void Start() {
        GetComponent<GridLayoutGroup>().startCorner = GridLayoutGroup.Corner.UpperLeft;
        GetComponent<GridLayoutGroup>().startAxis = GridLayoutGroup.Axis.Horizontal;

        TabletCellUI[] cells = GetComponentsInChildren<TabletCellUI>();
        if (cells.Length != 4)
            throw new Exception("Expected 4 TabletCellUI components in children, but found " + cells.Length);
        topLeft = cells[0];
        topRight = cells[1];
        bottomLeft = cells[2];
        bottomRight = cells[3];

        topLeft.parent = this;
        topRight.parent = this;
        bottomLeft.parent = this;
        bottomRight.parent = this;

        this.SetState(GlobalInput.InputTablet);
    }
}

Make input tablet start states be set right


using System;

namespace Atata
{
    public static class JsonConfigMapper
    {
        public static AtataContextBuilder Map<TConfig>(TConfig config, AtataContextBuilder builder)
            where TConfig : JsonConfig<TConfig>
        {
            if (config.BaseUrl != null)
                builder.UseBaseUrl(config.BaseUrl);

            if (config.RetryTimeout != null)
                builder.UseRetryTimeout(TimeSpan.FromSeconds(config.RetryTimeout.Value));

            if (config.RetryInterval != null)
                builder.UseRetryInterval(TimeSpan.FromSeconds(config.RetryInterval.Value));

            if (config.AssertionExceptionTypeName != null)
                builder.UseAssertionExceptionType(Type.GetType(config.AssertionExceptionTypeName));

            if (config.UseNUnitTestName)
                builder.UseNUnitTestName();

            if (config.LogNUnitError)
                builder.LogNUnitError();

            if (config.TakeScreenshotOnNUnitError)
            {
                if (config.TakeScreenshotOnNUnitErrorTitle != null)
                    builder.TakeScreenshotOnNUnitError(config.TakeScreenshotOnNUnitErrorTitle);
                else
                    builder.TakeScreenshotOnNUnitError();
            }

            return builder;
        }
    }
}

using System;

namespace Atata
{
    public static class JsonConfigMapper
    {
        public static AtataContextBuilder Map<TConfig>(TConfig config, AtataContextBuilder builder)
            where TConfig : JsonConfig<TConfig>
        {
            if (config.BaseUrl != null)
                builder.UseBaseUrl(config.BaseUrl);

            if (config.RetryTimeout != null)
                builder.UseRetryTimeout(TimeSpan.FromSeconds(config.RetryTimeout.Value));

            if (config.RetryInterval != null)
                builder.UseRetryInterval(TimeSpan.FromSeconds(config.RetryInterval.Value));

            if (config.AssertionExceptionTypeName != null)
                builder.UseAssertionExceptionType(Type.GetType(config.AssertionExceptionTypeName));

            if (config.UseNUnitTestName)
                builder.UseNUnitTestName();

            if (config.LogNUnitError)
                builder.LogNUnitError();

            if (config.TakeScreenshotOnNUnitError)
            {
                if (config.TakeScreenshotOnNUnitErrorTitle != null)
                    builder.TakeScreenshotOnNUnitError(config.TakeScreenshotOnNUnitErrorTitle);
                else
                    builder.TakeScreenshotOnNUnitError();
            }

            if (config.LogConsumers != null)
            {
                foreach (var item in config.LogConsumers)
                    MapLogConsumer(item, builder);
            }

            return builder;
        }

        private static void MapLogConsumer(LogConsumerJsonSection logConsumerSection, AtataContextBuilder builder)
        {
            Type type = ResolveLogConsumerType(logConsumerSection.TypeName);

            ILogConsumer logConsumer = (ILogConsumer)Activator.CreateInstance(type);

            if (logConsumerSection.MinLevel != null)
                ;

            if (logConsumerSection.SectionFinish == false)
                ;
        }

        private static Type ResolveLogConsumerType(string typeName)
        {
            //// Check log consumer aliases.

            return Type.GetType(typeName);
        }
    }
}

Add basic mapping functionality of log consumers


// 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.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.UI;

namespace osu.Game.Rulesets.Taiko.Tests
{
    [TestFixture]
    public class TestSceneDrumTouchInputArea : DrawableTaikoRulesetTestScene
    {
        protected const double NUM_HIT_OBJECTS = 10;
        protected const double HIT_OBJECT_TIME_SPACING_MS = 1000;

        [BackgroundDependencyLoader]
        private void load()
        {
            var drumTouchInputArea = new DrumTouchInputArea();
            DrawableRuleset.KeyBindingInputManager.Add(drumTouchInputArea);
            drumTouchInputArea.ShowTouchControls();
        }

        protected override IBeatmap CreateBeatmap(RulesetInfo ruleset)
        {
            List<TaikoHitObject> hitObjects = new List<TaikoHitObject>();

            for (int i = 0; i < NUM_HIT_OBJECTS; i++)
            {
                hitObjects.Add(new Hit
                {
                    StartTime = Time.Current + i * HIT_OBJECT_TIME_SPACING_MS,
                    IsStrong = isOdd(i),
                    Type = isOdd(i / 2) ? HitType.Centre : HitType.Rim
                });
            }

            var beatmap = new Beatmap<TaikoHitObject>
            {
                BeatmapInfo = { Ruleset = ruleset },
                HitObjects = hitObjects
            };

            return beatmap;
        }

        private bool isOdd(int number)
        {
            return number % 2 == 0;
        }
    }
}

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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Taiko.UI;
using osu.Game.Tests.Visual;

namespace osu.Game.Rulesets.Taiko.Tests
{
    [TestFixture]
    public class TestSceneDrumTouchInputArea : OsuTestScene
    {
        [Cached]
        private TaikoInputManager taikoInputManager = new TaikoInputManager(new TaikoRuleset().RulesetInfo);

        private DrumTouchInputArea drumTouchInputArea = null!;

        [SetUpSteps]
        public void SetUpSteps()
        {
            AddStep("create drum", () =>
            {
                Children = new Drawable[]
                {
                    new InputDrum
                    {
                        Anchor = Anchor.TopCentre,
                        Origin = Anchor.TopCentre,
                        Height = 0.5f,
                    },
                    drumTouchInputArea = new DrumTouchInputArea
                    {
                        Anchor = Anchor.BottomCentre,
                        Origin = Anchor.BottomCentre,
                        Height = 0.5f,
                    },
                };
            });
        }

        [Test]
        public void TestDrum()
        {
            AddStep("show drum", () => drumTouchInputArea.Show());
        }
    }
}

Make test actually test drum behaviours

Make test actually test drum behaviours


using Common;
using Exporter;
using System.Linq;

namespace Crayon
{
    // cmdLineFlags = Crayon::RunCbxFlagBuilder(command, buildContext)
    class RunCbxFlagBuilderWorker : AbstractCrayonWorker
    {
        public override CrayonWorkerResult DoWorkImpl(CrayonWorkerResult[] args)
        {
            ExportCommand command = (ExportCommand)args[0].Value;
            string finalCbxPath = (string)args[1].Value;

            string cbxFile = FileUtil.GetPlatformPath(finalCbxPath);
            int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
            string runtimeArgs = string.Join(",", command.DirectRunArgs.Select(s => Utf8Base64.ToBase64(s)));
            string flags = cbxFile + " vmpid:" + processId;
            if (runtimeArgs.Length > 0)
            {
                flags += " runtimeargs:" + runtimeArgs;
            }

            return new CrayonWorkerResult() { Value = flags };
        }
    }
}

using Common;
using Exporter;
using System.Linq;

namespace Crayon
{
    // cmdLineFlags = Crayon::RunCbxFlagBuilder(command, buildContext)
    class RunCbxFlagBuilderWorker : AbstractCrayonWorker
    {
        public override CrayonWorkerResult DoWorkImpl(CrayonWorkerResult[] args)
        {
            ExportCommand command = (ExportCommand)args[0].Value;
            string finalCbxPath = (string)args[1].Value;

            string cbxFile = FileUtil.GetPlatformPath(finalCbxPath);
            int processId = System.Diagnostics.Process.GetCurrentProcess().Id;
            string runtimeArgs = string.Join(",", command.DirectRunArgs.Select(s => Utf8Base64.ToBase64(s)));
            string flags = "\"" + cbxFile + "\" vmpid:" + processId;
            if (runtimeArgs.Length > 0)
            {
                flags += " runtimeargs:" + runtimeArgs;
            }

            return new CrayonWorkerResult() { Value = flags };
        }
    }
}

Fix bug where running a project without export in a directory with a space was confusing the command line arg generator.

Fixes https://github.com/blakeohare/crayon/issues/203


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

namespace Rs317.Sharp
{
	public static class Program
	{
		public static async Task Main(string[] args)
		{
			try
			{
				Console.WriteLine($"RS2 user client - release #{317} using Rs317.Sharp by Glader");
				await StartClient(0, 0, true);
			}
			catch(Exception exception)
			{
				throw new InvalidOperationException($"Erorr: {exception.Message} \n\n Stack: {exception.StackTrace}");
			}
		}

		private static async Task StartClient(int localWorldId, short portOffset, bool membersWorld)
		{
			Application.SetCompatibleTextRenderingDefault(false);

			Task clientRunningAwaitable = signlink.startpriv("127.0.0.1");
			ClientConfiguration configuration = new ClientConfiguration(localWorldId, (short) (portOffset + 1), membersWorld);

			RsWinForm windowsFormApplication = new RsWinForm(765, 503);
			RsWinFormsClient client1 = new RsWinFormsClient(configuration, windowsFormApplication.CreateGraphics(), new DefaultWebSocketClientFactory());
			windowsFormApplication.RegisterInputSubscriber(client1);
			client1.createClientFrame(765, 503);

			Application.Run(windowsFormApplication);

			await clientRunningAwaitable
				.ConfigureAwait(false);
		}
	}
}

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

namespace Rs317.Sharp
{
	public static class Program
	{
		public static async Task Main(string[] args)
		{
			try
			{
				Console.WriteLine($"RS2 user client - release #{317} using Rs317.Sharp by Glader");
				await StartClient(0, 0, true);
			}
			catch(Exception exception)
			{
				throw new InvalidOperationException($"Erorr: {exception.Message} \n\n Stack: {exception.StackTrace}");
			}
		}

		private static async Task StartClient(int localWorldId, short portOffset, bool membersWorld)
		{
			Application.SetCompatibleTextRenderingDefault(false);

			Task clientRunningAwaitable = signlink.startpriv("127.0.0.1");
			ClientConfiguration configuration = new ClientConfiguration(localWorldId, (short) (portOffset + 1), membersWorld);

			RsWinForm windowsFormApplication = new RsWinForm(765, 503);
			RsWinFormsClient client1 = new RsWinFormsClient(configuration, windowsFormApplication.CreateGraphics());
			windowsFormApplication.RegisterInputSubscriber(client1);
			client1.createClientFrame(765, 503);

			Application.Run(windowsFormApplication);

			await clientRunningAwaitable
				.ConfigureAwait(false);
		}
	}
}

Remove test websocket code from WF implementation


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

namespace Cube.FileSystem.Tests
{
    /* --------------------------------------------------------------------- */
    ///
    /// GlobalSetup
    ///
    /// <summary>
    /// NUnit で最初に実行する処理を記述するテストです。
    /// </summary>
    ///
    /* --------------------------------------------------------------------- */
    [SetUpFixture]
    public class GlobalSetup
    {
        /* ----------------------------------------------------------------- */
        ///
        /// OneTimeSetup
        ///
        /// <summary>
        /// 一度だけ実行される初期化処理です。
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [OneTimeSetUp]
        public void OneTimeSetup()
        {
            Logger.Configure();
            Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly());
        }
    }
}

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

namespace Cube.FileSystem.Tests
{
    /* --------------------------------------------------------------------- */
    ///
    /// GlobalSetup
    ///
    /// <summary>
    /// NUnit で最初に実行する処理を記述するテストです。
    /// </summary>
    ///
    /* --------------------------------------------------------------------- */
    [SetUpFixture]
    public class GlobalSetup
    {
        /* ----------------------------------------------------------------- */
        ///
        /// OneTimeSetup
        ///
        /// <summary>
        /// 一度だけ実行される初期化処理です。
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        [OneTimeSetUp]
        public void OneTimeSetup()
        {
            Logger.Configure();
            Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly());
        }
    }
}

Fix to apply for the library updates.

Fix to apply for the library updates.


using Flood.Tools.RPCGen;
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;

namespace RPCGen.Tests
{
    [TestFixture]
    class RPCGenTests
    {
        [Test]
        public void MainTest()
        {
            string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests");
            Directory.CreateDirectory(genDirectory);

            var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll");
            var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll");
            var sourcePdbPath = Path.GetFullPath("RPCGen.Tests.Services.pdb");
            var destPdbPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.pdb");

            System.IO.File.Copy(sourceDllPath, destDllPath, true);

            if (File.Exists(sourcePdbPath))
                System.IO.File.Copy(sourcePdbPath, destPdbPath, true);

            var args = new string[]
            {
                String.Format("-o={0}", genDirectory),
                destDllPath
            };

            var ret = Flood.Tools.RPCGen.Program.Main(args);
            Assert.AreEqual(0, ret);
        }

        [Test]
        public void GenAPI()
        {
            string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests.API");
            Directory.CreateDirectory(genDirectory);

            var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll");
            var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll");

            var rpcCompiler = new Compiler(sourceDllPath, genDirectory);
            rpcCompiler.Process();
            rpcCompiler.CompileApi(destDllPath);
        }
    }
}

using Flood.Tools.RPCGen;
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;

namespace RPCGen.Tests
{
    [TestFixture]
    class RPCGenTests
    {
        [Test]
        public void MainTest()
        {
            string genDirectory = Path.Combine("..", "..", "gen", "RPCGen.Tests");
            Directory.CreateDirectory(genDirectory);

            var sourceDllPath = Path.GetFullPath("RPCGen.Tests.Services.dll");
            var destDllPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.dll");
            var sourcePdbPath = Path.GetFullPath("RPCGen.Tests.Services.pdb");
            var destPdbPath = Path.Combine(genDirectory, "RPCGen.Tests.Services.pdb");

            System.IO.File.Copy(sourceDllPath, destDllPath, true);

            if (File.Exists(sourcePdbPath))
                System.IO.File.Copy(sourcePdbPath, destPdbPath, true);

            var args = new string[]
            {
                String.Format("-o={0}", genDirectory),
                destDllPath
            };

            var ret = Flood.Tools.RPCGen.Program.Main(args);
            Assert.AreEqual(0, ret);
        }
    }
}

Remove test of no longer existing method CompileApi.


using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using WordHunt.Data.Connection;

namespace WordHunt.Games.Create.Repository
{
    public interface IGameRepository
    {
        void SaveGame(string name);
    }

    public class GameRepository : IGameRepository
    {
        private readonly IDbConnectionProvider connectionProvider;
        public GameRepository(IDbConnectionProvider connectionProvider)
        {
            this.connectionProvider = connectionProvider;
        }

        public void SaveGame(string name)
        {
            var connection = connectionProvider.GetConnection();

            connection.Execute(@"INSERT INTO Words(LanguageId, Value) VALUES (@LanguageId, @Value)",
                new { LanguageId = 1, Value = name });
        }
    }
}

using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using WordHunt.Data.Connection;

namespace WordHunt.Games.Create.Repository
{
    public interface IGameRepository
    {
        void SaveGame(string name);
    }

    public class GameRepository : IGameRepository
    {
        private readonly IDbConnectionFactory connectionFactory;
        public GameRepository(IDbConnectionFactory connectionFactory)
        {
            this.connectionFactory = connectionFactory;
        }

        public void SaveGame(string name)
        {
            using (var connection = connectionFactory.CreateConnection())
            {
                connection.Execute(@"INSERT INTO Words(LanguageId, Value) VALUES (@LanguageId, @Value)",
                    new { LanguageId = 1, Value = name });
            }
        }
    }
}

Change usage of connection provider for connection factory.


using System;
using System.Collections.Generic;

namespace Elasticsearch.Net
{
	internal static class ErrorCauseExtensions
	{
		public static void FillValues(this ErrorCause rootCause, IDictionary<string, object> dict)
		{
			if (dict == null) return;

			if (dict.TryGetValue("reason", out var reason)) rootCause.Reason = Convert.ToString(reason);
			if (dict.TryGetValue("type", out var type)) rootCause.Type = Convert.ToString(type);
			if (dict.TryGetValue("stack_trace", out var stackTrace)) rootCause.StackTrace = Convert.ToString(stackTrace);

//			if (dict.TryGetValue("index", out var index)) rootCause.Index = Convert.ToString(index);
//			if (dict.TryGetValue("resource.id", out var resourceId)) rootCause.ResourceId = Convert.ToString(resourceId);
//			if (dict.TryGetValue("resource.type", out var resourceType)) rootCause.ResourceType = Convert.ToString(resourceType);
		}
	}
}

using System;
using System.Collections.Generic;

namespace Elasticsearch.Net
{
	internal static class ErrorCauseExtensions
	{
		public static void FillValues(this ErrorCause rootCause, IDictionary<string, object> dict)
		{
			if (dict == null) return;

			if (dict.TryGetValue("reason", out var reason) && reason != null) rootCause.Reason = Convert.ToString(reason);
			if (dict.TryGetValue("type", out var type) && type != null) rootCause.Type = Convert.ToString(type);
			if (dict.TryGetValue("stack_trace", out var stackTrace) && stackTrace != null) rootCause.StackTrace = Convert.ToString(stackTrace);

//			if (dict.TryGetValue("index", out var index)) rootCause.Index = Convert.ToString(index);
//			if (dict.TryGetValue("resource.id", out var resourceId)) rootCause.ResourceId = Convert.ToString(resourceId);
//			if (dict.TryGetValue("resource.type", out var resourceType)) rootCause.ResourceType = Convert.ToString(resourceType);
		}
	}
}

Convert ErrorCause properties only when not null


using System.Collections.Concurrent;

namespace CircuitBreaker
{
    public class CircuitBreakerStateStoreFactory
    {
        private static ConcurrentDictionary<string, ICircuitBreakerStateStore> _stateStores =
            new ConcurrentDictionary<string, ICircuitBreakerStateStore>();

        internal static ICircuitBreakerStateStore GetCircuitBreakerStateStore(ICircuit circuit)
        {
            // There is only one type of ICircuitBreakerStateStore to return...
            // The ConcurrentDictionary keeps track of ICircuitBreakerStateStore objects (across threads)
            // For example, a store for a db connection, web service client, and NAS storage could exist

            if (!_stateStores.ContainsKey(circuit.GetType().Name))
            {
                _stateStores.TryAdd(circuit.GetType().Name, new CircuitBreakerStateStore(circuit));
            }

            return _stateStores[circuit.GetType().Name];
        }

        // TODO: Add the ability for Circuit breaker stateStores to update the state in this dictionary?
    }
}

using System;
using System.Collections.Concurrent;

namespace CircuitBreaker
{
    public class CircuitBreakerStateStoreFactory
    {
        private static ConcurrentDictionary<Type, ICircuitBreakerStateStore> _stateStores =
            new ConcurrentDictionary<Type, ICircuitBreakerStateStore>();

        internal static ICircuitBreakerStateStore GetCircuitBreakerStateStore(ICircuit circuit)
        {
            // There is only one type of ICircuitBreakerStateStore to return...
            // The ConcurrentDictionary keeps track of ICircuitBreakerStateStore objects (across threads)
            // For example, a store for a db connection, web service client, and NAS storage could exist

            if (!_stateStores.ContainsKey(circuit.GetType()))
            {
                _stateStores.TryAdd(circuit.GetType(), new CircuitBreakerStateStore(circuit));
            }

            return _stateStores[circuit.GetType()];
        }

        // TODO: Add the ability for Circuit breaker stateStores to update the state in this dictionary?
    }
}

Use Type as a key...instead of a string.


using System;
using Mono.Terminal;

namespace School.REPL
{
    public class REPL
    {
        public REPL()
        {
        }

        public void Run()
        {
            Evaluator evaluator = new Evaluator();
            LineEditor editor = new LineEditor("School");

            Console.WriteLine("School REPL:");
            string line;
            while ((line = editor.Edit("> ", "")) != null)
            {
                if (!String.IsNullOrWhiteSpace(line))
                {
                    try {
                        Value value = evaluator.Evaluate(line);
                        Console.WriteLine(value);
                    } catch (Exception e) {
                        Console.WriteLine(e);
                    }
                }
            }
        }
    }
}

using System;
using Mono.Terminal;

namespace School.REPL
{
    public class REPL
    {
        public REPL()
        {
        }

        public void Run()
        {
            Evaluator evaluator = new Evaluator();
            LineEditor editor = new LineEditor("School");

            Console.WriteLine("School REPL:");
            string line;
            while ((line = editor.Edit("> ", "")) != null)
            {
                if (String.IsNullOrWhiteSpace(line))
                    continue;

                try {
                    Value value = evaluator.Evaluate(line);
                    Console.WriteLine(value);
                } catch (Exception e) {
                    Console.WriteLine(e);
                }
            }
        }
    }
}

Use continue to reduce one indentation level.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Company.Application1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }
}

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Company.Application1;

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .Build();

await host.RunAsync();

Use top level program for the Worker template


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

namespace elbgb.gameboy.Memory.Mappers
{
	class RomOnly : Cartridge
	{
		public RomOnly(CartridgeHeader header, byte[] romData)
			: base(header, romData)
		{

		}

		public override byte ReadByte(ushort address)
		{
			return _romData[address];
		}

		public override void WriteByte(ushort address, byte value)
		{
			return;
		}
	}
}

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

namespace elbgb.gameboy.Memory.Mappers
{
	class RomOnly : Cartridge
	{
		public RomOnly(CartridgeHeader header, byte[] romData)
			: base(header, romData)
		{

		}

		public override byte ReadByte(ushort address)
		{
			if (address < 0x8000)
			{
				return _romData[address];
			}
			else
				return 0x00;
		}

		public override void WriteByte(ushort address, byte value)
		{
			return;
		}
	}
}

Return a value for reads from expansion RAM even though not present


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Mania.UI;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
    /// <summary>
    /// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency.
    /// </summary>
    public class ColumnTestContainer : Container
    {
        protected override Container<Drawable> Content => content;

        private readonly Container content;

        [Cached]
        private readonly Column column;

        public ColumnTestContainer(int column, ManiaAction action)
        {
            this.column = new Column(column)
            {
                Action = { Value = action },
                AccentColour = Color4.Orange
            };

            InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4)
            {
                RelativeSizeAxes = Axes.Both
            };
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.UI;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
    /// <summary>
    /// A container to be used in a <see cref="ManiaSkinnableTestScene"/> to provide a resolvable <see cref="Column"/> dependency.
    /// </summary>
    public class ColumnTestContainer : Container
    {
        protected override Container<Drawable> Content => content;

        private readonly Container content;

        [Cached]
        private readonly Column column;

        public ColumnTestContainer(int column, ManiaAction action)
        {
            this.column = new Column(column)
            {
                Action = { Value = action },
                AccentColour = Color4.Orange,
                ColumnType = column % 2 == 0 ? ColumnType.Even : ColumnType.Odd
            };

            InternalChild = content = new ManiaInputManager(new ManiaRuleset().RulesetInfo, 4)
            {
                RelativeSizeAxes = Axes.Both
            };
        }
    }
}

Add odd/even type to test scenes

Add odd/even type to test scenes


using Machine.Specifications;

namespace Quarks.Tests
{
	[Subject(typeof(Inflector))]
	public class When_using_pluralize_for_count
	{
		It should_pluralize_when_count_is_greater_than_two = () =>
			"item".PluralizeForCount(2).ShouldEqual("items");

		It should_pluralize_when_count_is_zero = () =>
			"item".PluralizeForCount(0).ShouldEqual("items");

		It should_not_pluralize_when_count_is_one = () =>
			"item".PluralizeForCount(1).ShouldEqual("item");
	}
}

using Machine.Specifications;

namespace Quarks.Tests
{
	[Subject(typeof(Inflector))]
	class When_using_pluralize_for_count
	{
		It should_pluralize_when_count_is_greater_than_two = () =>
			"item".PluralizeForCount(2).ShouldEqual("items");

		It should_pluralize_when_count_is_zero = () =>
			"item".PluralizeForCount(0).ShouldEqual("items");

		It should_not_pluralize_when_count_is_one = () =>
			"item".PluralizeForCount(1).ShouldEqual("item");
	}
}

Remove "public" access modifier from test class


using System;
using System.Collections.Generic;

namespace Foundatio.Messaging {
    public interface IMessage {
        string Type { get; }
        Type ClrType { get; }
        byte[] Data { get; }
        object GetBody();
        IReadOnlyDictionary<string, string> Properties { get; }
    }

    public class Message : IMessage {
        private Lazy<object> _getBody;

        public Message(Func<object> getBody) {
            if (getBody == null)
                throw new ArgumentNullException("getBody");

            _getBody = new Lazy<object>(getBody);
        }

        public string Type { get; set; }
        public Type ClrType { get; set; }
        public byte[] Data { get; set; }
        public object GetBody() => _getBody.Value;
        public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
    }
}

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

namespace Foundatio.Messaging {
    public interface IMessage {
        string Type { get; }
        Type ClrType { get; }
        byte[] Data { get; }
        object GetBody();
        IReadOnlyDictionary<string, string> Properties { get; }
    }

    [DebuggerDisplay("Type: {Type}")]
    public class Message : IMessage {
        private Lazy<object> _getBody;

        public Message(Func<object> getBody) {
            if (getBody == null)
                throw new ArgumentNullException("getBody");

            _getBody = new Lazy<object>(getBody);
        }

        public string Type { get; set; }
        public Type ClrType { get; set; }
        public byte[] Data { get; set; }
        public object GetBody() => _getBody.Value;
        public IReadOnlyDictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
    }
}

Add message debugger display to show the message type


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

using UnityEngine;

namespace HoloToolkit.Unity
{
    /// <summary>
    /// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T>
    {
        private static T _Instance;
        public static T Instance
        {
            get
            {
                if (_Instance == null)
                {
                    T[] objects = Resources.FindObjectsOfTypeAll<T>();
                    if (objects.Length != 1)
                    {
                        Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length);
                    }
                    else
                    {
                        _Instance = objects[0];
                    }
                }
                return _Instance;
            }
        }

        /// <summary>
        /// Called by Unity when destroying a MonoBehaviour. Scripts that extend
        /// SingleInstance should be sure to call base.OnDestroy() to ensure the
        /// underlying static _Instance reference is properly cleaned up.
        /// </summary>
        protected virtual void OnDestroy()
        {
            _Instance = null;
        }
    }
}

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

using UnityEngine;

namespace HoloToolkit.Unity
{
    /// <summary>
    /// A simplified version of the Singleton class which doesn't depend on the Instance being set in Awake
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SingleInstance<T> : MonoBehaviour where T : SingleInstance<T>
    {
        private static T _Instance;
        public static T Instance
        {
            get
            {
                if (_Instance == null)
                {
                    T[] objects = FindObjectsOfType<T>();
                    if (objects.Length != 1)
                    {
                        Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}", typeof(T).ToString(), objects.Length);
                    }
                    else
                    {
                        _Instance = objects[0];
                    }
                }
                return _Instance;
            }
        }

        /// <summary>
        /// Called by Unity when destroying a MonoBehaviour. Scripts that extend
        /// SingleInstance should be sure to call base.OnDestroy() to ensure the
        /// underlying static _Instance reference is properly cleaned up.
        /// </summary>
        protected virtual void OnDestroy()
        {
            _Instance = null;
        }
    }
}

Revert "Instance isn't found if class is on a disabled GameObject."


// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Razor;

namespace Microsoft.VisualStudio.Editor.Razor
{
    [System.Composition.Shared]
    [ExportWorkspaceService(typeof(ProjectPathProvider), ServiceLayer.Default)]
    internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory
    {
        private readonly TextBufferProjectService _projectService;

        [ImportingConstructor]
        public DefaultProjectPathProviderFactory(TextBufferProjectService projectService)
        {
            if (projectService == null)
            {
                throw new ArgumentNullException(nameof(projectService));
            }

            _projectService = projectService;
        }

        public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
        {
            if (workspaceServices == null)
            {
                throw new ArgumentNullException(nameof(workspaceServices));
            }

            return new DefaultProjectPathProvider(_projectService);
        }
    }
}

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;

namespace Microsoft.VisualStudio.Editor.Razor
{
    [Shared]
    [ExportWorkspaceServiceFactory(typeof(ProjectPathProvider), ServiceLayer.Default)]
    internal class DefaultProjectPathProviderFactory : IWorkspaceServiceFactory
    {
        private readonly TextBufferProjectService _projectService;

        [ImportingConstructor]
        public DefaultProjectPathProviderFactory(TextBufferProjectService projectService)
        {
            if (projectService == null)
            {
                throw new ArgumentNullException(nameof(projectService));
            }

            _projectService = projectService;
        }

        public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
        {
            if (workspaceServices == null)
            {
                throw new ArgumentNullException(nameof(workspaceServices));
            }

            return new DefaultProjectPathProvider(_projectService);
        }
    }
}

Fix mef attributes project path provider


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

namespace DotNetOpen.PrerenderModule
{
    public static class Constants
    {
        #region Const
        public const string PrerenderIOServiceUrl = "http://service.prerender.io/";
        public const int DefaultPort = 80;
        public const string CrawlerUserAgentPattern = "(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)";

        public const string EscapedFragment = "_escaped_fragment_";
        public const string HttpProtocol = "http://";
        public const string HttpsProtocol = "https://";
        public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto";
        public const string HttpHeader_XPrerenderToken = "X-Prerender-Token";
        public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule";
        #endregion
    }
}

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

namespace DotNetOpen.PrerenderModule
{
    public static class Constants
    {
        #region Const
        public const string PrerenderIOServiceUrl = "http://service.prerender.io/";
        public const int DefaultPort = 80;
        public const string CrawlerUserAgentPattern = "(bingbot)|(googlebot)|(google)|(bing)|(Slurp)|(DuckDuckBot)|(YandexBot)|(baiduspider)|(Sogou)|(Exabot)|(ia_archiver)|(facebot)|(facebook)|(twitterbot)|(rogerbot)|(linkedinbot)|(embedly)|(quora)|(pinterest)|(slackbot)|(redditbot)|(Applebot)|(WhatsApp)|(flipboard)|(tumblr)|(bitlybot)|(Discordbot)";

        public const string EscapedFragment = "_escaped_fragment_";
        public const string HttpProtocol = "http://";
        public const string HttpsProtocol = "https://";
        public const string HttpHeader_XForwardedProto = "X-Forwarded-Proto";
        public const string HttpHeader_XPrerenderToken = "X-Prerender-Token";
        public const string AppSetting_UsePrestartForPrenderModule = "UsePrestartForPrenderModule";
        #endregion
    }
}

Add googlebot and bingbot to list of crawler user agents

Prerender.io docs recommend to upgrade these:
https://prerender.io/documentation/google-support

>>>Make sure to update your Prerender.io middleware or manually add googlebot and bingbot to the list of user agents being checked by your Prerender.io middleware. See the bottom of this page for examples on adding googlebot to your middleware.

There have been some reported issues with Googlebot rendering JavaScript on the first request to a URL that still uses the ?_escaped_fragment_= protocol, so upgrading will prevent any issues by serving a prerendered page directly to Googlebot on the first request.


using System;

namespace Mitternacht.Modules.Verification.Exceptions {
	public class UserAlreadyVerifyingException : Exception {}
	public class UserAlreadyVerifiedException : Exception {}
	public class UserCannotVerifyException : Exception { }
	//public class Exception : Exception { }
}

using System;

namespace Mitternacht.Modules.Verification.Exceptions {
	public class UserAlreadyVerifyingException : Exception { }
	public class UserAlreadyVerifiedException : Exception { }
	public class UserCannotVerifyException : Exception { }
}

Remove unnecessary comment and format file.


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
		@Styles.Render("~/Content/bootstrap.min.css")
	</head>
    <body>
        <div>
            @RenderBody()
        </div>
		@RenderSection("Scripts", false)
	</body>
</html>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/bootstrap.min.css")
        @Styles.Render("~/Content/bootstrap-responsive.min.css")
        @Styles.Render("~/bundles/font-awesome")

        <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
        <!--[if lt IE 9]>
          <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->

        @Scripts.Render("~/bundles/jquery")

        @Scripts.Render("~/bundles/modernizr")
        @Scripts.Render("~/bundles/knockout")

        <script type="text/javascript">
            Modernizr.load({
                test: Modernizr.input.placeholder,
                nope: '/scripts/placeholder.js'
            });

            Modernizr.load({
                test: Modernizr.inputtypes.date,
                nope: '/scripts/datepicker.js'
            });
        </script>
    </head>
    <body>
        <div>
            @RenderBody()
        </div>
        @RenderSection("Scripts", false)
    </body>
</html>

Add styles and scripts to admin Layout.

Add styles and scripts to admin Layout.

Bootstrap responsive stylesheet, plus jQuery, Modernizr, HTML5 shim, and
Knockout.


using System.Reflection;

[assembly: AssemblyCompany("Yin-Chun Wang")]
[assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")]

[assembly: AssemblyVersion(_ModernWPFVersionString.Release)]
[assembly: AssemblyFileVersion(_ModernWPFVersionString.Build)]
[assembly: AssemblyInformationalVersion(_ModernWPFVersionString.Build)]

static class _ModernWPFVersionString
{
    // keep this same in majors releases
    public const string Release = "1.0.0.0";
    // change this for each nuget release
    public const string Build = "1.1.30";
}

using System.Reflection;

[assembly: AssemblyCompany("Yin-Chun Wang")]
[assembly: AssemblyCopyright("Copyright © Yin-Chun Wang 2014")]

[assembly: AssemblyVersion(ModernWPF._ModernWPFVersionString.Release)]
[assembly: AssemblyFileVersion(ModernWPF._ModernWPFVersionString.Build)]
[assembly: AssemblyInformationalVersion(ModernWPF._ModernWPFVersionString.Build)]

namespace ModernWPF
{
    static class _ModernWPFVersionString
    {
        // keep this same in majors releases
        public const string Release = "1.0.0.0";
        // change this for each nuget release
        public const string Build = "1.1.30";
    }
}

Put version info class under namespace.

Put version info class under namespace.


using Devkoes.JenkinsManager.Model.Contract;
using Devkoes.JenkinsManager.UI;
using Devkoes.JenkinsManager.UI.Views;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;

namespace Devkoes.JenkinsManager.VSPackage.ExposedServices
{
    public class VisualStudioWindowHandler : IVisualStudioWindowHandler
    {
        public void ShowToolWindow()
        {
            // Get the instance number 0 of this tool window. This window is single instance so this instance
            // is actually the only one.
            // The last flag is set to true so that if the tool window does not exists it will be created.
            ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true);
            if ((null == window) || (null == window.Frame))
            {
                throw new NotSupportedException(Resources.CanNotCreateWindow);
            }
            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
        }

        public void ShowSettingsWindow()
        {
            try
            {
                VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost));
            }
            catch (Exception ex)
            {
                ServicesContainer.OutputWindowLogger.LogOutput("Showing settings panel failed:", ex);
            }
        }
    }
}

using Devkoes.JenkinsManager.Model.Contract;
using Devkoes.JenkinsManager.UI;
using Devkoes.JenkinsManager.UI.Views;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;

namespace Devkoes.JenkinsManager.VSPackage.ExposedServices
{
    public class VisualStudioWindowHandler : IVisualStudioWindowHandler
    {
        public void ShowToolWindow()
        {
            // Get the instance number 0 of this tool window. This window is single instance so this instance
            // is actually the only one.
            // The last flag is set to true so that if the tool window does not exists it will be created.
            ToolWindowPane window = VSJenkinsManagerPackage.Instance.FindToolWindow(typeof(JenkinsToolWindow), 0, true);
            if ((null == window) || (null == window.Frame))
            {
                throw new NotSupportedException(Resources.CanNotCreateWindow);
            }
            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
        }

        public void ShowSettingsWindow()
        {
            try
            {
                VSJenkinsManagerPackage.Instance.ShowOptionPage(typeof(UserOptionsHost));
            }
            catch (Exception ex)
            {
                ServicesContainer.OutputWindowLogger.LogOutput(
                    "Showing settings panel failed:",
                    ex.ToString());
            }
        }
    }
}

Revert "Logging has new overload for exceptions, use it"

This reverts commit 2fe8666247d45c289a6a2ca4fb716f0d25d756f1.


using UnityEngine;

namespace PJEI.Invaders {

    public class Level : MonoBehaviour {
        public Alien[] lines;
        public int width = 11;
        public int pixelsBetweenAliens = 48;

        private Alien[] aliens;

        void Start() {
            StartCoroutine(InitGame());
        }

        private System.Collections.IEnumerator InitGame() {
            aliens = new Alien[lines.Length * width];
            for (int i = lines.Length - 1; i >= 0; --i) {
                for (int j = 0; j < width; ++j) {
                    var alien = (Alien)Instantiate(lines[i]);
                    alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens);

                    aliens[i * width + j] = alien;

                    yield return new WaitForSeconds(.1f);
                }
            }

            foreach (var alien in aliens)
                alien.Run();
        }
    }

}

using UnityEngine;

namespace PJEI.Invaders {

    public class Level : MonoBehaviour {
        public Alien[] lines;
        public int width = 11;
        public int pixelsBetweenAliens = 48;

        private Alien[] aliens;

        void Start() {
            StartCoroutine(InitGame());
        }

        private System.Collections.IEnumerator InitGame() {
            aliens = new Alien[lines.Length * width];
            for (int i = lines.Length - 1; i >= 0; --i) {
                for (int j = 0; j < width; ++j) {
                    var alien = (Alien)Instantiate(lines[i]);
                    alien.Initialize(new Vector2D(j - width / 2, -i + lines.Length / 2), i, pixelsBetweenAliens);

                    aliens[i * width + j] = alien;

                    yield return new WaitForSeconds(.05f);
                }
            }

            foreach (var alien in aliens)
                alien.Run();
        }
    }

}

Speed up alien start up positioning.

Speed up alien start up positioning.


using System;
using NUnit.Framework;

namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests
{
    internal sealed class AuthorizeUser : Base
    {
        [Test]
        public void CanAuthorizeUser()
        {
            const string email = "test@cronofy.com";
            const string callbackUrl = "https://cronofy.com/test-callback";
            const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy";

            Http.Stub(
                HttpPost
                .Url("https://api.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"" +
                    "}}",
                    email,
                    callbackUrl,
                    scopes)
                .ResponseCode(202)
            );

            Client.AuthorizeUser(email, callbackUrl, scopes);
        }
    }
}

using System;
using NUnit.Framework;

namespace Cronofy.Test.CronofyEnterpriseConnectAccountClientTests
{
    internal sealed class AuthorizeUser : Base
    {
        [Test]
        public void CanAuthorizeUser()
        {
            const string email = "test@cronofy.com";
            const string callbackUrl = "https://cronofy.com/test-callback";
            const string scopes = "read_account list_calendars read_events create_event delete_event read_free_busy";

            Http.Stub(
                HttpPost
                .Url("https://api.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"" +
                    "}}",
                    email,
                    callbackUrl,
                    scopes)
                .ResponseCode(202)
            );

            Client.AuthorizeUser(email, callbackUrl, scopes);
        }

        [Test]
        public void CanAuthorizeUserWithEnumerableScopes()
        {
            const string email = "test@test.com";
            const string callbackUrl = "https://test.com/test-callback";
            string[] scopes = { "read_account", "list_calendars", "read_events", "create_event", "delete_event", "read_free_busy" };

            Http.Stub(
                HttpPost
                .Url("https://api.cronofy.com/v1/service_account_authorizations")
                .RequestHeader("Authorization", "Bearer " + AccessToken)
                .RequestHeader("Content-Type", "application/json; charset=utf-8")
                .RequestBodyFormat(
                    "{{\"email\":\"{0}\"," +
                    "\"callback_url\":\"{1}\"," +
                    "\"scope\":\"{2}\"" +
                    "}}",
                    email,
                    callbackUrl,
                    String.Join(" ", scopes))
                .ResponseCode(202)
            );

            Client.AuthorizeUser(email, callbackUrl, scopes);
        }
    }
}

Add test for Enterprise Connect Authorize User with enumerable string


using System;
using Mongo.Migration.Documents;
using Mongo.Migration.Documents.Serializers;
using Mongo.Migration.Services.Interceptors;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;

namespace Mongo.Migration.Services.MongoDB
{
    internal class MongoRegistrator : IMongoRegistrator
    {
        private readonly MigrationInterceptorProvider _provider;

        private readonly DocumentVersionSerializer _serializer;

        public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider)
        {
            _serializer = serializer;
            _provider = provider;
        }

        public void Register()
        {
            BsonSerializer.RegisterSerializationProvider(_provider);

            try
            {
                BsonSerializer.RegisterSerializer(typeof(DocumentVersion), _serializer);
            }
            catch (BsonSerializationException Exception)
            {
                // Catch if Serializer was registered already, not great. But for testing it must be catched.
            }
        }
    }
}

using System;
using Mongo.Migration.Documents;
using Mongo.Migration.Documents.Serializers;
using Mongo.Migration.Services.Interceptors;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;

namespace Mongo.Migration.Services.MongoDB
{
    internal class MongoRegistrator : IMongoRegistrator
    {
        private readonly MigrationInterceptorProvider _provider;

        private readonly DocumentVersionSerializer _serializer;

        public MongoRegistrator(DocumentVersionSerializer serializer, MigrationInterceptorProvider provider)
        {
            _serializer = serializer;
            _provider = provider;
        }

        public void Register()
        {
            RegisterSerializationProvider();
            RegisterSerializer();
        }

        private void RegisterSerializationProvider()
        {
            BsonSerializer.RegisterSerializationProvider(_provider);
        }

        private void RegisterSerializer()
        {
            var foundSerializer = BsonSerializer.LookupSerializer(_serializer.ValueType);

            if (foundSerializer == null)
                BsonSerializer.RegisterSerializer(_serializer.ValueType, _serializer);
        }
    }
}

Use lookup before registering serializer


using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;

namespace Propeller.Mvc.Model.Adapters
{
    public class Image : IFieldAdapter
    {
        public string Url { get; set; }
        public string Alt { get; set; }

        public void InitAdapter(Item item, ID propId)
        {
            ImageField image = item.Fields[propId];
            if (image == null)
                return;
            var mediaItem = image.MediaDatabase.GetItem(image.MediaID);
            Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
            Alt = image.Alt;

        }
    }
}

using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;

namespace Propeller.Mvc.Model.Adapters
{
    public class Image : IFieldAdapter
    {
        public string Url { get; set; }
        public string Alt { get; set; }

        public void InitAdapter(Item item, ID propId)
        {
            Url = string.Empty;
            Alt = string.Empty;

            ImageField image = item.Fields[propId];
            if (image == null ||image.MediaID == ItemIDs.Null)
                return;

            var mediaItem = image.MediaDatabase.GetItem(image.MediaID);
            Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
            Alt = image.Alt;

        }
    }
}

Fix problem with image adapter when an item has empty standard values.


using System.ComponentModel.DataAnnotations;
using System;
using asp_net_mvc_localization.Utils;
using Newtonsoft.Json.Serialization;

namespace asp_net_mvc_localization.Models
{
    public class User
    {
        [Required]
        public string Username { get; set; }

        [Display]
        [Required]
        [MyEmailAddress]
        public string Email { get; set; }

        [Display]
        [Required]
        [MinLength(6)]
        [MaxLength(64)]
        public string Password { get; set; }

        [Display]
        [Range(1,125)]
        public int Age { get; set; }

        [Display]
        public DateTime Birthday { get; set; }

        [Display]
        [Required]
        [Range(0.1, 9.9)]
        public double Rand { get; set; }
    }
}

using System.ComponentModel.DataAnnotations;
using System;
using asp_net_mvc_localization.Utils;
using Newtonsoft.Json.Serialization;

namespace asp_net_mvc_localization.Models
{
    public class User
    {
        [Required]
        public string Username { get; set; }

        [Required]
        [MyEmailAddress]
        public string Email { get; set; }

        [Required]
        [MinLength(6)]
        [MaxLength(64)]
        public string Password { get; set; }

        [Range(1,125)]
        public int Age { get; set; }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public DateTime Birthday { get; set; }

        [Required]
        [Range(0.1, 9.9)]
        public double Rand { get; set; }
    }
}

Delete [Display](all work's without it), fix Date format in Create


using System.Linq;

using JabbR.Services;

using Nancy;
using Nancy.ErrorHandling;
using Nancy.ViewEngines;

namespace JabbR.Nancy
{
    public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler
    {
        private readonly IJabbrRepository _repository;

        public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository)
            : base(factory)
        {
            _repository = repository;
        }

        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
        {
            // only handle 40x and 50x
            return (int)statusCode >= 400;
        }

        public void Handle(HttpStatusCode statusCode, NancyContext context)
        {
            string suggestRoomName = null;
            if (statusCode == HttpStatusCode.NotFound &&
                context.Request.Url.Path.Count(e => e == '/') == 1)
            {
                // trim / from start of path
                var potentialRoomName = context.Request.Url.Path.Substring(1);
                if (_repository.GetRoomByName(potentialRoomName) != null)
                {
                    suggestRoomName = potentialRoomName;
                }
            }

            var response = RenderView(
                context,
                "errorPage",
                new
                {
                    Error = statusCode,
                    ErrorCode = (int)statusCode,
                    SuggestRoomName = suggestRoomName
                });

            response.StatusCode = statusCode;
            context.Response = response;
        }
    }
}

using System.Text.RegularExpressions;

using JabbR.Services;

using Nancy;
using Nancy.ErrorHandling;
using Nancy.ViewEngines;

namespace JabbR.Nancy
{
    public class ErrorPageHandler : DefaultViewRenderer, IStatusCodeHandler
    {
        private readonly IJabbrRepository _repository;

        public ErrorPageHandler(IViewFactory factory, IJabbrRepository repository)
            : base(factory)
        {
            _repository = repository;
        }

        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)
        {
            // only handle 40x and 50x
            return (int)statusCode >= 400;
        }

        public void Handle(HttpStatusCode statusCode, NancyContext context)
        {
            string suggestRoomName = null;
            if (statusCode == HttpStatusCode.NotFound)
            {
                var match = Regex.Match(context.Request.Url.Path, "^/(rooms/)?(?<roomName>[^/]+)$", RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    var potentialRoomName = match.Groups["roomName"].Value;
                    if (_repository.GetRoomByName(potentialRoomName) != null)
                    {
                        suggestRoomName = potentialRoomName;
                    }
                }
            }

            var response = RenderView(
                context,
                "errorPage",
                new
                {
                    Error = statusCode,
                    ErrorCode = (int)statusCode,
                    SuggestRoomName = suggestRoomName
                });

            response.StatusCode = statusCode;
            context.Response = response;
        }
    }
}

Support 404 url suggestions for /rooms/xyz in addition to /xyz.


@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>

@{
    Layout = "razor-layout.cshtml";
}

You're here based on ther German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>

@{
    Layout = "razor-layout.cshtml";
}

You're here based on the German culture set in HomeModule however the HomeModule only calls return View["CultureView"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml

Fix typo on CultureView-de-De in Localization Demo


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

using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickNETTests
    {
        public class TheFeaturesProperty
        {
            [Fact]
            public void ContainsExpectedFeatures()
            {
                var expected = "Cipher DPC ";
#if Q16HDRI
                expected += "HDRI ";
#endif
#if WINDOWS_BUILD
                expected += "OpenCL ";
#endif
#if OPENMP
                expected += "OpenMP(2.0) ";
#endif
#if DEBUG_TEST
                expected = "Debug " + expected;
#endif

                Assert.Equal(expected, MagickNET.Features);
            }
        }
    }
}

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

using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickNETTests
    {
        public class TheFeaturesProperty
        {
            [Fact]
            public void ContainsExpectedFeatures()
            {
                var expected = "Cipher DPC ";
#if Q16HDRI
                expected += "HDRI ";
#endif
                if (OperatingSystem.IsWindows)
                    expected += "OpenCL ";
#if OPENMP
                expected += "OpenMP(2.0) ";
#endif
#if DEBUG_TEST
                expected = "Debug " + expected;
#endif

                Assert.Equal(expected, MagickNET.Features);
            }
        }
    }
}

Use the new OperatingSystem class.

Use the new OperatingSystem class.


using NUnit.Framework;
using RestSharp;

namespace TempoDB.Tests
{
    [TestFixture]
    public class TempoDBTests
    {
        [Test]
        public void Defaults()
        {
            var tempodb = new TempoDB("key", "secret");
            Assert.AreEqual("key", tempodb.Key);
            Assert.AreEqual("secret", tempodb.Secret);
            Assert.AreEqual("api.tempo-db.com", tempodb.Host);
            Assert.AreEqual(443, tempodb.Port);
            Assert.AreEqual(true, tempodb.Secure);
            Assert.AreEqual("v1", tempodb.Version);
            Assert.AreNotEqual(null, tempodb.Client);
            Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client);
        }
    }
}

using NUnit.Framework;
using RestSharp;

namespace TempoDB.Tests
{
    [TestFixture]
    public class TempoDBTests
    {
        [Test]
        public void Defaults()
        {
            var tempodb = new TempoDB("key", "secret");
            Assert.AreEqual("key", tempodb.Key);
            Assert.AreEqual("secret", tempodb.Secret);
            Assert.AreEqual("api.tempo-db.com", tempodb.Host);
            Assert.AreEqual(443, tempodb.Port);
            Assert.AreEqual(true, tempodb.Secure);
            Assert.AreEqual("v1", tempodb.Version);
            Assert.IsNotNull(tempodb.Client);
            Assert.IsInstanceOfType(typeof(RestClient), tempodb.Client);
        }
    }
}

Use the correct assertion for testing null


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

namespace StorageAzure.Tests
{
    [TestClass()]
    public class BlobTests
    {
        public Boolean Exist(string fileName)
        {
            var container = new BlobContanier().Create();
            var blob = container.GetBlockBlobReference(fileName);

            return blob.Exists();
        }

        [TestMethod()]
        public void BlobPut()
        {
            var blob = new Blob();
            var objeto = File.OpenRead(@"..\..\20160514_195832.jpg");
            var fileName = Path.GetFileName(objeto.Name);

            blob.Put(objeto);
            objeto.Close();

            Assert.IsTrue(Exist(fileName));
        }
        [TestMethod()]
        public void BlobGet()
        {
            var blob = new Blob();
            var fileName = "20160514_195832.jpg";

            var fichero = blob.Get(fileName);

            Assert.IsNotNull(fichero);
            Assert.IsTrue(fichero.Length > 0);
        }
        [TestMethod()]
        public void BlobDelete()
        {
            var blob = new Blob();
            var fileName = "20160514_195832.jpg";

            blob.Delete(fileName);

            Assert.IsFalse(Exist(fileName));
        }
    }
}

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

namespace StorageAzure.Tests
{
    [TestClass()]
    public class BlobTests
    {
        public Boolean Exist(string fileName)
        {
            var container = new BlobContanier().Create();
            var blob = container.GetBlockBlobReference(fileName);

            return blob.Exists();
        }

        [TestMethod()]
        public void BlobPut()
        {
            var blob = new Blob();
            var objeto = File.OpenRead(@"..\..\20160514_195832.jpg");
            var fileName = Path.GetFileName(objeto.Name);

            blob.Put(objeto);
            objeto.Close();

            Assert.IsTrue(Exist(fileName));
        }
        [TestMethod()]
        public void BlobPut_Fichero_de_55_Mb()
        {
            var blob = new Blob();
            var objeto = File.OpenRead(@"..\..\20160512_194750.mp4");
            var fileName = Path.GetFileName(objeto.Name);

            blob.Put(objeto);
            objeto.Close();

            Assert.IsTrue(Exist(fileName));
        }
        [TestMethod()]
        public void BlobGet()
        {
            var blob = new Blob();
            var fileName = "20160514_195832.jpg";

            var fichero = blob.Get(fileName);

            Assert.IsNotNull(fichero);
            Assert.IsTrue(fichero.Length > 0);
        }
        [TestMethod()]
        public void BlobDelete()
        {
            var blob = new Blob();
            var fileName = "20160514_195832.jpg";

            blob.Delete(fileName);

            Assert.IsFalse(Exist(fileName));
        }
    }
}

Test para comprobar qeu soporta ficheros de 55Mb.

Related Work Items: #44


namespace SkypeSharp {
    public enum UserStatus {
        OnlineStatus,
        BuddyStatus,
        ReceivedAuthRequest
    }

    public interface IUser : ISkypeObject {
        string FullName { get; }
        string Language { get; }
        string Country { get; }
        string City { get; }

        void Authorize();
    }
}

namespace SkypeSharp {
    public enum UserStatus {
        OnlineStatus,
        BuddyStatus,
        ReceivedAuthRequest,
        IsAuthorized,
        IsBlocked,
        Timezone,
        NROF_AUTHED_BUDDIES
    }

    public interface IUser : ISkypeObject {
        string FullName { get; }
        string Language { get; }
        string Country { get; }
        string City { get; }

        void Authorize();
    }
}

Add some missing user statuses

Add some missing user statuses


using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.FileSystem.FileSystemTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;

// ReSharper disable CheckNamespace
class DefaultBuild : GitHubBuild
{
    public static void Main () => Execute<DefaultBuild> (x => x.Compile);

    Target Restore => _ => _
            .Executes (() =>
            {
                if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
                    MSBuild (s => DefaultSettings.MSBuildRestore);
                else
                    NuGetRestore (SolutionFile);
            });

    Target Compile => _ => _
            .DependsOn (Restore)
            .Executes (() => MSBuild (s => DefaultSettings.MSBuildCompile
                    .SetMSBuildVersion (MSBuildVersion)));

    MSBuildVersion? MSBuildVersion =>
            !IsUnix
                ? GlobFiles (SolutionDirectory, "*.xproj").Any ()
                    ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
                    : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
                : default (MSBuildVersion);
}

using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.FileSystem.FileSystemTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;

class DefaultBuild : GitHubBuild
{
    public static void Main () => Execute<DefaultBuild>(x => x.Compile);

    Target Restore => _ => _
            .Executes(() =>
            {
                NuGetRestore(SolutionFile);

                if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
                    MSBuild(s => DefaultSettings.MSBuildRestore);
            });

    Target Compile => _ => _
            .DependsOn(Restore)
            .Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
                    .SetMSBuildVersion(MSBuildVersion)));

    MSBuildVersion? MSBuildVersion =>
            !IsUnix
                ? GlobFiles(SolutionDirectory, "*.xproj").Any()
                    ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
                    : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
                : default(MSBuildVersion);
}

Change NuGetRestore to be executed unconditionally.


using System;
using Cake.Core.IO;

namespace Cake.Core.Scripting.Processors
{
    /// <summary>
    /// Processor for using statements.
    /// </summary>
    public sealed class UsingStatementProcessor : LineProcessor
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class.
        /// </summary>
        /// <param name="environment">The environment.</param>
        public UsingStatementProcessor(ICakeEnvironment environment)
            : base(environment)
        {
        }

        /// <summary>
        /// Processes the specified line.
        /// </summary>
        /// <param name="processor">The script processor.</param>
        /// <param name="context">The script processor context.</param>
        /// <param name="currentScriptPath">The current script path.</param>
        /// <param name="line">The line to process.</param>
        /// <returns>
        ///   <c>true</c> if the processor handled the line; otherwise <c>false</c>.
        /// </returns>
        public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var tokens = Split(line);
            if (tokens.Length <= 0)
            {
                return false;
            }

            if (!tokens[0].Equals("using", StringComparison.Ordinal))
            {
                return false;
            }

            var @namespace = tokens[1].TrimEnd(';');
            context.AddNamespace(@namespace);

            return true;
        }
    }
}

using System;
using Cake.Core.IO;

namespace Cake.Core.Scripting.Processors
{
    /// <summary>
    /// Processor for using statements.
    /// </summary>
    public sealed class UsingStatementProcessor : LineProcessor
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class.
        /// </summary>
        /// <param name="environment">The environment.</param>
        public UsingStatementProcessor(ICakeEnvironment environment)
            : base(environment)
        {
        }

        /// <summary>
        /// Processes the specified line.
        /// </summary>
        /// <param name="processor">The script processor.</param>
        /// <param name="context">The script processor context.</param>
        /// <param name="currentScriptPath">The current script path.</param>
        /// <param name="line">The line to process.</param>
        /// <returns>
        ///   <c>true</c> if the processor handled the line; otherwise <c>false</c>.
        /// </returns>
        public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var tokens = Split(line);
            if (tokens.Length <= 1)
            {
                return false;
            }

            if (!tokens[0].Equals("using", StringComparison.Ordinal))
            {
                return false;
            }

            var @namespace = tokens[1].TrimEnd(';');

            if (@namespace.StartsWith("("))
            {
                return false;
            }

            context.AddNamespace(@namespace);

            return true;
        }
    }
}

Fix for using (IDisposable) statement

Fix for using (IDisposable) statement


using System;
using System.Threading;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using PacManGame;

namespace PacManGameTests
{
    [TestFixture]
    public class GameTimerTest
    {

        [Test]
        public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1()
        {
            //Arrange
            Board b = new Board(3, 4);
            ITimer gameTimer = new GameTimer(500);
            GameController gameController = new GameController(b, gameTimer);
            gameTimer.Start();

            //Act
            Thread.Sleep(TimeSpan.FromMilliseconds(600));

            // Assert
            b.PacMan.Position.Should().Be(new Position(1, 1));
        }

        [Test]
        public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled()
        {
            //Arrange
            ITickable boardMock = Mock.Of<ITickable>();
            FakeTimer timer = new FakeTimer();
            GameController gameController = new GameController(boardMock, timer);

            //Act
            timer.OnElapsed();

            //Assert
            Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once);
        }
    }

    public class FakeTimer : ITimer
    {
        public event EventHandler Elapsed;
        public void Start()
        {
            throw new NotImplementedException();
        }

        public void OnElapsed()
        {
            if (Elapsed != null)
            {
                Elapsed(this, new EventArgs());
            }
        }
    }
}

using System;
using System.Threading;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using PacManGame;

namespace PacManGameTests
{
    [TestFixture]
    public class GameTimerTest
    {

        [Test]
        public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1()
        {
            //Arrange
            Board b = new Board(3, 4);
            ITimer gameTimer = new GameTimer(500);
            GameController gameController = new GameController(b, gameTimer);
            gameTimer.Start();

            //Act
            Thread.Sleep(TimeSpan.FromMilliseconds(600));

            // Assert
            b.PacMan.Position.Should().Be(new Position(1, 1));
        }

        [Test]
        public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled()
        {
            //Arrange
            ITickable boardMock = Mock.Of<ITickable>();
            ITimer timerMock = Mock.Of<ITimer>();
            GameController gameController = new GameController(boardMock, timerMock);

            //Act
            Mock.Get(timerMock).Raise(t => t.Elapsed += null, new EventArgs());

            //Assert
            Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once);
        }
    }
}

Use a stub of ITimer instead of an actual implementation


using CommandLineParser.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LSTools.DebuggerFrontend
{
    class Program
    {
        static void Main(string[] args)
        {
            var logFile = new FileStream(@"C:\Dev\DOS\LS\LsLib\DebuggerFrontend\bin\Debug\DAP.log", FileMode.Create);
            var dap = new DAPStream();
            dap.EnableLogging(logFile);
            var dapHandler = new DAPMessageHandler(dap);
            dapHandler.EnableLogging(logFile);
            try
            {
                dap.RunLoop();
            }
            catch (Exception e)
            {
                using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true))
                {
                    writer.Write(e.ToString());
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }
}

using CommandLineParser.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LSTools.DebuggerFrontend
{
    class Program
    {
        static void Main(string[] args)
        {
            var currentPath = AppDomain.CurrentDomain.BaseDirectory;
            var logFile = new FileStream(currentPath + "\\DAP.log", FileMode.Create);
            var dap = new DAPStream();
            dap.EnableLogging(logFile);
            var dapHandler = new DAPMessageHandler(dap);
            dapHandler.EnableLogging(logFile);
            try
            {
                dap.RunLoop();
            }
            catch (Exception e)
            {
                using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true))
                {
                    writer.Write(e.ToString());
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }
}

Fix hardcoded DAP log path

Fix hardcoded DAP log path


using System;
using Eto.Forms;
using Eto.Drawing;

namespace Eto.Platform.GtkSharp
{
	public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout
	{
		public PixelLayoutHandler()
		{
			Control = new Gtk.Fixed();
		}

		public void Add(Control child, int x, int y)
		{
			IGtkControl ctl = ((IGtkControl)child.Handler);
			var gtkcontrol = (Gtk.Widget)child.ControlObject;
			Control.Put(gtkcontrol, x, y);
			ctl.Location = new Point(x, y);
			gtkcontrol.ShowAll();
		}

		public void Move(Control child, int x, int y)
		{
			IGtkControl ctl = ((IGtkControl)child.Handler);
			if (ctl.Location.X != x || ctl.Location.Y != y)
			{
				Control.Move (child.GetContainerWidget (), x, y);

				ctl.Location = new Point(x, y);
			}
		}

		public void Remove(Control child)
		{
			Control.Remove (child.GetContainerWidget ());
		}

	}
}

using System;
using Eto.Forms;
using Eto.Drawing;

namespace Eto.Platform.GtkSharp
{
	public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout
	{
		public PixelLayoutHandler ()
		{
			Control = new Gtk.Fixed ();
		}

		public void Add (Control child, int x, int y)
		{
			var ctl = ((IGtkControl)child.Handler);

			var gtkcontrol = child.GetContainerWidget ();
			Control.Put (gtkcontrol, x, y);
			ctl.Location = new Point (x, y);
			if (this.Control.Visible)
				gtkcontrol.ShowAll ();
		}

		public void Move (Control child, int x, int y)
		{
			var ctl = ((IGtkControl)child.Handler);
			if (ctl.Location.X != x || ctl.Location.Y != y) {
				Control.Move (child.GetContainerWidget (), x, y);

				ctl.Location = new Point (x, y);
			}
		}

		public void Remove (Control child)
		{
			Control.Remove (child.GetContainerWidget ());
		}
	}
}

Gtk: Fix adding controls to PixelLayout with a different container object


namespace WizardFramework.HTML
{
    partial class HtmlWizardPage<TM>
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.webView = new System.Windows.Forms.WebBrowser();
            this.SuspendLayout();
            //
            // webView
            //
            this.webView.AllowNavigation = false;
            this.webView.AllowWebBrowserDrop = false;
            this.webView.Dock = System.Windows.Forms.DockStyle.Fill;
            this.webView.IsWebBrowserContextMenuEnabled = true;
            this.webView.Location = new System.Drawing.Point(0, 0);
            this.webView.MinimumSize = new System.Drawing.Size(20, 20);
            this.webView.Name = "webView";
            this.webView.Size = new System.Drawing.Size(150, 150);
            this.webView.TabIndex = 0;
            this.webView.WebBrowserShortcutsEnabled = true;
            //
            // HtmlWizardPage
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.Controls.Add(this.webView);
            this.Name = "HtmlWizardPage";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.WebBrowser webView;
    }
}

namespace WizardFramework.HTML
{
    partial class HtmlWizardPage<TM>
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.webView = new System.Windows.Forms.WebBrowser();
            this.SuspendLayout();
            //
            // webView
            //
            this.webView.AllowNavigation = false;
            this.webView.AllowWebBrowserDrop = false;
            this.webView.Dock = System.Windows.Forms.DockStyle.Fill;
            this.webView.IsWebBrowserContextMenuEnabled = false;
            this.webView.Location = new System.Drawing.Point(0, 0);
            this.webView.MinimumSize = new System.Drawing.Size(20, 20);
            this.webView.Name = "webView";
            this.webView.Size = new System.Drawing.Size(150, 150);
            this.webView.TabIndex = 0;
            this.webView.WebBrowserShortcutsEnabled = false;
            //
            // HtmlWizardPage
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.Controls.Add(this.webView);
            this.Name = "HtmlWizardPage";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.WebBrowser webView;
    }
}

Disable shortcuts and ContextMenu in web browser control.


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

namespace Azuria.Community
{
    ///
    ///
    public class MessageEnumerable : IEnumerable<Message>
    {
        private readonly int _conferenceId;
        private readonly bool _markAsRead;
        private readonly Senpai _senpai;

        internal MessageEnumerable(int conferenceId, Senpai senpai, bool markAsRead = true)
        {
            this._conferenceId = conferenceId;
            this._senpai = senpai;
            this._markAsRead = markAsRead;
        }

        #region Methods

        /// Returns an enumerator that iterates through a collection.
        /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        /// Returns an enumerator that iterates through the collection.
        /// <returns>An enumerator that can be used to iterate through the collection.</returns>
        public IEnumerator<Message> GetEnumerator()
        {
            return new MessageEnumerator(this._conferenceId, this._markAsRead, this._senpai);
        }

        #endregion
    }
}

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

namespace Azuria.Community
{
    ///
    ///
    public class MessageEnumerable : IEnumerable<Message>
    {
        private readonly int _conferenceId;
        private readonly Senpai _senpai;

        internal MessageEnumerable(int conferenceId, Senpai senpai, bool markAsRead = true)
        {
            this._conferenceId = conferenceId;
            this._senpai = senpai;
            this.MarkAsRead = markAsRead;
        }

        #region Properties

        ///
        ///
        public bool MarkAsRead { get; set; }

        #endregion

        #region Methods

        /// Returns an enumerator that iterates through a collection.
        /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        /// Returns an enumerator that iterates through the collection.
        /// <returns>An enumerator that can be used to iterate through the collection.</returns>
        public IEnumerator<Message> GetEnumerator()
        {
            return new MessageEnumerator(this._conferenceId, this.MarkAsRead, this._senpai);
        }

        #endregion
    }
}

Add property to whether mark new Messages as read or not


using System;

namespace Avalonia.Styling
{
    public class Styler : IStyler
    {
        public void ApplyStyles(IStyleable target)
        {
            _ = target ?? throw new ArgumentNullException(nameof(target));

            // If the control has a themed templated parent then first apply the styles from
            // the templated parent theme.
            if (target.TemplatedParent is IStyleable styleableParent)
                styleableParent.GetEffectiveTheme()?.TryAttach(target, styleableParent);

            // Next apply the control theme.
            target.GetEffectiveTheme()?.TryAttach(target, target);

            // Apply styles from the rest of the tree.
            if (target is IStyleHost styleHost)
                ApplyStyles(target, styleHost);
        }

        private void ApplyStyles(IStyleable target, IStyleHost host)
        {
            var parent = host.StylingParent;

            if (parent != null)
                ApplyStyles(target, parent);

            if (host.IsStylesInitialized)
                host.Styles.TryAttach(target, host);
        }
    }
}

using System;

namespace Avalonia.Styling
{
    public class Styler : IStyler
    {
        public void ApplyStyles(IStyleable target)
        {
            _ = target ?? throw new ArgumentNullException(nameof(target));

            // Apply the control theme.
            target.GetEffectiveTheme()?.TryAttach(target, target);

            // If the control has a themed templated parent then apply the styles from the
            // templated parent theme.
            if (target.TemplatedParent is IStyleable styleableParent)
                styleableParent.GetEffectiveTheme()?.TryAttach(target, styleableParent);

            // Apply styles from the rest of the tree.
            if (target is IStyleHost styleHost)
                ApplyStyles(target, styleHost);
        }

        private void ApplyStyles(IStyleable target, IStyleHost host)
        {
            var parent = host.StylingParent;

            if (parent != null)
                ApplyStyles(target, parent);

            if (host.IsStylesInitialized)
                host.Styles.TryAttach(target, host);
        }
    }
}

Apply own control theme before templated parent's.


using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ZobShop.Models
{
    public class ProductRating
    {
        public ProductRating(int rating, string content, int productId, User author)
        {
            this.Rating = rating;
            this.Content = content;
            this.ProductId = productId;
            this.Author = author;
        }

        [Key]
        public int ProductRatingId { get; set; }

        public int Rating { get; set; }

        public string Content { get; set; }

        public int ProductId { get; set; }

        [ForeignKey("ProductId")]
        public virtual Product Product { get; set; }

        [ForeignKey("Author")]
        public string AuthorId { get; set; }

        [ForeignKey("Id")]
        public virtual User Author { get; set; }
    }
}

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ZobShop.Models
{
    public class ProductRating
    {
        public ProductRating()
        {

        }

        public ProductRating(int rating, string content, Product product, User author)
        {
            this.Rating = rating;
            this.Content = content;
            this.Author = author;
            this.Product = product;
        }

        [Key]
        public int ProductRatingId { get; set; }

        public int Rating { get; set; }

        public string Content { get; set; }

        public int ProductId { get; set; }

        [ForeignKey("ProductId")]
        public virtual Product Product { get; set; }

        [ForeignKey("Author")]
        public string AuthorId { get; set; }

        [ForeignKey("Id")]
        public virtual User Author { get; set; }
    }
}

Add default constructor for product rating