using System;

namespace Rooijakkers.MeditationTimer.Data
{
    /// <summary>
    /// Stores settings data in local settings storage
    /// </summary>
    public class Settings
    {
        private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage";

        public TimeSpan TimeToGetReady
        {
            get
            {
                var secondsToGetReady =
                    Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE];

                if (secondsToGetReady == null)
                {
                    secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS;
                    SetTimeToGetReady(Convert.ToInt32(secondsToGetReady));
                }

                // Return stored time in seconds as a TimeSpan.
                return new TimeSpan(0, 0, Convert.ToInt32(secondsToGetReady));
            }
            set
            {
                // Store time in seconds obtained from TimeSpan.
                SetTimeToGetReady(value.Seconds);
            }
        }

        private void SetTimeToGetReady(int value)
        {
            Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value;
        }
    }
}

using System;

namespace Rooijakkers.MeditationTimer.Data
{
    /// <summary>
    /// Stores settings data in local settings storage
    /// </summary>
    public class Settings
    {
        private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage";

        public TimeSpan TimeToGetReady
        {
            get
            {
                int? secondsToGetReady =
                    Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] as int?;

                // If settings were not yet stored set to default value.
                if (secondsToGetReady == null)
                {
                    secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS;
                    SetTimeToGetReady(secondsToGetReady.Value);
                }

                // Return stored time in seconds as a TimeSpan.
                return new TimeSpan(0, 0, secondsToGetReady.Value);
            }
            set
            {
                // Store time in seconds obtained from TimeSpan.
                SetTimeToGetReady(value.Seconds);
            }
        }

        private void SetTimeToGetReady(int value)
        {
            Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value;
        }
    }
}

Make settings object bit cleaner

Make settings object bit cleaner


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

#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;

namespace osu.Game.Online.RealtimeMultiplayer
{
    [Serializable]
    public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
    {
        public int? BeatmapID { get; set; }

        public int? RulesetID { get; set; }

        [NotNull]
        public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();

        public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID;

        public override string ToString() => $"Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
    }
}

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

#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;

namespace osu.Game.Online.RealtimeMultiplayer
{
    [Serializable]
    public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
    {
        public int? BeatmapID { get; set; }

        public int? RulesetID { get; set; }

        public string Name { get; set; } = "Unnamed room";

        [NotNull]
        public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();

        public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal);

        public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
    }
}

Add room name to settings

Add room name to settings


<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Calendar Proxy</title>
    <link href="~/Content/iCalStyles.min.css" rel="stylesheet" />
    <link href="~/Content/timer.min.css" rel="stylesheet" />
    <link href="~/Content/calendar-proxy-form.css" rel="stylesheet" />
    <link href="~/Content/texteffects.min.css" rel="stylesheet" />

                    @Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

            @RenderBody()

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Calendar Proxy</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/iCalStyles.min.css" rel="stylesheet" />
    <link href="~/Content/timer.min.css" rel="stylesheet" />
    <link href="~/Content/calendar-proxy-form.css" rel="stylesheet" />
    <link href="~/Content/texteffects.min.css" rel="stylesheet" />

                    @Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

            @RenderBody()

Add missing bootstrap reference (after removing bootswatch)


namespace OmniSharp.Rename
{
    public class ModifiedFileResponse
    {
        public ModifiedFileResponse() {}

        public ModifiedFileResponse(string fileName, string buffer) {
            this.FileName = fileName;
            this.Buffer = buffer;
        }

        public string FileName { get; set; }
        public string Buffer { get; set; }

    }
}

using OmniSharp.Solution;

namespace OmniSharp.Rename
{
    public class ModifiedFileResponse
    {
        private string _fileName;
        public ModifiedFileResponse() {}

        public ModifiedFileResponse(string fileName, string buffer) {
            this.FileName = fileName;
            this.Buffer = buffer;
        }

        public string FileName
        {
            get { return _fileName; }
            set
            {
                _fileName = value.ApplyPathReplacementsForClient();
            }
        }
        public string Buffer { get; set; }

    }
}

Add Cygwin path replacement for Rename/Override


namespace Gu.Units.Tests
{
    using NUnit.Framework;

    public class UnitParserTests
    {
        [TestCase("1m", 1)]
        [TestCase("-1m", -1)]
        [TestCase("1e3m", 1e3)]
        [TestCase("1e+3m", 1e+3)]
        [TestCase("-1e+3m", -1e+3)]
        [TestCase("1e-3m", 1e-3)]
        [TestCase("-1e-3m", -1e-3)]
        [TestCase(" 1m", 1)]
        [TestCase("1m ", 1)]
        [TestCase("1 m", 1)]
        [TestCase("1 m ", 1)]
        [TestCase("1    m", 1)]
        [TestCase("1m ", 1)]
        public void ParseLength(string s, double expected)
        {
            var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From);
            Assert.AreEqual(expected, length.Meters);
        }

        [TestCase("1s", 1)]
        public void ParseTime(string s, double expected)
        {
            var time = UnitParser.Parse<ITimeUnit, Time>(s, Time.From);
            Assert.AreEqual(expected, time.Seconds);
        }
    }
}

namespace Gu.Units.Tests
{
    using NUnit.Framework;

    public class UnitParserTests
    {
        [TestCase("1m", 1)]
        [TestCase("-1m", 1)]
        [TestCase("1e3m", 1e3)]
        [TestCase("1e+3m", 1e+3)]
        [TestCase("1e-3m", 1e-3)]
        [TestCase(" 1m", 1)]
        [TestCase("1 m", 1)]
        [TestCase("1m ", 1)]
        public void ParseLength(string s, double expected)
        {
            var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From);
            Assert.AreEqual(expected, length.Meters);
        }
    }
}

Revert "Added 5 tests for Length and a test for Time"

This reverts commit fc9d9dd8deef45fa4946f25d9293d1c6fc8bf970.


using System.Reflection;

#if XAMMAC
[assembly: AssemblyTitle("Eto.Forms - OS X Platform using Xamarin.Mac")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")]
#else
[assembly: AssemblyTitle("Eto.Forms - OS X Platform using MonoMac")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")]
#endif

using System.Reflection;

#if XAMMAC
[assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac Platform")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")]
#elif Mac64
[assembly: AssemblyTitle("Eto.Forms - MonoMac Platform")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")]
#else
[assembly: AssemblyTitle("Eto.Forms - MonoMac 64-bit Platform")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac with 64-bit mono")]
#endif

Use better title for Mac/Mac64/XamMac assemblies/nuget packages


@using Microsoft.AspNetCore.Identity
@using mvc_individual_authentication.Models

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">

                Hello @UserManager.GetUserName(User)!

                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>

    </form>
}
else
{

Register

Log in

}

@using Microsoft.AspNetCore.Identity
@using mvc_individual_authentication.Models

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" class="form-inline">

                Hello @UserManager.GetUserName(User)!

                <button type="submit" class="btn btn-link nav-link">Log out</button>

    </form>
}
else
{

Register

Log in

}

Rework login partial to BS4

Rework login partial to BS4


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

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
using System;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Microsoft.DirectX")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("alesliehughes")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

[assembly: AssemblyVersion("1.0.*")]

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

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]

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

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
using System;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Microsoft.DirectX")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("alesliehughes")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

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

[assembly: AssemblyVersion("1.0.2902.0")]

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

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]

Set specific version for Microsoft.DirectX.dll.

This is needed for strong-name references to work.


// Copyright 2013 J.C. Moyer
//
// 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.

#pragma warning disable 649

using System;
using Newtonsoft.Json;

namespace Yeena.PathOfExile {
    [JsonObject]
    class PoEItemSocket {
        [JsonProperty("group")] private readonly int _group;
        [JsonProperty("attr")] private readonly string _attr;

        public int Group {
            get { return _group; }
        }

        public PoESocketColor Color {
            get { return PoESocketColorUtilities.Parse(_attr); }
        }

