// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media.Imaging;

namespace Perspex.Markup.Xaml.Converters
{
    public class BitmapTypeConverter : ITypeConverter
    {
        public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
        {
            return false;
        }

        public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
        {
            return new Bitmap((string)value);
        }

        public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
        {
            throw new NotImplementedException();
        }
    }
}

// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System;
using System.Globalization;
using OmniXaml.TypeConversion;
using Perspex.Media.Imaging;
using Perspex.Platform;

namespace Perspex.Markup.Xaml.Converters
{
    public class BitmapTypeConverter : ITypeConverter
    {
        public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType)
        {
            return false;
        }

        public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value)
        {
            var uri = new Uri((string)value, UriKind.RelativeOrAbsolute);
            var scheme = uri.IsAbsoluteUri ? uri.Scheme : "file";

            switch (scheme)
            {
                case "file":
                    return new Bitmap((string)value);
                case "resource":
                    var assets = PerspexLocator.Current.GetService<IAssetLoader>();
                    return new Bitmap(assets.Open(uri));
                default:
                    throw new NotSupportedException($"Unsupported bitmap URI scheme: {uri.Scheme}.");
            }
        }

        public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType)
        {
            throw new NotImplementedException();
        }
    }
}

Support loading bitmaps from resources.

Support loading bitmaps from resources.

Closes #358.


using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;

namespace ConsoleExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var servicesProvider = BuildDi();
            var runner = servicesProvider.GetRequiredService<Runner>();

            runner.DoAction("Action1");

            Console.WriteLine("Press ANY key to exit");
            Console.ReadLine();
        }

        private static IServiceProvider BuildDi()
        {
            var services = new ServiceCollection();

            //Runner is the custom class
            services.AddTransient<Runner>();

            services.AddSingleton<ILoggerFactory, LoggerFactory>();
            services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
            services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));

            var serviceProvider = services.BuildServiceProvider();

            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();

            //configure NLog
            loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
            loggerFactory.ConfigureNLog("nlog.config");

            return serviceProvider;
        }
    }

    public class Runner
    {
        private readonly ILogger<Runner> _logger;

        public Runner(ILogger<Runner> logger)
        {
            _logger = logger;
        }

        public void DoAction(string name)
        {
            _logger.LogDebug(20, "Doing hard work! {Action}", name);
        }

    }
}

using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;

namespace ConsoleExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var servicesProvider = BuildDi();
            var runner = servicesProvider.GetRequiredService<Runner>();

            runner.DoAction("Action1");

            Console.WriteLine("Press ANY key to exit");
            Console.ReadLine();

            NLog.LogManager.Shutdown(); // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        }

        private static IServiceProvider BuildDi()
        {
            var services = new ServiceCollection();

            //Runner is the custom class
            services.AddTransient<Runner>();

            services.AddSingleton<ILoggerFactory, LoggerFactory>();
            services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
            services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));

            var serviceProvider = services.BuildServiceProvider();

            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();

            //configure NLog
            loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
            loggerFactory.ConfigureNLog("nlog.config");

            return serviceProvider;
        }
    }

    public class Runner
    {
        private readonly ILogger<Runner> _logger;

        public Runner(ILogger<Runner> logger)
        {
            _logger = logger;
        }

        public void DoAction(string name)
        {
            _logger.LogDebug(20, "Doing hard work! {Action}", name);
        }

    }
}

Update NetCore2 ConsoleExample with LogManager.Shutdown()


using UnrealBuildTool;

using System.IO;

public class OSVRClientKit : ModuleRules
{
    private string ModulePath
    {
        get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); }
    }

    public OSVRClientKit(TargetInfo Target)
    {
        Type = ModuleType.External;

        PublicIncludePaths.Add(ModulePath + "/include");

        if ((Target.Platform == UnrealTargetPlatform.Win64)
            || (Target.Platform == UnrealTargetPlatform.Win32))
        {

            string LibraryPath = ModulePath + "/lib";

            if (Target.Platform == UnrealTargetPlatform.Win64)
            {
                LibraryPath += "/Win64";
            }
            else if (Target.Platform == UnrealTargetPlatform.Win32)
            {
                LibraryPath += "/Win32";
            }

            PublicLibraryPaths.Add(LibraryPath);
            PublicAdditionalLibraries.Add("osvrClientKit.lib");
            PublicDelayLoadDLLs.AddRange(
        			new string[] {
                "osvrClientKit.dll",
                "osvrClient.dll",
                "osvrCommon.dll",
                "osvrUtil.dll"
              });
        }
    }
}

using UnrealBuildTool;

using System.IO;

public class OSVRClientKit : ModuleRules
{
    private string ModulePath
    {
        get { return Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); }
    }

    public OSVRClientKit(TargetInfo Target)
    {
        Type = ModuleType.External;

        PublicIncludePaths.Add(ModulePath + "/include");

        if ((Target.Platform == UnrealTargetPlatform.Win64)
            || (Target.Platform == UnrealTargetPlatform.Win32))
        {

            string LibraryPath = ModulePath + "/lib";
            string DllPath = ModulePath + "/bin";

            if (Target.Platform == UnrealTargetPlatform.Win64)
            {
                LibraryPath += "/Win64";
                DllPath += "/Win64";
            }
            else if (Target.Platform == UnrealTargetPlatform.Win32)
            {
                LibraryPath += "/Win32";
                DllPath += "/Win32";
            }

            PublicLibraryPaths.Add(LibraryPath);
            PublicAdditionalLibraries.Add("osvrClientKit.lib");
            PublicDelayLoadDLLs.AddRange(
        			new string[] {
                "osvrClientKit.dll",
                "osvrClient.dll",
                "osvrCommon.dll",
                "osvrUtil.dll"
              });

            DllPath += "/";

            foreach (var dll in PublicDelayLoadDLLs)
            {
                RuntimeDependencies.Add(new RuntimeDependency(DllPath + dll));
            }
        }
    }
}

Use new "RuntimeDependencies" UBT feature to get our DLLs in place.


namespace TraktApiSharp.Objects.Basic
{
    using System.Collections.Generic;

    public class TraktPaginationListResult<ListItem>
    {
        public IEnumerable<ListItem> Items { get; set; }

        public int? Page { get; set; }

        public int? Limit { get; set; }

        public int? PageCount { get; set; }

        public int? ItemCount { get; set; }

        public int? UserCount { get; set; }
    }
}

namespace TraktApiSharp.Objects.Basic
{
    using System.Collections.Generic;

    ///
    /// Represents results of requests supporting pagination.<para />
    /// Contains the current page, the item limitation per page, the total page count, the total item count
    /// and can also contain the total user count (e.g. in trending shows and movies requests).
    ///
    /// <typeparam name="ListItem">The underlying item type of the list results.</typeparam>
    public class TraktPaginationListResult<ListItem>
    {
        /// Gets or sets the actual list results.
        public IEnumerable<ListItem> Items { get; set; }

        /// Gets or sets the current page number.
        public int? Page { get; set; }

        /// Gets or sets the item limitation per page.
        public int? Limit { get; set; }

        /// Gets or sets the total page count.
        public int? PageCount { get; set; }

        /// Gets or sets the total item results count.
        public int? ItemCount { get; set; }

        ///
        /// Gets or sets the total user count.
        /// <para>
        /// May be only supported for trending shows and movies requests.
        /// </para>
        ///
        public int? UserCount { get; set; }
    }
}

