using JetBrains.Annotations;
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.Psi.Tree;

namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.Dispatcher
{
    public abstract class UnityElementProblemAnalyzer<T> : ElementProblemAnalyzer<T>
        where T : ITreeNode
    {
        protected UnityElementProblemAnalyzer([NotNull] UnityApi unityApi)
        {
            Api = unityApi;
        }

        protected UnityApi Api { get; }

        protected sealed override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            // TODO: Check other process kinds. Should we run for everything?
            // OTHER is used by scoped quick fixes
            var processKind = data.GetDaemonProcessKind();
            if (processKind != DaemonProcessKind.VISIBLE_DOCUMENT
                && processKind != DaemonProcessKind.SOLUTION_ANALYSIS
                && processKind != DaemonProcessKind.OTHER)
            {
                return;
            }

            if (!element.GetProject().IsUnityProject())
                return;

            Analyze(element, data, consumer);
        }

        protected abstract void Analyze(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer);
    }
}

using JetBrains.Annotations;
using JetBrains.ReSharper.Daemon.Stages.Dispatcher;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.Psi.Tree;

namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.Dispatcher
{
    public abstract class UnityElementProblemAnalyzer<T> : ElementProblemAnalyzer<T>
        where T : ITreeNode
    {
        protected UnityElementProblemAnalyzer([NotNull] UnityApi unityApi)
        {
            Api = unityApi;
        }

        protected UnityApi Api { get; }

        protected sealed override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            // Run for all daemon kinds except global analysis. Visible document and solution wide analysis are obvious
            // and required. "Other" is used by scoped quick fixes, and incremental solution analysis is only for stages
            // that respond to settings changes. We don't strictly need this, but it won't cause problems.
            var processKind = data.GetDaemonProcessKind();
            if (processKind == DaemonProcessKind.GLOBAL_WARNINGS)
                return;

            if (!element.GetProject().IsUnityProject())
                return;

            Analyze(element, data, consumer);
        }

        protected abstract void Analyze(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer);
    }
}

Support all daemon kinds except global analysis


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

using System.Collections.Generic;

namespace Microsoft.Azure.WebJobs.Script.WebHost.Models
{
    public class MSIContext
    {
        public string MSISecret { get; set; }

        public IEnumerable<ManagedServiceIdentity> Identities { get; set; }
    }
}

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

using System.Collections.Generic;

namespace Microsoft.Azure.WebJobs.Script.WebHost.Models
{
    public class MSIContext
    {
        public string SiteName { get; set; }

        public string MSISecret { get; set; }

        public IEnumerable<ManagedServiceIdentity> Identities { get; set; }
    }
}

Add sitename to MSI specialization payload.

Will be used by token service sidecar


namespace AppHarbor.Tests
{
	public class CommandDispatcherTest
	{
		public class FooCommand : ICommand
		{
			public virtual void Execute(string[] arguments)
			{
			}
		}
	}
}

using System.Linq;
using Castle.MicroKernel;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;

namespace AppHarbor.Tests
{
	public class CommandDispatcherTest
	{
		public class FooCommand : ICommand
		{
			public virtual void Execute(string[] arguments)
			{
			}
		}

		[Theory]
		[InlineAutoCommandData("foo", "foo", null)]
		[InlineAutoCommandData("foo:bar", "foo", "bar")]
		public void ShouldDispatchCommandWithASingleParameter(
			string argument,
			string commandName,
			string scope,
			[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
			[Frozen]Mock<IKernel> kernel,
			Mock<FooCommand> command,
			CommandDispatcher commandDispatcher)
		{
			var commandType = typeof(FooCommand);
			typeNameMatcher.Setup(x => x.GetMatchedType(commandName, scope)).Returns(commandType);

			kernel.Setup(x => x.Resolve(commandType)).Returns(command.Object);

			var dispatchArguments = new string[] { argument };
			commandDispatcher.Dispatch(dispatchArguments);

			command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any())));
		}
	}
}

Verify that executing single argument command works as expected


using System.Reflection;

[assembly: AssemblyTitle("Autofac.Extras.Tests.Multitenant")]
[assembly: AssemblyDescription("Tests for the Autofac multitenancy feature.")]

Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.


using UnityEngine;
using System.Collections;

public class mainMenuHandler : MonoBehaviour {

//	private Texture2D startButton;

	void OnGUI () {

		GUI.backgroundColor = Color.clear;

		if (GUI.Button (new Rect (260,300, 300, 300), "")) {
//			print ("Start Game");
			//start game
			Application.LoadLevel(2);

		}

		if (GUI.Button (new Rect (860, 300, 300, 300), "")) {
			print ("Level Selection");
			Application.LoadLevel(1);
		}
	}

}

using UnityEngine;
using System.Collections;

public class mainMenuHandler : MonoBehaviour {

	public Texture2D startButton;

	void OnGUI () {

		GUI.backgroundColor = Color.clear;

		if (GUI.Button (new Rect (Screen.width/20*3,Screen.height/10*4, 250, 250), startButton)) {
//			print ("Start Game");
			//start game
			Application.LoadLevel(2);

		}

		if (GUI.Button (new Rect (Screen.width/10*5, Screen.height/10*4, 250, 250), startButton)) {
			print ("Level Selection");
			Application.LoadLevel(1);
		}
	}

}

Fix pos of main menu buttons

Fix pos of main menu buttons


namespace EntityFramework.Filters
{
    using System.Data.Entity.Core.Common.CommandTrees;
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Infrastructure.Interception;
    using System.Linq;

    public class FilterInterceptor : IDbCommandTreeInterceptor
    {
        public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
        {
            if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
            {
                var queryCommand = interceptionContext.Result as DbQueryCommandTree;
                if (queryCommand != null)
                {
                    var newQuery =
                        queryCommand.Query.Accept(new FilterQueryVisitor(interceptionContext.DbContexts.First()));
                    interceptionContext.Result = new DbQueryCommandTree(
                        queryCommand.MetadataWorkspace, queryCommand.DataSpace, newQuery);
                }
            }
        }
    }
}

namespace EntityFramework.Filters
{
    using System.Data.Entity.Core.Common.CommandTrees;
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Infrastructure.Interception;
    using System.Linq;

    public class FilterInterceptor : IDbCommandTreeInterceptor
    {
        public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
        {
            if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
            {
                var queryCommand = interceptionContext.Result as DbQueryCommandTree;
                if (queryCommand != null)
                {
                    var context = interceptionContext.DbContexts.FirstOrDefault();
                    if (context != null)
                    {
                        var newQuery =
                            queryCommand.Query.Accept(new FilterQueryVisitor(context));
                        interceptionContext.Result = new DbQueryCommandTree(
                            queryCommand.MetadataWorkspace, queryCommand.DataSpace, newQuery);
                    }
                }
            }
        }
    }
}

Add DbContext null check to FieldInterceptor.cs