        public override string ToString() {
            return Enum.GetName(typeof(PoESocketColor), Color);
        }
    }
}

// Copyright 2013 J.C. Moyer
//
// 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.

#pragma warning disable 649

using Newtonsoft.Json;

namespace Yeena.PathOfExile {
    [JsonObject]
    class PoEItemSocket {
        [JsonProperty("group")] private readonly int _group;
        [JsonProperty("attr")] private readonly string _attr;

        public int Group {
            get { return _group; }
        }

        public PoESocketColor Color {
            get { return PoESocketColorUtilities.Parse(_attr); }
        }

        public override string ToString() {
            return Color.ToString();
        }
    }
}

Use ToString instead of Enum.GetName

Use ToString instead of Enum.GetName


using System;

Console.WriteLine("Hello World!");

using System;
using System.Linq.Expressions;
using ExpressionToCodeLib;

const int SomeConst = 27;
var myVariable = "implicitly closed over";
var withImplicitType = new {
    A = "ImplicitTypeMember",
};
Console.WriteLine(ExpressionToCode.ToCode(() => myVariable));
new InnerClass().DoIt();
LocalFunction(123);

void LocalFunction(int arg)
{
    var inLocalFunction = 42;
    Expression<Func<int>> expression1 = () => inLocalFunction + myVariable.Length - arg - withImplicitType.A.Length * SomeConst;

    Console.WriteLine(ExpressionToCode.ToCode(expression1));
}

sealed class InnerClass
{
    public static int StaticInt = 37;
    public int InstanceInt = 12;

    public void DoIt()
        => Console.WriteLine(ExpressionToCode.ToCode(() => StaticInt + InstanceInt));
}

Add a bunch of junk you might find in a top-level program


using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture.NUnit3;
using SlackConnector.Connections;
using SlackConnector.Connections.Clients.Channel;
using SlackConnector.Connections.Models;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Outbound;
using SlackConnector.Models;

namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
    internal class PingTests
    {
        [Test, AutoMoqData]
        public async Task should_return_expected_slack_hub([Frozen]Mock<IConnectionFactory> connectionFactory,
            Mock<IChannelClient> channelClient, Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
        {
            // given
            const string slackKey = "key-yay";
            const string userId = "some-id";

            var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
            await slackConnection.Initialise(connectionInfo);

            connectionFactory
                .Setup(x => x.CreateChannelClient())
                .Returns(channelClient.Object);

            var returnChannel = new Channel { Id = "super-id", Name = "dm-channel" };
            channelClient
                .Setup(x => x.JoinDirectMessageChannel(slackKey, userId))
                .ReturnsAsync(returnChannel);

            // when
            await slackConnection.Ping();

            // then
            webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>()));
        }
    }
}

using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture.NUnit3;
using SlackConnector.Connections;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Outbound;
using SlackConnector.Models;

namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
    internal class PingTests
    {
        [Test, AutoMoqData]
        public async Task should_send_ping([Frozen]Mock<IConnectionFactory> connectionFactory,
            Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
        {
            // given
            const string slackKey = "key-yay";

            var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
            await slackConnection.Initialise(connectionInfo);

            // when
            await slackConnection.Ping();

            // then
            webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>()));
        }
    }
}

Remove unused depedency from test

Remove unused depedency from test


using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public interface IRepository<TEntity, TPk>
        where TEntity : class
    {
        TEntity GetKey(TPk key, ISession session);
        Task<TEntity> GetKeyAsync(TPk key, ISession session );
        TEntity Get(TEntity entity, ISession session);
        Task<TEntity> GetAsync(TEntity entity, ISession session);
        IEnumerable<TEntity>  GetAll(ISession session);
        Task<IEnumerable<TEntity>> GetAllAsync(ISession session);
        TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow);
        Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow);
    }
}

using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;

namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
    public interface IRepository<TEntity, TPk>
        where TEntity : class
    {
        TEntity GetKey(TPk key, ISession session);
        TEntity GetKey<TSesssion>(TPk key) where TSesssion : class, ISession;
        Task<TEntity> GetKeyAsync(TPk key, ISession session);
        Task<TEntity> GetKeyAsync<TSesssion>(TPk key) where TSesssion : class, ISession;
        TEntity Get(TEntity entity, ISession session);
        TEntity Get<TSesssion>(TEntity entity) where TSesssion : class, ISession;
        Task<TEntity> GetAsync(TEntity entity, ISession session);
        Task<TEntity> GetAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
        IEnumerable<TEntity>  GetAll(ISession session);
        IEnumerable<TEntity> GetAll<TSesssion>() where TSesssion : class, ISession;
        Task<IEnumerable<TEntity>> GetAllAsync(ISession session);
        Task<IEnumerable<TEntity>> GetAllAsync<TSesssion>() where TSesssion : class, ISession;
        TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow);
        TPk SaveOrUpdate<TSesssion>(TEntity entity) where TSesssion : class, ISession;
        Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow);
        Task<TPk> SaveOrUpdateAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
    }
}

Expand interface to be more testable. So methods must have a session (i.e. not null) and add a generic for session when no session is needed.


namespace Glimpse.Core.Plugin.Assist
{
    public static class FormattingKeywords
    {
        public const string Error = "error";
        public const string Fail = "fail";
        public const string Info = "info";
        public const string Loading = "loading";
        public const string Ms = "ms";
        public const string Quiet = "quiet";
        public const string Selected = "selected";
        public const string Warn = "warn";
    }
}

namespace Glimpse.Core.Plugin.Assist
{
    public static class FormattingKeywords
    {
        public const string Error = "error";
        public const string Fail = "fail";
        public const string Info = "info";
        public const string Loading = "loading";
        public const string Ms = "ms";
        public const string Quiet = "quiet";
        public const string Selected = "selected";
        public const string Warn = "warn";

        public static string Convert(FormattingKeywordEnum keyword)
        {
            switch (keyword)
            {
                case FormattingKeywordEnum.Error:
                    return Error;
                case FormattingKeywordEnum.Fail:
                    return Fail;
                case FormattingKeywordEnum.Info:
                    return Info;
                case FormattingKeywordEnum.Loading:
                    return Loading;
                case FormattingKeywordEnum.Quite:
                    return Quiet;
                case FormattingKeywordEnum.Selected:
                    return Selected;
                case FormattingKeywordEnum.System:
                    return Ms;
                case FormattingKeywordEnum.Warn:
                    return Warn;
                default:
                    return null;
            }
        }
    }
}

Convert FormattingKeyword enum to it class name counterparts


using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace Auth0.AuthenticationApi
{
    internal class OpenIdConfigurationCache
    {
        private static volatile OpenIdConfigurationCache _instance;
        private static readonly object SyncRoot = new object();

        private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>();

        private OpenIdConfigurationCache() {}

        public static OpenIdConfigurationCache Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (_instance == null)
                            _instance = new OpenIdConfigurationCache();
                    }
                }

                return _instance;
            }
        }

        public async Task<OpenIdConnectConfiguration> GetAsync(string domain)
        {
            _innerCache.TryGetValue(domain, out var configuration);

            if (configuration == null)
            {
                var uri = new Uri(domain);

                IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{uri.AbsoluteUri}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
                configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None);

                _innerCache[domain] = configuration;
            }

            return configuration;
        }
    }
}

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace Auth0.AuthenticationApi
{
    internal class OpenIdConfigurationCache
    {
        private static volatile OpenIdConfigurationCache _instance;
        private static readonly object SyncRoot = new object();

        private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>();

        private OpenIdConfigurationCache() {}

        public static OpenIdConfigurationCache Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (_instance == null)
                            _instance = new OpenIdConfigurationCache();
                    }
                }

                return _instance;
            }
        }

        public async Task<OpenIdConnectConfiguration> GetAsync(string domain)
        {
            _innerCache.TryGetValue(domain, out var configuration);

            if (configuration == null)
            {
                var uri = new Uri(domain);

                IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
                    $"{uri.Scheme}://{uri.Authority}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
                configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None);

                _innerCache[domain] = configuration;
            }

            return configuration;
        }
    }
}

