using Gtk;
using SlimeSimulation.Controller.WindowComponentController;

namespace SlimeSimulation.View.WindowComponent
{
    public class NodeHighlightKey
    {
        public Widget GetVisualKey()
        {
            VBox key = new VBox(true, 10);

            HBox sourcePart = new HBox(true, 10);
            sourcePart.Add(new Label("Source"));
            sourcePart.Add(GetBoxColour(FlowResultNodeViewController.SourceColour));

            HBox sinkPart = new HBox(true, 10);
            sinkPart.Add(new Label("Sink"));
            sinkPart.Add(GetBoxColour(FlowResultNodeViewController.SinkColour));

            HBox normalPart = new HBox(true, 10);
            normalPart.Add(new Label("Normal node"));
            normalPart.Add(GetBoxColour(FlowResultNodeViewController.NormalNodeColour));

            key.Add(sourcePart);
            key.Add(sinkPart);
            key.Add(normalPart);
            return key;
        }

        private DrawingArea GetBoxColour(Rgb color)
        {
            return new ColorArea(color);
        }
    }

}

using Gtk;
using SlimeSimulation.Controller.WindowComponentController;

namespace SlimeSimulation.View.WindowComponent
{
    public class NodeHighlightKey
    {
        public Widget GetVisualKey()
        {
            VBox key = new VBox(true, 10);

            key.Add(new Label("Node colour key"));

            var sourcePart = new HBox(true, 10);
            sourcePart.Add(new Label("Source"));
            sourcePart.Add(GetBoxColour(FlowResultNodeViewController.SourceColour));

            HBox sinkPart = new HBox(true, 10);
            sinkPart.Add(new Label("Sink"));
            sinkPart.Add(GetBoxColour(FlowResultNodeViewController.SinkColour));

            HBox normalPart = new HBox(true, 10);
            normalPart.Add(new Label("Normal node"));
            normalPart.Add(GetBoxColour(FlowResultNodeViewController.NormalNodeColour));

            key.Add(sourcePart);
            key.Add(sinkPart);
            key.Add(normalPart);
            return key;
        }

        private DrawingArea GetBoxColour(Rgb color)
        {
            return new ColorArea(color);
        }
    }

}

Add label to the node colour key explaining what it is


using System;
using System.Collections.Generic;

namespace conekta
{
	public class Details
	{
		public string name { get; set; }
		public string phone { get; set; }
		public string email { get; set; }
		public Customer customer { get; set; }
		public List<LineItem> line_items { get; set; }
		public BillingAddress billing_address { get; set; }
	}
}

using System;
using System.Collections.Generic;

namespace conekta
{
	public class Details
	{
		public string name { get; set; }
		public string phone { get; set; }
		public string email { get; set; }
		public Customer customer { get; set; }
		public List<LineItem> line_items { get; set; }
		public BillingAddress billing_address { get; set; }
		public ShippingAddress shipment { get; set; }
	}
}

Add shipment for physical goods

Add shipment for physical goods


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

using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Utils;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Ranking.Statistics;

namespace osu.Game.Tests.NonVisual.Ranking
{
    [TestFixture]
    public class UnstableRateTest
    {
        [Test]
        public void TestDistributedHits()
        {
            var events = Enumerable.Range(-5, 11)
                                   .Select(t => new HitEvent(t - 5, HitResult.Great, new HitObject(), null, null));

            var unstableRate = new UnstableRate(events);

            Assert.IsTrue(Precision.AlmostEquals(unstableRate.Value, 10 * Math.Sqrt(10)));
        }

        [Test]
        public void TestMissesAndEmptyWindows()
        {
            var events = new[]
            {
                new HitEvent(-100, HitResult.Miss, new HitObject(), null, null),
                new HitEvent(0, HitResult.Great, new HitObject(), null, null),
                new HitEvent(200, HitResult.Meh, new HitObject { HitWindows = HitWindows.Empty }, null, null),
            };

            var unstableRate = new UnstableRate(events);

            Assert.IsTrue(Precision.AlmostEquals(0, unstableRate.Value));
        }
    }
}

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

using System;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Utils;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Ranking.Statistics;

namespace osu.Game.Tests.NonVisual.Ranking
{
    [TestFixture]
    public class UnstableRateTest
    {
        [Test]
        public void TestDistributedHits()
        {
            var events = Enumerable.Range(-5, 11)
                                   .Select(t => new HitEvent(t - 5, HitResult.Great, new HitObject(), null, null));

            var unstableRate = new UnstableRate(events);

            Assert.IsTrue(Precision.AlmostEquals(unstableRate.Value, 10 * Math.Sqrt(10)));
        }

        [Test]
        public void TestMissesAndEmptyWindows()
        {
            var events = new[]
            {
                new HitEvent(-100, HitResult.Miss, new HitObject(), null, null),
                new HitEvent(0, HitResult.Great, new HitObject(), null, null),
                new HitEvent(200, HitResult.Meh, new HitObject { HitWindows = HitWindows.Empty }, null, null),
            };

            var unstableRate = new UnstableRate(events);

            Assert.AreEqual(0, unstableRate.Value);
        }
    }
}

Replace precision check with absolute equality assert


// 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 osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Online.API.Requests
{
    public class GetSpotlightsRequest : APIRequest<List<APISpotlight>>
    {
        protected override string Target => "spotlights";
    }
}

// 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 Newtonsoft.Json;
using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Online.API.Requests
{
    public class GetSpotlightsRequest : APIRequest<SpotlightsArray>
    {
        protected override string Target => "spotlights";
    }

    public class SpotlightsArray
    {
        [JsonProperty("spotlights")]
        public List<APISpotlight> Spotlights;
    }
}

Fix incorrect return type for spotlight request


using System;
using System.Linq;
using BmpListener;
using BmpListener.Extensions;

namespace BmpListener.Bmp
{
    public class BmpHeader
    {
        public BmpHeader(byte[] data)
        {
            Version = data.First();
            //if (Version != 3)
            //{
            //    throw new Exception("invalid BMP version");
            //}
            Length = data.ToInt32(1);
            MessageType = (BmpMessage.Type)data.ElementAt(5);
        }

        public byte Version { get; }
        public int Length { get; }
        public BmpMessage.Type MessageType { get; }
    }
}

using System;
using System.Linq;
using BmpListener;
using BmpListener.Extensions;

namespace BmpListener.Bmp
{
    public class BmpHeader
    {
        private readonly int bmpVersion = 3;

        public BmpHeader(byte[] data)
        {
            Version = data.First();
            if (Version != bmpVersion)
            {
                throw new NotSupportedException("version error");
            }
            Length = data.ToInt32(1);
            MessageType = (BmpMessage.Type)data.ElementAt(5);
        }

        public byte Version { get; }
        public int Length { get; }
        public BmpMessage.Type MessageType { get; }
    }
}

Throw exception if BMP version != 3

Throw exception if BMP version != 3


using System;
using System.Net.Http;
using System.Threading;
using PactNet.Core;

namespace PactNet.Mocks.MockHttpService.Host
{
    internal class RubyHttpHost : IHttpHost
    {
        private readonly IPactCoreHost _coreHost;
        private readonly HttpClient _httpClient;

        internal RubyHttpHost(IPactCoreHost coreHost, HttpClient httpClient)
        {
            _coreHost = coreHost;
            _httpClient = httpClient; //TODO: Use the admin http client once extracted
        }

        public RubyHttpHost(Uri baseUri, string providerName, PactConfig config) :
            this(new PactCoreHost<MockProviderHostConfig>(
                new MockProviderHostConfig(baseUri.Port,
                    baseUri.Scheme.ToUpperInvariant().Equals("HTTPS"),
                    providerName, config)),
                new HttpClient { BaseAddress = baseUri })
        {
        }

        private bool IsMockProviderServiceRunning()
        {
            var aliveRequest = new HttpRequestMessage(HttpMethod.Get, "/");
            aliveRequest.Headers.Add(Constants.AdministrativeRequestHeaderKey, "true");

            var responseMessage = _httpClient.SendAsync(aliveRequest).Result;
            return responseMessage.IsSuccessStatusCode;
        }

        public void Start()
        {
            _coreHost.Start();

            var aliveChecks = 1;
            while (!IsMockProviderServiceRunning())
            {
                if (aliveChecks >= 20)
                {
                    throw new PactFailureException("Could not start the mock provider service");
                }

                Thread.Sleep(200);
                aliveChecks++;
            }
        }

        public void Stop()
        {
            _coreHost.Stop();
        }
    }
}

using System;
using System.Net.Http;
using System.Threading;
using PactNet.Core;

namespace PactNet.Mocks.MockHttpService.Host
{
    internal class RubyHttpHost : IHttpHost
    {
        private readonly IPactCoreHost _coreHost;
        private readonly HttpClient _httpClient;

        internal RubyHttpHost(IPactCoreHost coreHost, HttpClient httpClient)
        {
            _coreHost = coreHost;
            _httpClient = httpClient; //TODO: Use the admin http client once extracted
        }

