namespace Tanka.Web.Infrastructure
{
    using System;
    using System.Linq;
    using global::Nancy;
    using global::Nancy.Responses;

    public static class AppHarborCompatibilityExtensions
    {
        public static void RequiresHttpsOrXProto(this INancyModule module, bool redirect = true)
        {
            module.Before.AddItemToEndOfPipeline(RequiresHttpsOrXForwardedProto(redirect));
        }

        private static Func<NancyContext, Response> RequiresHttpsOrXForwardedProto(bool redirect)
        {
            return ctx =>
            {
                Response response = null;
                Request request = ctx.Request;

                string scheme = request.Headers["X-Forwarded-Proto"].SingleOrDefault();

                if (!IsSecure(scheme, request.Url))
                {
                    if (redirect && request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
                    {
                        Url redirectUrl = request.Url.Clone();
                        redirectUrl.Scheme = "https";
                        redirectUrl.Port = 443;
                        response = new RedirectResponse(redirectUrl.ToString());
                    }
                    else
                    {
                        response = new Response {StatusCode = HttpStatusCode.Forbidden};
                    }
                }

                return response;
            };
        }

        private static bool IsSecure(string scheme, Url url)
        {
            if (scheme == "https")
                return true;

            return url.IsSecure;
        }
    }
}

namespace Tanka.Web.Infrastructure
{
    using System;
    using System.Linq;
    using global::Nancy;
    using global::Nancy.Responses;

    public static class AppHarborCompatibilityExtensions
    {
        public static void RequiresHttpsOrXProto(this INancyModule module, bool redirect = true)
        {
            module.Before.AddItemToEndOfPipeline(RequiresHttpsOrXForwardedProto(redirect));
        }

        private static Func<NancyContext, Response> RequiresHttpsOrXForwardedProto(bool redirect)
        {
            return ctx =>
            {
                Response response = null;
                Request request = ctx.Request;

                if (!IsSecure(request))
                {
                    if (redirect && request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
                    {
                        Url redirectUrl = request.Url.Clone();
                        redirectUrl.Scheme = "https";
                        redirectUrl.Port = 443;
                        response = new RedirectResponse(redirectUrl.ToString());
                    }
                    else
                    {
                        response = new Response {StatusCode = HttpStatusCode.Forbidden};
                    }
                }

                return response;
            };
        }

        private static bool IsSecure(Request request)
        {
            if (request.Headers.Keys.Contains("X-Forwarded-Proto"))
            {
                var scheme = request.Headers["X-Forwarded-Proto"].FirstOrDefault();

                if (!string.IsNullOrWhiteSpace(scheme) && scheme == "https")
                    return true;
            }

            return request.Url.IsSecure;
        }
    }
}

Fix issue with checking header value

bugfix: Fix issue with checking header value

Fix the issue and handle the case of missing header value


// Copyright (c) Timm Krause. All rights reserved. See LICENSE file in the project root for license information.

using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("AspNet.Identity.OracleProvider")]
[assembly: AssemblyDescription("ASP.NET Identity provider for Oracle databases.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AspNet.Identity.OracleProvider")]
[assembly: AssemblyCopyright("Copyright © Timm Krause 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("en-US")]
[assembly: ComVisible(false)]
[assembly: Guid("051142e2-9936-4eb4-9a92-83a1d1ad63f6")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-alpha1")]
[assembly: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant", Justification = "Needless.")]

// Copyright (c) Timm Krause. All rights reserved. See LICENSE file in the project root for license information.

using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("AspNet.Identity.OracleProvider")]
[assembly: AssemblyDescription("ASP.NET Identity provider for Oracle databases.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AspNet.Identity.OracleProvider")]
[assembly: AssemblyCopyright("Copyright © Timm Krause 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("051142e2-9936-4eb4-9a92-83a1d1ad63f6")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-alpha1")]
[assembly: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant", Justification = "Needless.")]

Fix an issue with assembly binding which prevents the tests from running by removing the AssemblyCulture.


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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("479a5641-1614-4d2a-aeab-afa79884e207")]

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

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

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

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("479a5641-1614-4d2a-aeab-afa79884e207")]

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

Update model project to minor version 11


using System.Collections;
using PatchKit.Api;
using UnityEngine;

namespace PatchKit.Unity.UI
{
    public abstract class UIApiComponent : MonoBehaviour
    {
        private Coroutine _loadCoroutine;

        private bool _isDirty;

        private ApiConnection _apiConnection;

        public bool LoadOnAwake = true;

        protected ApiConnection ApiConnection
        {
            get { return _apiConnection; }
        }

        [ContextMenu("Reload")]
        public void SetDirty()
        {
            _isDirty = true;
        }

        protected abstract IEnumerator LoadCoroutine();

        private void Load()
        {
            try
            {
                if (_loadCoroutine != null)
                {
                    StopCoroutine(_loadCoroutine);
                }

                _loadCoroutine = StartCoroutine(LoadCoroutine());
            }
            finally
            {
                _isDirty = false;
            }
        }

        protected virtual void Awake()
        {
            _apiConnection = new ApiConnection(Settings.GetApiConnectionSettings());

            if (LoadOnAwake)
            {
                Load();
            }
        }

        protected virtual void Update()
        {
            if (_isDirty)
            {
                Load();
            }
        }
    }
}

using System.Collections;
using PatchKit.Api;
using UnityEngine;

namespace PatchKit.Unity.UI
{
    public abstract class UIApiComponent : MonoBehaviour
    {
        private Coroutine _loadCoroutine;

        private bool _isDirty;

        private ApiConnection _apiConnection;

        public bool LoadOnStart = true;

        protected ApiConnection ApiConnection
        {
            get { return _apiConnection; }
        }

        [ContextMenu("Reload")]
        public void SetDirty()
        {
            _isDirty = true;
        }

        protected abstract IEnumerator LoadCoroutine();

        private void Load()
        {
            try
            {
                if (_loadCoroutine != null)
                {
                    StopCoroutine(_loadCoroutine);
                }

                _loadCoroutine = StartCoroutine(LoadCoroutine());
            }
            finally
            {
                _isDirty = false;
            }
        }

        protected virtual void Awake()
        {
            _apiConnection = new ApiConnection(Settings.GetApiConnectionSettings());
        }

        protected virtual void Start()
        {
            if (LoadOnStart)
            {
                Load();
            }
        }

        protected virtual void Update()
        {
            if (_isDirty)
            {
                Load();
            }
        }
    }
}

Change load event of UI component to from Awake to Start


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

namespace Knapcode.TorSharp.Tools.Tor
{
    public class TorConfigurationDictionary : IConfigurationDictionary
    {
        private readonly string _torDirectoryPath;

        public TorConfigurationDictionary(string torDirectoryPath)
        {
            _torDirectoryPath = torDirectoryPath;
        }

        public IDictionary<string, string> GetDictionary(TorSharpSettings settings)
        {
            var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "SocksPort", settings.TorSocksPort.ToString(CultureInfo.InvariantCulture) },
                { "ControlPort", settings.TorControlPort.ToString(CultureInfo.InvariantCulture) }
            };

            if (settings.HashedTorControlPassword != null)
            {
                dictionary["HashedControlPassword"] = settings.HashedTorControlPassword;
            }

            if (!string.IsNullOrWhiteSpace(settings.TorDataDirectory))
            {
                dictionary["DataDirectory"] = settings.TorDataDirectory;
            }

            if (settings.TorExitNodes != null)
            {
                dictionary["ExitNodes"] = settings.TorExitNodes;
                dictionary["GeoIPFile"] = Path.Combine(_torDirectoryPath, "Data\\Tor\\geoip");
                dictionary["GeoIPv6File"] = Path.Combine(_torDirectoryPath, "Data\\Tor\\geoip6");
            }

            if (settings.TorStrictNodes != null)
            {
                dictionary["StrictNodes"] = (bool)settings.TorStrictNodes ? "1" : "0";
            }

            return dictionary;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

namespace Knapcode.TorSharp.Tools.Tor
{
    public class TorConfigurationDictionary : IConfigurationDictionary
    {
        private readonly string _torDirectoryPath;

        public TorConfigurationDictionary(string torDirectoryPath)
        {
            _torDirectoryPath = torDirectoryPath;
        }

        public IDictionary<string, string> GetDictionary(TorSharpSettings settings)
        {
            var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { "SocksPort", settings.TorSocksPort.ToString(CultureInfo.InvariantCulture) },
                { "ControlPort", settings.TorControlPort.ToString(CultureInfo.InvariantCulture) }
            };

            if (settings.HashedTorControlPassword != null)
            {
                dictionary["HashedControlPassword"] = settings.HashedTorControlPassword;
            }

            if (!string.IsNullOrWhiteSpace(settings.TorDataDirectory))
            {
                dictionary["DataDirectory"] = settings.TorDataDirectory;
            }

            if (settings.TorExitNodes != null)
            {
                dictionary["ExitNodes"] = settings.TorExitNodes;
                dictionary["GeoIPFile"] = Path.Combine(_torDirectoryPath, Path.Combine("Data", "Tor", "geoip"));
                dictionary["GeoIPv6File"] = Path.Combine(_torDirectoryPath, Path.Combine("Data", "Tor", "geoip6"));
            }

            if (settings.TorStrictNodes != null)
            {
                dictionary["StrictNodes"] = settings.TorStrictNodes.Value ? "1" : "0";
            }

            return dictionary;
        }
    }
}

Use Path.Combine instead of Windows-specific directory separators


using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace Telegram.Bot.Helpers
{
    /// <summary>
    /// Extension Methods
    /// </summary>
    internal static class Extensions
    {
        static string EncodeUtf8(this string value) =>
            new(Encoding.UTF8.GetBytes(value).Select(Convert.ToChar).ToArray());

        internal static void AddStreamContent(
            this MultipartFormDataContent multipartContent,
            Stream content,
            string name,
            string fileName = default)
        {
            fileName ??= name;
            var contentDisposition = $@"form-data; name=""{name}""; filename=""{fileName}""".EncodeUtf8();

            HttpContent mediaPartContent = new StreamContent(content)
            {
                Headers =
                {
                    {"Content-Type", "application/octet-stream"},
                    {"Content-Disposition", contentDisposition}
                }
            };

            multipartContent.Add(mediaPartContent, name, fileName);
        }

        internal static void AddContentIfInputFileStream(
            this MultipartFormDataContent multipartContent,
            params IInputMedia[] inputMedia)
        {
            foreach (var input in inputMedia)
            {
                if (input.Media.FileType == FileType.Stream)
                {
                    multipartContent.AddStreamContent(input.Media.Content, input.Media.FileName);
                }

                var mediaThumb = (input as IInputMediaThumb)?.Thumb;
                if (mediaThumb?.FileType == FileType.Stream)
                {
                    multipartContent.AddStreamContent(mediaThumb.Content, mediaThumb.FileName);
                }
            }
        }
    }
}

using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

namespace Telegram.Bot.Helpers
{
    /// <summary>
    /// Extension Methods
    /// </summary>
    internal static class Extensions
    {
        static string EncodeUtf8(this string value) =>
            new(Encoding.UTF8.GetBytes(value).Select(c => Convert.ToChar(c)).ToArray());

        internal static void AddStreamContent(this MultipartFormDataContent multipartContent,
                                              Stream content,
                                              string name,
                                              string? fileName = default)
        {
            fileName ??= name;
            var contentDisposition = $@"form-data; name=""{name}""; filename=""{fileName}""".EncodeUtf8();

            HttpContent mediaPartContent = new StreamContent(content)
            {
                Headers =
                {
                    {"Content-Type", "application/octet-stream"},
                    {"Content-Disposition", contentDisposition}
                }
            };

            multipartContent.Add(mediaPartContent, name, fileName);
        }

        internal static void AddContentIfInputFileStream(this MultipartFormDataContent multipartContent,
                                                         params IInputMedia[] inputMedia)
        {
            foreach (var input in inputMedia)
            {
                if (input.Media.FileType == FileType.Stream)
                {
                    multipartContent.AddStreamContent(input.Media.Content, input.Media.FileName);
                }

                var mediaThumb = (input as IInputMediaThumb)?.Thumb;
                if (mediaThumb?.FileType == FileType.Stream)
                {
                    multipartContent.AddStreamContent(mediaThumb.Content, mediaThumb.FileName);
                }
            }
        }
    }
}

Add nullability for helper extensions

Add nullability for helper extensions


//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Junle Li">
//     Copyright (c) Junle Li. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

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

[assembly: AssemblyTitle("Vsxmd")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Vsxmd")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1911d778-b05f-4eac-8fc8-4c2a8fd456ce")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]

//-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Junle Li">
//     Copyright (c) Junle Li. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

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

[assembly: AssemblyTitle("Vsxmd")]
[assembly: AssemblyDescription("VS XML documentation -> Markdown syntax.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Junle Li")]
[assembly: AssemblyProduct("Vsxmd")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1911d778-b05f-4eac-8fc8-4c2a8fd456ce")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]

Add necessary assembly info to project.

Add necessary assembly info to project.


@using System.Web.Mvc.Html
@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic>
@if (Model.value != null)
{
    string value = Model.value.ToString();
    var id = Guid.NewGuid().ToString() + "_map";
    var js_id = id.Replace('-', '_');

}

@inherits Umbraco.Web.Mvc.UmbracoViewPage<dynamic>
@if (Model.value != null)
{
    string value = Model.value.ToString();
    var id = string.Format("{0}_map", Guid.NewGuid());

}

Change code to use async defer call for Google Maps

Changed the map code so it uses the callback function of Google Maps. This way the google maps API can be called async.

<script src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&callback=initializeMap" async defer></script>


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

using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;

#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
    public class TextBlockTests : TestBase
    {
        public TextBlockTests()
            : base(@"Controls\TextBlock")
        {
        }

        [Fact]
        public async Task Wrapping_NoWrap()
        {
            Decorator target = new Decorator
            {
                Padding = new Thickness(8),
                Width = 200,
                Height = 200,
                Child = new TextBlock
                {
                    Background = Brushes.Red,
                    FontSize = 12,
                    Foreground = Brushes.Black,
                    Text = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit",
                    VerticalAlignment = VerticalAlignment.Top,
                    TextWrapping = TextWrapping.NoWrap,
                }
            };

            await RenderToFile(target);
            CompareImages();
        }
    }
}

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

using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Xunit;

#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests.Controls
#endif
{
    public class TextBlockTests : TestBase
    {
        public TextBlockTests()
            : base(@"Controls\TextBlock")
        {
        }

        [Fact]
        public async Task Wrapping_NoWrap()
        {
            Decorator target = new Decorator
            {
                FontFamily = new FontFamily("Courier New"),
                Padding = new Thickness(8),
                Width = 200,
                Height = 200,
                Child = new TextBlock
                {
                    Background = Brushes.Red,
                    FontSize = 12,
                    Foreground = Brushes.Black,
                    Text = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit",
                    VerticalAlignment = VerticalAlignment.Top,
                    TextWrapping = TextWrapping.NoWrap,
                }
            };

            await RenderToFile(target);
            CompareImages();
        }
    }
}

Fix unit test by specifying the font in the test image.


using System;
using System.ComponentModel;
using System.IO;
using System.Net;

namespace TweetLib.Core.Utils{
    public static class WebUtils{
        private static bool HasMicrosoftBeenBroughtTo2008Yet;

        private static void EnsureTLS12(){
            if (!HasMicrosoftBeenBroughtTo2008Yet){
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
                ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);
                HasMicrosoftBeenBroughtTo2008Yet = true;
            }
        }

        public static WebClient NewClient(string userAgent){
            EnsureTLS12();

            WebClient client = new WebClient{ Proxy = null };
            client.Headers[HttpRequestHeader.UserAgent] = userAgent;
            return client;
        }

        public static AsyncCompletedEventHandler FileDownloadCallback(string file, Action? onSuccess, Action<Exception>? onFailure){
            return (sender, args) => {
                if (args.Cancelled){
                    try{
                        File.Delete(file);
                    }catch{
                        // didn't want it deleted anyways
                    }
                }
                else if (args.Error != null){
                    onFailure?.Invoke(args.Error);
                }
                else{
                    onSuccess?.Invoke();
                }
            };
        }
    }
}

using System;
using System.ComponentModel;
using System.IO;
using System.Net;

namespace TweetLib.Core.Utils{
    public static class WebUtils{
        private static bool HasMicrosoftBeenBroughtTo2008Yet;