Load OIDC configuration from root of Authority


// 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.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Screens;
using osu.Game.Screens;
using osu.Game.Screens.Menu;
using osuTK.Graphics;

namespace osu.Game.Tests.Visual
{
    [TestFixture]
    public class TestCaseOsuGame : OsuTestCase
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(OsuLogo),
        };

        public TestCaseOsuGame()
        {
            Children = new Drawable[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Colour = Color4.Black,
                },
                new ScreenStack(new Loader())
                {
                    RelativeSizeAxes = Axes.Both,
                }
            };
        }
    }
}

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

using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osu.Game.Screens.Menu;
using osuTK.Graphics;

namespace osu.Game.Tests.Visual
{
    [TestFixture]
    public class TestCaseOsuGame : OsuTestCase
    {
        public override IReadOnlyList<Type> RequiredTypes => new[]
        {
            typeof(OsuLogo),
        };

        [BackgroundDependencyLoader]
        private void load(GameHost host)
        {
            OsuGame game = new OsuGame();
            game.SetHost(host);

            Children = new Drawable[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Colour = Color4.Black,
                },
                game
            };
        }
    }
}

Fix OsuGame test case not working

Fix OsuGame test case not working


using System.Collections;
using JetBrains.Annotations;
using UnityEngine;

namespace HarryPotterUnity.Utils
{
    public class StaticCoroutine : MonoBehaviour
    {

        private static StaticCoroutine _mInstance;

        private static StaticCoroutine Instance
        {
            get
            {
                if (_mInstance != null) return _mInstance;

                _mInstance = FindObjectOfType(typeof(StaticCoroutine)) as StaticCoroutine ??
                             new GameObject("StaticCoroutineManager").AddComponent<StaticCoroutine>();

                return _mInstance;
            }
        }

        [UsedImplicitly]
        void Awake()
        {
            if (_mInstance == null)
            {
                _mInstance = this;
            }
        }

        IEnumerator Perform(IEnumerator coroutine)
        {
            yield return StartCoroutine(coroutine);
            Die();
        }

        /// <summary>
        /// Place your lovely static IEnumerator in here and witness magic!
        /// </summary>
        /// <param name="coroutine">Static IEnumerator</param>
        public static void DoCoroutine(IEnumerator coroutine)
        {
            Instance.StartCoroutine(Instance.Perform(coroutine)); //this will launch the coroutine on our instance
        }

        public static void Die()
        {
            Destroy(_mInstance.gameObject);
            _mInstance = null;
        }

        [UsedImplicitly]
        void OnApplicationQuit()
        {
            _mInstance = null;
        }
    }
}

using System.Collections;
using JetBrains.Annotations;
using UnityEngine;

namespace HarryPotterUnity.Utils
{
    public class StaticCoroutine : MonoBehaviour
    {

        private static StaticCoroutine _mInstance;

        private static StaticCoroutine Instance
        {
            get
            {
                if (_mInstance != null) return _mInstance;

                _mInstance = FindObjectOfType(typeof(StaticCoroutine)) as StaticCoroutine ??
                             new GameObject("StaticCoroutineManager").AddComponent<StaticCoroutine>();

                return _mInstance;
            }
        }

        [UsedImplicitly]
        void Awake()
        {
            if (_mInstance == null)
            {
                _mInstance = this;
            }
        }

        IEnumerator Perform(IEnumerator coroutine)
        {
            yield return StartCoroutine(coroutine);
            Die();
        }

        /// <summary>
        /// Place your lovely static IEnumerator in here and witness magic!
        /// </summary>
        /// <param name="coroutine">Static IEnumerator</param>
        public static void DoCoroutine(IEnumerator coroutine)
        {
            Instance.StartCoroutine(Instance.Perform(coroutine)); //this will launch the coroutine on our instance
        }

        public static void Die()
        {
            _mInstance.StopAllCoroutines();
            Destroy(_mInstance.gameObject);
            _mInstance = null;
        }

        [UsedImplicitly]
        void OnApplicationQuit()
        {
            _mInstance = null;
        }
    }
}

Stop all coroutines on Die()

Stop all coroutines on Die()


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

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;

namespace System.Reflection.Metadata
{
    public static class AssemblyExtensions
    {
        [DllImport(JitHelpers.QCall)]
        [SecurityCritical] // unsafe method
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);

        // Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader.
        //   - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET
        //     native images, etc.
        //   - Callers should not write to the metadata blob
        //   - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is
        //     associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
        //     metadata blob.
        [CLSCompliant(false)] // out byte* blob
        [SecurityCritical] // unsafe method
        public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            blob = null;
            length = 0;
            return InternalTryGetRawMetadata((RuntimeAssembly)assembly, ref blob, ref length);
        }
    }
}

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

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;

namespace System.Reflection.Metadata
{
    public static class AssemblyExtensions
    {
        [DllImport(JitHelpers.QCall)]
        [SecurityCritical] // unsafe method
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);

        // Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader.
        //   - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET
        //     native images, etc.
        //   - Callers should not write to the metadata blob
        //   - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is
        //     associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
        //     metadata blob.
        [CLSCompliant(false)] // out byte* blob
        [SecurityCritical] // unsafe method
        public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            blob = null;
            length = 0;

            var runtimeAssembly = assembly as RuntimeAssembly;
            if (runtimeAssembly == null)
            {
                return false;
            }

            return InternalTryGetRawMetadata(runtimeAssembly, ref blob, ref length);
        }
    }
}

Fix TryGetRawMetadata to return false when the assembly is not a RuntimeAssembly

Related to dotnet/corefx#2768


using System;
using Xunit;

namespace FromString.Tests
{
    public class ParsedTTests
    {
        [Fact]
        public void CanParseAnInt()
        {
            var parsedInt = new Parsed<int>("123");

            Assert.True(parsedInt.HasValue);
            Assert.Equal(123, parsedInt.Value);
        }

        [Fact]
        public void AnInvalidStringSetsHasValueFalse()
        {
            var parsedInt = new Parsed<int>("this is not a string");

            Assert.False(parsedInt.HasValue);
        }

        [Fact]
        public void AnInvalidStringThrowsExceptionWhenAccessingValue()
        {
            var parsedInt = new Parsed<int>("this is not a string");

            Assert.Throws<InvalidOperationException>(() => parsedInt.Value);
        }

        [Fact]
        public void CanGetBackRawValue()
        {
            var parsedInt = new Parsed<int>("this is not a string");

            Assert.Equal("this is not a string", parsedInt.RawValue);
        }

        [Fact]
        public void CanAssignValueDirectly()
        {
            Parsed<decimal> directDecimal = 123.45m;

            Assert.True(directDecimal.HasValue);
            Assert.Equal(123.45m, directDecimal.Value);
        }

        [Fact]
        public void ParsingInvalidUriFails()
        {
            var parsedUri = new Parsed<Uri>("this is not an URI");

            Assert.False(parsedUri.HasValue);
        }
    }
}

using System;
using Xunit;

namespace FromString.Tests
{
    public class ParsedTTests
    {
        [Fact]
        public void CanParseAnInt()
        {
            var parsedInt = new Parsed<int>("123");

            Assert.True(parsedInt.HasValue);
            Assert.Equal(123, parsedInt.Value);
        }

        [Fact]
        public void AnInvalidStringSetsHasValueFalse()
        {
            var parsedInt = new Parsed<int>("this is not a string");

            Assert.False(parsedInt.HasValue);
        }

        [Fact]
        public void AnInvalidStringThrowsExceptionWhenAccessingValue()
        {
            var parsedInt = new Parsed<int>("this is not a string");

            Assert.Throws<InvalidOperationException>(() => parsedInt.Value);
        }