In some cases (outlined under "caveat" here, http://entityframework.codeplex.com/wikipage?title=Interception) EntityFramework interceptors may not have any DbContexts associated with them.  The current code will cause a null reference exception.  This can be replicated by using a profiling tool such as Glimpse.EF6 to a project using EntityFramework.Filters.  This PR adds a null check for context before continuing with filter execution.


using Glimpse.Core.Extensibility;

namespace Glimpse.Core.Resource
{
    /// <summary>
    /// The <see cref="IResource"/> implementation responsible for providing the Glimpse JavaScript client to the browser.
    /// </summary>
    public class InsightResource : FileResource, IKey
    {
        internal const string InternalName = "glimpse_insight";

        private EmbeddedResourceInfo ResourceInfo { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ClientResource" /> class.
        /// </summary>
        public InsightResource()
        {
            Name = InternalName;

            ResourceInfo = new EmbeddedResourceInfo(GetType().Assembly, "Glimpse.Core.glimpsePre.js", "application/x-javascript");
        }

        /// <summary>
        /// Gets the key.
        /// </summary>
        /// <value>
        /// The key. Only valid JavaScript identifiers should be used for future compatibility.
        /// </value>
        public string Key
        {
            get { return Name; }
        }

        /// <summary>
        /// Returns the embedded resource that represents the Glimpse Client which will be returned during the execution of the <see cref="FileResource"/>
        /// </summary>
        /// <param name="context">The resource context</param>
        /// <returns>Information about the embedded Glimpse Client</returns>
        protected override EmbeddedResourceInfo GetEmbeddedResourceInfo(IResourceContext context)
        {
            return ResourceInfo;
        }
    }
}

using Glimpse.Core.Extensibility;

namespace Glimpse.Core.Resource
{
    /// <summary>
    /// The <see cref="IResource"/> implementation responsible for providing the Glimpse JavaScript client to the browser.
    /// </summary>
    public class InsightResource : FileResource, IKey
    {
        internal const string InternalName = "glimpse_insight";

        private EmbeddedResourceInfo ResourceInfo { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ClientResource" /> class.
        /// </summary>
        public InsightResource()
        {
            Name = InternalName;

            ResourceInfo = new EmbeddedResourceInfo(GetType().Assembly, "Glimpse.Core.glimpseInsight.js", "application/x-javascript");
        }

        /// <summary>
        /// Gets the key.
        /// </summary>
        /// <value>
        /// The key. Only valid JavaScript identifiers should be used for future compatibility.
        /// </value>
        public string Key
        {
            get { return Name; }
        }

        /// <summary>
        /// Returns the embedded resource that represents the Glimpse Client which will be returned during the execution of the <see cref="FileResource"/>
        /// </summary>
        /// <param name="context">The resource context</param>
        /// <returns>Information about the embedded Glimpse Client</returns>
        protected override EmbeddedResourceInfo GetEmbeddedResourceInfo(IResourceContext context)
        {
            return ResourceInfo;
        }
    }
}

Add file that was missed in rename

Add file that was missed in rename


using System;
using System.Collections.Generic;

namespace TweetDck.Plugins{
    [Flags]
    enum PluginEnvironment{
        None = 0,
        Browser = 1,
        Notification = 2
    }

    static class PluginEnvironmentExtensions{
        public static IEnumerable<PluginEnvironment> Values{
            get{
                yield return PluginEnvironment.Browser;
                yield return PluginEnvironment.Notification;
            }
        }

        public static string GetScriptFile(this PluginEnvironment environment){
            switch(environment){
                case PluginEnvironment.Browser: return "browser.js";
                case PluginEnvironment.Notification: return "notification.js";
                default: return null;
            }
        }

        public static string GetScriptVariables(this PluginEnvironment environment){
            switch(environment){
                case PluginEnvironment.Browser: return "$,$TD,TD";
                case PluginEnvironment.Notification: return "$TD";
                default: return string.Empty;
            }
        }
    }
}

using System;
using System.Collections.Generic;

namespace TweetDck.Plugins{
    [Flags]
    enum PluginEnvironment{
        None = 0,
        Browser = 1,
        Notification = 2
    }

    static class PluginEnvironmentExtensions{
        public static IEnumerable<PluginEnvironment> Values{
            get{
                yield return PluginEnvironment.Browser;
                yield return PluginEnvironment.Notification;
            }
        }

        public static string GetScriptFile(this PluginEnvironment environment){
            switch(environment){
                case PluginEnvironment.Browser: return "browser.js";
                case PluginEnvironment.Notification: return "notification.js";
                default: return null;
            }
        }

        public static string GetScriptVariables(this PluginEnvironment environment){
            switch(environment){
                case PluginEnvironment.Browser: return "$,$TD,$TDP,TD";
                case PluginEnvironment.Notification: return "$TD,$TDP";
                default: return string.Empty;
            }
        }
    }
}

Add plugin bridge object to script variable list


using System;
using Abp.Collections.Extensions;
using AutoMapper;

namespace Abp.AutoMapper
{
    public class AutoMapFromAttribute : AutoMapAttributeBase
    {
        public MemberList MemberList { get; set; } = MemberList.Destination;

        public AutoMapFromAttribute(params Type[] targetTypes)
            : base(targetTypes)
        {

        }

        public AutoMapFromAttribute(MemberList memberList, params Type[] targetTypes)
            : this(targetTypes)
        {
            MemberList = memberList;
        }

        public override void CreateMap(IMapperConfigurationExpression configuration, Type type)
        {
            if (TargetTypes.IsNullOrEmpty())
            {
                return;
            }

            foreach (var targetType in TargetTypes)
            {
                configuration.CreateMap(targetType, type, MemberList.Destination);
            }
        }
    }
}

using System;
using Abp.Collections.Extensions;
using AutoMapper;

namespace Abp.AutoMapper
{
    public class AutoMapFromAttribute : AutoMapAttributeBase
    {
        public MemberList MemberList { get; set; } = MemberList.Destination;

        public AutoMapFromAttribute(params Type[] targetTypes)
            : base(targetTypes)
        {

        }

        public AutoMapFromAttribute(MemberList memberList, params Type[] targetTypes)
            : this(targetTypes)
        {
            MemberList = memberList;
        }

        public override void CreateMap(IMapperConfigurationExpression configuration, Type type)
        {
            if (TargetTypes.IsNullOrEmpty())
            {
                return;
            }

            foreach (var targetType in TargetTypes)
            {
                configuration.CreateMap(targetType, type, MemberList);
            }
        }
    }
}

Fix create map not using MemberList property


using UnityEngine;

public abstract class Curve : ICurve {
	protected abstract Vector3 GetPositionImpl(float u);

	protected abstract float LengthImpl { get; }

	public static readonly Vector3 DefaultUpVector = Vector3.up;

	protected bool Invalid { get; private set; }

	public float Length { get; private set; }

	protected void Invalidate() {
		Invalid = true;
	}

	protected void Validate() {
		if (Invalid) {
			Update();
			Invalid = false;
		}
	}

	protected virtual void Update() {
		Length = LengthImpl;
	}

	public Vector3 GetPosition(float u) {
		Validate();
		return GetPositionImpl(u);
	}

	public Vector3 GetForward(float u) {
		u = Mathf.Clamp01(u);
		const float epsilon = 0.01f;
		Validate();
		return (GetPosition(Mathf.Clamp01(u + epsilon)) -
			GetPosition(Mathf.Clamp01(u - epsilon))).normalized;
	}

	public Vector3 GetNormal(float u, Vector3 up) {
		return Vector3.Cross(GetForward(u), up);
	}

	public Vector3 GetNormal(float u) {
		return GetNormal(u, DefaultUpVector);
	}
}

using UnityEngine;

public abstract class Curve : ICurve {
	protected abstract Vector3 GetPositionImpl(float u);

	protected abstract float LengthImpl { get; }

	public static readonly Vector3 DefaultUpVector = Vector3.up;

	protected bool Invalid { get; private set; }

	private float _length;

	public float Length { get {
			Validate();
			return _length;
		}
	}

	protected void Invalidate() {
		Invalid = true;
	}

	protected void Validate() {
		if (Invalid) {
			Update();
			Invalid = false;
		}
	}

	protected virtual void Update() {
		_length = LengthImpl;
	}

	public Vector3 GetPosition(float u) {
		Validate();
		return GetPositionImpl(u);
	}

	public Vector3 GetForward(float u) {
		u = Mathf.Clamp01(u);
		const float epsilon = 0.01f;
		Validate();
		return (GetPosition(Mathf.Clamp01(u + epsilon)) -
			GetPosition(Mathf.Clamp01(u - epsilon))).normalized;
	}

	public Vector3 GetNormal(float u, Vector3 up) {
		return Vector3.Cross(GetForward(u), up);
	}

	public Vector3 GetNormal(float u) {
		return GetNormal(u, DefaultUpVector);
	}
}

Fix for using Length before GetPosition.


using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;

namespace SupportManager.Web.Areas.Teams
{
    [Area("Teams")]
    [Authorize]
    public abstract class BaseController : Controller
    {
        protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]);

        protected SupportTeam Team { get; private set; }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext));
            Team = await db.Teams.FindAsync(TeamId);

            ViewData["TeamName"] = Team.Name;

            await base.OnActionExecutionAsync(context, next);
        }
    }
}

using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;

namespace SupportManager.Web.Areas.Teams
{
    [Area("Teams")]
    [Authorize]
    public abstract class BaseController : Controller
    {
        protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]);

        protected SupportTeam Team { get; private set; }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext));
            Team = await db.Teams.FindAsync(TeamId);

            if (Team == null)
            {
                context.Result = NotFound();
                return;
            }

            ViewData["TeamName"] = Team.Name;

            await base.OnActionExecutionAsync(context, next);
        }
    }
}

Return NotFound on invalid team ID's

web: Return NotFound on invalid team ID's


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

using System.Collections.Immutable;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Newtonsoft.Json;

namespace Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets
{
    internal static partial class ProjectAssetsFileReader
    {
        /// <summary>
        /// Enhances references with the assemblies they bring into the compilation and their dependency hierarchy.
        /// </summary>
        public static async Task<ImmutableArray<ReferenceInfo>> ReadReferencesAsync(
            ImmutableArray<ReferenceInfo> projectReferences,
            string projectAssetsFilePath)
        {
            var doesProjectAssetsFileExist = IOUtilities.PerformIO(() => File.Exists(projectAssetsFilePath));
            if (!doesProjectAssetsFileExist)
            {
                return ImmutableArray<ReferenceInfo>.Empty;
            }

            var projectAssetsFileContents = await IOUtilities.PerformIOAsync(() =>
            {
                using var fileStream = File.OpenRead(projectAssetsFilePath);
                using var reader = new StreamReader(fileStream);
                return reader.ReadToEndAsync();
            }).ConfigureAwait(false);

            if (projectAssetsFileContents is null)
            {
                return ImmutableArray<ReferenceInfo>.Empty;
            }

            try
            {
                var projectAssets = JsonConvert.DeserializeObject<ProjectAssetsFile>(projectAssetsFileContents);
                return ProjectAssetsReader.AddDependencyHierarchies(projectReferences, projectAssets);
            }
            catch
            {
                return ImmutableArray<ReferenceInfo>.Empty;
            }
        }
    }
}

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