        private static void EnsureTLS12(){
            if (!HasMicrosoftBeenBroughtTo2008Yet){
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
                ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);
                HasMicrosoftBeenBroughtTo2008Yet = true;
            }
        }

        public static WebClient NewClient(string userAgent){
            EnsureTLS12();

            WebClient client = new WebClient{ Proxy = null };
            client.Headers[HttpRequestHeader.UserAgent] = userAgent;
            return client;
        }

        public static AsyncCompletedEventHandler FileDownloadCallback(string file, Action? onSuccess, Action<Exception>? onFailure){
            return (sender, args) => {
                if (args.Cancelled){
                    TryDeleteFile(file);
                }
                else if (args.Error != null){
                    TryDeleteFile(file);
                    onFailure?.Invoke(args.Error);
                }
                else{
                    onSuccess?.Invoke();
                }
            };
        }

        private static void TryDeleteFile(string file){
            try{
                File.Delete(file);
            }catch{
                // didn't want it deleted anyways
            }
        }
    }
}

Delete corrupted downloads after an error


@model IEnumerable<Benchmarks.AspNet.Models.Fortune>

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Fortunes</title>

    id
    message

@foreach (var fortune in Model)
{

    @fortune.ID
    @fortune.Message

}

@model IEnumerable<Benchmarks.AspNet.Models.Fortune>

<!DOCTYPE html>

    <title>Fortunes</title>

    id
    message

@foreach (var fortune in Model)
{

    @fortune.ID
    @fortune.Message

}

Remove meta charset from fortunes in ASP.NET


using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;

namespace MQTTnet.Adapter
{
    public class MqttConnectingFailedException : MqttCommunicationException
    {
        public MqttConnectingFailedException(MqttClientAuthenticateResult resultCode)
            : base($"Connecting with MQTT server failed ({resultCode.ResultCode.ToString()}).")
        {
            Result = resultCode;
        }

        public MqttClientAuthenticateResult Result { get; }
        public MqttClientConnectResultCode ResultCode => Result.ResultCode;
    }
}