        [Fact]
        public void CanGetBackRawValue()
        {
            var parsedInt = new Parsed<int>("this is not a string");

            Assert.Equal("this is not a string", parsedInt.RawValue);
        }

        [Fact]
        public void CanAssignValueDirectly()
        {
            Parsed<decimal> directDecimal = 123.45m;

            Assert.True(directDecimal.HasValue);
            Assert.Equal(123.45m, directDecimal.Value);
        }

        [Fact]
        public void ParsingInvalidUriFails()
        {
            var parsedUri = new Parsed<Uri>("this is not an URI");

            Assert.False(parsedUri.HasValue);
        }

        [Fact]
        public void ParsingValidAbsoluteUriSucceeds()
        {
            var parsedUri = new Parsed<Uri>("https://github.com/");

            Assert.True(parsedUri.HasValue);
            Assert.Equal(new Uri("https://github.com/"), parsedUri.Value);
        }
    }
}

Test parsing valid absolute URI

Test parsing valid absolute URI


using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using SwissArmyKnife.Benchmarks.Benches.Extensions;
using System;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Toolchains.CsProj;

namespace SwissArmyKnife.Benchmarks
{
    class Program
    {
        private static void Main(string[] args)
        {
            var config = GetConfig();
            var benchmarks = GetBenchmarks();

            for (var i = 0; i < benchmarks.Length; i++)
            {
                var typeToRun = benchmarks[i];
                BenchmarkRunner.Run(typeToRun, config);
            }

            //BenchmarkRunner.Run<StringExtensionsBenchmarks>(config);
        }

        private static Type[] GetBenchmarks()
        {
            var result = new Type[]
            {
                // Extensions
                typeof(ObjectExtensionsBenchmarks),
                typeof(IComparableExtensionsBenchmarks),
                typeof(StringBuilderExtensionsBenchmarks),
                typeof(StringExtensionsBenchmarks),
                typeof(IntExtensionsBenchmarks),
            };

            return result;
        }

        private static IConfig GetConfig()
        {
            var config = ManualConfig.Create(DefaultConfig.Instance);

            config
              .AddDiagnoser(MemoryDiagnoser.Default);

            config.AddJob(
              Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(),
              Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp21),
              Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48)
              );

            return config;
        }
    }
}

using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using SwissArmyKnife.Benchmarks.Benches.Extensions;
using System;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Toolchains.CsProj;

namespace SwissArmyKnife.Benchmarks
{
    class Program
    {
        private static void Main(string[] args)
        {
            var config = GetConfig();
            var benchmarks = GetBenchmarks();

            for (var i = 0; i < benchmarks.Length; i++)
            {
                var typeToRun = benchmarks[i];
                BenchmarkRunner.Run(typeToRun, config);
            }

            //BenchmarkRunner.Run<StringExtensionsBenchmarks>(config);
        }

        private static Type[] GetBenchmarks()
        {
            var result = new Type[]
            {
                // Extensions
                typeof(ObjectExtensionsBenchmarks),
                typeof(IComparableExtensionsBenchmarks),
                typeof(StringBuilderExtensionsBenchmarks),
                typeof(StringExtensionsBenchmarks),
                typeof(IntExtensionsBenchmarks),
            };

            return result;
        }

        private static IConfig GetConfig()
        {
            var config = ManualConfig.Create(DefaultConfig.Instance);

            config
              .AddDiagnoser(MemoryDiagnoser.Default);

            config.AddJob(
              Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(),
              Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48)
              );

            return config;
        }
    }
}

Remove running benchmarks on .NET Core 2.1

We're only running benchmarks on the latest LTS releases of frameworks, so currently we're only running benchmarks on .NET 4.8 and .NET Core 3.1.


using System;
using BudgetAnalyser.Engine.Annotations;

namespace BudgetAnalyser.Engine.Widgets
{
    public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget
    {
        private readonly string disabledToolTip;
        private string doNotUseId;

        public BudgetBucketMonitorWidget()
        {
            this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated.";
        }

        public string Id
        {
            get { return this.doNotUseId; }
            set
            {
                this.doNotUseId = value;
                OnPropertyChanged();
                BucketCode = Id;
            }
        }

        public Type WidgetType => GetType();

        public void Initialise(MultiInstanceWidgetState state, ILogger logger)
        {
        }

        public override void Update([NotNull] params object[] input)
        {
            base.Update(input);

            if (!Enabled)
            {
                ToolTip = this.disabledToolTip;
            }
        }
    }
}

using System;
using BudgetAnalyser.Engine.Annotations;

namespace BudgetAnalyser.Engine.Widgets
{
    public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget
    {
        private readonly string disabledToolTip;
        private string doNotUseId;

        public BudgetBucketMonitorWidget()
        {
            this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated.";
        }

        public string Id
        {
            get { return this.doNotUseId; }
            set
            {
                this.doNotUseId = value;
                OnPropertyChanged();
                BucketCode = Id;
            }
        }

        public Type WidgetType => GetType();

        public void Initialise(MultiInstanceWidgetState state, ILogger logger)
        {
        }

        public override void Update([NotNull] params object[] input)
        {
            base.Update(input);
            DetailedText = BucketCode;
            if (!Enabled)
            {
                ToolTip = this.disabledToolTip;
            }
        }
    }
}

Fix labels not appearing on BucketMonitorWidget


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TicTacToe.Core;
using TicTacToe.Web.Data;
using TicTacToe.Web.ViewModels;

namespace TicTacToe.Controllers
{
    public class GameController : Controller
    {
        private ApplicationDbContext context;
        public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext());

        public ActionResult Index()
        {
            //var context = new ApplicationDbContext();
            //var game = new Game {Player = "123"};
            //var field = new Field() {Game = game};
            //game.Field = field;
            //context.Games.Add(game);
            //context.Commit();
            //context.Dispose();
            return View();
        }

        public ActionResult Play(string playerName)
        {
            if (string.IsNullOrEmpty(playerName))
                return View("Index");
            var game  = new Game();
            game.CreateField();
            game.Player = playerName;
            Context.Games.Add(game);
            return View(game);
        }

        public JsonResult Turn(TurnClientViewModel turn)
        {
            return Json(turn);
        }

        public ActionResult About()
        {
            var context = new ApplicationDbContext();
            var games = context.Games.ToArray();
            context.Dispose();
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        protected override void Dispose(bool disposing)
        {
            context?.Dispose();
            base.Dispose(disposing);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TicTacToe.Core;
using TicTacToe.Web.Data;
using TicTacToe.Web.ViewModels;

namespace TicTacToe.Controllers
{
    public class GameController : Controller
    {
        private ApplicationDbContext context;
        public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext());

        public ActionResult Index()
        {
            //var context = new ApplicationDbContext();
            //var game = new Game {Player = "123"};
            //var field = new Field() {Game = game};
            //game.Field = field;
            //context.Games.Add(game);
            //context.Commit();
            //context.Dispose();
            return View();
        }

        public ActionResult Play(string playerName)
        {
            if (string.IsNullOrEmpty(playerName))
                return View("Index");
            var game  = new Game();
            game.CreateField();
            game.Player = playerName;
            Context.Games.Add(game);
            Context.Commit();
            return View(game);
        }

        public JsonResult Turn(TurnClientViewModel turn)
        {
            return Json(turn);
        }

        public ActionResult About()
        {
            var context = new ApplicationDbContext();
            var games = context.Games.ToArray();
            context.Dispose();
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        protected override void Dispose(bool disposing)
        {
            context?.Dispose();
            base.Dispose(disposing);
        }
    }
}

Add missing Commit, when game starts.

Add missing Commit, when game starts.


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

namespace Autofac.Test.Features.OpenGenerics
{
    public class OpenGenericDelegateTests
    {
        private interface IInterfaceA<T>
        {
        }

        private class ImplementationA<T> : IInterfaceA<T>
        {
        }

        [Fact]
        public void CanResolveByGenericInterface()
        {
            var builder = new ContainerBuilder();

            builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types)))
                   .As(typeof(IInterfaceA<>));

            var container = builder.Build();

            var instance = container.Resolve<IInterfaceA<string>>();

            var implementedType = instance.GetType().GetGenericTypeDefinition();

            Assert.Equal(typeof(ImplementationA<>), implementedType);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using Autofac.Core;
using Autofac.Core.Registration;
using Xunit;

namespace Autofac.Test.Features.OpenGenerics
{
    public class OpenGenericDelegateTests
    {
        private interface IInterfaceA<T>
        {
        }

        private interface IInterfaceB<T>
        {
        }

        private class ImplementationA<T> : IInterfaceA<T>
        {
        }

        [Fact]
        public void CanResolveByGenericInterface()
        {
            var builder = new ContainerBuilder();

            builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types)))
                   .As(typeof(IInterfaceA<>));

            var container = builder.Build();

            var instance = container.Resolve<IInterfaceA<string>>();

            var implementedType = instance.GetType().GetGenericTypeDefinition();

            Assert.Equal(typeof(ImplementationA<>), implementedType);
        }

        [Fact]
        public void DoesNotResolveForDifferentGenericService()
        {
            var builder = new ContainerBuilder();

            builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types)))
                   .As(typeof(IInterfaceA<>));

            var container = builder.Build();

            Assert.Throws<ComponentNotRegisteredException>(() => container.Resolve<IInterfaceB<string>>());
        }
    }
}