Add documentation for pagination list results.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Nether.Web.IntegrationTests.Identity
{
    public class UserApiTests : WebTestBase
    {
        private HttpClient _client;

        //[Fact]
        //public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers()
        //{
        //    AsPlayer();
        //    ResponseForGet("/users", hasStatusCode: HttpStatusCode.Forbidden);
        //}

        //private void ResponseForGet(string path, HttpStatusCode hasStatusCode)
        //{
        //    _client.GetAsync
        //}

        //private void AsPlayer()
        //{
        //    _client = GetClient(username:"testuser", isPlayer: true);
        //}

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Nether.Web.IntegrationTests.Identity
{
    public class UserApiTests : WebTestBase
    {
        private HttpClient _client;

        [Fact]
        public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers()
        {
            await AsPlayerAsync();
            await ResponseForGetAsync("/api/identity/users", hasStatusCode: HttpStatusCode.Forbidden);
        }

        private async Task<HttpResponseMessage> ResponseForGetAsync(string path, HttpStatusCode hasStatusCode)
        {
            var response = await _client.GetAsync(path);

            Assert.Equal(hasStatusCode, response.StatusCode);

            return response;
        }

        private async Task AsPlayerAsync()
        {
            _client = await GetClientAsync(username: "testuser", setPlayerGamertag: true);
        }

    }
}

Add Initial User API tests

Add Initial User API tests


using CommandLine;
using NadekoBot.Core.Common;

namespace NadekoBot.Core.Modules.Games.Common.Trivia
{
    public class TriviaOptions : INadekoCommandOptions
    {
        [Option('p', "pokemon", Required = false, Default = false, HelpText = "Whether it's 'Who's that pokemon?' trivia.")]
        public bool IsPokemon { get; set; } = false;
        [Option("nohint", Required = false, Default = false, HelpText = "Don't show any hints.")]
        public bool NoHint { get; set; } = false;
        [Option('w', "win-req", Required = false, Default = 10, HelpText = "Winning requirement. Set 0 for an infinite game. Default 10.")]
        public int WinRequirement { get; set; } = 10;
        [Option('q', "question-timer", Required = false, Default = 30, HelpText = "How long until the question ends. Default 30.")]
        public int QuestionTimer { get; set; } = 30;
        [Option('t', "timeout", Required = false, Default = 0, HelpText = "Number of questions of inactivity in order stop. Set 0 for never. Default 10.")]
        public int Timeout { get; set; } = 10;

        public void NormalizeOptions()
        {
            if (WinRequirement < 0)
                WinRequirement = 10;
            if (QuestionTimer < 10 || QuestionTimer > 300)
                QuestionTimer = 30;
            if (Timeout < 0 || Timeout > 20)
                Timeout = 10;

        }
    }
}

using CommandLine;
using NadekoBot.Core.Common;

namespace NadekoBot.Core.Modules.Games.Common.Trivia
{
    public class TriviaOptions : INadekoCommandOptions
    {
        [Option('p', "pokemon", Required = false, Default = false, HelpText = "Whether it's 'Who's that pokemon?' trivia.")]
        public bool IsPokemon { get; set; } = false;
        [Option("nohint", Required = false, Default = false, HelpText = "Don't show any hints.")]
        public bool NoHint { get; set; } = false;
        [Option('w', "win-req", Required = false, Default = 10, HelpText = "Winning requirement. Set 0 for an infinite game. Default 10.")]
        public int WinRequirement { get; set; } = 10;
        [Option('q', "question-timer", Required = false, Default = 30, HelpText = "How long until the question ends. Default 30.")]
        public int QuestionTimer { get; set; } = 30;
        [Option('t', "timeout", Required = false, Default = 10, HelpText = "Number of questions of inactivity in order stop. Set 0 for never. Default 10.")]
        public int Timeout { get; set; } = 10;

        public void NormalizeOptions()
        {
            if (WinRequirement < 0)
                WinRequirement = 10;
            if (QuestionTimer < 10 || QuestionTimer > 300)
                QuestionTimer = 30;
            if (Timeout < 0 || Timeout > 20)
                Timeout = 10;

        }
    }
}

Set default trivia timeout to match help text.


namespace Stripe
{
    using System.Collections.Generic;
    using Newtonsoft.Json;

    public class PaymentIntentCreateOptions : PaymentIntentSharedOptions
    {
        [JsonProperty("capture_method")]
        public string CaptureMethod { get; set; }

        [JsonProperty("confirm")]
        public bool? Confirm { get; set; }

        [JsonProperty("return_url")]
        public string ReturnUrl { get; set; }

        [JsonProperty("statement_descriptor")]
        public string StatementDescriptor { get; set; }
    }
}

namespace Stripe
{
    using System.Collections.Generic;
    using Newtonsoft.Json;

    public class PaymentIntentCreateOptions : PaymentIntentSharedOptions
    {
        [JsonProperty("capture_method")]
        public string CaptureMethod { get; set; }

        [JsonProperty("confirm")]
        public bool? Confirm { get; set; }

        [JsonProperty("confirmation_method")]
        public string ConfirmationMethod { get; set; }

        [JsonProperty("return_url")]
        public string ReturnUrl { get; set; }

        [JsonProperty("statement_descriptor")]
        public string StatementDescriptor { get; set; }
    }
}

Add support for `confirmation_method` on `PaymentIntent`


using System;
using System.Linq;

namespace Orleankka.Cluster
{
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection.Extensions;

    static class ServiceCollectionExtensions
    {
        public static void Decorate<T>(this IServiceCollection services, Func<T, T> decorator) where T : class
        {
            var registered = services.First(s => s.ServiceType == typeof(T));

            var factory = registered.ImplementationFactory;
            if (factory == null)
                services.TryAddSingleton(registered.ImplementationType);

            services.Replace(new ServiceDescriptor(typeof(T), sp =>
            {
                var inner = factory == null
                    ? sp.GetService(registered.ImplementationType)
                    : factory(sp);

                return decorator((T) inner);
            },
            registered.Lifetime));
        }
    }
}

using System;
using System.Linq;

namespace Orleankka.Cluster
{
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection.Extensions;

    static class ServiceCollectionExtensions
    {
        public static void Decorate<T>(this IServiceCollection services, Func<T, T> decorator) where T : class
        {
            var registered = services.First(s => s.ServiceType == typeof(T));

            var factory = registered.ImplementationFactory;
            if (factory == null && registered.ImplementationType != null)
                services.TryAddSingleton(registered.ImplementationType);

            services.Replace(new ServiceDescriptor(typeof(T), sp =>
            {
                var inner = registered.ImplementationInstance;
                if (inner != null)
                    return decorator((T) inner);

                inner = factory == null
                    ? sp.GetService(registered.ImplementationType)
                    : factory(sp);

                return decorator((T) inner);

            },
            registered.Lifetime));
        }
    }
}

Fix bug when pre-registered activator is instance


using Humanizer.Bytes;

namespace Humanizer
{
    public static class ByteSizeExtensions
    {
        public static ByteSize Bits(this long val)
        {
            return ByteSize.FromBits(val);
        }

        public static ByteSize Bytes(this double val)
        {
            return ByteSize.FromBytes(val);
        }

        public static ByteSize Kilobytes(this double val)
        {
            return ByteSize.FromKiloBytes(val);
        }

        public static ByteSize Megabytes(this double val)
        {
            return ByteSize.FromMegaBytes(val);
        }

        public static ByteSize Gigabytes(this double val)
        {
            return ByteSize.FromGigaBytes(val);
        }

        public static ByteSize Terabytes(this double val)
        {
            return ByteSize.FromTeraBytes(val);
        }
    }

    public static class HumanizeExtension
    {
        // TODO: Overload this to give access to formatting options in a Humanizey way
        public static string Humanize(this ByteSize val)
        {
            return val.ToString();
        }
    }
}

using Humanizer.Bytes;

namespace Humanizer
{
    public static class ByteSizeExtensions
    {
        /// <summary>
        /// Use value as a quantity of bits
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static ByteSize Bits(this long val)
        {
            return ByteSize.FromBits(val);
        }

        /// <summary>
        /// Use value as a quantity of bytes
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static ByteSize Bytes(this double val)
        {
            return ByteSize.FromBytes(val);
        }

        /// <summary>
        /// Use value as a quantity of kilobytes
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static ByteSize Kilobytes(this double val)
        {
            return ByteSize.FromKiloBytes(val);
        }

        /// <summary>
        /// Use value as a quantity of megabytes
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static ByteSize Megabytes(this double val)
        {
            return ByteSize.FromMegaBytes(val);
        }

        /// <summary>
        /// Use value as a quantity of gigabytes
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static ByteSize Gigabytes(this double val)
        {
            return ByteSize.FromGigaBytes(val);
        }

        /// <summary>
        /// Use value as a quantity of terabytes
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static ByteSize Terabytes(this double val)
        {
            return ByteSize.FromTeraBytes(val);
        }
    }

    public static class HumanizeExtension
    {
        /// <summary>
        /// Turns a byte quantity into human readable form, eg 2 GB
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string Humanize(this ByteSize val)
        {
            return val.ToString();
        }
    }
}

Add XML docs + remove code todo

Add XML docs + remove code todo


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

using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;
using osuTK;

namespace osu.Game.Rulesets.Mania.UI
{
    public class ManiaPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
    {
        public ManiaPlayfieldAdjustmentContainer()
        {
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;

            Size = new Vector2(1, 0.8f);
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Mania.UI
{
    public class ManiaPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
    {
        public ManiaPlayfieldAdjustmentContainer()
        {
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
        }
    }
}

Expand mania to fit vertical screen bounds


using System;
using System.Threading;
using System.Threading.Tasks;
using WebSocket.Portable.Interfaces;

namespace WebSocket.Portable.Internal
{
    internal static class DataLayerExtensions
    {
        public static Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken)
        {
            return layer.ReadAsync(length, cancellationToken, WebSocketErrorCode.CloseInvalidData);
        }

        public static async Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken, WebSocketErrorCode errorCode)
        {
            var buffer = new byte[length];
            var read = await layer.ReadAsync(buffer, 0, buffer.Length, cancellationToken);

            if (read != buffer.Length)
                throw new WebSocketException(errorCode);

            return buffer;
        }
    }
}

using System.Threading;
using System.Threading.Tasks;
using WebSocket.Portable.Interfaces;

namespace WebSocket.Portable.Internal
{
    internal static class DataLayerExtensions
    {
        public static Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken)
        {
            return layer.ReadAsync(length, cancellationToken, WebSocketErrorCode.CloseInvalidData);
        }

        public static async Task<byte[]> ReadAsync(this IDataLayer layer, int length, CancellationToken cancellationToken, WebSocketErrorCode errorCode)
        {
            var buffer = new byte[length];
            var read = 0;

            while (read < length && !cancellationToken.IsCancellationRequested)
            {
                var chunkOffset = read;
                var chunkLength = length - chunkOffset;
                var chunkSize = await layer.ReadAsync(buffer, chunkOffset, chunkLength, cancellationToken);

                if (chunkSize == 0)
                {
                    break;
                }

                read += chunkSize;
            }

            if (read != buffer.Length)
                throw new WebSocketException(errorCode);

            return buffer;
        }
    }
}

Read data from underlying stream in chunks if it does not return everything to us in one go.


#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
#endregion

namespace System.Runtime.WootzJs
{
    [Js(Export = false, Name = "RegExp")]
    public class JsRegExp
    {
        public JsRegExp(string s)
        {
        }

        public extern bool test(JsString value);
        public extern string[] match(JsString value);
    }
}

#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
#endregion

namespace System.Runtime.WootzJs
{
    [Js(Export = false, Name = "RegExp")]
    public class JsRegExp
    {
        public JsRegExp(string s)
        {
        }

        public extern bool test(JsString value);
        public extern string[] exec(JsString value);
    }
}

Add exec method to js regexp

Add exec method to js regexp


namespace Moya.Utility
{
    using System;
    using Exceptions;
    using Extensions;
    using Runners;

    public class Guard
    {
        public static void IsMoyaAttribute(Type type)
        {
            if (!Reflection.TypeIsMoyaAttribute(type))
            {
                throw new MoyaException("{0} is not a Moya Attribute.".FormatWith(type));
            }
        }

        public static void IsMoyaTestRunner(Type type)
        {
            if (!typeof(ITestRunner).IsAssignableFrom(type))
            {
                throw new MoyaException("{0} is not a Moya Test Runner.".FormatWith(type));
            }
        }
    }
}

namespace Moya.Utility
{
    using System;
    using Exceptions;
    using Extensions;
    using Runners;

    public class Guard
    {
        public static void IsMoyaAttribute(Type type)
        {
            if (!Reflection.TypeIsMoyaAttribute(type))
            {
                throw new MoyaException("{0} is not a Moya Attribute.".FormatWith(type));
            }
        }

        public static void IsMoyaTestRunner(Type type)
        {
            if (!typeof(IMoyaTestRunner).IsAssignableFrom(type))
            {
                throw new MoyaException("{0} is not a Moya Test Runner.".FormatWith(type));
            }
        }
    }
}

Fix IsMoyaTestRunner to check for correct interface to implement.


using LegoSharp;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace Scraper
{
    class Scraper
    {
        static async Task Main(string[] args)
        {
            foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets())
            {
                Console.WriteLine(entry.Key);
                foreach (var label in entry.Value)
                {
                    Console.WriteLine(label.name + " " + label.value);
                }
                Console.WriteLine();
            }

            Console.WriteLine("\n-----------------------------------------\n");

            foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets())
            {
                Console.WriteLine(entry.Key);
                foreach (var label in entry.Value)
                {
                    Console.WriteLine(label.name + " " + label.value);
                }
                Console.WriteLine();
            }
        }
    }
}