using System.Collections.Immutable;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Newtonsoft.Json;

namespace Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets
{
    internal static partial class ProjectAssetsFileReader
    {
        /// <summary>
        /// Enhances references with the assemblies they bring into the compilation and their dependency hierarchy.
        /// </summary>
        public static async Task<ImmutableArray<ReferenceInfo>> ReadReferencesAsync(
            ImmutableArray<ReferenceInfo> projectReferences,
            string projectAssetsFilePath)
        {
            var doesProjectAssetsFileExist = IOUtilities.PerformIO(() => File.Exists(projectAssetsFilePath));
            if (!doesProjectAssetsFileExist)
            {
                return ImmutableArray<ReferenceInfo>.Empty;
            }

            var projectAssetsFileContents = await IOUtilities.PerformIOAsync(async () =>
            {
                using var fileStream = File.OpenRead(projectAssetsFilePath);
                using var reader = new StreamReader(fileStream);
                return await reader.ReadToEndAsync().ConfigureAwait(false);
            }).ConfigureAwait(false);

            if (projectAssetsFileContents is null)
            {
                return ImmutableArray<ReferenceInfo>.Empty;
            }

            try
            {
                var projectAssets = JsonConvert.DeserializeObject<ProjectAssetsFile>(projectAssetsFileContents);
                return ProjectAssetsReader.AddDependencyHierarchies(projectReferences, projectAssets);
            }
            catch
            {
                return ImmutableArray<ReferenceInfo>.Empty;
            }
        }
    }
}

Read file before the reader is disposed

Read file before the reader is disposed


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - Quadruped WebInterface</title>
    <link rel="stylesheet" href="~/css/site.css" />
    <script src="~/js/site.min.js"></script>
</head>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - Quadruped WebInterface</title>
    <link rel="stylesheet" href="~/css/site.css" />
    @*<script src="~/js/site.min.js"></script>*@
</head>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>

Remove import for empty script file

Remove import for empty script file


using Microsoft.Extensions.Configuration;
using System;
using System.Linq;

namespace Tgstation.Server.Host.Core
{
	/// <inheritdoc />
	sealed class ServerPortProivder : IServerPortProvider
	{
		/// <inheritdoc />
		public ushort HttpApiPort { get; }

		/// <summary>
		/// Initializes a new instance of the <see cref="ServerPortProivder"/> <see langword="class"/>.
		/// </summary>
		/// <param name="configuration">The <see cref="IConfiguration"/> to use.</param>
		public ServerPortProivder(IConfiguration configuration)
		{
			if (configuration == null)
				throw new ArgumentNullException(nameof(configuration));

			var httpEndpoint = configuration
				.GetSection("Kestrel")
				.GetSection("EndPoints")
				.GetSection("Http")
				.GetSection("Url")
				.Value;

			if (httpEndpoint == null)
				throw new InvalidOperationException("Missing required configuration option for Kestrel:EndPoints:Http:Url!");

			var splits = httpEndpoint.Split(":", StringSplitOptions.RemoveEmptyEntries);
			var portString = splits.Last();
			portString = portString.TrimEnd('/');

			if (!UInt16.TryParse(portString, out var result))
				throw new InvalidOperationException($"Failed to parse HTTP EndPoint port: {httpEndpoint}");

			HttpApiPort = result;
		}
	}
}

using Microsoft.Extensions.Configuration;
using System;
using System.Linq;

namespace Tgstation.Server.Host.Core
{
	/// <inheritdoc />
	sealed class ServerPortProivder : IServerPortProvider
	{
		/// <inheritdoc />
		public ushort HttpApiPort { get; }

		/// <summary>
		/// Initializes a new instance of the <see cref="ServerPortProivder"/> <see langword="class"/>.
		/// </summary>
		/// <param name="configuration">The <see cref="IConfiguration"/> to use.</param>
		public ServerPortProivder(IConfiguration configuration)
		{
			if (configuration == null)
				throw new ArgumentNullException(nameof(configuration));

			var httpEndpoint = configuration
				.GetSection("Kestrel")
				.GetSection("EndPoints")
				.GetSection("Http")
				.GetSection("Url")
				.Value;

			if (httpEndpoint == null)
				throw new InvalidOperationException("Missing required configuration option Kestrel:EndPoints:Http:Url!");

			var splits = httpEndpoint.Split(":", StringSplitOptions.RemoveEmptyEntries);
			var portString = splits.Last();
			portString = portString.TrimEnd('/');

			if (!UInt16.TryParse(portString, out var result))
				throw new InvalidOperationException($"Failed to parse HTTP EndPoint port: {httpEndpoint}");

			HttpApiPort = result;
		}
	}
}

Improve wording of an exception

Improve wording of an exception


using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;
using System;
using System.Net;
using System.Threading.Tasks;

namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
    [ApiController]
    [Authorize]
    [Route("api/learners")]
    public class LearnerController : ControllerBase
    {
        private readonly IMediator _mediator;

        public LearnerController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpGet]
        public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
        {
            var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));

            var settings = new JsonSerializerSettings
            {
                 DateFormatString = "yyyy-MM-dd'T'HH:mm:ss"
            };

            var jsonResult = new JsonResult(new GetAllLearnersResponse()
            {
                Learners = result.Learners,
                BatchNumber = result.BatchNumber,
                BatchSize = result.BatchSize,
                TotalNumberOfBatches = result.TotalNumberOfBatches
            }, settings);
            jsonResult.StatusCode = (int)HttpStatusCode.OK;
            jsonResult.ContentType = "application/json";

            return jsonResult;
        }
    }
}

using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;
using System;
using System.Net;
using System.Threading.Tasks;

namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
    [ApiController]
    [Authorize]
    [Route("api/learners")]
    public class LearnerController : ControllerBase
    {
        private readonly IMediator _mediator;

        public LearnerController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpGet]
        public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
        {
            var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));

            var settings = new JsonSerializerSettings
            {
                 DateFormatString = "yyyy-MM-dd'T'HH:mm:ss",
                 ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            var jsonResult = new JsonResult(new GetAllLearnersResponse()
            {
                Learners = result.Learners,
                BatchNumber = result.BatchNumber,
                BatchSize = result.BatchSize,
                TotalNumberOfBatches = result.TotalNumberOfBatches
            }, settings);
            jsonResult.StatusCode = (int)HttpStatusCode.OK;
            jsonResult.ContentType = "application/json";

            return jsonResult;
        }
    }
}

Fix camel case on the Learners response

Fix camel case on the Learners response


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

using System;
using System.IO;
using System.Linq;
using osu.Framework;
using osu.Framework.Platform;
using osu.Game.IPC;

#if NET_FRAMEWORK
using System.Runtime;
#endif

namespace osu.Desktop
{
    public static class Program
    {
        [STAThread]
        public static int Main(string[] args)
        {
            useMultiCoreJit();

            // Back up the cwd before DesktopGameHost changes it
            var cwd = Environment.CurrentDirectory;

            using (DesktopGameHost host = Host.GetSuitableHost(@"osu", true))
            {
                if (!host.IsPrimaryInstance)
                {
                    var importer = new ArchiveImportIPCChannel(host);
                    // Restore the cwd so relative paths given at the command line work correctly
                    Directory.SetCurrentDirectory(cwd);
                    foreach (var file in args)
                    {
                        Console.WriteLine(@"Importing {0}", file);
                        if (!importer.ImportAsync(Path.GetFullPath(file)).Wait(3000))
                            throw new TimeoutException(@"IPC took too long to send");
                    }
                }
                else
                {
                    switch (args.FirstOrDefault() ?? string.Empty)
                    {
                        default:
                            host.Run(new OsuGameDesktop(args));
                            break;
                    }
                }

                return 0;
            }
        }

        private static void useMultiCoreJit()
        {
#if NET_FRAMEWORK
            var directory = Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles"));
            ProfileOptimization.SetProfileRoot(directory.FullName);
            ProfileOptimization.StartProfile("Startup.Profile");
#endif
        }
    }
}

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

using System;
using System.IO;
using System.Linq;
using osu.Framework;
using osu.Framework.Platform;
using osu.Game.IPC;

namespace osu.Desktop
{
    public static class Program
    {
        [STAThread]
        public static int Main(string[] args)
        {
            // Back up the cwd before DesktopGameHost changes it
            var cwd = Environment.CurrentDirectory;

            using (DesktopGameHost host = Host.GetSuitableHost(@"osu", true))
            {
                if (!host.IsPrimaryInstance)
                {
                    var importer = new ArchiveImportIPCChannel(host);
                    // Restore the cwd so relative paths given at the command line work correctly
                    Directory.SetCurrentDirectory(cwd);
                    foreach (var file in args)
                    {
                        Console.WriteLine(@"Importing {0}", file);
                        if (!importer.ImportAsync(Path.GetFullPath(file)).Wait(3000))
                            throw new TimeoutException(@"IPC took too long to send");
                    }
                }
                else
                {
                    switch (args.FirstOrDefault() ?? string.Empty)
                    {
                        default:
                            host.Run(new OsuGameDesktop(args));
                            break;
                    }
                }

                return 0;
            }
        }
    }
}