Add negative test for the registration source.


namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion
{
    using System;
    using TestClasses;
    using Xunit;

    public class WhenMappingToDateTimes
    {
        [Fact]
        public void ShouldMapANullableDateTimeToADateTime()
        {
            var source = new PublicProperty<DateTime?> { Value = DateTime.Today };
            var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();

            result.Value.ShouldBe(DateTime.Today);
        }

        [Fact]
        public void ShouldMapAYearMonthDayStringToADateTime()
        {
            var source = new PublicProperty<string> { Value = "2016/06/08" };
            var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();

            result.Value.ShouldBe(new DateTime(2016, 06, 08));
        }
    }
}

namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion
{
    using System;
    using Shouldly;
    using TestClasses;
    using Xunit;

    public class WhenMappingToDateTimes
    {
        [Fact]
        public void ShouldMapANullableDateTimeToADateTime()
        {
            var source = new PublicProperty<DateTime?> { Value = DateTime.Today };
            var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();

            result.Value.ShouldBe(DateTime.Today);
        }

        [Fact]
        public void ShouldMapAYearMonthDayStringToADateTime()
        {
            var source = new PublicProperty<string> { Value = "2016/06/08" };
            var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();

            result.Value.ShouldBe(new DateTime(2016, 06, 08));
        }

        [Fact]
        public void ShouldMapAnUnparseableStringToANullableDateTime()
        {
            var source = new PublicProperty<string> { Value = "OOH OOH OOH" };
            var result = Mapper.Map(source).ToNew<PublicProperty<DateTime?>>();

            result.Value.ShouldBeNull();
        }
    }
}

Test coverage for unparseable string -> DateTime conversion


using System;
using System.Collections.Generic;
using System.Linq;
using WalletWasabi.Bases;
using WalletWasabi.Coins;

namespace WalletWasabi.BlockchainAnalysis
{
	public class Cluster : NotifyPropertyChangedBase
	{
		private List<SmartCoin> Coins { get; set; }

		private string _labels;

		public Cluster(params SmartCoin[] coins)
			: this(coins as IEnumerable<SmartCoin>)
		{
		}

		public Cluster(IEnumerable<SmartCoin> coins)
		{
			Coins = coins.ToList();
			Labels = string.Join(", ", KnownBy);
		}

		public string Labels
		{
			get => _labels;
			private set => RaiseAndSetIfChanged(ref _labels, value);
		}

		public int Size => Coins.Count();

		public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase);

		public void Merge(Cluster clusters) => Merge(clusters.Coins);

		public void Merge(IEnumerable<SmartCoin> coins)
		{
			var insertPosition = 0;
			foreach (var coin in coins.ToList())
			{
				if (!Coins.Contains(coin))
				{
					Coins.Insert(insertPosition++, coin);
				}
				coin.Clusters = this;
			}
			if (insertPosition > 0) // at least one element was inserted
			{
				Labels = string.Join(", ", KnownBy);
			}
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using WalletWasabi.Bases;
using WalletWasabi.Coins;

namespace WalletWasabi.BlockchainAnalysis
{
	public class Cluster : NotifyPropertyChangedBase
	{
		private List<SmartCoin> Coins { get; set; }

		private string _labels;

		public Cluster(params SmartCoin[] coins)
			: this(coins as IEnumerable<SmartCoin>)
		{
		}

		public Cluster(IEnumerable<SmartCoin> coins)
		{
			Coins = coins.ToList();
			Labels = string.Join(", ", KnownBy);
		}

		public string Labels
		{
			get => _labels;
			private set => RaiseAndSetIfChanged(ref _labels, value);
		}

		public int Size => Coins.Count;

		public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase);

		public void Merge(Cluster clusters) => Merge(clusters.Coins);

		public void Merge(IEnumerable<SmartCoin> coins)
		{
			var insertPosition = 0;
			foreach (var coin in coins.ToList())
			{
				if (!Coins.Contains(coin))
				{
					Coins.Insert(insertPosition++, coin);
				}
				coin.Clusters = this;
			}
			if (insertPosition > 0) // at least one element was inserted
			{
				Labels = string.Join(", ", KnownBy);
			}
		}
	}
}

Use Count instead of Count()

Use Count instead of Count()

Co-Authored-By: Dávid Molnár <6d607974c44f675e0e525d39b2684f7b117c5263@gmail.com>


using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;

        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }
        [HttpPost]
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;

        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }

        [HttpPost]
        /// <summary>
        /// Add single multiple answer question into SingleMultipleAnswerQuestion model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }

        /// <summary>
        /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
        /// </summary>
        /// <param name="singleMultipleAnswerQuestionOption"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

Update server side API for single multiple answer question


// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace NOpenCL.Test
{
    internal static class TestCategories
    {
        public const string RequireGpu = nameof(RequireGpu);
    }
}

Fix a build warning for missing blank line at end of file


using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;

namespace Sample
{
    sealed partial class App : Template10.Common.BootStrapper
    {
        public App()
        {
            InitializeComponent();
        }

        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            NavigationService.Navigate(typeof(Views.MainPage));
            await Task.Yield();
        }
    }
}

using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;

namespace Sample
{
    sealed partial class App : Template10.Common.BootStrapper
    {
        public App()
        {
            InitializeComponent();
        }

        public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            NavigationService.Navigate(typeof(Views.MainPage));
			return Task.CompletedTask;
		}
    }
}

Replace another Task.Yield with Task.CompletedTask.


@page "{id}"
@model SessionModel

Agenda

Day @(Model.DayOffset + 1)

@Model.Session.Title

@Model.Session.Title

@Model.Session.Track?.Name

@foreach (var speaker in Model.Session.Speakers)
{
    @speaker.Name
}

@Html.Raw(Model.Session.Abstract)

<form method="post">
    <input type="hidden" name="sessionId" value="@Model.Session.ID" />

        Edit
        @if (Model.IsFavorite)
        {
            <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from Favorites</button>
        }
        else
        {
            <button authz="true" type="submit" class="btn btn-primary">Add to Favorites</button>
        }

</form>

@page "{id}"
@model SessionModel

Agenda

Day @(Model.DayOffset + 1)

@Model.Session.Title

@Model.Session.Title

@Model.Session.Track?.Name

@foreach (var speaker in Model.Session.Speakers)
{
    @speaker.Name
}

@Html.Raw(Model.Session.Abstract)