using LegoSharp;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace Scraper
{
    class Scraper
    {
        static async Task Main(string[] args)
        {
            foreach (var entry in await (new FacetScraper<ProductSearchQuery, ProductSearchResult>(new List<ProductSearchQuery> { new ProductSearchQuery() }, new ProductSearchFacetExtractor())).scrapeFacets())
            {
                Console.WriteLine(entry.Key);
                foreach (var label in entry.Value)
                {
                    Console.WriteLine(label.name + " " + label.value);
                }
                Console.WriteLine();
            }

            Console.WriteLine("\n-----------------------------------------\n");

            foreach (var entry in await (new FacetScraper<PickABrickQuery, PickABrickResult>(new List<PickABrickQuery> { new PickABrickQuery() }, new PickABrickFacetExtractor())).scrapeFacets())
            {
                Console.WriteLine(entry.Key);
                foreach (var label in entry.Value)
                {
                    Console.WriteLine(label.name + " " + label.value);
                }
                Console.WriteLine();
            }
        }
    }
}

Fix scraper to scrape pick a brick facets correctly


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

using osu.Framework.Graphics;
using osu.Framework.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets;
using osu.Game.Users;

namespace osu.Game.Overlays.Rankings
{
    public class RankingsOverlayHeader : TabControlOverlayHeader<RankingsScope>
    {
        public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();
        public readonly Bindable<Country> Country = new Bindable<Country>();

        protected override ScreenTitle CreateTitle() => new RankingsTitle
        {
            Scope = { BindTarget = Current }
        };

        protected override Drawable CreateTitleContent() => new OverlayRulesetSelector
        {
            Current = Ruleset
        };

        protected override Drawable CreateContent() => new CountryFilter
        {
            Current = Country
        };

        private class RankingsTitle : ScreenTitle
        {
            public readonly Bindable<RankingsScope> Scope = new Bindable<RankingsScope>();

            public RankingsTitle()
            {
                Title = "ranking";
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Scope.BindValueChanged(scope => Section = scope.NewValue.ToString().ToLowerInvariant(), true);
            }

            protected override Drawable CreateIcon() => new ScreenTitleTextureIcon(@"Icons/rankings");
        }
    }

    public enum RankingsScope
    {
        Performance,
        Spotlights,
        Score,
        Country
    }
}

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

using osu.Framework.Graphics;
using osu.Framework.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets;
using osu.Game.Users;

namespace osu.Game.Overlays.Rankings
{
    public class RankingsOverlayHeader : TabControlOverlayHeader<RankingsScope>
    {
        public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();
        public readonly Bindable<Country> Country = new Bindable<Country>();

        protected override ScreenTitle CreateTitle() => new RankingsTitle
        {
            Scope = { BindTarget = Current }
        };

        protected override Drawable CreateTitleContent() => new OverlayRulesetSelector
        {
            Current = Ruleset
        };

        protected override Drawable CreateContent() => new CountryFilter
        {
            Current = Country
        };

        protected override Drawable CreateBackground() => new OverlayHeaderBackground(@"Headers/rankings");

        private class RankingsTitle : ScreenTitle
        {
            public readonly Bindable<RankingsScope> Scope = new Bindable<RankingsScope>();

            public RankingsTitle()
            {
                Title = "ranking";
            }

            protected override void LoadComplete()
            {
                base.LoadComplete();
                Scope.BindValueChanged(scope => Section = scope.NewValue.ToString().ToLowerInvariant(), true);
            }

            protected override Drawable CreateIcon() => new ScreenTitleTextureIcon(@"Icons/rankings");
        }
    }

    public enum RankingsScope
    {
        Performance,
        Spotlights,
        Score,
        Country
    }
}

Add background to rankings header

Add background to rankings header


using System.Collections.Concurrent;
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;

namespace LunaClient.Systems.VesselFlightStateSys
{
    public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler
    {
        public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>();

        public void HandleMessage(IMessageData messageData)
        {
            var msgData = messageData as VesselFlightStateMsgData;
            if (msgData == null) return;

            var flightState = new FlightCtrlState
            {
                mainThrottle = msgData.MainThrottle,
                wheelThrottleTrim = msgData.WheelThrottleTrim,
                X = msgData.X,
                Y = msgData.Y,
                Z = msgData.Z,
                killRot = msgData.KillRot,
                gearUp = msgData.GearUp,
                gearDown = msgData.GearDown,
                headlight = msgData.Headlight,
                wheelThrottle = msgData.WheelThrottle,
                roll = msgData.Roll,
                yaw = msgData.Yaw,
                pitch = msgData.Pitch,
                rollTrim = msgData.RollTrim,
                yawTrim = msgData.YawTrim,
                pitchTrim = msgData.PitchTrim,
                wheelSteer = msgData.WheelSteer,
                wheelSteerTrim = msgData.WheelSteerTrim
            };

            System.FlightState = flightState;
        }
    }
}

using System.Collections.Concurrent;
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;

namespace LunaClient.Systems.VesselFlightStateSys
{
    public class VesselFlightStateMessageHandler : SubSystem<VesselFlightStateSystem>, IMessageHandler
    {
        public ConcurrentQueue<IMessageData> IncomingMessages { get; set; } = new ConcurrentQueue<IMessageData>();

        public void HandleMessage(IMessageData messageData)
        {
            var msgData = messageData as VesselFlightStateMsgData;
            if (msgData == null) return;

            var flightState = new FlightCtrlState
            {
                mainThrottle = msgData.MainThrottle,
                wheelThrottleTrim = msgData.WheelThrottleTrim,
                X = msgData.X,
                Y = msgData.Y,
                Z = msgData.Z,
                killRot = msgData.KillRot,
                gearUp = msgData.GearUp,
                gearDown = msgData.GearDown,
                headlight = msgData.Headlight,
                wheelThrottle = msgData.WheelThrottle,
                roll = msgData.Roll,
                yaw = msgData.Yaw,
                pitch = msgData.Pitch,
                rollTrim = msgData.RollTrim,
                yawTrim = msgData.YawTrim,
                pitchTrim = msgData.PitchTrim,
                wheelSteer = msgData.WheelSteer,
                wheelSteerTrim = msgData.WheelSteerTrim
            };

            //System.FlightState = flightState;
        }
    }
}