        public RubyHttpHost(Uri baseUri, string providerName, PactConfig config) :
            this(new PactCoreHost<MockProviderHostConfig>(
                new MockProviderHostConfig(baseUri.Port,
                    baseUri.Scheme.ToUpperInvariant().Equals("HTTPS"),
                    providerName, config)),
                new HttpClient { BaseAddress = baseUri })
        {
        }

        private bool IsMockProviderServiceRunning()
        {
            try
            {
                var aliveRequest = new HttpRequestMessage(HttpMethod.Get, "/");
                aliveRequest.Headers.Add(Constants.AdministrativeRequestHeaderKey, "true");

                var responseMessage = _httpClient.SendAsync(aliveRequest).Result;
                return responseMessage.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        public void Start()
        {
            _coreHost.Start();

            var aliveChecks = 1;
            while (!IsMockProviderServiceRunning())
            {
                if (aliveChecks >= 20)
                {
                    throw new PactFailureException("Could not start the mock provider service");
                }

                Thread.Sleep(200);
                aliveChecks++;
            }
        }

        public void Stop()
        {
            _coreHost.Stop();
        }
    }
}

Fix issues on first run, which takes a little longer to start up


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

namespace CollabEdit.VersionControl
{

    public class RepositoryBranch<TValue, TMeta>
    {
        private object syncRoot = new Object();
        public RepositoryBranch() { }

        public RepositoryBranch(string name, Repository<TValue, TMeta> repository, Commit<TValue, TMeta> head)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name may not be null or empty string.");
            if (repository == null) throw new ArgumentNullException(nameof(repository));

            Name = name;
            Repository = repository;
            Head = head;
        }

        public Repository<TValue, TMeta> Repository { get; }

        public string Name { get; }

        public Commit<TValue, TMeta> Head { get; protected set; }

        public Commit<TValue, TMeta> Commit(TValue value, TMeta metadata)
        {
            if (Head != null && Head.Value.Equals(value))
                return Head; // Value was not changed, so no need to create a new version.

            lock (syncRoot)
            {
                var commit = new Commit<TValue, TMeta>(value, metadata, Head);
                Head = commit;
                return commit;
            }
        }

        public virtual Commit<TValue, TMeta> MergeWith(RepositoryBranch<TValue, TMeta> sourceBranch)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Commit<TValue, TMeta>> GetHistory()
        {
            if (Head == null) yield break;

            var next = Head;
            while (next != null)
            {
                yield return next;
                next = next.Parent;
            }
        }
    }
}

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

namespace CollabEdit.VersionControl
{

    public class RepositoryBranch<TValue, TMeta>
    {
        private object syncRoot = new Object();
        public RepositoryBranch() { }

        public RepositoryBranch(string name, Repository<TValue, TMeta> repository, Commit<TValue, TMeta> head)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name may not be null or empty string.");
            if (repository == null) throw new ArgumentNullException(nameof(repository));

            Name = name;
            Repository = repository;
            Head = head;
        }

        public Repository<TValue, TMeta> Repository { get; }

        public string Name { get; }

        public Commit<TValue, TMeta> Head { get; protected set; }

        public Commit<TValue, TMeta> Commit(TValue value, TMeta metadata)
        {
            if (value == null) throw new ArgumentNullException(nameof(value));
            if (metadata == null) throw new ArgumentException(nameof(metadata));

            if (Head != null && Head.Value.Equals(value))
                return Head; // Value was not changed, so no need to create a new version.

            lock (syncRoot)
            {
                var commit = new Commit<TValue, TMeta>(value, metadata, Head);
                Head = commit;
                return commit;
            }
        }

        public virtual Commit<TValue, TMeta> MergeWith(RepositoryBranch<TValue, TMeta> sourceBranch)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Commit<TValue, TMeta>> GetHistory()
        {
            if (Head == null) yield break;

            var next = Head;
            while (next != null)
            {
                yield return next;
                next = next.Parent;
            }
        }
    }
}

Add argument checking on commit

Add argument checking on commit


@model Cash_Flow_Projection.Models.Dashboard

@{
    ViewData["Title"] = "Home Page";
}

    @foreach (var entry in Model.Entries.OrderBy(_ => _.Date))
    {

            @Html.DisplayFor(_ => entry.Date)
            @Html.DisplayFor(_ => entry.Description)
            @Html.DisplayFor(_ => entry.Amount)
            @Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)

                @using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post))
                {
                    @Html.AntiForgeryToken()
                    <button type="submit">Delete</button>
                }

    }

@model Cash_Flow_Projection.Models.Dashboard

@{
    ViewData["Title"] = "Home Page";
}

@using (Html.BeginForm("Balance", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <input type="text" id="balance" placeholder="Set Balance" />
    <button type="submit">Set</button>
}

    @foreach (var entry in Model.Entries.OrderBy(_ => _.Date))
    {

            @Html.DisplayFor(_ => entry.Date)
            @Html.DisplayFor(_ => entry.Description)
            @Html.DisplayFor(_ => entry.Amount)
            @Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)

                @using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post))
                {
                    @Html.AntiForgeryToken()
                    <button type="submit">Delete</button>
                }

    }

Add form for setting balance in one step

Fixes #7


using UnityEngine;
using System;
using System.Collections;

public class MapifyLevelPopulator {
  private MapifyMapIterator mapIterator;
  private MapifyTileRepository tileRepository;
  private Transform container;

  public MapifyLevelPopulator(MapifyMapIterator mapIterator, MapifyTileRepository tileRepository, Transform container) {
    this.mapIterator = mapIterator;
    this.tileRepository = tileRepository;
    this.container = container;
  }

  public void Populate() {
    mapIterator.Iterate((character, localPosition) => {
        var worldPosition = container.TransformPoint(localPosition);
        if (tileRepository.HasKey(character)) {
          var tile = tileRepository.Find(character);
          MapifyTileSpawner.Create(tile, worldPosition, container);
        }
    });
  }
}

using UnityEngine;
using System;
using System.Collections;

public class MapifyLevelPopulator {
  private MapifyMapIterator mapIterator;
  private MapifyTileRepository tileRepository;
  private Transform container;

  public MapifyLevelPopulator(MapifyMapIterator mapIterator, MapifyTileRepository tileRepository, Transform container) {
    this.mapIterator = mapIterator;
    this.tileRepository = tileRepository;
    this.container = container;
  }

  public void Populate() {
    mapIterator.Iterate((character, localPosition) => {
        if (tileRepository.HasKey(character)) {
          var tile = tileRepository.Find(character);
          var worldPosition = container.TransformPoint(localPosition);
          MapifyTileSpawner.Create(tile, worldPosition, container);
        }
    });
  }
}

Move variable to inner scope where it's used


using System.Globalization;

namespace Our.Umbraco.Ditto.Tests.Models
{
    using System.ComponentModel;

    using Our.Umbraco.Ditto.Tests.TypeConverters;
    using global::Umbraco.Core.Models;

    public class ComplexModel
    {
        public int Id { get; set; }

        [DittoValueResolver(typeof(NameVauleResovler))]
        public string Name { get; set; }

        [UmbracoProperty("myprop")]
        public IPublishedContent MyProperty { get; set; }

        [UmbracoProperty("Id")]
        [TypeConverter(typeof(MockPublishedContentConverter))]
        public IPublishedContent MyPublishedContent { get; set; }
    }

    public class NameVauleResovler : DittoValueResolver
    {
        public override object ResolveValue(ITypeDescriptorContext context,
            DittoValueResolverAttribute attribute, CultureInfo culture)
        {
            var content = context.Instance as IPublishedContent;
            if (content == null) return null;

            return content.Name + " Test";
        }
    }
}

using System.Globalization;

namespace Our.Umbraco.Ditto.Tests.Models
{
    using System.ComponentModel;

    using Our.Umbraco.Ditto.Tests.TypeConverters;
    using global::Umbraco.Core.Models;

    public class ComplexModel
    {
        public int Id { get; set; }

        [DittoValueResolver(typeof(NameValueResovler))]
        public string Name { get; set; }

        [UmbracoProperty("myprop")]
        public IPublishedContent MyProperty { get; set; }

        [UmbracoProperty("Id")]
        [TypeConverter(typeof(MockPublishedContentConverter))]
        public IPublishedContent MyPublishedContent { get; set; }
    }

    public class NameValueResovler : DittoValueResolver
    {
        public override object ResolveValue(ITypeDescriptorContext context,
            DittoValueResolverAttribute attribute, CultureInfo culture)
        {
            var content = context.Instance as IPublishedContent;
            if (content == null) return null;

            return content.Name + " Test";
        }
    }
}

Correct typo (just caught my eye, no biggie).

[skip ci]


using System;
using System.Collections.Generic;
using System.IO;
using FifteenBelow.Deployment.Update;