<form method="post">
    <input type="hidden" name="sessionId" value="@Model.Session.ID" />

        Edit
        @if (Model.IsFavorite)
        {
            <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from My Agenda</button>
        }
        else
        {
            <button authz="true" type="submit" class="btn btn-primary">Add to My Agenda</button>
        }

</form>

Change text from favorites to "My Agenda"


using System;
using System.Collections.Generic;
using System.Linq;
using Affecto.IdentityManagement.ApplicationServices.Model;
using Affecto.IdentityManagement.Interfaces.Model;
using Affecto.Mapping.AutoMapper;
using AutoMapper;

namespace Affecto.IdentityManagement.ApplicationServices.Mapping
{
    internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role>
    {
        protected override void ConfigureMaps()
        {
            Func<Querying.Data.Permission, IPermission> permissionCreator = o => new Permission();

            Mapper.CreateMap<Querying.Data.Permission, IPermission>().ConvertUsing(permissionCreator);
            Mapper.CreateMap<Querying.Data.Permission, Permission>();
            Mapper.CreateMap<Querying.Data.Role, Role>()
                .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<IPermission>>(c.Permissions.ToList())));
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using Affecto.IdentityManagement.ApplicationServices.Model;
using Affecto.Mapping.AutoMapper;
using AutoMapper;

namespace Affecto.IdentityManagement.ApplicationServices.Mapping
{
    internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role>
    {
        protected override void ConfigureMaps()
        {
            Mapper.CreateMap<Querying.Data.Permission, Permission>();

            Mapper.CreateMap<Querying.Data.Role, Role>()
                .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<Permission>>(c.Permissions.ToList())));
        }
    }
}

Remove interface mapping from role mapper


using System;
using Autofac;

namespace AGS.Engine.IOS
{
    public class AGSEngineIOS
    {
        private static IOSAssemblies _assembly;

        public static void Init()
        {
            OpenTK.Toolkit.Init();

            var device = new IOSDevice(_assembly);
            AGSGame.Device = device;

            //Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>());
            Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>());
        }

        public static void SetAssembly()
        {
            _assembly = new IOSAssemblies();
        }
    }
}

using System;
using Autofac;

namespace AGS.Engine.IOS
{
    public class AGSEngineIOS
    {
        private static IOSAssemblies _assembly;

        public static void Init()
        {
            // On IOS, when the mono linker is enabled (and it's enabled by default) it strips out all parts of
            // the framework which are not in use. The linker does not support reflection, however, therefore it
            // does not recognize the call to 'GetRuntimeMethod(nameof(Convert.ChangeType)' (which is called from
            // a method in this Autofac in ConstructorParameterBinding class, ConvertPrimitiveType method)
            // as using the 'Convert.ChangeType' method and strips it away unless it's
            // explicitly used somewhere else, crashing Autofac if that method is called.
            // Therefore, by explicitly calling it here, we're playing nicely with the linker and making sure
            // Autofac works on IOS.
            Convert.ChangeType((object)1234f, typeof(float));

            OpenTK.Toolkit.Init();

            var device = new IOSDevice(_assembly);
            AGSGame.Device = device;

            //Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>());
            Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>());
        }

        public static void SetAssembly()
        {
            _assembly = new IOSAssemblies();
        }
    }
}

Fix Autofac crash due to linker stripping out a function used by reflection only


using System;
using System.IO;
using Newtonsoft.Json;

namespace Scanner
{
    using System.Collections.Generic;

    public class BackingStore
    {
        private string backingStoreName;

        public BackingStore(string backingStoreName)
        {
            this.backingStoreName = backingStoreName;
        }

        public IEnumerable<Child> GetAll()
        {
            string json = File.ReadAllText(GetBackingStoreFilename());
            return JsonConvert.DeserializeObject<IEnumerable<Child>>(json);
        }

        public void SaveAll(IEnumerable<Child> children)
        {
            string json = JsonConvert.SerializeObject(children);

            var applicationFile = GetBackingStoreFilename();
            File.WriteAllText(applicationFile, json);
        }

        private static string GetBackingStoreFilename()
        {
            var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner");
            Directory.CreateDirectory(applicationFolder);
            var applicationFile = Path.Combine(applicationFolder, "children.json");
            return applicationFile;
        }
    }
}

using System;
using System.IO;
using Newtonsoft.Json;

namespace Scanner
{
    using System.Collections.Generic;

    public class BackingStore
    {
        private string backingStoreName;

        public BackingStore(string backingStoreName)
        {
            this.backingStoreName = backingStoreName;
        }

        public IEnumerable<Child> GetAll()
        {
            string json = File.ReadAllText(GetBackingStoreFilename());
            return JsonConvert.DeserializeObject<IEnumerable<Child>>(json);
        }

        public void SaveAll(IEnumerable<Child> children)
        {
            string json = JsonConvert.SerializeObject(children);

            var applicationFile = GetBackingStoreFilename();
            File.WriteAllText(applicationFile, json);
        }

        private string GetBackingStoreFilename()
        {
            var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner");
            Directory.CreateDirectory(applicationFolder);
            var applicationFile = Path.Combine(applicationFolder, string.Format("{0}.json", backingStoreName));
            return applicationFile;
        }
    }
}

Make sure we read the backing store name properly.


using System.Collections;
using System.Collections.Generic;
using HarryPotterUnity.Tween;
using HarryPotterUnity.Utils;
using JetBrains.Annotations;
using UnityEngine;

namespace HarryPotterUnity.Cards.Generic
{
    public abstract class GenericSpell : GenericCard {

        private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f);

        protected sealed override void OnClickAction(List<GenericCard> targets)
        {
            Enable();
            PreviewSpell();

            Player.Hand.Remove(this);
            Player.Discard.Add(this);

            SpellAction(targets);
        }

        protected abstract void SpellAction(List<GenericCard> targets);

        private void PreviewSpell()
        {
            State = CardStates.Discarded;
            var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate;
            UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State));
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using HarryPotterUnity.Tween;
using HarryPotterUnity.Utils;
using JetBrains.Annotations;
using UnityEngine;

namespace HarryPotterUnity.Cards.Generic
{
    public abstract class GenericSpell : GenericCard {

        private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f);

        protected sealed override void OnClickAction(List<GenericCard> targets)
        {
            Enable();
            PreviewSpell();

            Player.Hand.Remove(this);
            Player.Discard.Add(this);

            SpellAction(targets);
        }

        protected abstract void SpellAction(List<GenericCard> targets);

        private void PreviewSpell()
        {
            State = CardStates.Discarded;
            var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate;
            UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State, 0.6f));
        }
    }
}

Add 0.6 seconds preview time for spells

Add 0.6 seconds preview time for spells


using Microsoft.Azure.ServiceBus;
using System;
using System.Collections.Generic;
using QueueMessage = Storage.Net.Messaging.QueueMessage;

namespace Storage.Net.Microsoft.Azure.ServiceBus
{
   static class Converter
   {
      public static Message ToMessage(QueueMessage message)
      {
         if(message == null)
            throw new ArgumentNullException(nameof(message));

         var result = new Message(message.Content);
         if(message.Properties != null && message.Properties.Count > 0)
         {
            foreach(KeyValuePair<string, string> prop in message.Properties)
            {
               result.UserProperties.Add(prop.Key, prop.Value);
            }
         }
         return result;
      }

      public static QueueMessage ToQueueMessage(Message message)
      {
         string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString();

         var result = new QueueMessage(id, message.Body);
         result.DequeueCount = message.SystemProperties.DeliveryCount;
         if(message.UserProperties != null && message.UserProperties.Count > 0)
         {
            foreach(KeyValuePair<string, object> pair in message.UserProperties)
            {
               result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString();
            }
         }

         return result;
      }
   }
}

using Microsoft.Azure.ServiceBus;
using System;
using System.Collections.Generic;
using QueueMessage = Storage.Net.Messaging.QueueMessage;