using MQTTnet.Client.Connecting;
using MQTTnet.Exceptions;

namespace MQTTnet.Adapter
{
    public class MqttConnectingFailedException : MqttCommunicationException
    {
        public MqttConnectingFailedException(MqttClientAuthenticateResult result)
            : base($"Connecting with MQTT server failed ({result.ResultCode.ToString()}).")
        {
            Result = result;
        }

        public MqttClientAuthenticateResult Result { get; }
        public MqttClientConnectResultCode ResultCode => Result.ResultCode;
    }
}

Change variable name per review request

Change variable name per review request

Change the name of the variable from requestCode to request


using System;
using System.Threading.Tasks;
using BlogApp.Common.Contracts.Accessors;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace BlogApp.Accessors
{
    public sealed class BlogCacheAccessor : ICacheAccessor
    {
        #region Constructor and private members
        private readonly IConfiguration _config;
        private readonly IConnectionMultiplexer _connectionMultiplexer;

        public BlogCacheAccessor(IConfiguration config)
        {
            _config = config
                ?? throw new ArgumentNullException(nameof(config));

            _connectionMultiplexer = ConnectionMultiplexer.Connect(_config["redis:endpoint"]);
        }

        public BlogCacheAccessor(IConfiguration config, IConnectionMultiplexer multiplexer)
        {
            _config = config
                ?? throw new ArgumentNullException(nameof(config));

            _connectionMultiplexer = multiplexer
                ?? throw new ArgumentNullException(nameof(multiplexer));
        }
        #endregion

        public async Task<TEntity> GetEnt<TEntity>(string key) where TEntity : class
        {
            var db = _connectionMultiplexer.GetDatabase();
            var text = await db.StringGetAsync(key);

            return string.IsNullOrEmpty(text)
                ? null
                : JsonConvert.DeserializeObject<TEntity>(text);
        }

        public async Task CacheEnt<TEntity>(string key, TEntity ent, TimeSpan? ttl = null)
        {
            if (ttl == null)
                ttl = TimeSpan.FromMilliseconds(double.Parse(_config["redis:ttlMsDefault"]));

            var db = _connectionMultiplexer.GetDatabase();
            await db.StringSetAsync(key, JsonConvert.SerializeObject(ent), ttl, When.Always, CommandFlags.FireAndForget);
        }
    }
}

using System;
using System.Threading.Tasks;
using BlogApp.Common.Contracts.Accessors;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace BlogApp.Accessors
{
    public sealed class BlogCacheAccessor : ICacheAccessor
    {
        #region Constructor and private members
        private readonly IConfiguration _config;
        private readonly IConnectionMultiplexer _connectionMultiplexer;

        public BlogCacheAccessor(IConfiguration config)
        {
            _config = config
                ?? throw new ArgumentNullException(nameof(config));

            _connectionMultiplexer = ConnectionMultiplexer.Connect(_config["redis:endpoint"]);
        }

        internal BlogCacheAccessor(IConfiguration config, IConnectionMultiplexer multiplexer)
        {
            _config = config
                ?? throw new ArgumentNullException(nameof(config));

            _connectionMultiplexer = multiplexer
                ?? throw new ArgumentNullException(nameof(multiplexer));
        }
        #endregion

        public async Task<TEntity> GetEnt<TEntity>(string key) where TEntity : class
        {
            var db = _connectionMultiplexer.GetDatabase();
            var text = await db.StringGetAsync(key);

            return string.IsNullOrEmpty(text)
                ? null
                : JsonConvert.DeserializeObject<TEntity>(text);
        }

        public async Task CacheEnt<TEntity>(string key, TEntity ent, TimeSpan? ttl = null)
        {
            if (ttl == null)
                ttl = TimeSpan.FromMilliseconds(double.Parse(_config["redis:ttlMsDefault"]));

            var db = _connectionMultiplexer.GetDatabase();
            await db.StringSetAsync(key, JsonConvert.SerializeObject(ent), ttl, When.Always, CommandFlags.FireAndForget);
        }
    }
}

Update accessor constructor used for tests


#if LESSTHAN_NET471 || LESSTHAN_NETCOREAPP20 || LESSTHAN_NETSTANDARD21

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.ComponentModel;

namespace System.Runtime.CompilerServices
{
    /// <summary>
    /// Reserved to be used by the compiler for tracking metadata.
    /// This attribute should not be used by developers in source code.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    [AttributeUsage(AttributeTargets.All, Inherited = false)]
    public sealed class IsReadOnlyAttribute : Attribute
    {
        /// Empty
    }
}

#endif

#if LESSTHAN_NET471 || LESSTHAN_NETCOREAPP20 || LESSTHAN_NETSTANDARD21

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.ComponentModel;

namespace System.Runtime.CompilerServices
{
    /// <summary>
    /// Reserved to be used by the compiler for tracking metadata.
    /// This attribute should not be used by developers in source code.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    [AttributeUsage(AttributeTargets.All, Inherited = false)]
    public sealed class IsReadOnlyAttribute : Attribute
    {
        // Empty
    }
}

#endif

Comment should be // not ///

Comment should be // not ///


using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.Model;
using Nethereum.RPC.Eth.DTOs;

namespace Nethereum.RPC.ModelFactories
{
    public class BlockHeaderRPCFactory
    {
        public static BlockHeader FromRPC(Block rpcBlock)
        {
            var blockHeader = new BlockHeader();
            blockHeader.BlockNumber = rpcBlock.Number;
            blockHeader.Coinbase = rpcBlock.Miner;
            blockHeader.Difficulty = rpcBlock.Difficulty;
            blockHeader.ExtraData = rpcBlock.ExtraData.HexToByteArray();
            blockHeader.GasLimit = (long)rpcBlock.GasLimit.Value;
            blockHeader.GasUsed = (long)rpcBlock.GasUsed.Value;
            blockHeader.LogsBloom = rpcBlock.LogsBloom.HexToByteArray();
            blockHeader.MixHash = rpcBlock.MixHash.HexToByteArray();
            blockHeader.Nonce = rpcBlock.Nonce.HexToByteArray();
            blockHeader.ParentHash = rpcBlock.ParentHash.HexToByteArray();
            blockHeader.ReceiptHash = rpcBlock.ReceiptsRoot.HexToByteArray();
            blockHeader.StateRoot = rpcBlock.StateRoot.HexToByteArray();
            blockHeader.Timestamp = (long)rpcBlock.Timestamp.Value;
            blockHeader.TransactionsHash = rpcBlock.TransactionsRoot.HexToByteArray();
            blockHeader.UnclesHash = rpcBlock.Sha3Uncles.HexToByteArray();
            return blockHeader;
        }
    }
}

using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.Model;
using Nethereum.RPC.Eth.DTOs;

namespace Nethereum.RPC.ModelFactories
{
    public class BlockHeaderRPCFactory
    {
        public static BlockHeader FromRPC(Block rpcBlock, bool mixHasAndhNonceInSealFields = false)
        {
            var blockHeader = new BlockHeader();
            blockHeader.BlockNumber = rpcBlock.Number;
            blockHeader.Coinbase = rpcBlock.Miner;
            blockHeader.Difficulty = rpcBlock.Difficulty;
            blockHeader.ExtraData = rpcBlock.ExtraData.HexToByteArray();
            blockHeader.GasLimit = (long)rpcBlock.GasLimit.Value;
            blockHeader.GasUsed = (long)rpcBlock.GasUsed.Value;
            blockHeader.LogsBloom = rpcBlock.LogsBloom.HexToByteArray();
            blockHeader.ParentHash = rpcBlock.ParentHash.HexToByteArray();
            blockHeader.ReceiptHash = rpcBlock.ReceiptsRoot.HexToByteArray();
            blockHeader.StateRoot = rpcBlock.StateRoot.HexToByteArray();
            blockHeader.Timestamp = (long)rpcBlock.Timestamp.Value;
            blockHeader.TransactionsHash = rpcBlock.TransactionsRoot.HexToByteArray();
            blockHeader.UnclesHash = rpcBlock.Sha3Uncles.HexToByteArray();

            if (mixHasAndhNonceInSealFields && rpcBlock.SealFields != null && rpcBlock.SealFields.Length >= 2)
            {
                blockHeader.MixHash = rpcBlock.SealFields[0].HexToByteArray();
                blockHeader.Nonce = rpcBlock.SealFields[1].HexToByteArray();
            }
            else
            {
                blockHeader.MixHash = rpcBlock.MixHash.HexToByteArray();
                blockHeader.Nonce = rpcBlock.Nonce.HexToByteArray();
            }
            return blockHeader;
        }
    }
}

Support for parity clique mixhash and nonce in SealFields