Fix compile error by commenting out offending code.


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

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

namespace Microsoft.CodeAnalysis.Experiments
{
    internal interface IExperimentationService : IWorkspaceService
    {
        bool IsExperimentEnabled(string experimentName);
    }

    [ExportWorkspaceService(typeof(IExperimentationService)), Shared]
    internal class DefaultExperimentationService : IExperimentationService
    {
        public bool ReturnValue = false;

        [ImportingConstructor]
        public DefaultExperimentationService()
        {
        }

        public bool IsExperimentEnabled(string experimentName) => ReturnValue;
    }

    internal static class WellKnownExperimentNames
    {
        public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
        public const string PartialLoadMode = "Roslyn.PartialLoadMode";
        public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
        public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
        public const string RoslynToggleBlockComment = "Roslyn.ToggleBlockComment";
        public const string RoslynToggleLineComment = "Roslyn.ToggleLineComment";
        public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
        public const string RoslynInlineRenameFile = "Roslyn.FileRename";
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

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

namespace Microsoft.CodeAnalysis.Experiments
{
    internal interface IExperimentationService : IWorkspaceService
    {
        bool IsExperimentEnabled(string experimentName);
    }

    [ExportWorkspaceService(typeof(IExperimentationService)), Shared]
    internal class DefaultExperimentationService : IExperimentationService
    {
        public bool ReturnValue = false;

        [ImportingConstructor]
        public DefaultExperimentationService()
        {
        }

        public bool IsExperimentEnabled(string experimentName) => ReturnValue;
    }

    internal static class WellKnownExperimentNames
    {
        public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
        public const string PartialLoadMode = "Roslyn.PartialLoadMode";
        public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
        public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
        public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
        public const string RoslynInlineRenameFile = "Roslyn.FileRename";
    }
}

Delete unused experiment names added in merge.


// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;

namespace CefSharp
{
    [Flags]
    public enum DragOperationsMask : uint
    {
        None = 0,
        Copy = 1,
        Link = 2,
        Generic = 4,
        Private = 8,
        Move = 16,
        Delete = 32,
        Every = UInt32.MaxValue
    }
}

// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using System;

namespace CefSharp
{
    [Flags]
    public enum DragOperationsMask : uint
    {
        None = 0,
        Copy = 1,
        Link = 2,
        Generic = 4,
        Private = 8,
        Move = 16,
        Delete = 32,
        Every = uint.MaxValue
    }
}

Use uint instead of Uint32 for consistency (even though they're exactly the same)


// 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 System;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;

namespace Microsoft.AspNet.Builder.Extensions
{
    /// <summary>
    /// Options for the MapWhen middleware
    /// </summary>
    public class MapWhenOptions
    {
        /// <summary>
        /// The user callback that determines if the branch should be taken
        /// </summary>
        public Func<HttpContext, bool> Predicate { get; set; }

        /// <summary>
        /// The branch taken for a positive match
        /// </summary>
        public RequestDelegate Branch { get; set; }
    }
}

// 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 System;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;

namespace Microsoft.AspNet.Builder.Extensions
{
    /// <summary>
    /// Options for the MapWhen middleware
    /// </summary>
    public class MapWhenOptions
    {
        /// <summary>
        /// The user callback that determines if the branch should be taken
        /// </summary>
        public Func<HttpContext, bool> Predicate
        {
            get;
            [param: NotNull]
            set;
        }

        /// <summary>
        /// The branch taken for a positive match
        /// </summary>
        public RequestDelegate Branch { get; set; }
    }
}

Add NotNull to Predicate setter.

Add NotNull to Predicate setter.


namespace StudentSystem.Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}

namespace StudentSystem.Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using StudentSystem.Models;

    public sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(ApplicationDbContext context)
        {
            if (!context.Roles.Any())
            {
                const string adminUsername = "admin@admin.com";
                const string adminPass = "administrator";
                const string roleName = "Administrator";

                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                var role = new IdentityRole { Name = roleName };
                roleManager.Create(role);

                var userStore = new UserStore<User>(context);
                var userManager = new UserManager<User>(userStore);
                var admin = new User { Email = adminUsername };
                userManager.Create(admin, adminPass);

                userManager.AddToRole(admin.Id, roleName);
            }
        }
    }
}

Add Admin user in Seed method

Add Admin user in Seed method


using System;
using Microsoft.Win32;

namespace PlexServiceCommon {
	public static class PlexDirHelper {
		/// <summary>
		/// Returns the full path and filename of the plex media server executable
		/// </summary>
		/// <returns></returns>
		public static string GetPlexDataDir()
		{
			var result = string.Empty;

			//work out the os type (32 or 64) and set the registry view to suit. this is only a reliable check when this project is compiled to x86.
			var is64Bit = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"));

			var architecture = RegistryView.Registry32;
			if (is64Bit)
			{
				architecture = RegistryView.Registry64;
			}

			using var pmsDataKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, architecture).OpenSubKey(@"Software\Plex, Inc.\Plex Media Server");
			if (pmsDataKey == null) {
				return result;
			}

			var path = (string) pmsDataKey.GetValue("LocalAppdataPath");
			result = path;

			return result;
		}
	}
}

using System;
using System.IO;
using Microsoft.Win32;

namespace PlexServiceCommon {
	public static class PlexDirHelper {
		/// <summary>
		/// Returns the full path and filename of the plex media server executable
		/// </summary>
		/// <returns></returns>
		public static string GetPlexDataDir()
		{
			var result = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
			var path = Path.Combine(result, "Plex Media Server");
			if (Directory.Exists(path)) {
				return path;
			}
			result = String.Empty;
			//work out the os type	 (32 or 64) and set the registry view to suit. this is only a reliable check when this project is compiled to x86.
			var is64Bit = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"));

			var architecture = RegistryView.Registry32;
			if (is64Bit)
			{
				architecture = RegistryView.Registry64;
			}

			using var pmsDataKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, architecture).OpenSubKey(@"Software\Plex, Inc.\Plex Media Server");
			if (pmsDataKey == null) {
				return result;
			}

			path = (string) pmsDataKey.GetValue("LocalAppdataPath");
			result = path;

			return result;
		}
	}
}

Test for default plex path before checking for registry key.


using System.Globalization;

namespace GoldenAnvil.Utility
{
	public static class StringUtility
	{
		public static string FormatInvariant(this string format, params object[] args)
		{
			return string.Format(CultureInfo.InvariantCulture, format, args);
		}
	}
}

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

namespace GoldenAnvil.Utility
{
	public static class StringUtility
	{
		public static string FormatInvariant(this string format, params object[] args)
		{
			return string.Format(CultureInfo.InvariantCulture, format, args);
		}

		public static string Join(this IEnumerable<string> parts, string joinText)
		{
			var builder = new StringBuilder();
			foreach (var part in parts)
			{
				if (builder.Length != 0)
					builder.Append(joinText);
				builder.Append(part);
			}

			return builder.ToString();
		}
	}
}

Add Join extension for strings

Add Join extension for strings


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.ServiceModel;
using Infrastructure.Common;
using Xunit;

public static class UpnEndpointIdentityTest
{
#if FULLXUNIT_NOTSUPPORTED
    [Theory]
#endif
    [WcfTheory]
    [InlineData("")]
    [InlineData("test@wcf.example.com")]
    [Issue(1454, Framework = FrameworkID.NetNative)]
    public static void Ctor_UpnName(string upn)
    {
        UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upn);
    }

#if FULLXUNIT_NOTSUPPORTED
    [Fact]
#endif
    [WcfFact]
    public static void Ctor_NullUpn()
    {
        string upnName = null;

        Assert.Throws<ArgumentNullException>("upnName", () =>
        {
            UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upnName);
        });
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.ServiceModel;
using Infrastructure.Common;
using Xunit;

public static class UpnEndpointIdentityTest
{
#if FULLXUNIT_NOTSUPPORTED
    [Theory]
#endif
    [WcfTheory]
    [InlineData("")]
    [InlineData("test@wcf.example.com")]
    public static void Ctor_UpnName(string upn)
    {
        UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upn);
    }

#if FULLXUNIT_NOTSUPPORTED
    [Fact]
#endif
    [WcfFact]
    public static void Ctor_NullUpn()
    {
        string upnName = null;

        Assert.Throws<ArgumentNullException>("upnName", () =>
        {
            UpnEndpointIdentity upnEndpointEntity = new UpnEndpointIdentity(upnName);
        });
    }
}

Enable UpnEndpointIdentity tests on UWP

Enable UpnEndpointIdentity tests on UWP