Remove only remaining .NET desktop code

Remove only remaining .NET desktop code


using System;
using System.IO;
using System.Net;
using NUnit.Framework;

namespace HttpMock.Integration.Tests
{
	[TestFixture]
	public class EndpointsReturningFilesTests
	{
		private const string FILE_NAME = "transcode-input.mp3";
		private const string RES_TRANSCODE_INPUT_MP3 = "./res/"+FILE_NAME;

		[Test]
		public void A_Setting_return_file_return_the_correct_content_length() {
			var stubHttp = HttpMockRepository.At("http://localhost.:9191");
			stubHttp.Stub(x => x.Get("/afile"))
				.ReturnFile(RES_TRANSCODE_INPUT_MP3)
				.OK();

			Console.WriteLine(stubHttp.WhatDoIHave());

			var fileLength = new FileInfo(RES_TRANSCODE_INPUT_MP3).Length;

			var webRequest = (HttpWebRequest) WebRequest.Create("http://localhost.:9191/afile");
			using (var response = webRequest.GetResponse())
			using(var responseStream = response.GetResponseStream())
			{

				var bytes = new byte[response.ContentLength];
				responseStream.Read(bytes, 0, (int) response.ContentLength);

				Assert.That(response.ContentLength, Is.EqualTo(fileLength));
			}
		}

	}
}

using System;
using System.IO;
using System.Net;
using NUnit.Framework;

namespace HttpMock.Integration.Tests
{
	[TestFixture]
	public class EndpointsReturningFilesTests
	{
		private const string FILE_NAME = "transcode-input.mp3";
		private const string RES_TRANSCODE_INPUT_MP3 = "res\\"+FILE_NAME;

		[Test]
		public void A_Setting_return_file_return_the_correct_content_length() {
			var stubHttp = HttpMockRepository.At("http://localhost.:9191");

		    var pathToFile = Path.Combine(TestContext.CurrentContext.TestDirectory, RES_TRANSCODE_INPUT_MP3);

		    stubHttp.Stub(x => x.Get("/afile"))
				.ReturnFile(pathToFile)
				.OK();

			Console.WriteLine(stubHttp.WhatDoIHave());

			var fileLength = new FileInfo(pathToFile).Length;

			var webRequest = (HttpWebRequest) WebRequest.Create("http://localhost.:9191/afile");
			using (var response = webRequest.GetResponse())
			using(var responseStream = response.GetResponseStream())
			{

				var bytes = new byte[response.ContentLength];
				responseStream.Read(bytes, 0, (int) response.ContentLength);

				Assert.That(response.ContentLength, Is.EqualTo(fileLength));
			}
		}

	}
}

Fix path, because NUnit does nto run from the current assembly dir


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace BeerCellier
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace BeerCellier
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
    }
}

Fix authentication crash on edit

Fix authentication crash on edit


using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using Obvs.Types;
using Obvs.ActiveMQ.Configuration;
using Obvs.Configuration;
using Obvs.Example.Messages;
using Obvs.Serialization.Json.Configuration;

namespace Obvs.Example.Client
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            var brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
            var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Obvs.Service1";

            Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}");

            var serviceBus = ServiceBus.Configure()
                .WithActiveMQEndpoints<IServiceMessage1>()
                    .Named(serviceName)
                    .UsingQueueFor<ICommand>()
                    .ConnectToBroker(brokerUri)
                    .WithCredentials("admin", "admin")
                    .SerializedAsJson()
                    .AsClient()
                .CreateClient();

            serviceBus.Events.Subscribe(ev => Console.WriteLine("Received event: " + ev));

            Console.WriteLine("Type some text and hit <Enter> to send as command.");
            while (true)
            {
                string data = Console.ReadLine();
                serviceBus.SendAsync(new Command1 { Data = data });
            }
        }
    }
}

using System;
using Obvs.Types;
using Obvs.ActiveMQ.Configuration;
using Obvs.Configuration;
using Obvs.Example.Messages;
using Obvs.Serialization.Json.Configuration;

namespace Obvs.Example.Client
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            var brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
            var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Obvs.Service1";

            Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}");

            var serviceBus = ServiceBus.Configure()
                .WithActiveMQEndpoints<IServiceMessage1>()
                    .Named(serviceName)
                    .UsingQueueFor<ICommand>()
                    .ConnectToBroker(brokerUri)
                    .WithCredentials("admin", "admin")
                    .SerializedAsJson()
                    .AsClient()
                .CreateClient();

            serviceBus.Events.Subscribe(ev => Console.WriteLine("Received event: " + ev));

            Console.WriteLine("Type some text and hit <Enter> to send as command.");
            while (true)
            {
                string data = Console.ReadLine();
                serviceBus.SendAsync(new Command1 { Data = data });
            }
        }
    }
}

Remove unused references from example client


using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using IronAHK.Scripting;
using NUnit.Framework;

namespace Tests
{
    [TestFixture]
    public partial class Scripting
    {
        [Test]
        public void RunScripts()
        {
            string path = string.Format("..{0}..{0}Scripting{0}Code", Path.DirectorySeparatorChar.ToString());

            foreach (string file in Directory.GetFiles(path, "*.ia"))
            {
                string name = Path.GetFileNameWithoutExtension(file);
                var provider = new IACodeProvider();

                var options = new CompilerParameters();
                options.GenerateExecutable = true;
                options.GenerateInMemory = false;
                options.ReferencedAssemblies.Add(typeof(IronAHK.Rusty.Core).Namespace + ".dll");
                options.OutputAssembly = Path.GetTempFileName() + ".exe";

                provider.CompileAssemblyFromFile(options, file);

                bool exists = File.Exists(options.OutputAssembly);
                Assert.IsTrue(exists, name + " assembly");

                if (exists)
                {
                    AppDomain domain = AppDomain.CreateDomain(name);

                    var buffer = new StringBuilder();
                    var writer = new StringWriter(buffer);
                    Console.SetOut(writer);

                    domain.ExecuteAssembly(options.OutputAssembly);
                    AppDomain.Unload(domain);

                    string output = buffer.ToString();
                    Assert.AreEqual("pass", output, name);

                    var standardOutput = new StreamWriter(Console.OpenStandardOutput());
                    standardOutput.AutoFlush = true;
                    Console.SetOut(standardOutput);
                }
            }
        }
    }
}

using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using IronAHK.Scripting;
using NUnit.Framework;

namespace Tests
{
    [TestFixture]
    public partial class Scripting
    {
        [Test]
        public void RunScripts()
        {
            string path = string.Format("..{0}..{0}Scripting{0}Code", Path.DirectorySeparatorChar.ToString());

            foreach (string file in Directory.GetFiles(path, "*.ia"))
            {
                string name = Path.GetFileNameWithoutExtension(file);
                var provider = new IACodeProvider();

                var options = new CompilerParameters();
                options.GenerateExecutable = true;
                options.GenerateInMemory = false;
                options.ReferencedAssemblies.Add(typeof(IronAHK.Rusty.Core).Namespace + ".dll");
                options.OutputAssembly = Path.GetTempFileName() + ".exe";

                provider.CompileAssemblyFromFile(options, file);

                bool exists = File.Exists(options.OutputAssembly);
                Assert.IsTrue(exists, name + " assembly");

                if (exists)
                {
                    var buffer = new StringBuilder();
                    var writer = new StringWriter(buffer);
                    Console.SetOut(writer);

                    AppDomain.CurrentDomain.ExecuteAssembly(options.OutputAssembly);

                    try { File.Delete(options.OutputAssembly); }
                    catch (UnauthorizedAccessException) { }

                    writer.Flush();
                    string output = buffer.ToString();
                    Assert.AreEqual("pass", output, name);

                    var stdout = new StreamWriter(Console.OpenStandardOutput());
                    stdout.AutoFlush = true;
                    Console.SetOut(stdout);
                }
            }
        }
    }
}

Set NUnit tests to run scripts under the current domain for access to the same console.


// Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Collections.Generic;

namespace NodaTime.Web.Models
{
    /// <summary>
    /// Fake implementation of IReleaseRepository used in cases of emergency...
    /// </summary>
    public class FakeReleaseRepository : IReleaseRepository
    {
        private static readonly IList<ReleaseDownload> releases = new[]
        {
            new ReleaseDownload(new StructuredVersion("2.4.3"), "NodaTime-2.4.4.zip",
                "https://storage.cloud.google.com/nodatime/releases/NodaTime-2.4.4.zip",
                "5a672e0910353eef53cd3b6a4ff08e1287ec6fe40faf96ca42e626b107c8f8d4",
                new LocalDate(2018, 12, 31))
        };

        public ReleaseDownload LatestRelease => releases[0];