namespace AgileObjects.ReadableExpressions.UnitTests
{
    using System;
    using System.Linq.Expressions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class WhenTranslatingBlockExpressions
    {
        [TestMethod]
        public void ShouldTranslateANoVariableNoReturnValueBlock()
        {
            Expression<Action> writeLine = () => Console.WriteLine();
            Expression<Func<int>> read = () => Console.Read();
            Expression<Action> beep = () => Console.Beep();

            var consoleBlock = Expression.Block(writeLine.Body, read.Body, beep.Body);

            var translated = consoleBlock.ToReadableString();

            const string EXPECTED = @"
Console.WriteLine();
Console.Read();
Console.Beep();";

            Assert.AreEqual(EXPECTED.TrimStart(), translated);
        }

        [TestMethod]
        public void ShouldTranslateANoVariableBlockWithAReturnValue()
        {
            Expression<Action> writeLine = () => Console.WriteLine();
            Expression<Func<int>> read = () => Console.Read();

            var consoleBlock = Expression.Block(writeLine.Body, read.Body);

            var translated = consoleBlock.ToReadableString();

            const string EXPECTED = @"
Console.WriteLine();
return Console.Read();";

            Assert.AreEqual(EXPECTED.TrimStart(), translated);
        }
    }
}

namespace AgileObjects.ReadableExpressions.UnitTests
{
    using System;
    using System.Linq.Expressions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class WhenTranslatingBlockExpressions
    {
        [TestMethod]
        public void ShouldTranslateANoVariableBlockWithNoReturnValue()
        {
            Expression<Action> writeLine = () => Console.WriteLine();
            Expression<Func<int>> read = () => Console.Read();
            Expression<Action> beep = () => Console.Beep();

            var consoleBlock = Expression.Block(writeLine.Body, read.Body, beep.Body);

            var translated = consoleBlock.ToReadableString();

            const string EXPECTED = @"
Console.WriteLine();
Console.Read();
Console.Beep();";

            Assert.AreEqual(EXPECTED.TrimStart(), translated);
        }

        [TestMethod]
        public void ShouldTranslateANoVariableBlockWithAReturnValue()
        {
            Expression<Action> writeLine = () => Console.WriteLine();
            Expression<Func<int>> read = () => Console.Read();

            var consoleBlock = Expression.Block(writeLine.Body, read.Body);

            var translated = consoleBlock.ToReadableString();

            const string EXPECTED = @"
Console.WriteLine();
return Console.Read();";

            Assert.AreEqual(EXPECTED.TrimStart(), translated);
        }

        [TestMethod]
        public void ShouldTranslateAVariableBlockWithNoReturnValue()
        {
            var countVariable = Expression.Variable(typeof(int), "count");
            var countEqualsZero = Expression.Assign(countVariable, Expression.Constant(0));
            var incrementCount = Expression.Increment(countVariable);
            var noReturnValue = Expression.Default(typeof(void));

            var consoleBlock = Expression.Block(
                new[] { countVariable },
                countEqualsZero,
                incrementCount,
                noReturnValue);

            var translated = consoleBlock.ToReadableString();

            const string EXPECTED = @"
var count = 0;
++count;";

            Assert.AreEqual(EXPECTED.TrimStart(), translated);
        }
    }
}

Test coverage for simple void blocks with a variable


using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using GitHub.Exports;
using GitHub.Services;
using GitHub.ViewModels;