using System;
using System.IO;
using System.Net.Http;
using System.Net.Mime;
using System.Threading.Tasks;

namespace Dotnet.Script.Core
{
    public class ScriptDownloader
    {
        public async Task<string> Download(string uri)
        {
            const string plainTextMediaType = "text/plain";
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(uri))
                {
                    response.EnsureSuccessStatusCode();

                    using (HttpContent content = response.Content)
                    {
                        string mediaType = content.Headers.ContentType.MediaType;

                        if (string.IsNullOrWhiteSpace(mediaType) || mediaType.Equals(plainTextMediaType, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return await content.ReadAsStringAsync();
                        }

                        throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
                    }
                }
            }
        }
    }
}

using System;
using System.IO;
using System.Net.Http;
using System.Net.Mime;
using System.Threading.Tasks;

namespace Dotnet.Script.Core
{
    public class ScriptDownloader
    {
        public async Task<string> Download(string uri)
        {
            const string plainTextMediaType = "text/plain";
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();

                    using (HttpContent content = response.Content)
                    {
                        string mediaType = content.Headers.ContentType.MediaType;

                        if (string.IsNullOrWhiteSpace(mediaType) || mediaType.Equals(plainTextMediaType, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return await content.ReadAsStringAsync();
                        }

                        throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
                    }
                }
            }
        }
    }
}

Validate remote script MIME type early

Validate remote script MIME type early


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

namespace osu.Framework.Input.Bindings
{
    /// <summary>
    /// A binding of a <see cref="Bindings.KeyCombination"/> to an action.
    /// </summary>
    public interface IKeyBinding
    {
        /// <summary>
        /// The combination of keys which will trigger this binding.
        /// </summary>
        KeyCombination KeyCombination { get; set; }

        /// <summary>
        /// The resultant action which is triggered by this binding.
        /// </summary>
        object Action { get; set; }
    }
}

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

namespace osu.Framework.Input.Bindings
{
    /// <summary>
    /// A binding of a <see cref="Bindings.KeyCombination"/> to an action.
    /// </summary>
    public interface IKeyBinding
    {
        /// <summary>
        /// The combination of keys which will trigger this binding.
        /// </summary>
        KeyCombination KeyCombination { get; set; }

        /// <summary>
        /// The resultant action which is triggered by this binding.
        /// Generally an enum type, but may also be an int representing an enum (converted via <see cref="KeyBindingExtensions.GetAction{T}"/>
        /// </summary>
        object Action { get; set; }
    }
}

Add note about action type

Add note about action type


using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;

namespace Auth0.Owin
{
    /// <summary>
    /// Context passed when the redirect_uri is generated during the token exchange.
    /// </summary>
    public class Auth0CustomizeTokenExchangeRedirectUriContext : BaseContext<Auth0AuthenticationOptions>
    {
        /// <summary>
        /// Creates a new context object.
        /// </summary>
        /// <param name="context">The OWIN request context</param>
        /// <param name="options">The Auth0 middleware options</param>
        /// <param name="properties">The authenticaiton properties of the challenge</param>
        /// <param name="redirectUri">The initial redirect URI</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#",
            Justification = "Represents header value")]
        public Auth0CustomizeTokenExchangeRedirectUriContext(IOwinContext context, Auth0AuthenticationOptions options,
            AuthenticationProperties properties, string redirectUri)
            : base(context, options)
        {
            RedirectUri = redirectUri;
            Properties = properties;
        }

        /// <summary>
        /// Gets the URI used for the redirect operation.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Represents header value")]
        public string RedirectUri { get; private set; }

        /// <summary>
        /// Gets the authenticaiton properties of the challenge
        /// </summary>
        public AuthenticationProperties Properties { get; private set; }
    }
}

using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;

namespace Auth0.Owin
{
    /// <summary>
    /// Context passed when the redirect_uri is generated during the token exchange.
    /// </summary>
    public class Auth0CustomizeTokenExchangeRedirectUriContext : BaseContext<Auth0AuthenticationOptions>
    {
        /// <summary>
        /// Creates a new context object.
        /// </summary>
        /// <param name="context">The OWIN request context</param>
        /// <param name="options">The Auth0 middleware options</param>
        /// <param name="properties">The authenticaiton properties of the challenge</param>
        /// <param name="redirectUri">The initial redirect URI</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#",
            Justification = "Represents header value")]
        public Auth0CustomizeTokenExchangeRedirectUriContext(IOwinContext context, Auth0AuthenticationOptions options,
            AuthenticationProperties properties, string redirectUri)
            : base(context, options)
        {
            RedirectUri = redirectUri;
            Properties = properties;
        }

        /// <summary>
        /// Gets the URI used for the redirect operation.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Represents header value")]
        public string RedirectUri { get; set; }

        /// <summary>
        /// Gets the authenticaiton properties of the challenge
        /// </summary>
        public AuthenticationProperties Properties { get; private set; }
    }
}

Fix issue with readonly RedirectUri

Fix issue with readonly RedirectUri


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Xunit;

namespace System.Reflection.PortableExecutable.Tests
{
    public class PEHeaderBuilderTests
    {
        [Fact]
        public void Ctor_Errors()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 0));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 0));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 512, fileAlignment: 1024));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 513));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: int.MinValue));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 513));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 64*1024*2));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MaxValue));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MinValue));
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Xunit;

namespace System.Reflection.PortableExecutable.Tests
{
    public class PEHeaderBuilderTests
    {
        [Fact]
        public void Ctor_Errors()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 0));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 0));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 512, fileAlignment: 1024));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: 513));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(sectionAlignment: int.MinValue));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 513));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: 64*1024*2));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MaxValue));
            Assert.Throws<ArgumentOutOfRangeException>(() => new PEHeaderBuilder(fileAlignment: int.MinValue));
        }

        [Fact]
        public void ValidateFactoryMethods()
        {
            var peHeaderExe = PEHeaderBuilder.CreateExecutableHeader();
            Assert.NotNull(peHeaderExe);
            Assert.True((peHeaderExe.ImageCharacteristics & Characteristics.ExecutableImage) != 0);

            var peHeaderLib = PEHeaderBuilder.CreateLibraryHeader();
            Assert.NotNull(peHeaderLib);
            Assert.True((peHeaderLib.ImageCharacteristics & Characteristics.ExecutableImage) != 0);
            Assert.True((peHeaderLib.ImageCharacteristics & Characteristics.Dll) != 0);
        }
    }
}

Add unit tests for PEHeaderBuilder factory methods

See: #35758


using Dolstagis.Web.Auth;
using Dolstagis.Web.Lifecycle;
using Dolstagis.Web.Lifecycle.ResultProcessors;
using Dolstagis.Web.Sessions;
using Dolstagis.Web.Static;
using Dolstagis.Web.Views;

namespace Dolstagis.Web
{
    internal class CoreServices : Feature
    {
        public CoreServices()
        {
            Container.Setup.Application(c => {
                c.Use<IExceptionHandler, ExceptionHandler>(Scope.Request);
                c.Use<ISessionStore, InMemorySessionStore>(Scope.Application);
                c.Use<IAuthenticator, SessionAuthenticator>(Scope.Application);
                c.Use<ILoginHandler, LoginHandler>(Scope.Request);

                c.Add<IResultProcessor, StaticResultProcessor>(Scope.Transient);
                c.Add<IResultProcessor, ViewResultProcessor>(Scope.Transient);
                c.Add<IResultProcessor>(JsonResultProcessor.Instance);
                c.Add<IResultProcessor>(ContentResultProcessor.Instance);
                c.Add<IResultProcessor>(HeadResultProcessor.Instance);

                c.Use<ViewRegistry, ViewRegistry>(Scope.Request);
            });
        }
    }
}

using Dolstagis.Web.Auth;
using Dolstagis.Web.Http;
using Dolstagis.Web.Lifecycle;
using Dolstagis.Web.Lifecycle.ResultProcessors;
using Dolstagis.Web.Sessions;
using Dolstagis.Web.Static;
using Dolstagis.Web.Views;

namespace Dolstagis.Web
{
    internal class CoreServices : Feature
    {
        public CoreServices()
        {
            Container.Setup.Application(c => {
                c.Use<IExceptionHandler, ExceptionHandler>(Scope.Request);
                c.Use<ISessionStore, InMemorySessionStore>(Scope.Application);
                c.Use<IAuthenticator, SessionAuthenticator>(Scope.Application);
                c.Use<ILoginHandler, LoginHandler>(Scope.Request);

                c.Add<IResultProcessor, StaticResultProcessor>(Scope.Transient);
                c.Add<IResultProcessor, ViewResultProcessor>(Scope.Transient);
                c.Add<IResultProcessor>(JsonResultProcessor.Instance);
                c.Add<IResultProcessor>(ContentResultProcessor.Instance);
                c.Add<IResultProcessor>(HeadResultProcessor.Instance);

                c.Use<ViewRegistry, ViewRegistry>(Scope.Request);

                c.Use<IRequest>(ctx => ctx.GetService<IRequestContext>().Request, Scope.Request);
                c.Use<IResponse>(ctx => ctx.GetService<IRequestContext>().Response, Scope.Request);
                c.Use<IUser>(ctx => ctx.GetService<IRequestContext>().User, Scope.Request);
                c.Use<ISession>(ctx => ctx.GetService<IRequestContext>().Session, Scope.Request);
            })
            .Setup.Request(c => {
            });
        }
    }
}