        public IList<ReleaseDownload> GetReleases() => releases;
    }
}

// Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Collections.Generic;

namespace NodaTime.Web.Models
{
    /// <summary>
    /// Fake implementation of IReleaseRepository used in cases of emergency...
    /// </summary>
    public class FakeReleaseRepository : IReleaseRepository
    {
        private static readonly IList<ReleaseDownload> releases = new[]
        {
            new ReleaseDownload(new StructuredVersion("2.4.4"), "NodaTime-2.4.4.zip",
                "https://storage.cloud.google.com/nodatime/releases/NodaTime-2.4.4.zip",
                "5a672e0910353eef53cd3b6a4ff08e1287ec6fe40faf96ca42e626b107c8f8d4",
                new LocalDate(2018, 12, 31))
        };

        public ReleaseDownload LatestRelease => releases[0];

        public IList<ReleaseDownload> GetReleases() => releases;
    }
}

Fix version number for the fake release

Fix version number for the fake release


using System;
using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;

namespace CppSharp
{
    /// <summary>
    /// This class is used to build passes that will be run against the AST
    /// that comes from C++.
    /// </summary>
    public class PassBuilder<T>
    {
        public List<T> Passes { get; private set; }
        public Driver Driver { get; private set; }

        public PassBuilder(Driver driver)
        {
            Passes = new List<T>();
            Driver = driver;
        }

        /// <summary>
        /// Adds a new pass to the builder.
        /// </summary>
        public void AddPass(T pass)
        {
            Passes.Add(pass);
        }

        /// <summary>
        /// Finds a previously-added pass of the given type.
        /// </summary>
        public U FindPass<U>() where U : TranslationUnitPass
        {
            return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault();
        }

        /// <summary>
        /// Adds a new pass to the builder.
        /// </summary>
        public void RunPasses(Action<T> action)
        {
            foreach (var pass in Passes)
                action(pass);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;

namespace CppSharp
{
    /// <summary>
    /// This class is used to build passes that will be run against the AST
    /// that comes from C++.
    /// </summary>
    public class PassBuilder<T>
    {
        public List<T> Passes { get; private set; }
        public Driver Driver { get; private set; }

        public PassBuilder(Driver driver)
        {
            Passes = new List<T>();
            Driver = driver;
        }

        /// <summary>
        /// Adds a new pass to the builder.
        /// </summary>
        public void AddPass(T pass)
        {
            if (pass is TranslationUnitPass)
                (pass as TranslationUnitPass).Driver = Driver;

            Passes.Add(pass);
        }

        /// <summary>
        /// Finds a previously-added pass of the given type.
        /// </summary>
        public U FindPass<U>() where U : TranslationUnitPass
        {
            return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault();
        }

        /// <summary>
        /// Adds a new pass to the builder.
        /// </summary>
        public void RunPasses(Action<T> action)
        {
            foreach (var pass in Passes)
                action(pass);
        }
    }
}

Set the driver property in TranslationUnitPass when adding new passes.


using System.Reflection;

// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// 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("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta01")]

using System.Reflection;

// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// 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("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta02")]

Increase nuget version to 2.0.0-beta02

Increase nuget version to 2.0.0-beta02


using System;
using System.Reflection;

namespace Configgy.Coercion
{
    /// <summary>
    /// A base class for any coercer attributes.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
    public abstract class ValueCoercerAttributeBase : Attribute, IValueCoercer
    {
        private static readonly Type NullableType = typeof(Nullable<>);

        /// <summary>
        /// Coerce the raw string value into the expected result type.
        /// </summary>
        /// <typeparam name="T">The expected result type after coercion.</typeparam>
        /// <param name="value">The raw string value to be coerced.</param>
        /// <param name="valueName">The name of the value to be coerced.</param>
        /// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
        /// <param name="result">The coerced value.</param>
        /// <returns>True if the value could be coerced, false otherwise.</returns>
        public abstract bool Coerce<T>(string value, string valueName, PropertyInfo property, out T result);

        protected bool IsNullable<T>()
        {
            var type = typeof(T);
            return type.IsClass || (type.IsGenericType && type.GetGenericTypeDefinition() == NullableType);
        }
    }
}

using System;
using System.Reflection;

namespace Configgy.Coercion
{
    /// <summary>
    /// A base class for any coercer attributes.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
    public abstract class ValueCoercerAttributeBase : Attribute, IValueCoercer
    {
        private static readonly Type NullableType = typeof(Nullable<>);

        /// <summary>
        /// Coerce the raw string value into the expected result type.
        /// </summary>
        /// <typeparam name="T">The expected result type after coercion.</typeparam>
        /// <param name="value">The raw string value to be coerced.</param>
        /// <param name="valueName">The name of the value to be coerced.</param>
        /// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
        /// <param name="result">The coerced value.</param>
        /// <returns>True if the value could be coerced, false otherwise.</returns>
        public abstract bool Coerce<T>(string value, string valueName, PropertyInfo property, out T result);

        protected static bool IsNullable<T>()
        {
            var type = typeof(T);
            return type.IsClass || (type.IsGenericType && type.GetGenericTypeDefinition() == NullableType);
        }
    }
}

Make a method static because it can be

Make a method static because it can be


namespace Fixie
{
    using System;
    using System.Reflection;
    using Internal;

    /// <summary>
    /// The context in which a test class is running.
    /// </summary>
    public class TestClass
    {
        readonly Action<Action<Case>> runCases;
        readonly bool isStatic;
        internal TestClass(Type type, Action<Action<Case>> runCases) : this(type, runCases, null) { }

        internal TestClass(Type type, Action<Action<Case>> runCases, MethodInfo targetMethod)
        {
            this.runCases = runCases;
            Type = type;
            TargetMethod = targetMethod;
            isStatic = Type.IsStatic();
        }

        /// <summary>
        /// The test class to execute.
        /// </summary>
        public Type Type { get; }

        /// <summary>
        /// Gets the target MethodInfo identified by the
        /// test runner as the sole method to be executed.
        /// Null under normal test execution.
        /// </summary>
        public MethodInfo TargetMethod { get; }

        /// <summary>
        /// Constructs an instance of the test class type, using its default constructor.
        /// If the class is static, no action is taken and null is returned.
        /// </summary>
        public object Construct()
        {
            if (isStatic)
                return null;

            try
            {
                return Activator.CreateInstance(Type);
            }
            catch (TargetInvocationException exception)
            {
                throw new PreservedException(exception.InnerException);
            }
        }

        public void RunCases(Action<Case> caseLifecycle)
        {
            runCases(caseLifecycle);
        }
    }
}

namespace Fixie
{
    using System;
    using System.Reflection;
    using System.Runtime.ExceptionServices;
    using Internal;

    /// <summary>
    /// The context in which a test class is running.
    /// </summary>
    public class TestClass
    {
        readonly Action<Action<Case>> runCases;
        readonly bool isStatic;
        internal TestClass(Type type, Action<Action<Case>> runCases) : this(type, runCases, null) { }

        internal TestClass(Type type, Action<Action<Case>> runCases, MethodInfo targetMethod)
        {
            this.runCases = runCases;
            Type = type;
            TargetMethod = targetMethod;
            isStatic = Type.IsStatic();
        }

        /// <summary>
        /// The test class to execute.
        /// </summary>
        public Type Type { get; }

        /// <summary>
        /// Gets the target MethodInfo identified by the
        /// test runner as the sole method to be executed.
        /// Null under normal test execution.
        /// </summary>
        public MethodInfo TargetMethod { get; }

        /// <summary>
        /// Constructs an instance of the test class type, using its default constructor.
        /// If the class is static, no action is taken and null is returned.
        /// </summary>
        public object Construct()
        {
            if (isStatic)
                return null;

            try
            {
                return Activator.CreateInstance(Type);
            }
            catch (TargetInvocationException exception)
            {
                ExceptionDispatchInfo.Capture(exception.InnerException).Throw();
                throw; //Unreachable.
            }
        }

        public void RunCases(Action<Case> caseLifecycle)
        {
            runCases(caseLifecycle);
        }
    }
}

Use ExceptionDispatchInfo to rethrow test class constructor exceptions, now that all other such exception rethrows use ExceptionDispatchInfo.


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

namespace Breeze.Core {

  /**
   * @author IdeaBlade
   *
   */
  public class AndOrPredicate : BasePredicate {
    private List<BasePredicate> _predicates;

    public AndOrPredicate(Operator op, params BasePredicate[] predicates) : this(op, predicates.ToList()) {
    }

    public AndOrPredicate(Operator op, IEnumerable<BasePredicate> predicates) : base(op) {
      _predicates = predicates.ToList();
    }

    public IEnumerable<BasePredicate> Predicates {
      get { return _predicates.AsReadOnly(); }
    }

    public override void Validate(Type entityType) {
      _predicates.ForEach(p => p.Validate(entityType));
    }

    public override Expression ToExpression(ParameterExpression paramExpr) {
      var exprs = _predicates.Select(p => p.ToExpression(paramExpr));
      return BuildAndOrExpr(exprs, Operator);

    }

    private Expression BuildAndOrExpr(IEnumerable<Expression> exprs, Operator op) {
      if (op == Operator.And) {
        return exprs.Aggregate((result, expr) => Expression.And(result, expr));
      } else if (op == Operator.Or) {
        return exprs.Aggregate((result, expr) => Expression.Or(result, expr));
      } else {
        throw new Exception("Invalid AndOr operator" + op.Name);
      }
    }

  }
}

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

namespace Breeze.Core {

  /**
   * @author IdeaBlade
   *
   */
  public class AndOrPredicate : BasePredicate {
    private List<BasePredicate> _predicates;

    public AndOrPredicate(Operator op, params BasePredicate[] predicates) : this(op, predicates.ToList()) {
    }

    public AndOrPredicate(Operator op, IEnumerable<BasePredicate> predicates) : base(op) {
      _predicates = predicates.ToList();
    }

    public IEnumerable<BasePredicate> Predicates {
      get { return _predicates.AsReadOnly(); }
    }

    public override void Validate(Type entityType) {
      _predicates.ForEach(p => p.Validate(entityType));
    }

    public override Expression ToExpression(ParameterExpression paramExpr) {
      var exprs = _predicates.Select(p => p.ToExpression(paramExpr));
      return BuildAndOrExpr(exprs, Operator);

    }

    private Expression BuildAndOrExpr(IEnumerable<Expression> exprs, Operator op) {
      if (op == Operator.And) {
        return exprs.Aggregate((result, expr) => Expression.AndAlso(result, expr));
      } else if (op == Operator.Or) {
        return exprs.Aggregate((result, expr) => Expression.OrElse(result, expr));
      } else {
        throw new Exception("Invalid AndOr operator " + op.Name);
      }
    }

  }
}

Change BuildAndOrExpr to use AndAlso & OrElse to make NHibernate Linq happy


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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Skinning.Editor;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestSceneSkinEditor : PlayerTestScene
    {
        private SkinEditor skinEditor;

        [Resolved]
        private SkinManager skinManager { get; set; }

        [SetUpSteps]
        public override void SetUpSteps()
        {
            AddStep("set empty legacy skin", () =>
            {
                var imported = skinManager.Import(new SkinInfo { Name = "test skin" }).Result;

                skinManager.CurrentSkinInfo.Value = imported;
            });

            base.SetUpSteps();

            AddStep("reload skin editor", () =>
            {
                skinEditor?.Expire();
                Player.ScaleTo(SkinEditorOverlay.VISIBLE_TARGET_SCALE);
                LoadComponentAsync(skinEditor = new SkinEditor(Player), Add);
            });
        }

        [Test]
        public void TestToggleEditor()
        {
            AddToggleStep("toggle editor visibility", visible => skinEditor.ToggleVisibility());
        }

        protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
    }
}

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

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Skinning.Editor;

namespace osu.Game.Tests.Visual.Gameplay
{
    public class TestSceneSkinEditor : PlayerTestScene
    {
        private SkinEditor skinEditor;