namespace Storage.Net.Microsoft.Azure.ServiceBus
{
   static class Converter
   {
      public static Message ToMessage(QueueMessage message)
      {
         if(message == null)
            throw new ArgumentNullException(nameof(message));

         var result = new Message(message.Content)
         {
            MessageId = message.Id
         };
         if(message.Properties != null && message.Properties.Count > 0)
         {
            foreach(KeyValuePair<string, string> prop in message.Properties)
            {
               result.UserProperties.Add(prop.Key, prop.Value);
            }
         }
         return result;
      }

      public static QueueMessage ToQueueMessage(Message message)
      {
         string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString();

         var result = new QueueMessage(id, message.Body);
         result.DequeueCount = message.SystemProperties.DeliveryCount;
         if(message.UserProperties != null && message.UserProperties.Count > 0)
         {
            foreach(KeyValuePair<string, object> pair in message.UserProperties)
            {
               result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString();
            }
         }

         return result;
      }
   }
}

Add message id to storage convert process


using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
using NoAdsHere.Database;
using NoAdsHere.Database.Models.GuildSettings;
using NoAdsHere.Common;
using NoAdsHere.Common.Preconditions;
using NoAdsHere.Services.AntiAds;

namespace NoAdsHere.Commands.Blocks
{
    [Name("Blocks"), Group("Blocks")]
    public class BlockModule : ModuleBase
    {
        private readonly MongoClient _mongo;

        public BlockModule(IServiceProvider provider)
        {
            _mongo = provider.GetService<MongoClient>();
        }

        [Command("Invites"), Alias("Invite")]
        [RequirePermission(AccessLevel.HighModerator)]
        public async Task Invites(bool setting)
        {
            bool success;
            if (setting)
                success = await AntiAds.TryEnableGuild(BlockType.InstantInvite, Context.Guild.Id);
            else
                success = await AntiAds.TryDisableGuild(BlockType.InstantInvite, Context.Guild.Id);

            if (success)
                await ReplyAsync($":white_check_mark: Discord Invite Blockings have been set to {setting}. {(setting ? "Please ensure that the bot can ManageMessages in the required channels" : "")} :white_check_mark:");
            else
                await ReplyAsync($":exclamation: Discord Invite Blocks already set to {setting} :exclamation:");
        }
    }
}

using System.Threading.Tasks;
using Discord.Commands;
using NoAdsHere.Common;
using NoAdsHere.Common.Preconditions;
using NoAdsHere.Services.AntiAds;

namespace NoAdsHere.Commands.Blocks
{
    [Name("Blocks"), Group("Blocks")]
    public class BlockModule : ModuleBase
    {
        [Command("Invite")]
        [RequirePermission(AccessLevel.HighModerator)]
        public async Task Invites(bool setting)
        {
            bool success;
            if (setting)
                success = await AntiAds.TryEnableGuild(BlockType.InstantInvite, Context.Guild.Id);
            else
                success = await AntiAds.TryDisableGuild(BlockType.InstantInvite, Context.Guild.Id);

            if (success)
                await ReplyAsync($":white_check_mark: Discord Invite Blockings have been set to {setting}. {(setting ? "Please ensure that the bot can ManageMessages in the required channels" : "")} :white_check_mark:");
            else
                await ReplyAsync($":exclamation: Discord Invite Blocks already set to {setting} :exclamation:");
        }
    }
}

Clean the Blocks Module of unused code

Clean the Blocks Module of unused code


using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using ClientSamples.CachingTools;

namespace Tavis.PrivateCache
{
    public class CacheEntry
    {
        public PrimaryCacheKey Key { get; private set; }
        public HttpHeaderValueCollection<string> VaryHeaders { get; private set; }

        internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders)
        {
            Key = key;
            VaryHeaders = varyHeaders;
        }

        public string CreateSecondaryKey(HttpRequestMessage request)
        {

            var key = "";
            foreach (var h in VaryHeaders.OrderBy(v => v))  // Sort the vary headers so that ordering doesn't generate different stored variants
            {
                if (h != "*")
                {
                    key += h + ":" + String.Join(",", request.Headers.GetValues(h));
                }
                else
                {
                    key += "*";
                }
            }
            return key.ToLower();
        }

        public CacheContent CreateContent(HttpResponseMessage response)
        {
            return new CacheContent()
            {
                CacheEntry = this,
                Key = CreateSecondaryKey(response.RequestMessage),
                HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null),
                Expires = HttpCache.GetExpireDate(response),
                CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(),
                Response = response,
            };
        }

    }
}

using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using ClientSamples.CachingTools;

namespace Tavis.PrivateCache
{
    public class CacheEntry
    {
        public PrimaryCacheKey Key { get; private set; }
        public HttpHeaderValueCollection<string> VaryHeaders { get; private set; }

        internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders)
        {
            Key = key;
            VaryHeaders = varyHeaders;
        }

        public string CreateSecondaryKey(HttpRequestMessage request)
        {
            var key = new StringBuilder();
            foreach (var h in VaryHeaders.OrderBy(v => v))  // Sort the vary headers so that ordering doesn't generate different stored variants
            {
                if (h != "*")
                {
                    key.Append(h).Append(':');
                    bool addedOne = false;

                    foreach (var val in request.Headers.GetValues(h))
                    {
                        key.Append(val).Append(',');
                        addedOne = true;
                    }

                    if (addedOne)
                    {
                        key.Length--;  // truncate trailing comma.
                    }
                }
                else
                {
                    key.Append('*');
                }
            }
            return key.ToString().ToLowerInvariant();
        }

        public CacheContent CreateContent(HttpResponseMessage response)
        {
            return new CacheContent()
            {
                CacheEntry = this,
                Key = CreateSecondaryKey(response.RequestMessage),
                HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null),
                Expires = HttpCache.GetExpireDate(response),
                CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(),
                Response = response,
            };
        }

    }
}

Switch to StringBuilder for speed.

Switch to StringBuilder for speed.

String concatenation of varying-count of items should almost always use StringBuilder.


using NBi.Core.Evaluate;
using NBi.Core.ResultSet;
using NBi.Core.Transformation;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace NBi.Xml.Items.Calculation
{
    [XmlType("")]
    public class ExpressionXml: IColumnExpression
    {
        [Obsolete("Use the attribute Script in place of Value")]
        [XmlText()]
        public string Value
        {
            get => ShouldSerializeValue() ? Script.Code : null;
            set => Script = new ScriptXml() { Language = LanguageType.NCalc, Code = value };
        }

        public bool ShouldSerializeValue() => Script?.Language == LanguageType.NCalc;

        [XmlElement("script")]
        public ScriptXml Script { get; set; }

        public bool ShouldSerializeScript() => Script?.Language != LanguageType.NCalc;

        [XmlIgnore()]
        public LanguageType Language
        {
            get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language;
        }

        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("column-index")]
        [DefaultValue(0)]
        public int Column { get; set; }

        [XmlAttribute("type")]
        [DefaultValue(ColumnType.Text)]
        public ColumnType Type { get; set; }

        [XmlAttribute("tolerance")]
        [DefaultValue("")]
        public string Tolerance { get; set; }
    }
}

using NBi.Core.Evaluate;
using NBi.Core.ResultSet;
using NBi.Core.Transformation;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace NBi.Xml.Items.Calculation
{
    [XmlType("")]
    public class ExpressionXml: IColumnExpression
    {
        [XmlText()]
        public string Value
        {
            get => Script.Code;
            set => Script.Code = value;
        }

        public bool ShouldSerializeValue() => Script.Language == LanguageType.NCalc;

        [XmlElement("script")]
        public ScriptXml Script { get; set; }

        public bool ShouldSerializeScript() => Script.Language != LanguageType.NCalc;

        [XmlIgnore()]
        public LanguageType Language
        {
            get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language;
        }

        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("column-index")]
        [DefaultValue(0)]
        public int Column { get; set; }

        [XmlAttribute("type")]
        [DefaultValue(ColumnType.Text)]
        public ColumnType Type { get; set; }

        [XmlAttribute("tolerance")]
        [DefaultValue("")]
        public string Tolerance { get; set; }

        public ExpressionXml()
        {
            Script = new ScriptXml() { Language = LanguageType.NCalc };
        }
    }
}