Make components of IRequestContext independently injectable.


using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Web.UI.JavaScript;

namespace Umbraco.Tests.Web.AngularIntegration
{
    [TestFixture]
    public class JsInitializationTests
    {

        [Test]
        public void Get_Default_Init()
        {
            var init = JsInitialization.GetDefaultInitialization();
            Assert.IsTrue(init.Any());
        }

        [Test]
        public void Parse_Main()
        {
            var result = JsInitialization.WriteScript("[World]", "Hello", "Blah");

            Assert.AreEqual(@"LazyLoad.js([World], function () {
    //we need to set the legacy UmbClientMgr path
    UmbClientMgr.setUmbracoPath('Hello');

    jQuery(document).ready(function () {

        angular.bootstrap(document, ['Blah']);

    });
});".StripWhitespace(), result.StripWhitespace());
        }
    }
}

using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Web.UI.JavaScript;

namespace Umbraco.Tests.Web.AngularIntegration
{
    [TestFixture]
    public class JsInitializationTests
    {

        [Test]
        public void Get_Default_Init()
        {
            var init = JsInitialization.GetDefaultInitialization();
            Assert.IsTrue(init.Any());
        }

        [Test]
        public void Parse_Main()
        {
            var result = JsInitialization.WriteScript("[World]", "Hello", "Blah");

            Assert.AreEqual(@"LazyLoad.js([World], function () {
    //we need to set the legacy UmbClientMgr path
    if ((typeof UmbClientMgr) !== ""undefined"") {
        UmbClientMgr.setUmbracoPath('Hello');
    }

    jQuery(document).ready(function () {

        angular.bootstrap(document, ['Blah']);

    });
});".StripWhitespace(), result.StripWhitespace());
        }
    }
}

Fix test broken by e771e78

Fix test broken by e771e78


using System.Web;
using System.Web.Optimization;
using wwwplatform.Models;
using wwwplatform.Models.Support;

namespace wwwplatform
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            var settings = Settings.Create(new HttpContextWrapper(HttpContext.Current));

            string skin = settings.SkinDefinitionFile ??  "~/App_Data/Skins/Default/skin.json";
            SkinDefinition skindef = SkinDefinition.Load(HttpContext.Current.Server.MapPath(skin));
            HttpContext.Current.Application["Layout"] = skindef.layout;
            foreach (var script in skindef.scripts.Keys)
            {
                bundles.Add(new ScriptBundle(script).Include(skindef.scripts[script].ToArray()));
            }

            foreach (var css in skindef.css.Keys)
            {
                bundles.Add(new StyleBundle(css).Include(skindef.css[css].ToArray()));
            }
        }
    }
}

using System.Web;
using System.Web.Optimization;
using wwwplatform.Models;
using wwwplatform.Models.Support;

namespace wwwplatform
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            var settings = Settings.Create(new HttpContextWrapper(HttpContext.Current));

            string skin = settings.SkinDefinitionFile ??  "~/App_Data/Skins/Default/skin.json";
            SkinDefinition skindef = SkinDefinition.Load(HttpContext.Current.Server.MapPath(skin));
            HttpContext.Current.Application["Layout"] = skindef.layout;
            foreach (var script in skindef.scripts.Keys)
            {
                bundles.Add(new ScriptBundle(script).Include(skindef.scripts[script].ToArray()));
            }

            foreach (var css in skindef.css.Keys)
            {
                StyleBundle bundle = new StyleBundle(css);
                foreach(string file in skindef.css[css])
                {
                    bundle.Include(file, new CssRewriteUrlTransform());
                }
                bundles.Add(bundle);
            }
        }
    }
}

Allow mixed path references and url transforms


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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osuTK;

namespace osu.Game.Tests.Visual.Gameplay
{
    [TestFixture]
    public class TestSceneParticleExplosion : OsuTestScene
    {
        [BackgroundDependencyLoader]
        private void load(TextureStore textures)
        {
            AddRepeatStep(@"display", () =>
            {
                Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Size = new Vector2(400)
                };
            }, 10);
        }
    }
}

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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osuTK;

namespace osu.Game.Tests.Visual.Gameplay
{
    [TestFixture]
    public class TestSceneParticleExplosion : OsuTestScene
    {
        private ParticleExplosion explosion;

        [BackgroundDependencyLoader]
        private void load(TextureStore textures)
        {
            AddStep("create initial", () =>
            {
                Child = explosion = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Size = new Vector2(400)
                };
            });

            AddWaitStep("wait for playback", 5);

            AddRepeatStep(@"restart animation", () =>
            {
                explosion.Restart();
            }, 10);
        }
    }
}

Add test coverage of animation restarting


using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Data.Repositories;
using SFA.DAS.EAS.Domain.Models.UserProfile;
using SFA.DAS.Sql.Client;
using SFA.DAS.NLog.Logger;

namespace SFA.DAS.EAS.Infrastructure.Data
{
    public class UserRepository : BaseRepository, IUserRepository
    {
        private readonly Lazy<EmployerAccountsDbContext> _db;

        public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db)
            : base(configuration.DatabaseConnectionString, logger)
        {
            _db = db;
        }

        public Task Upsert(User user)
        {
            return WithConnection(c =>
            {
                var parameters = new DynamicParameters();

                parameters.Add("@email", user.Email, DbType.String);
                parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid);
                parameters.Add("@firstName", user.FirstName, DbType.String);
                parameters.Add("@lastName", user.LastName, DbType.String);

                return c.ExecuteAsync(
                    sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName",
                    param: parameters,
                    commandType: CommandType.Text);
            });
        }
    }
}

using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.EAS.Domain.Configuration;
using SFA.DAS.EAS.Domain.Data.Repositories;
using SFA.DAS.EAS.Domain.Models.UserProfile;
using SFA.DAS.Sql.Client;
using SFA.DAS.NLog.Logger;

namespace SFA.DAS.EAS.Infrastructure.Data
{
    public class UserRepository : BaseRepository, IUserRepository
    {
        private readonly Lazy<EmployerAccountsDbContext> _db;

        public UserRepository(EmployerApprenticeshipsServiceConfiguration configuration, ILog logger, Lazy<EmployerAccountsDbContext> db)
            : base(configuration.DatabaseConnectionString, logger)
        {
            _db = db;
        }

        public Task Upsert(User user)
        {
            return WithConnection(c =>
            {
                var parameters = new DynamicParameters();

                parameters.Add("@email", user.Email, DbType.String);
                parameters.Add("@userRef", new Guid(user.UserRef), DbType.Guid);
                parameters.Add("@firstName", user.FirstName, DbType.String);
                parameters.Add("@lastName", user.LastName, DbType.String);
                parameters.Add("@correlationId", null, DbType.String);

                return c.ExecuteAsync(
                    sql: "[employer_account].[UpsertUser] @userRef, @email, @firstName, @lastName, @correlationId",
                    param: parameters,
                    commandType: CommandType.Text);
            });
        }
    }
}

[CON-1384] Fix for missing correlationId preventing startup of EAS


// 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 Newtonsoft.Json;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;

namespace osu.Game.Online.Spectator
{
    [Serializable]
    public class FrameHeader
    {
        public int Combo { get; set; }

        public int MaxCombo { get; set; }

        public Dictionary<HitResult, int> Statistics { get; set; }

        /// <summary>
        /// Construct header summary information from a point-in-time reference to a score which is actively being played.
        /// </summary>
        /// <param name="score">The score for reference.</param>
        public FrameHeader(ScoreInfo score)
        {
            Combo = score.Combo;
            MaxCombo = score.MaxCombo;

            // copy for safety
            Statistics = new Dictionary<HitResult, int>(score.Statistics);
        }

        [JsonConstructor]
        public FrameHeader(int combo, int maxCombo, Dictionary<HitResult, int> statistics)
        {
            Combo = combo;
            MaxCombo = maxCombo;
            Statistics = statistics;
        }
    }
}

// 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 Newtonsoft.Json;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;

namespace osu.Game.Online.Spectator
{
    [Serializable]
    public class FrameHeader
    {
        /// <summary>
        /// The current combo of the score.
        /// </summary>
        public int Combo { get; set; }

        /// <summary>
        /// The maximum combo achieved up to the current point in time.
        /// </summary>
        public int MaxCombo { get; set; }

        /// <summary>
        /// Cumulative hit statistics.
        /// </summary>
        public Dictionary<HitResult, int> Statistics { get; set; }

        /// <summary>
        /// The time at which this frame was received by the server.
        /// </summary>
        public DateTimeOffset ReceivedTime { get; set; }