namespace GitHub.Factories
{
    /// <summary>
    /// Factory for creating views and view models.
    /// </summary>
    [Export(typeof(IViewViewModelFactory))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class ViewViewModelFactory : IViewViewModelFactory
    {
        readonly IGitHubServiceProvider serviceProvider;

        [ImportingConstructor]
        public ViewViewModelFactory(
            IGitHubServiceProvider serviceProvider,
            ICompositionService cc)
        {
            this.serviceProvider = serviceProvider;
            cc.SatisfyImportsOnce(this);
        }

        [ImportMany(AllowRecomposition = true)]
        IEnumerable<ExportFactory<FrameworkElement, IViewModelMetadata>> Views { get; set; }

        /// <inheritdoc/>
        public TViewModel CreateViewModel<TViewModel>() where TViewModel : IViewModel
        {
            return serviceProvider.ExportProvider.GetExport<TViewModel>().Value;
        }

        /// <inheritdoc/>
        public FrameworkElement CreateView<TViewModel>() where TViewModel : IViewModel
        {
            return CreateView(typeof(TViewModel));
        }

        /// <inheritdoc/>
        public FrameworkElement CreateView(Type viewModel)
        {
            var f = Views.FirstOrDefault(x => x.Metadata.ViewModelType.Contains(viewModel));
            return f?.CreateExport().Value;
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using GitHub.Exports;
using GitHub.Services;
using GitHub.ViewModels;

namespace GitHub.Factories
{
    /// <summary>
    /// Factory for creating views and view models.
    /// </summary>
    [Export(typeof(IViewViewModelFactory))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class ViewViewModelFactory : IViewViewModelFactory
    {
        readonly IGitHubServiceProvider serviceProvider;

        [ImportingConstructor]
        public ViewViewModelFactory(
            IGitHubServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }

        [ImportMany(AllowRecomposition = true)]
        IEnumerable<ExportFactory<FrameworkElement, IViewModelMetadata>> Views { get; set; }

        /// <inheritdoc/>
        public TViewModel CreateViewModel<TViewModel>() where TViewModel : IViewModel
        {
            return serviceProvider.ExportProvider.GetExport<TViewModel>().Value;
        }

        /// <inheritdoc/>
        public FrameworkElement CreateView<TViewModel>() where TViewModel : IViewModel
        {
            return CreateView(typeof(TViewModel));
        }

        /// <inheritdoc/>
        public FrameworkElement CreateView(Type viewModel)
        {
            var f = Views.FirstOrDefault(x => x.Metadata.ViewModelType.Contains(viewModel));
            return f?.CreateExport().Value;
        }
    }
}

Remove redundant call to SatisfyImportsOnce


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

using osu.Game.Rulesets.Mania.Judgements;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Mania.Scoring
{
    internal class ManiaScoreProcessor : ScoreProcessor<ManiaHitObject, ManiaJudgement>
    {
        public ManiaScoreProcessor()
        {
        }

        public ManiaScoreProcessor(HitRenderer<ManiaHitObject, ManiaJudgement> hitRenderer)
            : base(hitRenderer)
        {
        }

        protected override void OnNewJudgement(ManiaJudgement judgement)
        {
        }
    }
}

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

using osu.Game.Rulesets.Mania.Judgements;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;

namespace osu.Game.Rulesets.Mania.Scoring
{
    internal class ManiaScoreProcessor : ScoreProcessor<ManiaHitObject, ManiaJudgement>
    {
        public ManiaScoreProcessor()
        {
        }

        public ManiaScoreProcessor(HitRenderer<ManiaHitObject, ManiaJudgement> hitRenderer)
            : base(hitRenderer)
        {
        }

        protected override void OnNewJudgement(ManiaJudgement judgement)
        {
        }

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

            Health.Value = 1;
        }
    }
}

Fix osu!mania failing due to 0 hp.

Fix osu!mania failing due to 0 hp.


using CommandLine;

namespace Arkivverket.Arkade.CLI
{
    public abstract class ArchiveProcessingOptions : OutputOptions
    {
        [Option('t', "type", HelpText = "Optional. Archive type, valid values: noark3, noark5 or fagsystem")]
        public string ArchiveType { get; set; }

        [Option('a', "archive", HelpText = "Archive directory or file (.tar) to process.", Required = true)]
        public string Archive { get; set; }

        [Option('p', "processing-area", HelpText = "Directory to place temporary files and logs.", Required = true)]
        public string ProcessingArea { get; set; }
    }
}

using CommandLine;

namespace Arkivverket.Arkade.CLI
{
    public abstract class ArchiveProcessingOptions : OutputOptions
    {
        [Option('t', "type", HelpText = "Optional. Archive type, valid values: noark3, noark4, noark5 or fagsystem")]
        public string ArchiveType { get; set; }

        [Option('a', "archive", HelpText = "Archive directory or file (.tar) to process.", Required = true)]
        public string Archive { get; set; }

        [Option('p', "processing-area", HelpText = "Directory to place temporary files and logs.", Required = true)]
        public string ProcessingArea { get; set; }
    }
}

Update information about valid archive types

ARKADE-608


using Umbraco.Core;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    [PropertyEditor(Constants.PropertyEditors.EmailAddressAlias, "Email address", "email", Icon="icon-message")]
    public class EmailAddressPropertyEditor : PropertyEditor
    {
        protected override PropertyValueEditor CreateValueEditor()
        {
            var editor = base.CreateValueEditor();
            //add an email address validator
            editor.Validators.Add(new EmailValidator());
            return editor;
        }

        protected override PreValueEditor CreatePreValueEditor()
        {
            return new EmailAddressePreValueEditor();
        }

        internal class EmailAddressePreValueEditor : PreValueEditor
        {
            //TODO: This doesn't seem necessary since it can be specified at the property type level - this will however be useful if/when
            // we support overridden property value pre-value options.
            [PreValueField("Required?", "boolean")]
            public bool IsRequired { get; set; }
        }

    }
}

using Umbraco.Core;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    [PropertyEditor(Constants.PropertyEditors.EmailAddressAlias, "Email address", "email", IsParameterEditor = true, Icon ="icon-message")]
    public class EmailAddressPropertyEditor : PropertyEditor
    {
        protected override PropertyValueEditor CreateValueEditor()
        {
            var editor = base.CreateValueEditor();
            //add an email address validator
            editor.Validators.Add(new EmailValidator());
            return editor;
        }

        protected override PreValueEditor CreatePreValueEditor()
        {
            return new EmailAddressePreValueEditor();
        }

        internal class EmailAddressePreValueEditor : PreValueEditor
        {
            //TODO: This doesn't seem necessary since it can be specified at the property type level - this will however be useful if/when
            // we support overridden property value pre-value options.
            [PreValueField("Required?", "boolean")]
            public bool IsRequired { get; set; }
        }

    }
}

Enable email address as macro parameter editor


using System.Linq;
using System.Text;
using AsmResolver.DotNet.Bundles;
using AsmResolver.PE.DotNet.Metadata.Strings;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using Xunit;

namespace AsmResolver.DotNet.Tests.Bundles
{
    public class BundleFileTest
    {
        [Fact]
        public void ReadUncompressedStringContents()
        {
            var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
            var file = manifest.Files.First(f => f.Type == BundleFileType.RuntimeConfigJson);
            string contents = Encoding.UTF8.GetString(file.GetData());

            Assert.Equal(@"{
  ""runtimeOptions"": {
    ""tfm"": ""net6.0"",
    ""framework"": {
      ""name"": ""Microsoft.NETCore.App"",
      ""version"": ""6.0.0""
    },
    ""configProperties"": {
      ""System.Reflection.Metadata.MetadataUpdater.IsSupported"": false
    }
  }
}", contents);
        }

        [Fact]
        public void ReadUncompressedAssemblyContents()
        {
            var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
            var bundleFile = manifest.Files.First(f => f.RelativePath == "HelloWorld.dll");

            var embeddedImage = ModuleDefinition.FromBytes(bundleFile.GetData());
            Assert.Equal("HelloWorld.dll", embeddedImage.Name);
        }
    }
}

using System.Linq;
using System.Text;
using AsmResolver.DotNet.Bundles;
using AsmResolver.PE.DotNet.Metadata.Strings;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using Xunit;

namespace AsmResolver.DotNet.Tests.Bundles
{
    public class BundleFileTest
    {
        [Fact]
        public void ReadUncompressedStringContents()
        {
            var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
            var file = manifest.Files.First(f => f.Type == BundleFileType.RuntimeConfigJson);
            string contents = Encoding.UTF8.GetString(file.GetData()).Replace("\r", "");

            Assert.Equal(@"{
  ""runtimeOptions"": {
    ""tfm"": ""net6.0"",
    ""framework"": {
      ""name"": ""Microsoft.NETCore.App"",
      ""version"": ""6.0.0""
    },
    ""configProperties"": {
      ""System.Reflection.Metadata.MetadataUpdater.IsSupported"": false
    }
  }
}".Replace("\r", ""), contents);
        }

        [Fact]
        public void ReadUncompressedAssemblyContents()
        {
            var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
            var bundleFile = manifest.Files.First(f => f.RelativePath == "HelloWorld.dll");

            var embeddedImage = ModuleDefinition.FromBytes(bundleFile.GetData());
            Assert.Equal("HelloWorld.dll", embeddedImage.Name);
        }
    }
}

Normalize newlines in json test.

Normalize newlines in json test.


@using CkanDotNet.Web.Models.Helpers

As part of an initiative to improve the accessibility, transparency, and
accountability of the Town of Castle Rock, this catalog provides open access to City-managed data.

@if (SettingsHelper.GetUserVoiceEnabled()) {

We invite you to actively participate in shaping the future of this data catalog by
    suggesting additional datasets
    or building applications with the available data.

}

@Html.Action("PackageCount", "Widget") registered datasets are available.

@using CkanDotNet.Web.Models.Helpers

As part of an initiative to improve the accessibility, transparency, and
accountability of the Town of Castle Rock, this catalog provides open access to town-managed data.

@if (SettingsHelper.GetUserVoiceEnabled()) {

We invite you to actively participate in shaping the future of this data catalog by
    suggesting additional datasets
    or building applications with the available data.

}

@Html.Action("PackageCount", "Widget") registered datasets are available.

Update to Castle Rock header text

Update to Castle Rock header text


using System.IO;
using System.Reflection;

namespace Tiver.Fowl.Drivers.Configuration
{
    public class DriversConfiguration
    {
        /// <summary>
        /// Location for binaries to be saved
        /// Defaults to assembly location
        /// </summary>
        public string DownloadLocation { get; set; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

        /// <summary>
        /// Configured driver instances
        /// </summary>
        public DriverElement[] Drivers { get; set; } = {};

        /// <summary>
        /// Timeout to be used for HTTP requests
        /// Value in seconds
        /// </summary>
        public int HttpTimeout { get; set; } = 100;
    }
}

using System.IO;
using System.Reflection;

namespace Tiver.Fowl.Drivers.Configuration
{
    public class DriversConfiguration
    {
        /// <summary>
        /// Location for binaries to be saved
        /// Defaults to assembly location
        /// </summary>
        public string DownloadLocation { get; set; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

        /// <summary>
        /// Configured driver instances
        /// </summary>
        public DriverElement[] Drivers { get; set; } = {};

        /// <summary>
        /// Timeout to be used for HTTP requests
        /// Value in seconds
        /// </summary>
        public int HttpTimeout { get; set; } = 120;
    }
}

Change default HttpTimeout to 120 seconds


using System;
using System.Collections.Generic;
using Arkivverket.Arkade.Util;

namespace Arkivverket.Arkade.Core.Addml.Definitions
{
    public class Separator
    {
        private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string>
            {
                {"CRLF", "\r\n"},
                {"LF", "\n"}
            };

        public static readonly Separator CRLF = new Separator("CRLF");

        private readonly string _name;
        private readonly string _separator;

        public Separator(string separator)
        {
            Assert.AssertNotNullOrEmpty("separator", separator);

            _name = separator;
            _separator = Convert(separator);
        }

        public string Get()
        {
            return _separator;
        }

        public override string ToString()
        {
            return _name;
        }

        protected bool Equals(Separator other)
        {
            return string.Equals(_name, other._name);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((Separator) obj);
        }

        public override int GetHashCode()
        {
            return _name?.GetHashCode() ?? 0;
        }

        private string Convert(string s)
        {
            return SpecialSeparators.ContainsKey(s) ? SpecialSeparators[s] : s;
        }

        internal int GetLength()
        {
            return _separator.Length;
        }
    }
}

using System;
using System.Collections.Generic;
using Arkivverket.Arkade.Util;

namespace Arkivverket.Arkade.Core.Addml.Definitions
{
    public class Separator
    {
        private static readonly Dictionary<string, string> SpecialSeparators = new Dictionary<string, string>
            {
                {"CRLF", "\r\n"},
                {"LF", "\n"}
            };

        public static readonly Separator CRLF = new Separator("CRLF");

        private readonly string _name;
        private readonly string _separator;

        public Separator(string separator)
        {
            Assert.AssertNotNullOrEmpty("separator", separator);

            _name = separator;
            _separator = Convert(separator);
        }

        public string Get()
        {
            return _separator;
        }

        public override string ToString()
        {
            return _name;
        }

        protected bool Equals(Separator other)
        {
            return string.Equals(_name, other._name);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((Separator) obj);
        }

        public override int GetHashCode()
        {
            return _name?.GetHashCode() ?? 0;
        }

        private static string Convert(string separator)
        {
            foreach (string key in SpecialSeparators.Keys)
                if (separator.Contains(key))
                    separator = separator.Replace(key, SpecialSeparators[key]);

            return separator;
        }

        internal int GetLength()
        {
            return _separator.Length;
        }
    }
}

Support complex field- and record separators


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

namespace CotcSdk {

	/** @cond private */
	[Serializable]
	public class CotcSettings : ScriptableObject {
		public const string AssetPath = "Assets/Resources/CotcSettings.asset";

		public static CotcSettings Instance {
			get {
				if (instance == null) {
					instance = Resources.Load(Path.GetFileNameWithoutExtension(AssetPath)) as CotcSettings;
				}
				return instance;
			}
		}

		private static CotcSettings instance;

		[Serializable]
		public class Environment {
			[SerializeField]
			public string Name;
			[SerializeField]
			public string ApiKey;
			[SerializeField]
			public string ApiSecret;
			[SerializeField]
			public string ServerUrl;
			[SerializeField]
			public int LbCount = 1;
			[SerializeField]
			public bool HttpVerbose = true;
			[SerializeField]
			public int HttpTimeout = 60;
			[SerializeField]
			public int HttpClientType = 0;
		}

		[SerializeField]
		public int FileVersion = 2;
		[SerializeField]
		public List<Environment> Environments = new List<Environment>();
		[SerializeField]
		public int SelectedEnvironment = 0;
	}
	/** @endcond */
}

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

namespace CotcSdk {

	/** @cond private */
	[Serializable]
	public class CotcSettings : ScriptableObject {
		public const string AssetPath = "Assets/Resources/CotcSettings.asset";

		public static CotcSettings Instance {
			get {
				if (instance == null) {
					instance = Resources.Load(Path.GetFileNameWithoutExtension(AssetPath)) as CotcSettings;
				}
				return instance;
			}
		}

		private static CotcSettings instance;

		[Serializable]
		public class Environment {
			[SerializeField]
			public string Name;
			[SerializeField]
			public string ApiKey;
			[SerializeField]
			public string ApiSecret;
			[SerializeField]
			public string ServerUrl;
			[SerializeField]
			public int LbCount = 1;
			[SerializeField]
			public bool HttpVerbose = true;
			[SerializeField]
			public int HttpTimeout = 60;
			[SerializeField]
			public int HttpClientType = 1;
		}

		[SerializeField]
		public int FileVersion = 2;
		[SerializeField]
		public List<Environment> Environments = new List<Environment>();
		[SerializeField]
		public int SelectedEnvironment = 0;
	}
	/** @endcond */
}

Use of UnityWebRequest for default http client.


/*
 * Copyright (c) 2018 Håkan Edling
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 *
 * https://github.com/piranhacms/piranha.core
 *
 */

using Microsoft.Extensions.DependencyInjection;
using Piranha;
using Piranha.Local;

public static class FileStorageExtensions
{
    /// <summary>
    /// Adds the services for the local FileStorage service.
    /// </summary>
    /// <param name="services">The current service collection</param>
    /// <param name="scope">The optional service scope</param>
    /// <returns>The service collection</returns>
    public static IServiceCollection AddPiranhaFileStorage(this IServiceCollection services,
        ServiceLifetime scope = ServiceLifetime.Singleton)
    {
        services.Add(new ServiceDescriptor(typeof(IStorage), typeof(FileStorage), scope));

        return services;
    }
}

/*
 * Copyright (c) 2018 Håkan Edling
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 *
 * https://github.com/piranhacms/piranha.core
 *
 */

using Microsoft.Extensions.DependencyInjection;
using Piranha;
using Piranha.Local;

public static class FileStorageExtensions
{
    /// <summary>
    /// Adds the services for the local FileStorage service.
    /// </summary>
    /// <param name="services">The current service collection</param>
    /// <param name="scope">The optional service scope</param>
    /// <returns>The service collection</returns>
    public static IServiceCollection AddPiranhaFileStorage(this IServiceCollection services,
        ServiceLifetime scope = ServiceLifetime.Singleton, string basePath = null, string baseUrl = null)
    {
        services.Add(new ServiceDescriptor(typeof(IStorage), sp => new FileStorage(basePath, baseUrl), scope));

        return services;
    }
}

Add basePath and baseUrl parameters at AddPiranhaFileStorage extension method.


using Ganss.XSS;

namespace CollAction.Helpers
{
    public static class InputSanitizer
    {
        public static string Sanitize(string input)
        {
            var saniziter = new HtmlSanitizer(
                allowedTags: new[] { "p", "br", "strong", "em", "i", "u", "a", "ol", "ul", "li" },
                allowedAttributes: new[] { "href", "target" },
                allowedCssClasses: new string[] {},
                allowedCssProperties: new string[] {}
            );

            return saniziter.Sanitize(input);

        }
    }
}

using Ganss.XSS;

namespace CollAction.Helpers
{
    public static class InputSanitizer
    {
        public static string Sanitize(string input)
        {
            var saniziter = new HtmlSanitizer(
                allowedTags: new[] { "p", "br", "strong", "em", "i", "u", "a", "ol", "ul", "li" },
                allowedSchemes: new string[] { "http", "https"},
                allowedAttributes: new[] { "target" },
                uriAttributes: new[] { "href" },
                allowedCssProperties: new string[] {},
                allowedCssClasses: new string[] {}
            );

            return saniziter.Sanitize(input);
        }
    }
}

Allow only http/https schemes, and href attribute to contain an uri.


using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace NuGet.Dialog.Providers {

    internal class PackagesSearchNode : PackagesTreeNodeBase {

        private string _searchText;
        private readonly PackagesTreeNodeBase _baseNode;

        public PackagesTreeNodeBase BaseNode {
            get {
                return _baseNode;
            }
        }

        public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
            base(parent, provider) {

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

            _searchText = searchText;
            _baseNode = baseNode;

            // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
            IsSearchResultsNode = true;
        }

        public override string Name {
            get {
                return Resources.Dialog_RootNodeSearch;
            }
        }

        public void SetSearchText(string newSearchText) {
            if (newSearchText == null) {
                throw new ArgumentNullException("newSearchText");
            }

            if (_searchText != newSearchText) {
                _searchText = newSearchText;

                if (IsSelected) {
                    ResetQuery();
                    LoadPage(1);
                }
            }
        }

        public override IQueryable<IPackage> GetPackages() {
            return _baseNode.GetPackages().Find(_searchText);
        }
    }
}

using System;
using System.Linq;
using Microsoft.VisualStudio.ExtensionsExplorer;

namespace NuGet.Dialog.Providers {

    internal class PackagesSearchNode : PackagesTreeNodeBase {

        private string _searchText;
        private readonly PackagesTreeNodeBase _baseNode;

        public PackagesTreeNodeBase BaseNode {
            get {
                return _baseNode;
            }
        }

        public PackagesSearchNode(PackagesProviderBase provider, IVsExtensionsTreeNode parent, PackagesTreeNodeBase baseNode, string searchText) :
            base(parent, provider) {

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

            _searchText = searchText;
            _baseNode = baseNode;

            // Mark this node as a SearchResults node to assist navigation in ExtensionsExplorer
            IsSearchResultsNode = true;
        }

        public override string Name {
            get {
                return Resources.Dialog_RootNodeSearch;
            }
        }

        public void SetSearchText(string newSearchText) {
            if (newSearchText == null) {
                throw new ArgumentNullException("newSearchText");
            }

            _searchText = newSearchText;

            if (IsSelected) {
                ResetQuery();
                LoadPage(1);
            }
        }

        public override IQueryable<IPackage> GetPackages() {
            return _baseNode.GetPackages().Find(_searchText);
        }
    }
}

Fix bug: Searching too fast in dialog returns no results when enter is pressed
Work items: 598

--HG--
branch : 1.1


using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OpenOrderFramework.Controllers
{
    public class JsonNetResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            var response = context.HttpContext.Response;

            response.ContentType = !String.IsNullOrEmpty(ContentType)
                ? ContentType
                : "application/json";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            // If you need special handling, you can call another form of SerializeObject below
//            var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings{ ContractResolver = new CamelCasePropertyNamesContractResolver() });
            var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() });
            response.Write(serializedObject);
        }
    }