namespace Ensconce
{
    internal static class TextRendering
    {
        private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(BuildTagDictionary);
        public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } }

        internal static string Render(this string s)
        {
            return s.RenderTemplate(LazyTags.Value);
        }

        private static TagDictionary BuildTagDictionary()
        {
            Logging.Log("Building Tag Dictionary");
            var instanceName = Environment.GetEnvironmentVariable("InstanceName");
            Logging.Log("Building Tag Dictionary ({0})", instanceName);
            var tags = new TagDictionary(instanceName);
            Logging.Log("Built Tag Dictionary ({0})", instanceName);

            Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags);
            if (File.Exists(Arguments.FixedPath))
            {
                Logging.Log("Loading xml config from file {0}", Path.GetFullPath(Arguments.FixedPath));
                var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5));
                Logging.Log("Re-Building Tag Dictionary (Using Config File)");
                tags = new TagDictionary(instanceName, configXml);
                Logging.Log("Built Tag Dictionary (Using Config File)");
            }
            else
            {
                Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath));
            }

            return tags;
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using FifteenBelow.Deployment.Update;

namespace Ensconce
{
    internal static class TextRendering
    {
        private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(() => Retry.Do(BuildTagDictionary, TimeSpan.FromSeconds(5)));
        public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } }

        internal static string Render(this string s)
        {
            return s.RenderTemplate(TagDictionary);
        }

        private static TagDictionary BuildTagDictionary()
        {
            Logging.Log("Building Tag Dictionary");
            var instanceName = Environment.GetEnvironmentVariable("InstanceName");
            Logging.Log("Building Tag Dictionary ({0})", instanceName);
            var tags = new TagDictionary(instanceName);
            Logging.Log("Built Tag Dictionary ({0})", instanceName);

            Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags);
            if (File.Exists(Arguments.FixedPath))
            {
                Logging.Log("Loading xml config from file {0}", Path.GetFullPath(Arguments.FixedPath));
                var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5));
                Logging.Log("Re-Building Tag Dictionary (Using Config File)");
                tags = new TagDictionary(instanceName, configXml);
                Logging.Log("Built Tag Dictionary (Using Config File)");
            }
            else
            {
                Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath));
            }

            return tags;
        }
    }
}

Add retry when invoking the lazy to build TagDictionary


using Newtonsoft.Json;

namespace FplClient.Data
{
    public class FplPick
    {
        [JsonProperty("element")]
        public int PlayerId { get; set; }

        [JsonProperty("element_type")]
        public int ElementType { get; set; }

        [JsonProperty("position")]
        public FplPlayerPosition Position { get; set; }

        [JsonProperty("points")]
        public int Points { get; set; }

        [JsonProperty("can_captain")]
        public bool? CanCaptain { get; set; }

        [JsonProperty("is_captain")]
        public bool IsCaptain { get; set; }

        [JsonProperty("is_vice_captain")]
        public bool IsViceCaptain { get; set; }

        [JsonProperty("can_sub")]
        public bool? CanSub { get; set; }

        [JsonProperty("is_sub")]
        public bool IsSub { get; set; }

        [JsonProperty("has_played")]
        public bool HasPlayed { get; set; }

        [JsonProperty("stats")]
        public FplPickStats Stats { get; set; }

        [JsonProperty("multiplier")]
        public int Multiplier { get; set; }
    }
}

using Newtonsoft.Json;

namespace FplClient.Data
{
    public class FplPick
    {
        [JsonProperty("element")]
        public int PlayerId { get; set; }

        [JsonProperty("element_type")]
        public int ElementType { get; set; }

        [JsonProperty("position")]
        public int TeamPosition { get; set; }

        [JsonProperty("points")]
        public int Points { get; set; }

        [JsonProperty("can_captain")]
        public bool? CanCaptain { get; set; }

        [JsonProperty("is_captain")]
        public bool IsCaptain { get; set; }

        [JsonProperty("is_vice_captain")]
        public bool IsViceCaptain { get; set; }

        [JsonProperty("can_sub")]
        public bool? CanSub { get; set; }

        [JsonProperty("is_sub")]
        public bool IsSub { get; set; }

        [JsonProperty("has_played")]
        public bool HasPlayed { get; set; }

        [JsonProperty("stats")]
        public FplPickStats Stats { get; set; }

        [JsonProperty("multiplier")]
        public int Multiplier { get; set; }
    }
}

Change Pick 'position' property to int as it represents position in team


using System;
using System.IO;
using System.Linq;
using Xunit.Abstractions;

namespace OpenSage.Data.Tests
{
    internal static class InstalledFilesTestData
    {
        private static readonly IInstallationLocator Locator;

        static InstalledFilesTestData()
        {
            Locator = new RegistryInstallationLocator();
        }

        public static string GetInstallationDirectory(SageGame game) => Locator.FindInstallations(game).First().Path;

        public static void ReadFiles(string fileExtension, ITestOutputHelper output, Action<FileSystemEntry> processFileCallback)
        {
            var rootDirectories = SageGames.GetAll().SelectMany(Locator.FindInstallations).Select(i => i.Path);

            var foundAtLeastOneFile = false;
            foreach (var rootDirectory in rootDirectories.Where(x => Directory.Exists(x)))
            {
                var fileSystem = new FileSystem(rootDirectory);

                foreach (var file in fileSystem.Files)
                {
                    if (Path.GetExtension(file.FilePath).ToLower() != fileExtension)
                    {
                        continue;
                    }

                    output.WriteLine($"Reading file {file.FilePath}.");

                    processFileCallback(file);

                    foundAtLeastOneFile = true;
                }
            }

            if (!foundAtLeastOneFile)
            {
                throw new Exception($"No files were found matching file extension {fileExtension}");
            }
        }
    }
}

using System;
using System.IO;
using System.Linq;
using Xunit.Abstractions;

namespace OpenSage.Data.Tests
{
    internal static class InstalledFilesTestData
    {
        private static readonly IInstallationLocator Locator;

        static InstalledFilesTestData()
        {
            Locator = new RegistryInstallationLocator();
        }

        public static string GetInstallationDirectory(SageGame game) => Locator.FindInstallations(game).First().Path;

        public static void ReadFiles(string fileExtension, ITestOutputHelper output, Action<FileSystemEntry> processFileCallback)
        {
            var rootDirectories = SageGames.GetAll()
                .SelectMany(Locator.FindInstallations)
                .Select(i => i.Path);

            var foundAtLeastOneFile = false;
            foreach (var rootDirectory in rootDirectories.Where(x => Directory.Exists(x)))
            {
                var fileSystem = new FileSystem(rootDirectory);

                foreach (var file in fileSystem.Files)
                {
                    if (Path.GetExtension(file.FilePath).ToLower() != fileExtension)
                    {
                        continue;
                    }

                    output.WriteLine($"Reading file {file.FilePath}.");

                    processFileCallback(file);

                    foundAtLeastOneFile = true;
                }
            }

            if (!foundAtLeastOneFile)
            {
                throw new Exception($"No files were found matching file extension {fileExtension}");
            }
        }
    }
}

Add line breaks to ease filtering by individual game


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

namespace NuGet.VisualStudio {
    public static class AggregatePackageSource {
        public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);

        public static bool IsAggregate(this PackageSource source) {
            return source == Instance;
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) {
            return Enumerable.Repeat(Instance, 1).Concat(provider.LoadPackageSources());
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() {
            return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
        }
    }
}

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

namespace NuGet.VisualStudio {
    public static class AggregatePackageSource {
        public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName);

        public static bool IsAggregate(this PackageSource source) {
            return source == Instance;
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) {
            return new[] { Instance }.Concat(provider.LoadPackageSources());
        }

        public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() {
            return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>());
        }
    }
}

Replace Enumerable.Repeat call with an one-element array.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using MalApi;

namespace MalApi.IntegrationTests
{
    [TestFixture]
    public class GetAnimeListForUserTest
    {
        [Test]
        public void GetAnimeListForUser()
        {
            string username = "lordhighcaptain";
            using (MyAnimeListApi api = new MyAnimeListApi())
            {
                MalUserLookupResults userLookup = api.GetAnimeListForUser(username);

                // Just a smoke test that checks that getting an anime list returns something
                Assert.That(userLookup.AnimeList, Is.Not.Empty);
            }
        }
    }
}