Fix some xml parsing issues

Fix some xml parsing issues


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

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace TagHelpersWebSite
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            var configuration = app.GetTestConfiguration();

            app.UseServices(services =>
            {
                services.AddMvc(configuration);
            });

            app.UseMvc();
        }
    }
}

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

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace TagHelpersWebSite
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            var configuration = app.GetTestConfiguration();

            app.UsePerRequestServices(services =>
            {
                services.AddMvc(configuration);
            });

            app.UseMvc();
        }
    }
}

Update new test to use UsePerRequestServices


using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace VigilantCupcake.SubForms {

    partial class AboutBox : Form {

        public AboutBox() {
            InitializeComponent();
            Text = $"About {AssemblyTitle}";
            labelProductName.Text = AssemblyTitle;
            labelVersion.Text = AssemblyVersion;
            lastUpdatedBox.Text = LastUpdatedDate.ToString();
            linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
        }

        public string LatestVersionText {
            set { latestBox.Text = value; }
        }

        public static string AssemblyTitle { get; } = "Vigilant Cupcake";

        public static string AssemblyVersion {
            get {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        public static DateTime LastUpdatedDate {
            get {
                return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
            }
        }

        void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            this.linkLabel1.LinkVisited = true;
            System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
        }
    }
}

using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace VigilantCupcake.SubForms {

    partial class AboutBox : Form {

        public AboutBox() {
            InitializeComponent();
            Text = $"About {AssemblyTitle}";
            labelProductName.Text = AssemblyTitle;
            labelVersion.Text = AssemblyVersion;
            lastUpdatedBox.Text = LastUpdatedDate.ToString();
            linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
        }

        public string LatestVersionText {
            set { latestBox.Text = value; }
        }

        public static string AssemblyTitle { get; } = "Vigilant Cupcake";

        public static string AssemblyVersion {
            get {
                var version = Assembly.GetExecutingAssembly().GetName().Version;
                return $"{version.Major}.{version.Minor}.{version.Revision}";
            }
        }

        public static DateTime LastUpdatedDate {
            get {
                return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
            }
        }

        void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            this.linkLabel1.LinkVisited = true;
            System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
        }
    }
}

Reduce information displayed in about box


using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace VigilantCupcake.SubForms {

    partial class AboutBox : Form {

        public AboutBox() {
            InitializeComponent();
            Text = $"About {AssemblyTitle}";
            labelProductName.Text = AssemblyTitle;
            labelVersion.Text = AssemblyVersion;
            lastUpdatedBox.Text = LastUpdatedDate.ToString();
            linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
        }

        public string LatestVersionText {
            set { latestBox.Text = value; }
        }

        public static string AssemblyTitle { get; } = "Vigilant Cupcake";

        public static string AssemblyVersion {
            get {
                var version = Assembly.GetExecutingAssembly().GetName().Version;
                return $"{version.Major}.{version.Minor}.{version.Revision}";
            }
        }

        public static DateTime LastUpdatedDate {
            get {
                return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
            }
        }

        void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            this.linkLabel1.LinkVisited = true;
            System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
        }
    }
}

using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace VigilantCupcake.SubForms {

    partial class AboutBox : Form {

        public AboutBox() {
            InitializeComponent();
            Text = $"About {AssemblyTitle}";
            labelProductName.Text = AssemblyTitle;
            labelVersion.Text = AssemblyVersion;
            lastUpdatedBox.Text = LastUpdatedDate.ToString();
            linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
        }

        public string LatestVersionText {
            set { latestBox.Text = value; }
        }

        public static string AssemblyTitle { get; } = "Vigilant Cupcake";

        public static string AssemblyVersion {
            get {
                var version = Assembly.GetExecutingAssembly().GetName().Version;
                return $"{version.Major}.{version.Minor}.{version.Build}";
            }
        }

        public static DateTime LastUpdatedDate {
            get {
                return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
            }
        }

        void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            this.linkLabel1.LinkVisited = true;
            System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
        }
    }
}

Fix wrong attribute for about box

Fix wrong attribute for about box


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("Digital Color Meter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Digital Color Meter")]
[assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")]
[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("ca199dd4-2017-4ee7-808c-3747101e04b1")]

// 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")]

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("Digital Color Meter")]
[assembly: AssemblyDescription("Released under the MIT License")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Digital Color Meter")]
[assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")]
[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("ca199dd4-2017-4ee7-808c-3747101e04b1")]

// 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")]

Add license info in assembly.

Add license info in assembly.


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

using System;
using Newtonsoft.Json;

namespace osu.Framework.IO.Network
{
    /// <summary>
    /// A web request with a specific JSON response format.
    /// </summary>
    /// <typeparam name="T">the response format.</typeparam>
    public class JsonWebRequest<T> : WebRequest
    {
        public JsonWebRequest(string url = null, params object[] args)
            : base(url, args)
        {
            base.Finished += finished;
        }

        private void finished(WebRequest request, Exception e)
        {
            try
            {
                deserialisedResponse = JsonConvert.DeserializeObject<T>(ResponseString);
            }
            catch (Exception se)
            {
                e = e == null ? se : new AggregateException(e, se);
            }

            Finished?.Invoke(this, e);
        }

        private T deserialisedResponse;

        public T ResponseObject => deserialisedResponse;

        /// <summary>
        /// Request has finished with success or failure. Check exception == null for success.
        /// </summary>
        public new event RequestCompleteHandler<T> Finished;
    }
}

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

using System;
using System.Net;
using Newtonsoft.Json;

namespace osu.Framework.IO.Network
{
    /// <summary>
    /// A web request with a specific JSON response format.
    /// </summary>
    /// <typeparam name="T">the response format.</typeparam>
    public class JsonWebRequest<T> : WebRequest
    {
        public JsonWebRequest(string url = null, params object[] args)
            : base(url, args)
        {
            base.Finished += finished;
        }

        protected override HttpWebRequest CreateWebRequest(string requestString = null)
        {
            var req = base.CreateWebRequest(requestString);
            req.Accept = @"application/json";
            return req;
        }

        private void finished(WebRequest request, Exception e)
        {
            try
            {
                deserialisedResponse = JsonConvert.DeserializeObject<T>(ResponseString);
            }
            catch (Exception se)
            {
                e = e == null ? se : new AggregateException(e, se);
            }

            Finished?.Invoke(this, e);
        }

        private T deserialisedResponse;

        public T ResponseObject => deserialisedResponse;

        /// <summary>
        /// Request has finished with success or failure. Check exception == null for success.
        /// </summary>
        public new event RequestCompleteHandler<T> Finished;
    }
}

Use the correct Accept type for json requests

We were getting html error responses from the API when http response code errors were expected


using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Api.Startup))]

namespace SFA.DAS.EmployerUsers.Api
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

using System.Net;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Api.Startup))]

namespace SFA.DAS.EmployerUsers.Api
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

            ConfigureAuth(app);
        }
    }
}

Add TLS change to make the call to the Audit api work


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("TSRandom")]
[assembly: AssemblyDescription("Thread safe random number generator")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TSRandom")]
[assembly: AssemblyCopyright("Copyright © Soleil Rojas 2017")]
[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("82f2ca28-6157-41ff-b644-2ef357ee4d6c")]

// 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")]

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("TSRandom")]
[assembly: AssemblyDescription("Thread safe random number generator")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TSRandom")]
[assembly: AssemblyCopyright("Copyright © Soleil Rojas 2017")]
[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("82f2ca28-6157-41ff-b644-2ef357ee4d6c")]

// 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.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Change the assembly version to use wildcard