        [Resolved]
        private SkinManager skinManager { get; set; }

        [SetUpSteps]
        public override void SetUpSteps()
        {
            base.SetUpSteps();

            AddStep("reload skin editor", () =>
            {
                skinEditor?.Expire();
                Player.ScaleTo(SkinEditorOverlay.VISIBLE_TARGET_SCALE);
                LoadComponentAsync(skinEditor = new SkinEditor(Player), Add);
            });
        }

        [Test]
        public void TestToggleEditor()
        {
            AddToggleStep("toggle editor visibility", visible => skinEditor.ToggleVisibility());
        }

        protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
    }
}

Remove unnecessary test step creating needless skins


// 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 osuTK.Graphics;

namespace osu.Game.Skinning
{
    /// <summary>
    /// A skin configuration pre-populated with sane defaults.
    /// </summary>
    public class DefaultSkinConfiguration : SkinConfiguration
    {
        public DefaultSkinConfiguration()
        {
            ComboColours.AddRange(new[]
            {
                new Color4(17, 136, 170, 255),
                new Color4(102, 136, 0, 255),
                new Color4(204, 102, 0, 255),
                new Color4(121, 9, 13, 255)
            });
        }
    }
}

// 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 osuTK.Graphics;

namespace osu.Game.Skinning
{
    /// <summary>
    /// A skin configuration pre-populated with sane defaults.
    /// </summary>
    public class DefaultSkinConfiguration : SkinConfiguration
    {
        public DefaultSkinConfiguration()
        {
            ComboColours.AddRange(new[]
            {
                new Color4(255, 192, 0, 255),
                new Color4(0, 202, 0, 255),
                new Color4(18, 124, 255, 255),
                new Color4(242, 24, 57, 255),
            });
        }
    }
}

Update lazer default combo colours to match stable


using System;
using System.IO;
using System.Web;
using Cassette.UI;

namespace Cassette.Web
{
    public class PlaceholderReplacingResponseFilter : MemoryStream
    {
        public PlaceholderReplacingResponseFilter(HttpResponseBase response, IPlaceholderTracker placeholderTracker)
        {
            this.response = response;
            this.placeholderTracker = placeholderTracker;
            outputStream = response.Filter;
        }

        readonly Stream outputStream;
        readonly HttpResponseBase response;
        readonly IPlaceholderTracker placeholderTracker;

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (response.Headers["Content-Encoding"] != null)
            {
                throw new InvalidOperationException("Cannot rewrite page output when it has been compressed. Either set ICassetteApplication.HtmlRewritingEnabled to false in the Cassette configuration, or set <urlCompression dynamicCompressionBeforeCache=\"false\" /> in Web.config.");
            }

            if (IsHtmlResponse)
            {
                buffer = ReplacePlaceholders(buffer, offset, count);
                outputStream.Write(buffer, 0, buffer.Length);
            }
            else
            {
                outputStream.Write(buffer, offset, count);
            }
        }

        byte[] ReplacePlaceholders(byte[] buffer, int offset, int count)
        {
            var encoding = response.Output.Encoding;
            var html = encoding.GetString(buffer, offset, count);
            html = placeholderTracker.ReplacePlaceholders(html);
            return encoding.GetBytes(html);
        }

        bool IsHtmlResponse
        {
            get
            {
                return response.ContentType == "text/html" ||
                       response.ContentType == "application/xhtml+xml";
            }
        }
    }
}

using System;
using System.IO;
using System.Web;
using Cassette.UI;

namespace Cassette.Web
{
    public class PlaceholderReplacingResponseFilter : MemoryStream
    {
        public PlaceholderReplacingResponseFilter(HttpResponseBase response, IPlaceholderTracker placeholderTracker)
        {
            this.response = response;
            this.placeholderTracker = placeholderTracker;
            outputStream = response.Filter;
        }

        readonly Stream outputStream;
        readonly HttpResponseBase response;
        readonly IPlaceholderTracker placeholderTracker;

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (response.Headers["Content-Encoding"] != null)
            {
                throw new InvalidOperationException("Cannot rewrite page output when it has been compressed. Either set ICassetteApplication.HtmlRewritingEnabled to false in the Cassette configuration, or set <urlCompression dynamicCompressionBeforeCache=\"false\" /> in Web.config.");
            }

            buffer = ReplacePlaceholders(buffer, offset, count);
            outputStream.Write(buffer, 0, buffer.Length);
        }

        byte[] ReplacePlaceholders(byte[] buffer, int offset, int count)
        {
            var encoding = response.Output.Encoding;
            var html = encoding.GetString(buffer, offset, count);
            html = placeholderTracker.ReplacePlaceholders(html);
            return encoding.GetBytes(html);
        }
    }
}

Remove HTML content type check from response filter because the check is performed in CassetteApplication instead.


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