        /// <summary>
        /// Construct header summary information from a point-in-time reference to a score which is actively being played.
        /// </summary>
        /// <param name="score">The score for reference.</param>
        public FrameHeader(ScoreInfo score)
        {
            Combo = score.Combo;
            MaxCombo = score.MaxCombo;

            // copy for safety
            Statistics = new Dictionary<HitResult, int>(score.Statistics);
        }

        [JsonConstructor]
        public FrameHeader(int combo, int maxCombo, Dictionary<HitResult, int> statistics, DateTimeOffset receivedTime)
        {
            Combo = combo;
            MaxCombo = maxCombo;
            Statistics = statistics;
            ReceivedTime = receivedTime;
        }
    }
}

Add received timestamp and basic xmldoc for header class


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

namespace EarTrumpet.Services
{
    public static class WhatsNewDisplayService
    {
        internal static void ShowIfAppropriate()
        {
            if (App.HasIdentity())
            {
                var currentVersion = PackageVersionToReadableString(Package.Current.Id.Version);
                var hasShownFirstRun = false;
                var lastVersion = Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)];
                if ((lastVersion != null && currentVersion == (string)lastVersion))
                {
                    return;
                }

                Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)] = currentVersion;

                var versionArray = lastVersion?.ToString().Split('.');
                if (versionArray?.Length > 2 && (versionArray[0] == Package.Current.Id.Version.Major.ToString() && versionArray[1] == Package.Current.Id.Version.Minor.ToString()))
                {
                    return;
                }

                if (!Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey(nameof(hasShownFirstRun)))
                {
                    return;
                }

                try
                {
                    System.Diagnostics.Process.Start("eartrumpet:");
                }
                catch { }
            }
        }

        private static string PackageVersionToReadableString(PackageVersion packageVersion)
        {
            return $"{packageVersion.Major}.{packageVersion.Minor}.{packageVersion.Build}.{packageVersion.Revision}";
        }
    }
}

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

namespace EarTrumpet.Services
{
    public static class WhatsNewDisplayService
    {
        internal static void ShowIfAppropriate()
        {
            if (App.HasIdentity())
            {
                var currentVersion = PackageVersionToReadableString(Package.Current.Id.Version);
                var hasShownFirstRun = false;
                var lastVersion = Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)];
                if ((lastVersion != null && currentVersion == (string)lastVersion))
                {
                    return;
                }

                Windows.Storage.ApplicationData.Current.LocalSettings.Values[nameof(currentVersion)] = currentVersion;

                Version.TryParse(lastVersion?.ToString(), out var oldVersion);
                if (oldVersion?.Major == Package.Current.Id.Version.Major && oldVersion?.Minor == Package.Current.Id.Version.Minor)
                {
                    return;
                }

                if (!Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey(nameof(hasShownFirstRun)))
                {
                    return;
                }

                try
                {
                    System.Diagnostics.Process.Start("eartrumpet:");
                }
                catch { }
            }
        }

        private static string PackageVersionToReadableString(PackageVersion packageVersion)
        {
            return $"{packageVersion.Major}.{packageVersion.Minor}.{packageVersion.Build}.{packageVersion.Revision}";
        }
    }
}

Use version parser instead of string.split


using System;
using System.Collections.Generic;
using System.Linq;
using CIV.Ccs;
using CIV.Common;

namespace CIV.Hml
{
    class BoxFormula : HmlLabelFormula
    {
        protected override string BuildRepr() => $"[{String.Join(",", Label)}]{Inner}";

        protected override bool CheckStrategy(IEnumerable<IProcess> processes)
			=> processes.All(Inner.Check);

        protected override IEnumerable<Transition> TransitionStrategy(IProcess process)
        {
			return process.GetTransitions();
		}
		public override bool Check(IProcess process)
		{
            var grouped = MatchedTransitions(process).GroupBy(x => x.Label);
			return grouped.All(procs => procs.All(p => Inner.Check(p.Process)));
		}
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using CIV.Common;

namespace CIV.Hml
{
    class BoxFormula : HmlLabelFormula
    {
        protected override string BuildRepr() => $"[{String.Join(",", Label)}]{Inner}";

        protected override bool CheckStrategy(IEnumerable<IProcess> processes)
			=> processes.All(Inner.Check);

        protected override IEnumerable<Transition> TransitionStrategy(IProcess process)
        {
			return process.GetTransitions();
		}
		public override bool Check(IProcess process)
		{
            var grouped = MatchedTransitions(process).GroupBy(x => x.Label);
			return grouped.All(procs => procs.All(p => Inner.Check(p.Process)));
		}
    }
}

Remove CIV.Ccs reference from CIV.Hml

Remove CIV.Ccs reference from CIV.Hml


using System;

namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories
{
    using System.Collections.Generic;
    using System.Linq;

    using RightpointLabs.Pourcast.Domain.Models;
    using RightpointLabs.Pourcast.Domain.Repositories;
    using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections;

    public class UserRepository : EntityRepository<User>, IUserRepository
    {
        public UserRepository(UserCollectionDefinition userCollectionDefinition)
            : base(userCollectionDefinition)
        {
        }

        public User GetByUsername(string username)
        {
            // TODO: use a Regex so we can drop the ToList() and push the work to Mongo
            return Queryable.ToList().SingleOrDefault(x => string.Equals(x.Username, username, StringComparison.InvariantCultureIgnoreCase));
        }

        public IEnumerable<User> GetUsersInRole(string id)
        {
            return Queryable.Where(x => x.RoleIds.Contains(id));
        }
    }
}

using System;

namespace RightpointLabs.Pourcast.Infrastructure.Persistence.Repositories
{
    using System.Collections.Generic;
    using System.Linq;

    using RightpointLabs.Pourcast.Domain.Models;
    using RightpointLabs.Pourcast.Domain.Repositories;
    using RightpointLabs.Pourcast.Infrastructure.Persistence.Collections;

    public class UserRepository : EntityRepository<User>, IUserRepository
    {
        public UserRepository(UserCollectionDefinition userCollectionDefinition)
            : base(userCollectionDefinition)
        {
        }

        public User GetByUsername(string username)
        {
            // TODO: Update to Mongo 2.0 so we can drop the .ToList() and push the work to Mongo
            return Queryable.ToList().SingleOrDefault(x => x.Username.Equals(username, StringComparison.InvariantCultureIgnoreCase));
        }

        public IEnumerable<User> GetUsersInRole(string id)
        {
            return Queryable.Where(x => x.RoleIds.Contains(id));
        }
    }
}

Use a fix that's closer to the Mongo 2.0 driver's way of doing things


@model PagedList.IPagedList<AstroPhotoGallery.Models.Category>
@using PagedList.Mvc;
@using System.Linq;
@{
    ViewBag.Title = "List";
}
<link href="~/Content/PagedList.css" rel="stylesheet" />

Browse by categories

    @foreach (var category in Model)
    {

                @if (category.Pictures.Any(p => p.CategoryId == category.Id))
                {
                     p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="height:190px;width:350px">
                }
                else
                {

                }

                        @Html.ActionLink(string.Format($"{category.Name}"),
                                "ListPictures", "Home", new { @categoryId = category.Id }, null)

    }

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("ListCategories",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

@model PagedList.IPagedList<AstroPhotoGallery.Models.Category>
@using PagedList.Mvc;
@using System.Linq;
@{
    ViewBag.Title = "List";
}
<link href="~/Content/PagedList.css" rel="stylesheet" />

Browse by categories

    @foreach (var category in Model)
    {

                @if (category.Pictures.Any(p => p.CategoryId == category.Id))
                {
                     p.CategoryId == category.Id).FirstOrDefault().ImagePath)" style="height:190px;width:350px">
                }
                else
                {

                }

                        @Html.ActionLink(string.Format($"{category.Name}({category.Pictures.Count})"),
                                "ListPictures", "Home", new { @categoryId = category.Id }, null)

    }

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("ListCategories",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Add pictures count of category

Add pictures count of category


using System;
using Aliencube.EntityContextLibrary.Interfaces;
using FluentAssertions;
using NUnit.Framework;

namespace Aliencube.EntityContextLibrary.Tests
{
    [TestFixture]
    public class DbContextFactoryTest
    {
        private IDbContextFactory _factory;

        [SetUp]
        public void Init()
        {
            AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());

            this._factory = new DbContextFactory<ProductContext>();
        }

        [TearDown]
        public void Cleanup()
        {
            if (this._factory != null)
            {
                this._factory.Dispose();
            }
        }

        [Test]
        [TestCase(typeof(ProductContext))]
        public void GetContext_GivenDetails_ReturnContext(Type expectedType)
        {
            var context = this._factory.Context;
            context.Should().NotBeNull();
            context.Should().BeOfType(expectedType);
        }
    }
}

using System;

using Aliencube.EntityContextLibrary.Interfaces;

using FluentAssertions;

using NUnit.Framework;

namespace Aliencube.EntityContextLibrary.Tests
{
    /// <summary>
    /// This represents the test entity for the <see cref="DbContextFactory{TContext}" /> class.
    /// </summary>
    [TestFixture]
    public class DbContextFactoryTest
    {
        private IDbContextFactory _factory;