    public class JsonHandlerAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;

            if (jsonResult != null)
            {
                filterContext.Result = new JsonNetResult
                {
                    ContentEncoding = jsonResult.ContentEncoding,
                    ContentType = jsonResult.ContentType,
                    Data = jsonResult.Data,
                    JsonRequestBehavior = jsonResult.JsonRequestBehavior
                };
            }

            base.OnActionExecuted(filterContext);
        }
    }
}

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OpenOrderFramework.Controllers
{
    public class JsonNetResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            var response = context.HttpContext.Response;

            response.ContentType = !String.IsNullOrEmpty(ContentType)
                ? ContentType
                : "application/json";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            // If you need special handling, you can call another form of SerializeObject below
            var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            //var serializedObject = JsonConvert.SerializeObject(Data, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() });
            response.Write(serializedObject);
        }
    }

    public class JsonHandlerAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;

            if (jsonResult != null)
            {
                filterContext.Result = new JsonNetResult
                {
                    ContentEncoding = jsonResult.ContentEncoding,
                    ContentType = jsonResult.ContentType,
                    Data = jsonResult.Data,
                    JsonRequestBehavior = jsonResult.JsonRequestBehavior
                };
            }

            base.OnActionExecuted(filterContext);
        }
    }
}

Use camelCase for new widgets

Use camelCase for new widgets


using System;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Auth0.Tests.Shared;

namespace Auth0.ManagementApi.IntegrationTests
{
    public class StatsTests : TestBase
    {
        [Fact(Skip = "Inactivity causes these to fail")]
        public async Task Test_stats_sequence()
        {
            string token = await GenerateManagementApiToken();

            using (var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL")))
            {
                // Get stats for the past 10 days
                var dailyStats = await apiClient.Stats.GetDailyStatsAsync(DateTime.Now.AddDays(-100), DateTime.Now);
                dailyStats.Should().NotBeNull();
                dailyStats.Count.Should().BeGreaterOrEqualTo(1);

                // Get the active users
                var activeUsers = await apiClient.Stats.GetActiveUsersAsync();
                activeUsers.Should().BeGreaterOrEqualTo(1); // These integration tests themselves trigger non-zero values
            }
        }
    }
}

using System;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Auth0.Tests.Shared;
using System.Linq;

namespace Auth0.ManagementApi.IntegrationTests
{
    public class StatsTests : TestBase
    {
        [Fact]
        public async Task Daily_Stats_Returns_Values()
        {
            string token = await GenerateManagementApiToken();

            using (var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL")))
            {
                var dailyStats = await apiClient.Stats.GetDailyStatsAsync(DateTime.Now.AddDays(-100), DateTime.Now);
                dailyStats.Should().NotBeNull();
                dailyStats.Count.Should().BeGreaterOrEqualTo(1);
                dailyStats.Max(d => d.Logins).Should().BeGreaterThan(0);
            }
        }

        [Fact(Skip = "Inactivity causes these to fail")]
        public async Task Active_Users_Returns_Values()
        {
            string token = await GenerateManagementApiToken();

            using (var apiClient = new ManagementApiClient(token, GetVariable("AUTH0_MANAGEMENT_API_URL")))
            {
                var activeUsers = await apiClient.Stats.GetActiveUsersAsync();
                activeUsers.Should().BeGreaterThan(0);
            }
        }
    }
}

Break failing test into working & non-working parts


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

namespace Gibe.DittoProcessors.Processors
{
	public class ParentAttribute : TestableDittoProcessorAttribute
	{
		private readonly uint _parentDepth;