using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis.NavigateTo
{
    internal interface INavigateToSearchService : ILanguageService
    {
        IImmutableSet<string> KindsProvided { get; }
        bool CanFilter { get; }

        Task<ImmutableArray<INavigateToSearchResult>> SearchProjectAsync(Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
        Task<ImmutableArray<INavigateToSearchResult>> SearchDocumentAsync(Document document, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
    }

    [Obsolete("Use " + nameof(INavigateToSearchResult) + " instead", error: false)]
    internal interface INavigateToSeINavigateToSearchService_RemoveInterfaceAboveAndRenameThisAfterInternalsVisibleToUsersUpdatearchService : ILanguageService
    {
        IImmutableSet<string> KindsProvided { get; }
        bool CanFilter { get; }

        Task<ImmutableArray<INavigateToSearchResult>> SearchProjectAsync(Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
        Task<ImmutableArray<INavigateToSearchResult>> SearchDocumentAsync(Document document, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
    }
}

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

using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis.NavigateTo
{
    internal interface INavigateToSearchService : ILanguageService
    {
        IImmutableSet<string> KindsProvided { get; }
        bool CanFilter { get; }

        Task<ImmutableArray<INavigateToSearchResult>> SearchProjectAsync(Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
        Task<ImmutableArray<INavigateToSearchResult>> SearchDocumentAsync(Document document, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
    }
}

Remove interface that is no longer user.


@model Portal.CMS.Web.Areas.PageBuilder.ViewModels.Section.CloneViewModel
@{
    Layout = "";

    var pageList = Model.PageList.Select(x => new SelectListItem { Value = x.PageId.ToString(), Text = x.PageName });
}

    @using (Html.BeginForm("Clone", "Section", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        @Html.HiddenFor(x => x.PageAssociationId)

Clone a Section onto another Page to keep your content synced across all relevant pages

        @Html.ValidationMessage("PageId")

            @Html.LabelFor(x => x.PageId)
            @Html.DropDownListFor(m => m.PageId, pageList)

            <button class="btn primary">Clone Section</button>
            <button class="btn" data-dismiss="modal">Cancel</button>

    }

@model Portal.CMS.Web.Areas.PageBuilder.ViewModels.Section.CloneViewModel
@{
    Layout = "";

    var pageList = Model.PageList.Select(x => new SelectListItem { Value = x.PageId.ToString(), Text = x.PageName });
}

    @using (Html.BeginForm("Clone", "Section", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        @Html.HiddenFor(x => x.PageAssociationId)

        if (pageList.Any())
        {

Clone a Section onto another Page to keep your content synced across all relevant pages

        }
        else
        {

You can't Clone this Section because you don't have any other pages yet...

        }

        @Html.ValidationMessageFor(x => x.PageId)

            @Html.LabelFor(x => x.PageId)
            @Html.DropDownListFor(m => m.PageId, pageList)

            <button class="btn primary">Clone Section</button>
            <button class="btn" data-dismiss="modal">Cancel</button>

    }

Add Validation Messages to the Clone Section Screen


using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace AllReady.Models
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        [Display(Name = "Associated skills")]
        public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>();

        public string Name { get; set; }

        [Display(Name = "Time Zone")]
        [Required]
        public string TimeZoneId { get; set; }

        public string PendingNewEmail { get; set; }

        public IEnumerable<ValidationResult> ValidateProfileCompleteness()
        {
            List<ValidationResult> validationResults = new List<ValidationResult>();

            if (!EmailConfirmed)
            {
                validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) }));
            }

            if (string.IsNullOrWhiteSpace(Name))
            {
                validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) }));
            }

            if (string.IsNullOrWhiteSpace(PhoneNumber))
            {
                validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) }));
            }

            if (!string.IsNullOrWhiteSpace(PhoneNumber) && !PhoneNumberConfirmed)
            {
                validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) }));
            }
            return validationResults;
        }

        public bool IsProfileComplete()
        {
            return !ValidateProfileCompleteness().Any();
        }
    }

}

using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace AllReady.Models
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        [Display(Name = "Associated skills")]
        public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>();

        public string Name { get; set; }

        [Display(Name = "Time Zone")]
        [Required]
        public string TimeZoneId { get; set; }

        public string PendingNewEmail { get; set; }

        public IEnumerable<ValidationResult> ValidateProfileCompleteness()
        {
            List<ValidationResult> validationResults = new List<ValidationResult>();

            if (!EmailConfirmed)
            {
                validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) }));
            }

            if (string.IsNullOrWhiteSpace(Name))
            {
                validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) }));
            }

            if (string.IsNullOrWhiteSpace(PhoneNumber))
            {
                validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) }));
            }
            else if (!PhoneNumberConfirmed)
            {
                validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) }));
            }
            return validationResults;
        }

        public bool IsProfileComplete()
        {
            return !ValidateProfileCompleteness().Any();
        }
    }

}

Simplify logic in user profile validation


namespace AlertRoster.Web.Models
{
    public class MemberGroup
    {
        public int MemberId { get; private set; }

        public virtual Member Member { get; private set; }

        public int GroupId { get; private set; }

        public virtual Group Group { get; private set; }

        private MemberGroup()
        {
            // Parameter-less ctor for EF
        }

        public MemberGroup(int memberId, int groupId)
        {
            this.MemberId = memberId;
            this.GroupId = groupId;
        }
    }
}

namespace AlertRoster.Web.Models
{
    public class MemberGroup
    {
        public int MemberId { get; private set; }

        public virtual Member Member { get; private set; }

        public int GroupId { get; private set; }

        public virtual Group Group { get; private set; }

        public GroupRole Role { get; set; } = GroupRole.Member;

        private MemberGroup()
        {
            // Parameter-less ctor for EF
        }

        public MemberGroup(int memberId, int groupId)
        {
            this.MemberId = memberId;
            this.GroupId = groupId;
        }

        public enum GroupRole : byte
        {
            Member = 0,

            Administrator = 1
        }
    }
}

Add group role to relationship

Add group role to relationship


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

using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Checks.Components;
using osu.Game.Rulesets.Osu.Edit.Checks;

namespace osu.Game.Rulesets.Osu.Edit
{
    public class OsuBeatmapVerifier : IBeatmapVerifier
    {
        private readonly List<ICheck> checks = new List<ICheck>
        {
            new CheckOffscreenObjects()
        };

        public IEnumerable<Issue> Run(BeatmapVerifierContext context)
        {
            return checks.SelectMany(check => check.Run(context));
        }
    }
}

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

using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Checks.Components;
using osu.Game.Rulesets.Osu.Edit.Checks;

namespace osu.Game.Rulesets.Osu.Edit
{
    public class OsuBeatmapVerifier : IBeatmapVerifier
    {
        private readonly List<ICheck> checks = new List<ICheck>
        {
            // Compose
            new CheckOffscreenObjects(),

            // Spread
            new CheckTimeDistanceEquality(),
            new CheckLowDiffOverlaps()
        };

        public IEnumerable<Issue> Run(BeatmapVerifierContext context)
        {
            return checks.SelectMany(check => check.Run(context));
        }
    }
}

Add new checks to verifier

Add new checks to verifier


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

using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Screens.Edit.Components;
using osu.Game.Tests.Beatmaps;
using OpenTK;

namespace osu.Game.Tests.Visual
{
    public class TestCasePlaybackControl : OsuTestCase
    {
        public TestCasePlaybackControl()
        {
            var playback = new PlaybackControl
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Size = new Vector2(200,100)
            };
            playback.Beatmap.Value = new TestWorkingBeatmap(new Beatmap());

            Add(playback);
        }
    }
}

// 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.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Screens.Edit.Components;
using osu.Game.Tests.Beatmaps;
using OpenTK;

namespace osu.Game.Tests.Visual
{
    public class TestCasePlaybackControl : OsuTestCase
    {
        public TestCasePlaybackControl()
        {
            var playback = new PlaybackControl
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                Size = new Vector2(200,100)
            };
            playback.Beatmap.Value = new TestWorkingBeatmap(new Beatmap());

            Add(playback);
        }
    }
}

Fix license header from wrong project

Fix license header from wrong project


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ThoughtWorks.CruiseControl.Remote.Parameters;

namespace JenkinsTransport.BuildParameters
{
    public abstract class BaseBuildParameter
    {
        public string Name { get; private set; }
        public string Description { get; private set; }
        public BuildParameterType ParameterType { get; protected set; }
        public string DefaultValue { get; private set; }

        public virtual ParameterBase ToParameterBase()
        {
            throw new NotImplementedException("Must be overridden in derived class");
        }