/*
 Copyright 2012 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using MalApi;
using System.Threading.Tasks;

namespace MalApi.IntegrationTests
{
    [TestFixture]
    public class GetAnimeListForUserTest
    {
        [Test]
        public void GetAnimeListForUser()
        {
            string username = "lordhighcaptain";
            using (MyAnimeListApi api = new MyAnimeListApi())
            {
                MalUserLookupResults userLookup = api.GetAnimeListForUser(username);

                // Just a smoke test that checks that getting an anime list returns something
                Assert.That(userLookup.AnimeList, Is.Not.Empty);
            }
        }

        [Test]
        public void GetAnimeListForNonexistentUserThrowsCorrectException()
        {
            using (MyAnimeListApi api = new MyAnimeListApi())
            {
                Assert.Throws<MalUserNotFoundException>(() => api.GetAnimeListForUser("oijsfjisfdjfsdojpfsdp"));
            }
        }

        [Test]
        public void GetAnimeListForNonexistentUserThrowsCorrectExceptionAsync()
        {
            using (MyAnimeListApi api = new MyAnimeListApi())
            {
                Assert.ThrowsAsync<MalUserNotFoundException>(() => api.GetAnimeListForUserAsync("oijsfjisfdjfsdojpfsdp"));
            }
        }
    }
}

/*
 Copyright 2017 Greg Najda

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

Add integration tests for MalUserNotFoundException being thrown.


// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;
    using System.Linq;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle012 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "What is the value of the first triangle number to have the specified number of divisors?";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int divisors;

            if (!TryParseInt32(args[0], out divisors) || divisors < 1)
            {
                Console.Error.WriteLine("The specified number of divisors is invalid.");
                return -1;
            }

            for (int i = 1; ; i++)
            {
                long triangleNumber = ParallelEnumerable.Range(1, i)
                    .Select((p) => (long)p)
                    .Sum();

                int numberOfFactors = Maths.GetFactors(triangleNumber).Count();

                if (numberOfFactors >= divisors)
                {
                    Answer = triangleNumber;
                    break;
                }
            }

            return 0;
        }
    }
}

// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;
    using System.Linq;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle012 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "What is the value of the first triangle number to have the specified number of divisors?";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int divisors;

            if (!TryParseInt32(args[0], out divisors) || divisors < 1)
            {
                Console.Error.WriteLine("The specified number of divisors is invalid.");
                return -1;
            }

            long triangleNumber = 0;

            for (int n = 1; ; n++)
            {
                triangleNumber += n;

                int numberOfFactors = Maths.GetFactors(triangleNumber).Count();

                if (numberOfFactors >= divisors)
                {
                    Answer = triangleNumber;
                    break;
                }
            }

            return 0;
        }
    }
}

Improve the efficiency of puzzle 12

Improve the efficiency of puzzle 12

Improve the efficiency of puzzle 12 by not re-computing the triangle
number sum continuously.


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

namespace SPAD.neXt.Interfaces.ServiceContract
{

    public sealed class RemoteServiceResponse
    {
        public bool HasError { get; set; }
        public string Error { get; set; }
        public double Value { get; set; }
    }

    [ServiceContract]
    [ServiceKnownType(typeof(RemoteServiceResponse))]
    public interface IRemoteService
    {
        [OperationContract]
        RemoteServiceResponse GetValue(string variableName);

        [OperationContract]
        RemoteServiceResponse SetValue(string variableName, double newValue);

        [OperationContract]
        RemoteServiceResponse EmulateEvent(string eventTarget, string eventName, string eventParameter);
    }
}

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

namespace SPAD.neXt.Interfaces.ServiceContract
{
    public static class RemoteServiceContract
    {
        public static readonly Uri ServiceUrl  = new Uri("net.pipe://localhost/SPAD.neXt");
        public static readonly string ServiceEndpoint = "RemoteService";
    }

    public sealed class RemoteServiceResponse
    {
        public bool HasError { get; set; }
        public string Error { get; set; }
        public double Value { get; set; }
    }

    public sealed class RemoteEventTarget
    {
        public string Name { get; set; }
        public HashSet<string> EventNames { get; set; }
    }

    [ServiceContract( Namespace = Constants.Namespace , CallbackContract = typeof(IRemoteServiceCallback))]
    [ServiceKnownType(typeof(RemoteServiceResponse))]
    [ServiceKnownType(typeof(RemoteEventTarget))]
    public interface IRemoteService
    {
        [OperationContract]
        RemoteServiceResponse GetValue(string variableName);

        [OperationContract]
        RemoteServiceResponse SetValue(string variableName, double newValue);

        [OperationContract]
        RemoteServiceResponse EmulateEvent(string eventTarget, string eventName, string eventParameter);

        [OperationContract]
        List<RemoteEventTarget> GetEventTargets();

        [OperationContract]
        string GetVersion();
    }

    public interface IRemoteServiceCallback
    {
        [OperationContract(IsOneWay = true)]
        void RemoteEvent(string eventName);
    }
}

Make RemoteService a Duplex Service

Make RemoteService a Duplex Service


namespace Host.UnitTests.Serialization
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Crest.Host.Serialization;
    using FluentAssertions;
    using Xunit;

    public class MethodsTests
    {
        private readonly Methods methods = new Methods(typeof(FakeSerializerBase));

        public sealed class StreamWriter : MethodsTests
        {
            private const int StreamWriterWriteMethods = 17;

            [Fact]
            public void ShouldEnumerateAllTheWriteMethods()
            {
                int count = this.methods.StreamWriter.Count();

                count.Should().Be(StreamWriterWriteMethods);
            }

            [Fact]
            public void ShouldProvideANonGenericEnumerateMethod()
            {
                int count = ((IEnumerable)this.methods.StreamWriter)
                    .Cast<KeyValuePair<Type, MethodInfo>>()
                    .Count();

                count.Should().Be(StreamWriterWriteMethods);
            }
        }
    }
}

namespace Host.UnitTests.Serialization
{
    using System.Collections;
    using System.Linq;
    using Crest.Host.Serialization;
    using FluentAssertions;
    using Xunit;

    public class MethodsTests
    {
        private readonly Methods methods = new Methods(typeof(FakeSerializerBase));

        public sealed class StreamWriter : MethodsTests
        {
            private const int StreamWriterWriteMethods = 17;

            [Fact]
            public void ShouldEnumerateAllTheWriteMethods()
            {
                int count = this.methods.StreamWriter.Count();

                count.Should().Be(StreamWriterWriteMethods);
            }

            [Fact]
            public void ShouldProvideANonGenericEnumerateMethod()
            {
                var enumerable = (IEnumerable)this.methods.StreamWriter;
                int count = 0;
                foreach (object x in enumerable)
                {
                    count++;
                }

                count.Should().Be(StreamWriterWriteMethods);
            }
        }
    }
}

Update StreamWriter tests + Explicitly iterate IEnumerable method


using Dapper;
using SeleniumDesignPatternsDemo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern.Models
{
    public class AccessExcelData
    {
        public static string TestDataFileConnection()
        {
            var path = ConfigurationManager.AppSettings["TestDataSheetPath"];

            var fileName = "UserData.xlsx";

            var connection = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;
                                             Data Source = {0};
                                             Extended Properties=Excel 12.0;", path + fileName);

            return connection;
        }

        public static RegistrateUser GetTestData(string keyName)
        {
            using (var connection = new OleDbConnection(TestDataFileConnection()))
            {
                connection.Open();

                var query = string.Format("SELECT * FROM [DataSet$] WHERE KEY = '{0}'", keyName);

                var value = connection.Query<RegistrateUser>(query).First();

                connection.Close();

                return value;
            }
        }
    }
}

using Dapper;
using SeleniumDesignPatternsDemo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern.Models
{
    public class AccessExcelData
    {
        public static string TestDataFileConnection()
        {
            var path = ConfigurationManager.AppSettings["TestDataSheetPath"];

            var fileName = "UserData.xlsx";

            var connection = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;
                                             Data Source = {0};
                                             Extended Properties=Excel 12.0 Xml; HDR=YES", path + fileName);

            return connection;
        }

        public static RegistrateUser GetTestData(string keyName)
        {
            using (var connection = new OleDbConnection(TestDataFileConnection()))
            {
                connection.Open();

                var query = string.Format("SELECT * FROM [DataSet$] WHERE KEY = '{0}'", keyName);

                var value = connection.Query<RegistrateUser>(query).First();

                connection.Close();

                return value;
            }
        }
    }
}

Add "HDR=YES" in connection string, but other error is thrown


using System;
using Mono.Cecil;
using Mono.Cecil.Inject;
using Pathfinder.Attribute;
using Pathfinder.Util;

namespace Pathfinder.Internal.Patcher
{

    internal static class Executor
    {
        internal static void Main(AssemblyDefinition gameAssembly)
        {
            // Retrieve the hook methods
            var hooks = typeof(PathfinderHooks);
            MethodDefinition method;
            PatchAttribute attrib;
            string sig;

            foreach (var meth in hooks.GetMethods())
            {
                attrib = meth.GetFirstAttribute<PatchAttribute>();
                if (attrib == null) continue;
                sig = attrib.MethodSig;
                if (sig == null)
                {
                    Console.WriteLine($"Null method signature found, skipping {nameof(PatchAttribute)} on method.");
                }
                method = gameAssembly.MainModule.GetType(sig.Remove(sig.LastIndexOf('.')))?.GetMethod(sig.Substring(sig.LastIndexOf('.') + 1));
                if(method == null)
                {
                    Console.WriteLine($"Method signature '{sig}' could not be found, method hook patching failed, skipping {nameof(PatchAttribute)} on '{sig}'.");
                    continue;
                }

                method.InjectWith(
                    gameAssembly.MainModule.ImportReference(hooks.GetMethod(meth.Name)).Resolve(),
                    attrib.Offset,
                    attrib.Tag,
                    (InjectFlags)attrib.Flags,
                    attrib.After ? InjectDirection.After : InjectDirection.Before,
                    attrib.LocalIds);
            }
        }
    }
}

using System;
using Mono.Cecil;
using Mono.Cecil.Inject;
using Pathfinder.Attribute;
using Pathfinder.Util;

namespace Pathfinder.Internal.Patcher
{

    internal static class Executor
    {
        internal static void Main(AssemblyDefinition gameAssembly)
        {
            // Retrieve the hook methods
            var hooks = typeof(PathfinderHooks);
            MethodDefinition method;
            PatchAttribute attrib;
            string sig;

            foreach (var meth in hooks.GetMethods())
            {
                attrib = meth.GetFirstAttribute<PatchAttribute>();
                if (attrib == null) continue;
                sig = attrib.MethodSig;
                if (sig == null)
                {
                    Console.WriteLine($"Null method signature found, skipping {nameof(PatchAttribute)} on method.");
                }
                method = gameAssembly.MainModule.GetType(sig.Remove(sig.LastIndexOf('.')))?.GetMethod(sig.Substring(sig.LastIndexOf('.') + 1));
                if(method == null)
                {
                    Console.WriteLine($"Method signature '{sig}' could not be found, method hook patching failed, skipping {nameof(PatchAttribute)} on '{sig}'.");
                    continue;
                }

                try
                {
                    method.InjectWith(
                        gameAssembly.MainModule.ImportReference(hooks.GetMethod(meth.Name)).Resolve(),
                        attrib.Offset,
                        attrib.Tag,
                        (InjectFlags) attrib.Flags,
                        attrib.After ? InjectDirection.After : InjectDirection.Before,
                        attrib.LocalIds);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Error applying patch for {sig}", ex);
                }
            }
        }
    }
}

Add more information to failed Hooks

Add more information to failed Hooks

Now reports the target method not being patched
properly.


using System;
using Newtonsoft.Json;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;

namespace Eto.Serialization.Json
{
	public class TypeConverterConverter : JsonConverter
	{
		readonly Dictionary<Type, TypeConverter> converters = new Dictionary<Type, TypeConverter>();

		public override bool CanRead { get { return true; } }
		public override bool CanWrite { get { return false; } }

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
		}

		public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			TypeConverter converter;
			if (converters.TryGetValue(objectType, out converter))
			{
				return converter.ConvertFrom(reader.Value);
			}
			return existingValue;
		}

		public override bool CanConvert(Type objectType)
		{
			if (converters.ContainsKey(objectType))
				return true;
			var converter = TypeDescriptor.GetConverter(objectType);
			if (converter != null && converter.CanConvertFrom(typeof(string)))
			{
				converters.Add(objectType, converter);
				return true;
			}
			return false;
		}
	}
}

using System;
using Newtonsoft.Json;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;

namespace Eto.Serialization.Json
{
	public class TypeConverterConverter : JsonConverter
	{
		readonly Dictionary<Type, TypeConverter> converters = new Dictionary<Type, TypeConverter>();

		public override bool CanRead { get { return true; } }
		public override bool CanWrite { get { return false; } }

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
		}

		public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			TypeConverter converter;
			if (objectType == reader.ValueType)
				return reader.Value;
			if (converters.TryGetValue(objectType, out converter))
			{
				return converter.ConvertFrom(reader.Value);
			}
			return existingValue;
		}

		public override bool CanConvert(Type objectType)
		{
			if (converters.ContainsKey(objectType))
				return true;
			var converter = TypeDescriptor.GetConverter(objectType);
			if (converter != null && converter.CanConvertFrom(typeof(string)))
			{
				converters.Add(objectType, converter);
				return true;
			}
			return false;
		}
	}
}

Fix json serialization when the destination type is equal to the value type (fixes net40 for boolean conversions)


using Godot;
using GodotTools.Internals;
using static GodotTools.Internals.Globals;

namespace GodotTools
{
    public class HotReloadAssemblyWatcher : Node
    {
        private Timer watchTimer;

        public override void _Notification(int what)
        {
            if (what == Node.NotificationWmFocusIn)
            {
                RestartTimer();

                if (Internal.IsAssembliesReloadingNeeded())
                    Internal.ReloadAssemblies(softReload: false);
            }
        }

        private void TimerTimeout()
        {
            if (Internal.IsAssembliesReloadingNeeded())
                Internal.ReloadAssemblies(softReload: false);
        }

        public void RestartTimer()
        {
            watchTimer.Stop();
            watchTimer.Start();
        }

        public override void _Ready()
        {
            base._Ready();

            watchTimer = new Timer
            {
                OneShot = false,
                WaitTime = (float)EditorDef("mono/assembly_watch_interval_sec", 0.5)
            };
            watchTimer.Timeout += TimerTimeout;
            AddChild(watchTimer);
            watchTimer.Start();
        }
    }
}

using Godot;
using GodotTools.Internals;
using static GodotTools.Internals.Globals;

namespace GodotTools
{
    public class HotReloadAssemblyWatcher : Node
    {
        private Timer watchTimer;

        public override void _Notification(int what)
        {
            if (what == Node.NotificationWmWindowFocusIn)
            {
                RestartTimer();

                if (Internal.IsAssembliesReloadingNeeded())
                    Internal.ReloadAssemblies(softReload: false);
            }
        }

        private void TimerTimeout()
        {
            if (Internal.IsAssembliesReloadingNeeded())
                Internal.ReloadAssemblies(softReload: false);
        }

        public void RestartTimer()
        {
            watchTimer.Stop();
            watchTimer.Start();
        }

        public override void _Ready()
        {
            base._Ready();

            watchTimer = new Timer
            {
                OneShot = false,
                WaitTime = (float)EditorDef("mono/assembly_watch_interval_sec", 0.5)
            };
            watchTimer.Timeout += TimerTimeout;
            AddChild(watchTimer);
            watchTimer.Start();
        }
    }
}

Change assembly watcher after notification changes

Fixed Mono not building after #39986 was merged due to a constant that got renamed.


using NBi.Core.Query;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Testing.Unit.Core.Query
{
    [TestFixture]
    public class CommandBuilderTest
    {
        [Test]
        public void Build_TimeoutSpecified_TimeoutSet()
        {
            var builder = new CommandBuilder();
            var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 5000);
            Assert.That(cmd.CommandTimeout, Is.EqualTo(5));
        }

        [Test]
        public void Build_TimeoutSetToZero_TimeoutSet30Seconds()
        {
            var builder = new CommandBuilder();
            var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 0);
            Assert.That(cmd.CommandTimeout, Is.EqualTo(30));
        }

        [Test]
        public void Build_TimeoutSetTo30_TimeoutSet30Seconds()
        {
            var builder = new CommandBuilder();
            var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 30000);
            Assert.That(cmd.CommandTimeout, Is.EqualTo(30));
        }
    }
}

using NBi.Core.Query;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Testing.Unit.Core.Query
{
    [TestFixture]
    public class CommandBuilderTest
    {
        [Test]
        public void Build_TimeoutSpecified_TimeoutSet()
        {
            var builder = new CommandBuilder();
            var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 5000);
            Assert.That(cmd.CommandTimeout, Is.EqualTo(5));
        }

        [Test]
        public void Build_TimeoutSetToZero_TimeoutSet0Seconds()
        {
            var builder = new CommandBuilder();
            var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 0);
            Assert.That(cmd.CommandTimeout, Is.EqualTo(0));
        }

        [Test]
        public void Build_TimeoutSetTo30_TimeoutSet30Seconds()
        {
            var builder = new CommandBuilder();
            var cmd = builder.Build("Data Source=server;Initial Catalog=database;Integrated Security=SSPI", "WAITFOR DELAY '00:00:15'", null, null, 30000);
            Assert.That(cmd.CommandTimeout, Is.EqualTo(30));
        }
    }
}

Change test to map with allign with initial design and documentation


using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;

namespace Sandbox
{
    public class App : Application
    {
        public override void Initialize()
        {
            AvaloniaXamlLoader.Load(this);
        }

        public override void OnFrameworkInitializationCompleted()
        {
            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime)
            {
                desktopLifetime.MainWindow = new MainWindow();

                desktopLifetime.ShutdownRequested += DesktopLifetime_ShutdownRequested;
            }
        }

        private void DesktopLifetime_ShutdownRequested(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
        }
    }
}

using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;

namespace Sandbox
{
    public class App : Application
    {
        public override void Initialize()
        {
            AvaloniaXamlLoader.Load(this);
        }

        public override void OnFrameworkInitializationCompleted()
        {
            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime)
            {
                desktopLifetime.MainWindow = new MainWindow();
            }
        }
    }
}

Revert "sandbox demo of shutdown cancel."

This reverts commit 851baa6537859ea6df8d774911003c97aa1e1bf8.


using System;
using Aspose.Slides.Export;
using Aspose.Slides.Charts;
using Aspose.Slides;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Slides.Examples.CSharp.Text
{
    class UseCustomFonts
    {
        public static void Run()
        {
            //ExStart:UseCustomFonts
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Text();

            String[] loadFonts = new String[] { dataDir + "CustomFonts.ttf" };

            // Load the custom font directory fonts
            FontsLoader.LoadExternalFonts(loadFonts);

            // Do Some work and perform presentation/slides rendering
            using (Presentation presentation = new Presentation(dataDir + "DefaultFonts.pptx"))
                presentation.Save(dataDir + "NewFonts_out.pptx", SaveFormat.Pptx);

            // Clear Font Cachce
            FontsLoader.ClearCache();
            //ExEnd:UseCustomFonts
        }
    }
}

using System;
using Aspose.Slides.Export;
using Aspose.Slides.Charts;
using Aspose.Slides;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Slides.Examples.CSharp.Text
{
    class UseCustomFonts
    {
        public static void Run()
        {
            //ExStart:UseCustomFonts
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Text();

            // folders to seek fonts
            String[] folders = new String[] { dataDir };

            // Load the custom font directory fonts
            FontsLoader.LoadExternalFonts(folders);

            // Do Some work and perform presentation/slides rendering
            using (Presentation presentation = new Presentation(dataDir + "DefaultFonts.pptx"))
                presentation.Save(dataDir + "NewFonts_out.pptx", SaveFormat.Pptx);

            // Clear Font Cachce
            FontsLoader.ClearCache();
            //ExEnd:UseCustomFonts
        }
    }
}

SLIDESNET-42483: Fix external fonts loading example (use folders to seek fonts)


using System;
using SFA.DAS.CommitmentsV2.Types;

namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
    public class CreateChangeOfPartyRequestRequest : SaveDataRequest
    {
        public ChangeOfPartyRequestType ChangeOfPartyRequestType { get; set; }
        public long NewPartyId { get; set; }
        public int? NewPrice { get; set; }
        public DateTime? NewStartDate { get; set; }
        public DateTime? NewEndDate { get; set; }
    }
}

using System;
using SFA.DAS.CommitmentsV2.Types;

namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
    public class CreateChangeOfPartyRequestRequest : SaveDataRequest
    {
        public ChangeOfPartyRequestType ChangeOfPartyRequestType { get; set; }
        public long NewPartyId { get; set; }
        public int? NewPrice { get; set; }
        public DateTime? NewStartDate { get; set; }
        public DateTime? NewEndDate { get; set; }
        public DateTime? NewEmploymentEndDate { get; set; }
        public int? NewEmploymentPrice { get; set; }
    }
}

Add new employment fields for change employer (Portable)


using System;

namespace UpdateManager
{
    public class UpdateManagerUpdateable : IUpdateable
    {
        private UpdateManagerUpdateable() { }

        private static UpdateManagerUpdateable _Instance { get; set; }

        public static UpdateManagerUpdateable Instance
        {
            get
            {
                if (_Instance == null)
                    _Instance = new UpdateManagerUpdateable();
                return _Instance;
            }
        }

        public string UpdateName
        {
            get { return "Update Manager"; }
        }

        public string XMLURL
        {
            get { return "http://livesplit.org/update/update.updater.xml"; }
        }

        public string UpdateURL
        {
            get { return "http://livesplit.org/update/"; }
        }

        public Version Version
        {
            get { return Version.Parse("2.0"); }
        }
    }
}

using System;

namespace UpdateManager
{
    public class UpdateManagerUpdateable : IUpdateable
    {
        private UpdateManagerUpdateable() { }

        private static UpdateManagerUpdateable _Instance { get; set; }

        public static UpdateManagerUpdateable Instance
        {
            get
            {
                if (_Instance == null)
                    _Instance = new UpdateManagerUpdateable();
                return _Instance;
            }
        }

        public string UpdateName
        {
            get { return "Update Manager"; }
        }

        public string XMLURL
        {
            get { return "http://livesplit.org/update/update.updater.xml"; }
        }

        public string UpdateURL
        {
            get { return "http://livesplit.org/update/"; }
        }

        public Version Version
        {
            get { return Version.Parse("2.0.1"); }
        }
    }
}

Change the UpdateManager's version to 2.0.1


using System;
using System.Xml;
using Arkivverket.Arkade.Core;

namespace Arkivverket.Arkade.Tests.Noark5
{
    public class NumberOfArchives : BaseTest
    {
        public const string AnalysisKeyArchives = "Archives";

        public NumberOfArchives(IArchiveContentReader archiveReader) : base(TestType.Content, archiveReader)
        {
        }

        protected override void Test(Archive archive)
        {
            using (var reader = XmlReader.Create(ArchiveReader.GetContentAsStream(archive)))
            {
                int counter = 0;
                while (reader.ReadToFollowing("arkiv"))
                {
                    counter++;
                }

                AddAnalysisResult(AnalysisKeyArchives, counter.ToString());

                TestSuccess($"Antall arkiver: {counter}.");
            }
        }

    }
}

using System;
using System.Xml;
using Arkivverket.Arkade.Core;

namespace Arkivverket.Arkade.Tests.Noark5
{
    public class NumberOfArchives : BaseTest
    {
        public const string AnalysisKeyArchives = "Archives";

        public NumberOfArchives(IArchiveContentReader archiveReader) : base(TestType.Content, archiveReader)
        {
        }

        protected override void Test(Archive archive)
        {
            using (var reader = XmlReader.Create(ArchiveReader.GetContentAsStream(archive)))
            {
                int counter = 0;
                while (reader.ReadToFollowing("arkiv"))
                {
                    counter++;
                }

                AddAnalysisResult(AnalysisKeyArchives, counter.ToString());

                TestSuccess($"Antall arkiv: {counter}.");
            }
        }

    }
}

Fix typo in test message.

Fix typo in test message.


using LanguageSchoolApp.Data.Model;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LanguageSchoolApp.Data
{
    public class MsSqlDbContext : IdentityDbContext<User>
    {
        public MsSqlDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public IDbSet<Course> Courses { get; set; }

        public static MsSqlDbContext Create()
        {
            return new MsSqlDbContext();
        }
    }
}

using LanguageSchoolApp.Data.Model;
using LanguageSchoolApp.Data.Model.Contracts;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LanguageSchoolApp.Data
{
    public class MsSqlDbContext : IdentityDbContext<User>
    {
        public MsSqlDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public IDbSet<Course> Courses { get; set; }

        public override int SaveChanges()
        {
            this.ApplyAuditInfoRules();
            return base.SaveChanges();
        }

        private void ApplyAuditInfoRules()
        {
            foreach (var entry in
                this.ChangeTracker.Entries()
                    .Where(e =>
                        e.Entity is IAuditable && ((e.State == EntityState.Added) || (e.State == EntityState.Modified))))
            {
                var entity = (IAuditable)entry.Entity;
                if (entry.State == EntityState.Added && entity.CreatedOn == default(DateTime))
                {
                    entity.CreatedOn = DateTime.Now;
                }
                else
                {
                    entity.ModifiedOn = DateTime.Now;
                }
            }
        }

        public static MsSqlDbContext Create()
        {
            return new MsSqlDbContext();
        }
    }
}

Update CreatedOn or MmodifiedOn properties of tracked entities when saving changes.


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

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

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

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

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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ecceafc0-b15a-4932-99ec-36315a4e82e7")]

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

Revert "Removed Guid from iOS project"

Revert "Removed Guid from iOS project"

This reverts commit 30b8de6d6e18973a53d7284010d4b65ba3a1adb4.


using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Engine {

    public class BaseEngine : BaseEngineObject {

        public BaseEngine() {
        }

        public virtual void Tick(float deltaTime) {
        }
    }
}

Remove + cleanup warnings. Refactor pass.


using System;
using System.Linq;
using AutoMapper;

namespace PicklesDoc.Pickles.ObjectModel
{
    public class KeywordResolver : ITypeConverter<string, Keyword>
    {
        private readonly string language;

        public KeywordResolver(string language)
        {
            this.language = language;
        }

        public Keyword Convert(ResolutionContext context)
        {
            string source = (string) context.SourceValue;
            return this.MapToKeyword(source);
        }

        private Keyword MapToKeyword(string keyword)
        {
            keyword = keyword.Trim();

            var gherkinDialect = new LanguageServices(new Configuration() { Language = this.language });

            if (gherkinDialect.WhenStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.When;
            }
            if (gherkinDialect.GivenStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.Given;
            }
            if (gherkinDialect.ThenStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.Then;
            }
            if (gherkinDialect.AndStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.And;
            }
            if (gherkinDialect.ButStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.But;
            }

            throw new ArgumentOutOfRangeException("keyword");
        }
    }
}

using System;
using System.Linq;
using AutoMapper;

namespace PicklesDoc.Pickles.ObjectModel
{
    public class KeywordResolver : ITypeConverter<string, Keyword>
    {
        private readonly string language;

        public KeywordResolver(string language)
        {
            this.language = language;
        }

        public Keyword Convert(ResolutionContext context)
        {
            string source = (string) context.SourceValue;
            return this.MapToKeyword(source);
        }

        private Keyword MapToKeyword(string keyword)
        {
            keyword = keyword.Trim();

            var gherkinDialect = new LanguageServices(new Configuration() { Language = this.language });

            if (gherkinDialect.WhenStepKeywords.Contains(keyword))
            {
                return Keyword.When;
            }
            if (gherkinDialect.GivenStepKeywords.Contains(keyword))
            {
                return Keyword.Given;
            }
            if (gherkinDialect.ThenStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.Then;
            }
            if (gherkinDialect.AndStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.And;
            }
            if (gherkinDialect.ButStepKeywords.Select(s => s.Trim()).Contains(keyword))
            {
                return Keyword.But;
            }

            throw new ArgumentOutOfRangeException("keyword");
        }
    }
}

Remove unnecessary call to Trim

Remove unnecessary call to Trim


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

namespace MonoTorrent.Common
{
    public interface ITorrentFileSource
    {
        IEnumerable<FileMapping> Files { get; }
        bool IgnoreHidden { get; }
        string TorrentName { get; }
    }
}

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

namespace MonoTorrent.Common
{
    public interface ITorrentFileSource
    {
        IEnumerable<FileMapping> Files { get; }
        string TorrentName { get; }
    }
}

Remove the 'IgnoreHidden' parameter from ITorrentFileSource

This property makes on sense to be on the interface as it's
implementation specific as to whether or not it applies. All the
interfaces should care about is providing a name for the torrent and a
list of files which should be added to it.


using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;

namespace Promact.Trappist.Repository.Questions
{
    public class QuestionRepository : IQuestionRepository
    {
        private readonly TrappistDbContext _dbContext;

        public QuestionRepository(TrappistDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// Get all questions
        /// </summary>
        /// <returns>Question list</returns>
        public List<SingleMultipleAnswerQuestion> GetAllQuestions()
        {
            var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
            return questions;
        }
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
            _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
            _dbContext.SaveChanges();
        }
    }
}

Update server side API for single multiple answer question


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

using System.Diagnostics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Screens.Testing;
using osu.Game.Graphics.Sprites;
using osu.Game.Screens.Select.Filter;
using osu.Game.Graphics.UserInterface;

namespace osu.Desktop.VisualTests.Tests
{
    public class TestCaseTabControl : TestCase
    {
        public override string Description => @"Filter for song select";

        public override void Reset()
        {
            base.Reset();

            OsuSpriteText text;
            OsuTabControl<GroupMode> filter;

            Add(new FillFlowContainer
            {
                Direction = FillDirection.Horizontal,
                AutoSizeAxes = Axes.Both,
                Children = new Drawable[]
                {
                    filter = new OsuTabControl<GroupMode>
                    {
                        Width = 229,
                        AutoSort = true
                    },
                    text = new OsuSpriteText
                    {
                        Text = "None",
                        Margin = new MarginPadding(4)
                    }
                }
            });

            filter.PinTab(GroupMode.All);
            filter.PinTab(GroupMode.RecentlyPlayed);

            filter.ValueChanged += (sender, mode) =>
            {
                Debug.WriteLine($"Selected {mode}");
                text.Text = mode.ToString();
            };
        }
    }
}

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

using OpenTK;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Screens.Testing;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Select.Filter;

namespace osu.Desktop.VisualTests.Tests
{
    public class TestCaseTabControl : TestCase
    {
        public override string Description => @"Filter for song select";

        public override void Reset()
        {
            base.Reset();

            OsuSpriteText text;
            OsuTabControl<GroupMode> filter;
            Add(filter = new OsuTabControl<GroupMode>
            {
                Width = 229,
                AutoSort = true
            });
            Add(text = new OsuSpriteText
            {
                Text = "None",
                Margin = new MarginPadding(4),
                Position = new Vector2(275, 5)
            });

            filter.PinTab(GroupMode.All);
            filter.PinTab(GroupMode.RecentlyPlayed);

            filter.ValueChanged += (sender, mode) =>
            {
                text.Text = "Currently Selected: " + mode.ToString();
            };
        }
    }
}

Make TabControl test label more clear

Make TabControl test label more clear


using System;
using System.Net.Http;
using System.Threading.Tasks;
using GlobalExceptionHandler.Tests.WebApi.Fixtures;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Shouldly;
using Xunit;

namespace GlobalExceptionHandler.Tests.WebApi.LoggerTests
{
    public class LogExceptionTests : IClassFixture<WebApiServerFixture>
    {
        private Exception _exception;
        private HttpContext _context;

        public LogExceptionTests(WebApiServerFixture fixture)
        {
            // Arrange
            const string requestUri = "/api/productnotfound";
            var webHost = fixture.CreateWebHost();
            webHost.Configure(app =>
            {
                app.UseWebApiGlobalExceptionHandler(x =>
                {
                    x.OnError((ex, context) =>
                    {
                        Console.WriteLine("Log error");
                        _exception = ex;
                        _context = context;
                        return Task.CompletedTask;
                    });
                });

                app.Map(requestUri, config =>
                {
                    config.Run(context => throw new ArgumentException("Invalid request"));
                });
            });

            // Act
            var server = new TestServer(webHost);
            using (var client = server.CreateClient())
            {
                var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), requestUri);
                client.SendAsync(requestMessage).Wait();
                Task.Delay(TimeSpan.FromSeconds(3));
            }
        }

        [Fact]
        public void Invoke_logger()
        {
            _exception.ShouldBeOfType<ArgumentException>();
        }

        [Fact]
        public void Context_is_set()
        {
            _context.ShouldBeOfType<DefaultHttpContext>();
        }
    }
}

using System;
using System.Net.Http;
using System.Threading.Tasks;
using GlobalExceptionHandler.Tests.WebApi.Fixtures;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Shouldly;
using Xunit;

namespace GlobalExceptionHandler.Tests.WebApi.LoggerTests
{
    public class LogExceptionTests : IClassFixture<WebApiServerFixture>
    {
        private Exception _exception;
        private HttpContext _context;

        public LogExceptionTests(WebApiServerFixture fixture)
        {
            // Arrange
            const string requestUri = "/api/productnotfound";
            var webHost = fixture.CreateWebHost();
            webHost.Configure(app =>
            {
                app.UseWebApiGlobalExceptionHandler(x =>
                {
                    x.OnError((ex, context) =>
                    {
                        _exception = ex;
                        _context = context;
                        return Task.CompletedTask;
                    });
                });

                app.Map(requestUri, config =>
                {
                    config.Run(context => throw new ArgumentException("Invalid request"));
                });
            });

            // Act
            var server = new TestServer(webHost);
            using (var client = server.CreateClient())
            {
                var requestMessage = new HttpRequestMessage(new HttpMethod("GET"), requestUri);
                client.SendAsync(requestMessage).Wait();
                Task.Delay(1000);
            }
        }

        [Fact]
        public void Invoke_logger()
        {
            _exception.ShouldBeOfType<ArgumentException>();
        }

        [Fact]
        public void Context_is_set()
        {
            _context.ShouldBeOfType<DefaultHttpContext>();
        }
    }
}

Add artificial wait to fix tests

Add artificial wait to fix tests


using System;
using System.Linq;

namespace CefSharp.Example
{
    public static class CefExample
    {
        public const string DefaultUrl = "custom://cefsharp/home";

        // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
        private const bool debuggingSubProcess = false;

        public static void Init()
        {
            var settings = new CefSettings();
            settings.RemoteDebuggingPort = 8088;

            if (debuggingSubProcess)
            {
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe";
            }

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            if (!Cef.Initialize(settings))
            {
                if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    return;
                }
            }

            Cef.RegisterJsObject("bound", new BoundObject());
        }
    }
}

using System;
using System.Linq;

namespace CefSharp.Example
{
    public static class CefExample
    {
        public const string DefaultUrl = "custom://cefsharp/home";

        // Use when debugging the actual SubProcess, to make breakpoints etc. inside that project work.
        private const bool debuggingSubProcess = false;

        public static void Init()
        {
            var settings = new CefSettings();
            settings.RemoteDebuggingPort = 8088;
            settings.LogSeverity = LogSeverity.Verbose;

            if (debuggingSubProcess)
            {
                settings.BrowserSubprocessPath = "..\\..\\..\\..\\CefSharp.BrowserSubprocess\\bin\\x86\\Debug\\CefSharp.BrowserSubprocess.exe";
            }

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });

            if (!Cef.Initialize(settings))
            {
                if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    return;
                }
            }

            Cef.RegisterJsObject("bound", new BoundObject());
        }
    }
}

Increase logging to Verbose for examples


@model ForgotPasswordViewModel
@{
    ViewData["Title"] = "Forgot your password?";
}

@ViewData["Title"].

    For more information on how to enable reset password please see this article.

@*<form asp-controller="Account" asp-action="ForgotPassword" method="post" role="form">

Enter your email.

            <input asp-for="Email" class="form-control" />

            <button type="submit" class="btn btn-default">Submit</button>

</form>*@

@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

@model ForgotPasswordViewModel
@{
    ViewData["Title"] = "Forgot your password?";
}

@ViewData["Title"].

    For more information on how to enable reset password please see this article.

@*
<form asp-controller="Account" asp-action="ForgotPassword" method="post" role="form">

Enter your email.

    <fieldset>

              <input asp-for="Email" class="form-control" />

              <button type="submit" class="btn btn-primary">Submit</button>

    </fieldset>
</form>
*@

@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

Rewrite markup for password reminder form


using System.Collections.Generic;

namespace EngineLayer
{
    static class ProductTypeToTerminusType
    {
        public static TerminusType IdentifyTerminusType(List<ProductType> lp)
        {
            if ((lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C)) && (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot)))
            {
                return TerminusType.None;
            }
            else if (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot))
            {
                return TerminusType.C;
            }
            else //if(lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C))
            {
                return TerminusType.N;
            }
        }
    }
}

using System.Collections.Generic;

namespace EngineLayer
{
    static class ProductTypeToTerminusType
    {
        public static TerminusType IdentifyTerminusType(List<ProductType> lp)
        {
            if ((lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C) || lp.Contains(ProductType.Adot))
                && (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot) || lp.Contains(ProductType.X)))
            {
                return TerminusType.None;
            }
            else if (lp.Contains(ProductType.Y) || lp.Contains(ProductType.Zdot) || lp.Contains(ProductType.X))
            {
                return TerminusType.C;
            }
            else //if(lp.Contains(ProductType.B) || lp.Contains(ProductType.BnoB1ions) || lp.Contains(ProductType.C) || lp.Contains(ProductType.Adot))
            {
                return TerminusType.N;
            }
        }
    }
}

Add a and x ions

Add a and x ions


using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using VasysRomanNumeralsKata;

namespace VasysRomanNumeralsKataTest
{
    [TestClass]
    public class FromRomanNumeralsTest
    {
        [TestMethod]
        public void WhenStringExtensionIsPassedXItReturns10()
        {
            Assert.IsTrue(10 == "X".ParseAsRomanNumeralToLong());
        }

        [TestMethod]
        public void WhenStringExtensionIsPassedARomanNumeralItReturnsArabic()
        {
            Assert.IsTrue(6 == "VI".ParseAsRomanNumeralToLong());
        }

        [TestMethod]
        public void WhenStringExtensionIsPassedARomanNumeralWithUnrecognizedCharactersItReturnsArabicRepresentingTheCharactersRecognized()
        {
            Assert.IsTrue(4 == "I V".ParseAsRomanNumeralToLong());
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using VasysRomanNumeralsKata;

namespace VasysRomanNumeralsKataTest
{
    [TestClass]
    public class FromRomanNumeralsTest
    {
        [TestMethod]
        public void WhenStringExtensionIsPassedXItReturns10()
        {
            Assert.IsTrue(10 == "X".ParseAsRomanNumeralToLong());
        }

        [TestMethod]
        public void WhenStringExtensionIsPassedARomanNumeralItReturnsArabic()
        {
            Assert.IsTrue(6 == "VI".ParseAsRomanNumeralToLong());
        }

        [TestMethod]
        public void WhenStringExtensionIsPassedARomanNumeralWithUnrecognizedCharactersItReturnsArabicRepresentingTheCharactersRecognized()
        {
            Assert.IsTrue(4 == "I V".ParseAsRomanNumeralToLong());
            Assert.IsTrue(4 == "IQV".ParseAsRomanNumeralToLong());
        }
    }
}

Add another test for unrecognized characters.


namespace AspNetCore.RouteAnalyzer
{
    public class RouteInformation
    {
        public string HttpMethod { get; set; } = "GET";
        public string Area { get; set; } = "";
        public string Path { get; set; } = "";
        public string Invocation { get; set; } = "";

        public override string ToString()
        {
            return $"RouteInformation{{Area:\"{Area}\", HttpMethod: \"{HttpMethod}\" Path:\"{Path}\", Invocation:\"{Invocation}\"}}";
        }
    }
}

namespace AspNetCore.RouteAnalyzer
{
    public class RouteInformation
    {
        public string HttpMethod { get; set; } = "GET";
        public string Area { get; set; } = "";
        public string Path { get; set; } = "";
        public string Invocation { get; set; } = "";

        public override string ToString()
        {
            return $"RouteInformation{{Area:\"{Area}\", HttpMethod: \"{HttpMethod}\", Path:\"{Path}\", Invocation:\"{Invocation}\"}}";
        }
    }
}

Add comma between HttpMethod and Path

Add comma between HttpMethod and Path


namespace NServiceBus
{
    using System;
    using System.Data.Common;
    using System.Data.SqlClient;

    public abstract partial class SqlDialect
    {
        /// <summary>
        /// Microsoft SQL Server
        /// </summary>
        public partial class MsSqlServer : SqlDialect
        {
            /// <summary>
            /// Microsoft SQL Server
            /// </summary>
            public MsSqlServer()
            {
                Schema = "dbo";
            }

            internal override void AddCreationScriptParameters(DbCommand command)
            {
                command.AddParameter("schema", Schema);
            }

            internal override void SetJsonParameterValue(DbParameter parameter, object value)
            {
                SetParameterValue(parameter, value);
            }

            internal override void SetParameterValue(DbParameter parameter, object value)
            {
                //TODO: do ArraySegment fro outbox
                if (value is ArraySegment<char> charSegment)
                {
                    var sqlParameter = (SqlParameter)parameter;

                    sqlParameter.Value = charSegment.Array;
                    sqlParameter.Offset = charSegment.Offset;
                    sqlParameter.Size = charSegment.Count;
                }
                else
                {
                    parameter.Value = value;
                }
            }

            internal override CommandWrapper CreateCommand(DbConnection connection)
            {
                var command = connection.CreateCommand();
                return new CommandWrapper(command, this);
            }

            internal override object GetCustomDialectDiagnosticsInfo()
            {
                return new
                {
                    CustomSchema = string.IsNullOrEmpty(Schema),
                    DoNotUseTransportConnection
                };
            }

            internal string Schema { get; set; }
        }
    }
}

namespace NServiceBus
{
    using System;
    using System.Data.Common;

    public abstract partial class SqlDialect
    {
        /// <summary>
        /// Microsoft SQL Server
        /// </summary>
        public partial class MsSqlServer : SqlDialect
        {
            /// <summary>
            /// Microsoft SQL Server
            /// </summary>
            public MsSqlServer()
            {
                Schema = "dbo";
            }

            internal override void AddCreationScriptParameters(DbCommand command)
            {
                command.AddParameter("schema", Schema);
            }

            internal override void SetJsonParameterValue(DbParameter parameter, object value)
            {
                SetParameterValue(parameter, value);
            }

            internal override void SetParameterValue(DbParameter parameter, object value)
            {
                if (value is ArraySegment<char> charSegment)
                {
                    parameter.Value = charSegment.Array;
                    parameter.Size = charSegment.Count;
                }
                else
                {
                    parameter.Value = value;
                }
            }

            internal override CommandWrapper CreateCommand(DbConnection connection)
            {
                var command = connection.CreateCommand();
                return new CommandWrapper(command, this);
            }

            internal override object GetCustomDialectDiagnosticsInfo()
            {
                return new
                {
                    CustomSchema = string.IsNullOrEmpty(Schema),
                    DoNotUseTransportConnection
                };
            }

            internal string Schema { get; set; }
        }
    }
}

Remove unneeded setting of SqlParameter.Offset


using System;

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

using System;

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

Use Enum.Parse overload available in PCL


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WhitelistExecuter.Lib;
using WhitelistExecuter.Web.Models;

namespace WhitelistExecuter.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Whitelist Executer.";

            return View(new HomeModel());
        }

        [HttpPost]
        public ActionResult ExecuteCommand(HomeModel model)
        {
            model.Error = null;

            using (var client = new WhitelistExecuterClient())
            {
                ExecutionResult result;
                try
                {
                    result = client.API.ExecuteCommand(model.Command, model.RelativePath);
                }
                catch (Exception e)
                {
                    model.Error = (e.InnerException ?? e).Message;
                    return View("Index", model);
                }
                //.....ViewBag.ViewBag.mo
                model.StandardOutput = result.StandardOutput;
                model.StandardError = result.StandardError;

            }
            return View("Index", model);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WhitelistExecuter.Lib;
using WhitelistExecuter.Web.Filters;
using WhitelistExecuter.Web.Models;

namespace WhitelistExecuter.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Whitelist Executer.";

            return View(new HomeModel());
        }

        [Authorize]
        [HttpPost]
        public ActionResult ExecuteCommand(HomeModel model)
        {
            model.Error = null;

            using (var client = new WhitelistExecuterClient())
            {
                ExecutionResult result;
                try
                {
                    result = client.API.ExecuteCommand(model.Command, model.RelativePath);
                }
                catch (Exception e)
                {
                    model.Error = (e.InnerException ?? e).Message;
                    return View("Index", model);
                }
                //.....ViewBag.ViewBag.mo
                model.StandardOutput = result.StandardOutput;
                model.StandardError = result.StandardError;

            }
            return View("Index", model);
        }
    }
}

Add [Authorize] to ExecuteCommand action