		public ParentAttribute(uint parentDepth = 1)
		{
			_parentDepth = parentDepth;
		}

		public override object ProcessValue()
		{
			var content = Context.Content;
			for (var i = 0; i < _parentDepth; i++)
			{
				content = content.Parent;
			}

			return content;
		}
	}
}

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

namespace Gibe.DittoProcessors.Processors
{
	public class ParentAttribute : TestableDittoProcessorAttribute
	{
		public override object ProcessValue()
		{
			return Context.Content.Parent;
		}
	}
}

Revert "Navigate up many parents"

Revert "Navigate up many parents"

This reverts commit f430cc765b43b22d56ce20dae47a331401f0dbd3.


using System.Collections.Generic;

namespace PublicApiGenerator
{
    partial class AttributeFilter
    {
        private static readonly HashSet<string> RequiredAttributeNames = new HashSet<string>
        {
            "System.Diagnostics.CodeAnalysis.AllowNullAttribute",
            "System.Diagnostics.CodeAnalysis.DisallowNullAttribute",
            "System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute",
            "System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute",
            "System.Diagnostics.CodeAnalysis.MaybeNullAttribute",
            "System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute",
            "System.Diagnostics.CodeAnalysis.NotNullAttribute",
            "System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute",
            "System.Diagnostics.CodeAnalysis.NotNullWhenAttribute"
        };
    }
}

using System.Collections.Generic;

namespace PublicApiGenerator
{
    partial class AttributeFilter
    {
        private static readonly HashSet<string> RequiredAttributeNames = new HashSet<string>
        {
            "System.Diagnostics.CodeAnalysis.AllowNullAttribute",
            "System.Diagnostics.CodeAnalysis.DisallowNullAttribute",
            "System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute",
            "System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute",
            "System.Diagnostics.CodeAnalysis.MaybeNullAttribute",
            "System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute",
            "System.Diagnostics.CodeAnalysis.NotNullAttribute",
            "System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute",
            "System.Diagnostics.CodeAnalysis.NotNullWhenAttribute",
            "System.SerializableAttribute",
            "System.Runtime.CompilerServices.CallerArgumentExpressionAttribute",
            "System.Runtime.CompilerServices.CallerFilePath",
            "System.Runtime.CompilerServices.CallerLineNumberAttribute",
            "System.Runtime.CompilerServices.CallerMemberName",
            "System.Runtime.CompilerServices.ReferenceAssemblyAttribute"
        };
    }
}

Add attributes that can't be easily tested due to being public in the current target framework


using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Noesis.Javascript.Tests
{
    [TestClass]
    public class JavascriptFunctionTests
    {
        private JavascriptContext _context;

        [TestInitialize]
        public void SetUp()
        {
            _context = new JavascriptContext();
        }

        [TestCleanup]
        public void TearDown()
        {
            _context.Dispose();
        }

        [TestMethod]
        public void GetFunctionFromJsContext()
        {
            _context.Run("a = function(a,b) {return a+b;}");

            JavascriptFunction funcObj = _context.GetParameter("a") as JavascriptFunction;
            funcObj.Should().NotBeNull();
            funcObj.Call(1, 2).Should().BeOfType<int>().Which.Should().Be(3);
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Noesis.Javascript.Tests
{
    [TestClass]
    public class JavascriptFunctionTests
    {
        private JavascriptContext _context;

        [TestInitialize]
        public void SetUp()
        {
            _context = new JavascriptContext();
        }

        [TestCleanup]
        public void TearDown()
        {
            _context.Dispose();
        }

        [TestMethod]
        public void GetFunctionExpressionFromJsContext()
        {
            _context.Run("a = function(a, b) { return a + b; }");

            JavascriptFunction funcObj = _context.GetParameter("a") as JavascriptFunction;
            funcObj.Should().NotBeNull();
            funcObj.Call(1, 2).Should().BeOfType<int>().Which.Should().Be(3);
        }

        [TestMethod]
        public void GetNamedFunctionFromJsContext()
        {
            _context.Run("function test(a, b) { return a + b; }");

            JavascriptFunction funcObj = _context.GetParameter("test") as JavascriptFunction;
            funcObj.Should().NotBeNull();
            funcObj.Call(1, 2).Should().BeOfType<int>().Which.Should().Be(3);
        }

        [TestMethod]
        public void GetArrowFunctionExpressionFromJsContext()
        {
            _context.Run("a = (a, b) => a + b");

            JavascriptFunction funcObj = _context.GetParameter("a") as JavascriptFunction;
            funcObj.Should().NotBeNull();
            funcObj.Call(1, 2).Should().BeOfType<int>().Which.Should().Be(3);
        }

        [TestMethod]
        public void PassFunctionToMethodInManagedObjectAndUseItToFilterAList()
        {
            _context.SetParameter("collection", new CollectionWrapper());

            var result = _context.Run("collection.Filter(x => x % 2 === 0)") as IEnumerable<int>;
            result.Should().NotBeNull();
            result.Should().BeEquivalentTo(2, 4);
        }
    }

    class CollectionWrapper
    {
        private IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        public IEnumerable<int> Filter(JavascriptFunction predicate)
        {
            return numbers.Where(x => (bool) predicate.Call(x));
        }
    }
}

Add more tests for function passing and managed object interop


// 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.Game.Online
{
    public class ProductionEndpointConfiguration : EndpointConfiguration
    {
        public ProductionEndpointConfiguration()
        {
            WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh";
            APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk";
            APIClientID = "5";
            SpectatorEndpointUrl = "https://spectator.ppy.sh/spectator";
            MultiplayerEndpointUrl = "https://spectator.ppy.sh/multiplayer";
        }
    }
}

// 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.Game.Online
{
    public class ProductionEndpointConfiguration : EndpointConfiguration
    {
        public ProductionEndpointConfiguration()
        {
            WebsiteRootUrl = APIEndpointUrl = @"https://osu.ppy.sh";
            APIClientSecret = @"FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk";
            APIClientID = "5";
            SpectatorEndpointUrl = "https://spectator2.ppy.sh/spectator";
            MultiplayerEndpointUrl = "https://spectator2.ppy.sh/multiplayer";
        }
    }
}

Update production endpoint to new version


#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

namespace FluentMigrator.VersionTableInfo
{
    public class DefaultVersionTableMetaData : IVersionTableMetaData
    {
        public string SchemaName
        {
            get { return string.Empty; }
        }

        public string TableName
        {
            get { return "VersionInfo"; }
        }

        public string ColumnName
        {
            get { return "Version"; }
        }

        public string UniqueIndexName
        {
            get { return "UC_Version"; }
        }
    }
}

#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

namespace FluentMigrator.VersionTableInfo
{
    public class DefaultVersionTableMetaData : IVersionTableMetaData
    {
        public virtual string SchemaName
        {
            get { return string.Empty; }
        }

        public virtual string TableName
        {
            get { return "VersionInfo"; }
        }

        public virtual string ColumnName
        {
            get { return "Version"; }
        }

        public virtual string UniqueIndexName
        {
            get { return "UC_Version"; }
        }
    }
}

Make default version table meta data virtual


namespace Cassette.Views
{
#if NET35
    public interface IHtmlString
    {
        string ToHtmlString();
    }

    public class HtmlString : IHtmlString
    {
        string _htmlString;

        public HtmlString(string htmlString)
        {
            this._htmlString = htmlString;
        }

        public string ToHtmlString()
        {
            return _htmlString;
        }

        public override string ToString()
        {
            return this._htmlString;
        }
    }
#endif
}

#if NET35
namespace Cassette.Views
{
    public interface IHtmlString
    {
        string ToHtmlString();
    }

    public class HtmlString : IHtmlString
    {
        string _htmlString;

        public HtmlString(string htmlString)
        {
            this._htmlString = htmlString;
        }

        public string ToHtmlString()
        {
            return _htmlString;
        }

        public override string ToString()
        {
            return this._htmlString;
        }
    }
}
#endif

Move conditional compilation around namespace.


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

namespace SO115App.API.Oracle.Controllers
{
    public class MezziController : ApiController
    {
        // GET: api/Mezzi
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Mezzi/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Mezzi
        public void Post([FromBody]string value)
        {
        }
    }
}

using SO115App.Persistence.Oracle.Classi;
using SO115App.Persistence.Oracle.Servizi.Mezzi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SO115App.API.Oracle.Controllers
{
    public class MezziController : ApiController
    {
        [HttpGet]
        public List<ORAAutomezzi> GetListaMezziUtilizzabili(string CodSede)
        {
            GetListaMezziUtilizzabili listamezzi = new GetListaMezziUtilizzabili();
            return listamezzi.GetListaAutomezziUtilizzabili(CodSede);
        }

        // POST: api/Mezzi
        public void Post([FromBody]string value)
        {
        }
    }
}

ADD - Aggiunto controller per il reperimento dei mezzi utilizzabili


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using ExtraLinq;
using FluentAssertions;
using NUnit.Framework;

namespace ExtraLINQ.Tests
{
    [TestFixture]
    public class ToDictionaryTests
    {
        [ExpectedException(typeof(ArgumentNullException))]
        [Test]
        public void ThrowsArgumentNullExceptionWhenCollectionIsNull()
        {
            NameValueCollection collection = null;
            Dictionary<string, string> dictionary = collection.ToDictionary();
        }

        [Test]
        public void ReturnedDictionaryContainsExactlyTheElementsFromTheNameValueCollection()
        {
            var collection = new NameValueCollection
            {
                { "a", "1" },
                { "b", "2" },
                { "c", "3" }
            };

            Dictionary<string, string> dictionary = collection.ToDictionary();

            dictionary.Should().Equal(new Dictionary<string, string>
            {
                { "a", "1" },
                { "b", "2" },
                { "c", "3" }
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using ExtraLinq;
using FluentAssertions;
using NUnit.Framework;

namespace ExtraLINQ.Tests
{
    [TestFixture]
    public class ToDictionaryTests
    {
        [ExpectedException(typeof(ArgumentNullException))]
        [Test]
        public void ThrowsArgumentNullExceptionWhenCollectionIsNull()
        {
            NameValueCollection collection = null;
            Dictionary<string, string> dictionary = collection.ToDictionary();
        }

        [Test]
        public void ReturnedDictionaryContainsExactlyTheElementsFromTheNameValueCollection()
        {
            var collection = new NameValueCollection
            {
                { "a", "1" },
                { "b", "2" },
                { "c", "3" }
            };

            Dictionary<string, string> dictionary = collection.ToDictionary();

            dictionary.Should().Equal(new Dictionary<string, string>
            {
                { "a", "1" },
                { "b", "2" },
                { "c", "3" }
            });
        }

        [Test]
        public void ReturnsAnEmptyDictionaryForAnEmptyNameValueCollection()
        {
            var emptyCollection = new NameValueCollection();

            Dictionary<string, string> dictionary = emptyCollection.ToDictionary();

            dictionary.Should().HaveCount(0);
        }
    }
}

Test for converting an empty NameValueCollection


using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.ComponentModelHost;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;

namespace GitHub.InlineReviews
{
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [Guid(Guids.PullRequestStatusPackageId)]
    [ProvideAutoLoad(UIContextGuids80.SolutionExists)]
    public class PullRequestStatusPackage : Package
    {
        protected override void Initialize()
        {
            var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
            var exportProvider = componentModel.DefaultExportProvider;
            var pullRequestStatusManager = exportProvider.GetExportedValue<IPullRequestStatusManager>();
            pullRequestStatusManager.Initialize();
        }
    }
}

using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.ComponentModelHost;
using GitHub.VisualStudio;
using GitHub.InlineReviews.Services;

namespace GitHub.InlineReviews
{
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [Guid(Guids.PullRequestStatusPackageId)]
    [ProvideAutoLoad(Guids.GitSccProviderId)]
    public class PullRequestStatusPackage : Package
    {
        protected override void Initialize()
        {
            var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
            var exportProvider = componentModel.DefaultExportProvider;
            var pullRequestStatusManager = exportProvider.GetExportedValue<IPullRequestStatusManager>();
            pullRequestStatusManager.Initialize();
        }
    }
}

Make PR status visible when GitSccProvider is loaded


// 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.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;

namespace osu.Game.Rulesets.Mania.Configuration
{
    public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
    {
        public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
            : base(settings, ruleset, variant)
        {
        }

        protected override void InitialiseDefaults()
        {
            base.InitialiseDefaults();

            Set(ManiaRulesetSetting.ScrollTime, 2250.0, 50.0, 10000.0, 50.0);
            Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
        }

        public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
        {
            new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
        };
    }

    public enum ManiaRulesetSetting
    {
        ScrollTime,
        ScrollDirection
    }
}

// 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.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;

namespace osu.Game.Rulesets.Mania.Configuration
{
    public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
    {
        public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
            : base(settings, ruleset, variant)
        {
        }

        protected override void InitialiseDefaults()
        {
            base.InitialiseDefaults();

            Set(ManiaRulesetSetting.ScrollTime, 1500.0, 50.0, 5000.0, 50.0);
            Set(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
        }

        public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
        {
            new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, v => new SettingDescription(v, "Scroll Time", $"{v}ms"))
        };
    }

    public enum ManiaRulesetSetting
    {
        ScrollTime,
        ScrollDirection
    }
}

Adjust osu!mania scroll speed defaults to be more sane


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

public class SuikaShakeSparkleSpawner : MonoBehaviour
{
    [SerializeField]
    private float spanwStartTime = .05f;
    [SerializeField]
    private float spawnFrequency = .25f;
    [SerializeField]
    private GameObject sparklePrefab;
    [SerializeField]
    private SuikaShakeSpriteFinder spriteCollection;
    [SerializeField]
    private BoxCollider2D spawnCollider;

	void Update ()
    {

        InvokeRepeating("createSparkle", spanwStartTime, spawnFrequency);
        enabled = false;
    }

    void createSparkle()
    {
        var newSparkle = Instantiate(sparklePrefab, transform);

        newSparkle.transform.localScale = new Vector3(Random.Range(0, 2) == 0 ? -1f : 1f, 1f, 1f);
        newSparkle.transform.eulerAngles = Vector3.forward * Random.Range(0f, 360f);

        var chosenSprite = spriteCollection.sprites[Random.Range(0, spriteCollection.sprites.Length)];
        var spriteRenderers = newSparkle.GetComponentsInChildren<SpriteRenderer>();
        foreach (var sparkleRenderer in spriteRenderers)
        {
            sparkleRenderer.sprite = chosenSprite;
        }

        float xOffset = spawnCollider.bounds.extents.x;
        float yOffset = spawnCollider.bounds.extents.y;
        print(newSparkle.transform.position);
        newSparkle.transform.position += (Vector3)spawnCollider.offset + new Vector3(Random.Range(-xOffset, xOffset), Random.Range(-yOffset, yOffset), 0f);
    }
}

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

public class SuikaShakeSparkleSpawner : MonoBehaviour
{
    [SerializeField]
    private float spanwStartTime = .05f;
    [SerializeField]
    private float spawnFrequency = .25f;
    [SerializeField]
    private GameObject sparklePrefab;
    [SerializeField]
    private SuikaShakeSpriteFinder spriteCollection;
    [SerializeField]
    private BoxCollider2D spawnCollider;

	void Update ()
    {

        InvokeRepeating("createSparkle", spanwStartTime, spawnFrequency);
        enabled = false;
    }

    void createSparkle()
    {
        var newSparkle = Instantiate(sparklePrefab, transform);

        newSparkle.transform.localScale = new Vector3(Random.Range(0, 2) == 0 ? -1f : 1f, 1f, 1f);
        newSparkle.transform.eulerAngles = Vector3.forward * Random.Range(0f, 360f);

        var chosenSprite = spriteCollection.sprites[Random.Range(0, spriteCollection.sprites.Length)];
        var spriteRenderers = newSparkle.GetComponentsInChildren<SpriteRenderer>();
        foreach (var sparkleRenderer in spriteRenderers)
        {
            sparkleRenderer.sprite = chosenSprite;
        }

        float xOffset = spawnCollider.bounds.extents.x;
        float yOffset = spawnCollider.bounds.extents.y;
        newSparkle.transform.position += (Vector3)spawnCollider.offset + new Vector3(Random.Range(-xOffset, xOffset), Random.Range(-yOffset, yOffset), 0f);
    }
}

Remove star creation debug printing

Remove star creation debug printing


using System;
using Kayak;
using Kayak.Framework;

namespace csharp_github_api.IntegrationTests
{
    public abstract class IntegrationTestBase : IDisposable
    {
        protected readonly KayakServer WebServer = new KayakServer();
        protected string BaseUrl = "http://localhost:8080";

        protected IntegrationTestBase()
        {
            WebServer.UseFramework();
            WebServer.Start();
        }

        public void Dispose()
        {
            WebServer.Stop();
        }
    }
}

using System;
using System.Linq;
using System.Text;
using Kayak;
using Kayak.Framework;

namespace csharp_github_api.IntegrationTests
{
    public abstract class IntegrationTestBase : IDisposable
    {
        protected readonly KayakServer WebServer = new KayakServer();
        protected string BaseUrl = "http://localhost:8080";
        protected int RequestCount;

        protected IntegrationTestBase()
        {
            var framework = WebServer.UseFramework();
            framework.Invoking += framework_Invoking;
            WebServer.Start();

        }

        void framework_Invoking(object sender, InvokingEventArgs e)
        {
            RequestCount++;

            var header = e.Invocation.Context.Request.Headers["Authorization"];

            if (!string.IsNullOrEmpty(header))
            {
                var parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))).Split(':');

                if (parts.Count() == 2)
                {
                    // Purely an aid to unit testing.
                    e.Invocation.Context.Response.Headers.Add("Authenticated", "true");

                    // We don't want to write anything here because it will interfere with our json response from the Services
                    //e.Invocation.Context.Response.Write(string.Join("|", parts));
                }
            }
        }

        public void Dispose()
        {
            WebServer.Stop();
        }
    }
}

Handle Kayak framwork's Invoking event - here we can catch the total number of requests made, as well as do some basic authentication.