        /// <summary>
        /// Initialises all resources for tests.
        /// </summary>
        [SetUp]
        public void Init()
        {
            AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());

            this._factory = new DbContextFactory<ProductContext>();
        }

        /// <summary>
        /// Release all resources after tests.
        /// </summary>
        [TearDown]
        public void Cleanup()
        {
            if (this._factory != null)
            {
                this._factory.Dispose();
            }
        }

        /// <summary>
        /// Tests whether the context factory returns DbContext with given type or not.
        /// </summary>
        /// <param name="expectedType">
        /// The expected type.
        /// </param>
        [Test]
        [TestCase(typeof(ProductContext))]
        public void ContextFactory_Should_Return_Context_Of_Given_Type(Type expectedType)
        {
            var context = this._factory.Context;
            context.Should().NotBeNull();
            context.Should().BeOfType(expectedType);
        }
    }
}

Update test methods for DbContextFactory


@using SFA.DAS.EmployerApprenticeshipsService.Web
@using SFA.DAS.EmployerApprenticeshipsService.Web.Models
@model dynamic
@{
    var viewModel = Model as OrchestratorResponse;

}
@if (viewModel?.FlashMessage != null)
{

                @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline))
                {

@viewModel.FlashMessage.Headline

                }
                @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message))
                {

@viewModel.FlashMessage.Message

                }
                @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage))
                {

@viewModel.FlashMessage.SubMessage

                }

}

@using SFA.DAS.EmployerApprenticeshipsService.Web
@using SFA.DAS.EmployerApprenticeshipsService.Web.Models
@model dynamic
@{
    var viewModel = Model as OrchestratorResponse;

}
@if (!string.IsNullOrEmpty(viewModel?.FlashMessage?.Message))
{

                @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline))
                {

@viewModel.FlashMessage.Headline

                }
                @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message))
                {

@viewModel.FlashMessage.Message

                }
                @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage))
                {

@viewModel.FlashMessage.SubMessage

                }

}

Check we have a message as well when checking the flashmessage view model


namespace Ploeh.AutoFixture
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using Kernel;

    public class LambdaExpressionGenerator : ISpecimenBuilder
    {
        public object Create(object request, ISpecimenContext context)
        {
            var requestType = request as Type;
            if (requestType == null)
            {
                return new NoSpecimen();
            }

            if (requestType.BaseType != typeof(LambdaExpression))
            {
                return new NoSpecimen();
            }

            var delegateType = requestType.GetGenericArguments().Single();
            var genericArguments = delegateType.GetGenericArguments().Select(Expression.Parameter).ToList();

            if (delegateType.Name.StartsWith( "Action"))
            {
                return Expression.Lambda(Expression.Empty(), genericArguments);
            }

            var body = genericArguments.Last();
            var parameters = new List<ParameterExpression>();
            if (genericArguments.Count > 1)
            {
                parameters = genericArguments.Take(genericArguments.Count - 1).ToList();
            }

            return Expression.Lambda(body, parameters);
        }
    }
}

namespace Ploeh.AutoFixture
{
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using Kernel;

    public class LambdaExpressionGenerator : ISpecimenBuilder
    {
        public object Create(object request, ISpecimenContext context)
        {
            var requestType = request as Type;
            if (requestType == null)
            {
                return new NoSpecimen();
            }

            if (requestType.BaseType != typeof(LambdaExpression))
            {
                return new NoSpecimen();
            }

            var delegateType = requestType.GetGenericArguments().Single();
            var genericArguments = delegateType.GetGenericArguments().Select(Expression.Parameter).ToList();

            if (delegateType.Name.StartsWith("Action"))
            {
                return Expression.Lambda(Expression.Empty(), genericArguments);
            }

            var body = genericArguments.Last();
            var parameters = genericArguments.Except(new[] { body });

            return Expression.Lambda(body, parameters);
        }
    }
}

Simplify the Expression<Func<>> specimen building


using System;
using System.Drawing;
using MonoHaven.Graphics;
using MonoHaven.Utils;
using OpenTK.Input;

namespace MonoHaven.UI
{
	public class ImageButton : Widget
	{
		private bool isPressed;

		public ImageButton(Widget parent)
			: base(parent)
		{
			IsFocusable = true;
		}

		public event EventHandler Clicked;

		public Drawable Image
		{
			get;
			set;
		}

		public Drawable PressedImage
		{
			get;
			set;
		}

		protected override void OnDraw(DrawingContext dc)
		{
			var tex = isPressed ? PressedImage : Image;
			if (tex != null)
				dc.Draw(tex, 0, 0);
		}

		protected override void OnMouseButtonDown(MouseButtonEventArgs e)
		{
			Host.GrabMouse(this);
			isPressed = true;
		}

		protected override void OnMouseButtonUp(MouseButtonEventArgs e)
		{
			Host.ReleaseMouse();
			isPressed = false;

			// button released outside of borders?
			var p = PointToWidget(e.Position);
			if (Rectangle.FromLTRB(0, 0, Width, Height).Contains(p))
				Clicked.Raise(this, EventArgs.Empty);
		}
	}
}

using System;
using System.Drawing;
using MonoHaven.Graphics;
using MonoHaven.Utils;
using OpenTK.Input;

namespace MonoHaven.UI
{
	public class ImageButton : Widget
	{
		private bool isPressed;

		public ImageButton(Widget parent)
			: base(parent)
		{
			IsFocusable = true;
		}

		public event EventHandler Clicked;

		public Drawable Image
		{
			get;
			set;
		}

		public Drawable PressedImage
		{
			get;
			set;
		}

		public Drawable HoveredImage
		{
			get;
			set;
		}

		protected override void OnDraw(DrawingContext dc)
		{
			Drawable image = null;

			if (isPressed && PressedImage != null)
				image = PressedImage;
			else if (IsHovered && HoveredImage != null)
				image = HoveredImage;
			else
				image = Image;

			if (image != null)
				dc.Draw(image, 0, 0);
		}

		protected override void OnMouseButtonDown(MouseButtonEventArgs e)
		{
			Host.GrabMouse(this);
			isPressed = true;
		}

		protected override void OnMouseButtonUp(MouseButtonEventArgs e)
		{
			Host.ReleaseMouse();
			isPressed = false;

			// button released outside of borders?
			var p = PointToWidget(e.Position);
			if (Rectangle.FromLTRB(0, 0, Width, Height).Contains(p))
				Clicked.Raise(this, EventArgs.Empty);
		}
	}
}

Add image for a hovered state in image button


using System.Threading.Tasks;
using Mntone.NintendoNetworkHelper;
using Mntone.SplatoonClient.Internal;

namespace Mntone.SplatoonClient
{
	public static class SplatoonContextFactory
	{
		public static async Task<SplatoonContext> GetContextAsync(string username, string password)
		{
			var authorizer = new NintendoNetworkAuthorizer();
			var requestToken = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false);
			var accessToken = await authorizer.Authorize(requestToken, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false);
			var requestToken2 = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false);
			var accessToken2 = await authorizer.Authorize(requestToken2, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false);
			authorizer.Dispose();
			return new SplatoonContext(accessToken2);
		}
	}
}

using System.Threading.Tasks;
using Mntone.NintendoNetworkHelper;
using Mntone.SplatoonClient.Internal;

namespace Mntone.SplatoonClient
{
	public static class SplatoonContextFactory
	{
		public static async Task<SplatoonContext> GetContextAsync(string username, string password)
		{
			var authorizer = new NintendoNetworkAuthorizer();
			var requestToken = await authorizer.GetRequestTokenAsync(SplatoonConstantValues.AUTH_FORWARD_URI).ConfigureAwait(false);
			var accessToken = await authorizer.Authorize(requestToken, new AuthenticationToken(username, password), SplatoonHelper.GetSessionValue).ConfigureAwait(false);
			authorizer.Dispose();
			return new SplatoonContext(accessToken);
		}
	}
}

Change source code as Nintendo updates SplatNet (bug fix).


using System;
using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.NH1119
{
	[TestFixture]
	public class Fixture : BugTestCase
	{
		public override string BugNumber
		{
			get { return "NH1119"; }
		}

		[Test]
		public void SelectMinFromEmptyTable()
		{
			using (ISession s = OpenSession())
			{
				DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>();
				Assert.AreEqual(default(DateTime), dt);
			}
		}
	}
}

using System;
using NUnit.Framework;

namespace NHibernate.Test.NHSpecificTest.NH1119
{
	[TestFixture]
	public class Fixture : BugTestCase
	{
		public override string BugNumber
		{
			get { return "NH1119"; }
		}

		[Test]
		public void SelectMinFromEmptyTable()
		{
			using (ISession s = OpenSession())
			{
				DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>();
				Assert.AreEqual(default(DateTime), dt);
				DateTime? dtn = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime?>();
				Assert.IsFalse(dtn.HasValue);
			}
		}
	}
}

Check that it can work with nullables too.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@3063