        protected BaseBuildParameter(XContainer document)
        {
            Name = (string)document.Element("name");
            Description = (string)document.Element("description");
            DefaultValue = (string)document.Descendants("defaultParameterValue").First().Element("value");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ThoughtWorks.CruiseControl.Remote.Parameters;

namespace JenkinsTransport.BuildParameters
{
    public abstract class BaseBuildParameter
    {
        public string Name { get; private set; }
        public string Description { get; private set; }
        public BuildParameterType ParameterType { get; protected set; }
        public string DefaultValue { get; private set; }

        public abstract ParameterBase ToParameterBase();

        protected BaseBuildParameter(XContainer document)
        {
            Name = (string)document.Element("name");
            Description = (string)document.Element("description");
            DefaultValue = (string)document.Descendants("defaultParameterValue").First().Element("value");
        }
    }
}

Modify method to abstract which will force a compile error if the implementation is not supplied in a derived class rather than throw a NotImplementedException()


using Xunit;

namespace OpenGost.Security.Cryptography
{
    public abstract class CmacTest<T> : CryptoConfigRequiredTest
        where T : CMAC, new()
    {
        protected void VerifyCmac(string dataHex, string keyHex, string digestHex)
        {
            var digestBytes = digestHex.HexToByteArray();
            byte[] computedDigest;

            using (var cmac = new T())
            {
                Assert.True(cmac.HashSize > 0);

                var key = keyHex.HexToByteArray();
                cmac.Key = key;

                // make sure the getter returns different objects each time
                Assert.NotSame(key, cmac.Key);
                Assert.NotSame(cmac.Key, cmac.Key);

                // make sure the setter didn't cache the exact object we passed in
                key[0] = (byte)(key[0] + 1);
                Assert.NotEqual<byte>(key, cmac.Key);

                computedDigest = cmac.ComputeHash(dataHex.HexToByteArray());
            }

            Assert.Equal(digestBytes, computedDigest);
        }
    }
}

using System;
using Xunit;

namespace OpenGost.Security.Cryptography
{
    public abstract class CmacTest<T> : CryptoConfigRequiredTest
        where T : CMAC, new()
    {
        protected void VerifyCmac(string dataHex, string keyHex, string digestHex)
        {
            var digestBytes = digestHex.HexToByteArray();
            byte[] computedDigest;

            using (var cmac = new T())
            {
                Assert.True(cmac.HashSize > 0);

                var key = keyHex.HexToByteArray();
                cmac.Key = key;

                // make sure the getter returns different objects each time
                Assert.NotSame(key, cmac.Key);
                Assert.NotSame(cmac.Key, cmac.Key);

                // make sure the setter didn't cache the exact object we passed in
                key[0] = (byte)(key[0] + 1);
                Assert.NotEqual<byte>(key, cmac.Key);

                computedDigest = cmac.ComputeHash(dataHex.HexToByteArray());
            }

            Assert.Equal(digestBytes, computedDigest);
        }

        [Fact]
        public void Key_Throws_IfValueIsNull()
        {
            byte[] value = null!;
            using var cmac = new T();

            Assert.Throws<ArgumentNullException>(nameof(value), () => cmac.Key = value);
        }
    }
}

Cover CMAC -> Key property setter with null check test


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

namespace ShopifySharp
{
    public class ShopifyClientDetails
    {
        /// <summary>
        /// Shopify does not offer documentation for this field.
        /// </summary>
        [JsonProperty("accept_language")]
        public string AcceptLanguage { get; set; }

        /// <summary>
        /// The browser screen height in pixels, if available.
        /// </summary>
        [JsonProperty("browser_height")]
        public string BrowserHeight { get; set; }

        /// <summary>
        /// The browser IP address.
        /// </summary>
        [JsonProperty("browser_ip")]
        public string BrowserIp { get; set; }

        /// <summary>
        /// The browser screen width in pixels, if available.
        /// </summary>
        [JsonProperty("browser_width")]
        public string BrowserWidth { get; set; }

        /// <summary>
        /// A hash of the session.
        /// </summary>
        [JsonProperty("session_height")]
        public string SessionHeight { get; set; }

        /// <summary>
        /// The browser's user agent string.
        /// </summary>
        [JsonProperty("user_agent")]
        public string UserAgent { get; set; }
    }
}

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

namespace ShopifySharp
{
    public class ShopifyClientDetails
    {
        /// <summary>
        /// Shopify does not offer documentation for this field.
        /// </summary>
        [JsonProperty("accept_language")]
        public string AcceptLanguage { get; set; }

        /// <summary>
        /// The browser screen height in pixels, if available.
        /// </summary>
        [JsonProperty("browser_height")]
        public string BrowserHeight { get; set; }

        /// <summary>
        /// The browser IP address.
        /// </summary>
        [JsonProperty("browser_ip")]
        public string BrowserIp { get; set; }

        /// <summary>
        /// The browser screen width in pixels, if available.
        /// </summary>
        [JsonProperty("browser_width")]
        public string BrowserWidth { get; set; }

        /// <summary>
        /// Obsolete: This property is incorrect and will be removed in a future release.
        /// </summary>
        [JsonProperty("session_height"), Obsolete("This property is incorrect and will be removed in a future release.")]
        public string SessionHeight { get; set; }

        /// <summary>
        /// A hash of the session.
        /// </summary>
        [JsonProperty("session_hash")]
        public string SessionHash { get; set; }

        /// <summary>
        /// The browser's user agent string.
        /// </summary>
        [JsonProperty("user_agent")]
        public string UserAgent { get; set; }
    }
}

Add SessionHash property and mark SessionHeight as obsolete.

Closes #99


using Content.Server.Mobs;
using Robust.Shared.GameObjects;

namespace Content.Server.GameObjects.Components.Mobs
{
    [RegisterComponent]
    public sealed class VisitingMindComponent : Component
    {
        public override string Name => "VisitingMind";

        public Mind Mind { get; set; }

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

            Mind?.UnVisit();
        }
    }
}

using Content.Server.Mobs;
using Robust.Shared.GameObjects;
using Robust.Shared.ViewVariables;

namespace Content.Server.GameObjects.Components.Mobs
{
    [RegisterComponent]
    public sealed class VisitingMindComponent : Component
    {
        public override string Name => "VisitingMind";

        [ViewVariables]
        public Mind Mind { get; set; }

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

            Mind?.UnVisit();
        }
    }
}

Make VisitingMind's Mind readable by VV

Make VisitingMind's Mind readable by VV


using System;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

namespace System.Diagnostics {
    internal class ProcessWaitHandle : WaitHandle {

        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        internal ProcessWaitHandle( SafeProcessHandle processHandle): base() {
            SafeWaitHandle waitHandle = null;
            bool succeeded = NativeMethods.DuplicateHandle(
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                processHandle,
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                out waitHandle,
                0,
                false,
                NativeMethods.DUPLICATE_SAME_ACCESS);

            if (!succeeded) {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            this.SafeWaitHandle = waitHandle;
        }
    }
}

using System;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

namespace System.Diagnostics {
    internal class ProcessWaitHandle : WaitHandle {

        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        internal ProcessWaitHandle( SafeProcessHandle processHandle): base() {
            SafeWaitHandle waitHandle = null;
            bool succeeded = NativeMethods.DuplicateHandle(
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                processHandle,
                new HandleRef(this, NativeMethods.GetCurrentProcess()),
                out waitHandle,
                0,
                false,
                NativeMethods.DUPLICATE_SAME_ACCESS);

            if (!succeeded) {
#if MONO
                // In Mono, Marshal.GetHRForLastWin32Error is not implemented;
                // and also DuplicateHandle throws its own exception rather
                // than returning false on error, so this code is unreachable.
                throw new SystemException("Unknown error in DuplicateHandle");
#else
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
#endif
            }

            this.SafeWaitHandle = waitHandle;
        }
    }
}

[System] Remove Marshal.GetHRForLastWin32Error call from Diagnostics.Process

GetHRForLastWin32Error breaks the build on AOT, and even on non-AOT is unimplemented.


using Microsoft.AspNetCore.Hosting;

namespace MusicStore
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                // We set the server before default args so that command line arguments can override it.
                // This is used to allow deployers to choose the server for testing.
                .UseKestrel()
                .UseDefaultHostingConfiguration(args)
                .UseIISIntegration()
                .UseStartup("MusicStore")
                .Build();

            host.Run();
        }
    }
}

using Microsoft.AspNetCore.Hosting;

namespace MusicStore
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                // We set the server by name before default args so that command line arguments can override it.
                // This is used to allow deployers to choose the server for testing.
                .UseServer("Microsoft.AspNetCore.Server.Kestrel")
                .UseDefaultHostingConfiguration(args)
                .UseIISIntegration()
                .UseStartup("MusicStore")
                .Build();

            host.Run();
        }
    }
}

Use UseServer() instead of UseKestrel() to allow override in tests


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

// 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: 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("1489ac72-1967-48b8-a302-79b2900acbe3")]

[assembly: CollectionBehavior(DisableTestParallelization = true)]

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

// 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: 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("1489ac72-1967-48b8-a302-79b2900acbe3")]

[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]

Disable parallelization for RhinoMock using alternative way

It appeared that explicit console runner parameter could cause
assembly to be still parallelized.


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

using System;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;

namespace osu.Game.Screens.Play
{
    /// <summary>
    /// Ensures screen is not suspended / dimmed while gameplay is active.
    /// </summary>
    public class ScreenSuspensionHandler : Component
    {
        private readonly GameplayClockContainer gameplayClockContainer;
        private Bindable<bool> isPaused;

        [Resolved]
        private GameHost host { get; set; }

        public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
        {
            this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
        }

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

            isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
            isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            isPaused?.UnbindAll();

            if (host != null)
                host.AllowScreenSuspension.Value = true;
        }
    }
}

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

using System;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;

namespace osu.Game.Screens.Play
{
    /// <summary>
    /// Ensures screen is not suspended / dimmed while gameplay is active.
    /// </summary>
    public class ScreenSuspensionHandler : Component
    {
        private readonly GameplayClockContainer gameplayClockContainer;
        private Bindable<bool> isPaused;

        [Resolved]
        private GameHost host { get; set; }

        public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
        {
            this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
        }

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

            // This is the only usage game-wide of suspension changes.
            // Assert to ensure we don't accidentally forget this in the future.
            Debug.Assert(host.AllowScreenSuspension.Value);

            isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
            isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            isPaused?.UnbindAll();

            if (host != null)
                host.AllowScreenSuspension.Value = true;
        }
    }
}

Add assertion of only usage game-wide

Add assertion of only usage game-wide