using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AspNetCore.RouteAnalyzer.SampleWebProject
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddRouteAnalyzer();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRouteAnalyzer("/routes");
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;

namespace AspNetCore.RouteAnalyzer.SampleWebProject
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        private IRouteAnalyzer m_routeAnalyzer;

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddRouteAnalyzer();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IApplicationLifetime applicationLifetime,
            IRouteAnalyzer routeAnalyzer
        )
        {
            m_routeAnalyzer = routeAnalyzer;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRouteAnalyzer("/routes");
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            // Lifetime events
            applicationLifetime.ApplicationStarted.Register(OnStarted);
            applicationLifetime.ApplicationStopping.Register(OnStopping);
            applicationLifetime.ApplicationStopped.Register(OnStopped);
        }

        void OnStarted()
        {
            var infos = m_routeAnalyzer.GetAllRouteInformations();
            Debug.WriteLine("======== ALL ROUTE INFORMATION ========");
            foreach(var info in infos)
            {
                Debug.WriteLine(info.ToString());
            }
            Debug.WriteLine("");
            Debug.WriteLine("");
        }

        void OnStopping()
        {
        }

        void OnStopped()
        {
        }
    }
}

Sample: Print all route information to debug stream (Visual Studio Output panel).


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.TeamIntro;

namespace osu.Game.Tournament.Tests.Screens
{
    public class TestSceneSeedingScreen : TournamentTestScene
    {
        [Cached]
        private readonly LadderInfo ladder = new LadderInfo();

        [BackgroundDependencyLoader]
        private void load()
        {
            Add(new SeedingScreen
            {
                FillMode = FillMode.Fit,
                FillAspectRatio = 16 / 9f
            });
        }
    }
}

// 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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Ladder.Components;
using osu.Game.Tournament.Screens.TeamIntro;

namespace osu.Game.Tournament.Tests.Screens
{
    public class TestSceneSeedingScreen : TournamentTestScene
    {
        [Cached]
        private readonly LadderInfo ladder = new LadderInfo
        {
            Teams =
            {
                new TournamentTeam
                {
                    FullName = { Value = @"Japan" },
                    Acronym = { Value = "JPN" },
                    SeedingResults =
                    {
                        new SeedingResult
                        {
                            // Mod intentionally left blank.
                            Seed = { Value = 4 }
                        },
                        new SeedingResult
                        {
                            Mod = { Value = "DT" },
                            Seed = { Value = 8 }
                        }
                    }
                }
            }
        };

        [Test]
        public void TestBasic()
        {
            AddStep("create seeding screen", () => Add(new SeedingScreen
            {
                FillMode = FillMode.Fit,
                FillAspectRatio = 16 / 9f
            }));

            AddStep("set team to Japan", () => this.ChildrenOfType<SettingsTeamDropdown>().Single().Current.Value = ladder.Teams.Single());
        }
    }
}

Add test coverage for null mod on seeding screen


// 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.Runtime;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;

namespace osu.Game.Overlays.Settings.Sections.Debug
{
    public class GCSettings : SettingsSubsection
    {
        protected override string Header => "Garbage Collector";

        [BackgroundDependencyLoader]
        private void load(FrameworkDebugConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsEnumDropdown<GCLatencyMode>
                {
                    LabelText = "Active mode",
                    Bindable = config.GetBindable<GCLatencyMode>(DebugSetting.ActiveGCMode)
                },
                new SettingsButton
                {
                    Text = "Force garbage collection",
                    Action = GC.Collect
                },
            };
        }
    }
}

// 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.Runtime;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;

namespace osu.Game.Overlays.Settings.Sections.Debug
{
    public class GCSettings : SettingsSubsection
    {
        protected override string Header => "Garbage Collector";

        private readonly Bindable<LatencyMode> latencyMode = new Bindable<LatencyMode>();
        private Bindable<GCLatencyMode> configLatencyMode;

        [BackgroundDependencyLoader]
        private void load(FrameworkDebugConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsEnumDropdown<LatencyMode>
                {
                    LabelText = "Active mode",
                    Bindable = latencyMode
                },
                new SettingsButton
                {
                    Text = "Force garbage collection",
                    Action = GC.Collect
                },
            };

            configLatencyMode = config.GetBindable<GCLatencyMode>(DebugSetting.ActiveGCMode);
            configLatencyMode.BindValueChanged(v => latencyMode.Value = (LatencyMode)v, true);
            latencyMode.BindValueChanged(v => configLatencyMode.Value = (GCLatencyMode)v);
        }

        private enum LatencyMode
        {
            Batch = GCLatencyMode.Batch,
            Interactive = GCLatencyMode.Interactive,
            LowLatency = GCLatencyMode.LowLatency,
            SustainedLowLatency = GCLatencyMode.SustainedLowLatency
        }
    }
}

Fix invalid GC latency mode being set

Fix invalid GC latency mode being set


using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

namespace Alexa.NET.Response
{
    public class ResponseBody
    {
        [JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)]
        public IOutputSpeech OutputSpeech { get; set; }

        [JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)]
        public ICard Card { get; set; }

        [JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)]
        public Reprompt Reprompt { get; set; }

        private bool? _shouldEndSession = null;

        [JsonProperty("shouldEndSession", NullValueHandling = NullValueHandling.Ignore)]
        public bool? ShouldEndSession
        {
            get
            {
                var overrideDirectives = Directives?.OfType<IEndSessionDirective>();
                if (overrideDirectives == null || !overrideDirectives.Any())
                {
                    return _shouldEndSession;
                }

                var first = overrideDirectives.First().ShouldEndSession;
                if (!overrideDirectives.All(od => od.ShouldEndSession == first))
                {
                    return _shouldEndSession;
                }

                return first;

            }
            set => _shouldEndSession = value;
        }

        [JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)]
        public IList<IDirective> Directives { get; set; } = new List<IDirective>();

        public bool ShouldSerializeDirectives()
        {
            return Directives.Count > 0;
        }
    }
}

using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

namespace Alexa.NET.Response
{
    public class ResponseBody
    {
        [JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)]
        public IOutputSpeech OutputSpeech { get; set; }

        [JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)]
        public ICard Card { get; set; }

        [JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)]
        public Reprompt Reprompt { get; set; }

        private bool? _shouldEndSession = false;

        [JsonProperty("shouldEndSession", NullValueHandling = NullValueHandling.Ignore)]
        public bool? ShouldEndSession
        {
            get
            {
                var overrideDirectives = Directives?.OfType<IEndSessionDirective>();
                if (overrideDirectives == null || !overrideDirectives.Any())
                {
                    return _shouldEndSession;
                }

                var first = overrideDirectives.First().ShouldEndSession;
                if (!overrideDirectives.All(od => od.ShouldEndSession == first))
                {
                    return _shouldEndSession;
                }

                return first;

            }
            set => _shouldEndSession = value;
        }

        [JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)]
        public IList<IDirective> Directives { get; set; } = new List<IDirective>();

        public bool ShouldSerializeDirectives()
        {
            return Directives.Count > 0;
        }
    }
}

Make _shouldEndSession false rather than null


using System.Collections.Generic;
using System.Xml;

namespace PROProtocol
{
    public class Language
    {
        private Dictionary<string, string> _texts;

        public Language()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load("Resources/Lang.xml");

            _texts = new Dictionary<string, string>();

            XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0];
            if (languageNode != null)
            {
                foreach (XmlElement textNode in languageNode)
                {
                    _texts.Add(textNode.GetAttribute("name"), textNode.InnerText);
                }
            }
        }

        public string GetText(string name)
        {
            return _texts[name];
        }

        public string Replace(string originalText)
        {
            if (originalText.IndexOf('$') != -1)
            {
                foreach (var text in _texts)
                {
                    originalText = originalText.Replace("$" + text.Key, text.Value);
                }
            }
            return originalText;
        }
    }
}

using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace PROProtocol
{
    public class Language
    {
        private const string FileName = "Resources/Lang.xml";

        private Dictionary<string, string> _texts = new Dictionary<string, string>();

        public Language()
        {
            if (File.Exists(FileName))
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(FileName);
                LoadXmlDocument(xml);
            }
        }

        private void LoadXmlDocument(XmlDocument xml)
        {
            XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0];
            if (languageNode != null)
            {
                foreach (XmlElement textNode in languageNode)
                {
                    _texts.Add(textNode.GetAttribute("name"), textNode.InnerText);
                }
            }
        }

        public string GetText(string name)
        {
            return _texts[name];
        }

        public string Replace(string originalText)
        {
            if (originalText.IndexOf('$') != -1)
            {
                foreach (var text in _texts)
                {
                    originalText = originalText.Replace("$" + text.Key, text.Value);
                }
            }
            return originalText;
        }
    }
}

Make the language XML file optional

Make the language XML file optional


using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;

namespace BobTheBuilder.Tests
{
    public class BuildFacts
    {
        [Fact]
        public void CreateADynamicInstanceOfTheRequestedType()
        {
            var sut = A.BuilderFor<SampleType>();

            var result = sut.Build();

            Assert.IsAssignableFrom<dynamic>(result);
            Assert.IsAssignableFrom<SampleType>(result);
        }

        [Theory, AutoData]
        public void SetStringStateByName(string expected)
        {
            var sut = A.BuilderFor<SampleType>();

            sut.WithStringProperty(expected);
            var result = sut.Build();

            Assert.Equal(expected, result.StringProperty);
        }
    }
}

using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;

namespace BobTheBuilder.Tests
{
    public class BuildFacts
    {
        [Fact]
        public void CreateADynamicInstanceOfTheRequestedType()
        {
            var sut = A.BuilderFor<SampleType>();

            var result = sut.Build();

            Assert.IsAssignableFrom<dynamic>(result);
            Assert.IsAssignableFrom<SampleType>(result);
        }

        [Theory, AutoData]
        public void SetStringStateByName(string expected)
        {
            var sut = A.BuilderFor<SampleType>();

            sut.WithStringProperty(expected);
            SampleType result = sut.Build();

            Assert.Equal(expected, result.StringProperty);
        }
    }
}

Use explicit type to cast back to SampleType.

Using var on the `sut.Build()` line will always result in result being of
type `dynamic`, which we don't want. We need to explicitly specify the
type of the `result` variable to fix intellisense and compilation.


using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Diagnostics;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi.ExtensionsAPI.ExternalAnnotations;
using JetBrains.TestFramework.Utils;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.Tests
{
    [ShellComponent]
    public class AnnotationsLoader : IExternalAnnotationsFileProvider
    {
        private readonly OneToSetMap<string, VirtualFileSystemPath> myAnnotations;

        public AnnotationsLoader()
        {
            myAnnotations = new OneToSetMap<string, VirtualFileSystemPath>(StringComparer.OrdinalIgnoreCase);
            var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly).ToVirtualFileSystemPath();
            var annotationsPath = testDataPathBase.Parent.Parent / "src" / "annotations";
            Assertion.Assert(annotationsPath.ExistsDirectory, $"Cannot find annotations: {annotationsPath}");
            var annotationFiles = annotationsPath.GetChildFiles();
            foreach (var annotationFile in annotationFiles)
            {
                myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
            }
        }

        public IEnumerable<VirtualFileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, VirtualFileSystemPath assemblyLocation = null)
        {
            if (assemblyName == null)
                return myAnnotations.Values;
            return myAnnotations[assemblyName.Name];
        }
    }
}

using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Diagnostics;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi.ExtensionsAPI.ExternalAnnotations;
using JetBrains.TestFramework.Utils;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.Tests
{
    [ShellComponent]
    public class AnnotationsLoader : IExternalAnnotationsFileProvider
    {
        private readonly OneToSetMap<string, VirtualFileSystemPath> myAnnotations;

        public AnnotationsLoader()
        {
            myAnnotations = new OneToSetMap<string, VirtualFileSystemPath>(StringComparer.OrdinalIgnoreCase);
            var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly).ToVirtualFileSystemPath();
            var annotationsPath = testDataPathBase.Parent.Parent / "src" / "Unity" / "annotations";
            Assertion.Assert(annotationsPath.ExistsDirectory, $"Cannot find annotations: {annotationsPath}");
            var annotationFiles = annotationsPath.GetChildFiles();
            foreach (var annotationFile in annotationFiles)
            {
                myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
            }
        }

        public IEnumerable<VirtualFileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, VirtualFileSystemPath assemblyLocation = null)
        {
            if (assemblyName == null)
                return myAnnotations.Values;
            return myAnnotations[assemblyName.Name];
        }
    }
}

Fix path to annotations in tests

Fix path to annotations in tests


using System.Collections.ObjectModel;

namespace Espera.Network
{
    public class NetworkPlaylist
    {
        public int? CurrentIndex { get; set; }

        public string Name { get; set; }

        public int? RemainingVotes { get; set; }

        public ReadOnlyCollection<NetworkSong> Songs { get; set; }
    }
}

using System.Collections.ObjectModel;

namespace Espera.Network
{
    public class NetworkPlaylist
    {
        public int? CurrentIndex { get; set; }

        public string Name { get; set; }

        public NetworkPlaybackState PlaybackState { get; set; }

        public int? RemainingVotes { get; set; }

        public ReadOnlyCollection<NetworkSong> Songs { get; set; }
    }
}

Add a playback state property to the playlist


using JoinRpg.DataModel;
using JoinRpg.Domain;
using Microsoft.AspNetCore.Mvc;

namespace JoinRpg.Portal.Controllers.Comments
{
    internal static class CommentRedirectHelper
    {
        public static ActionResult RedirectToDiscussion(IUrlHelper Url, CommentDiscussion discussion, int? commentId = null)
        {
            var extra = commentId != null ? $"#comment{commentId}" : null;
            var claim = discussion.GetClaim();
            if (claim != null)
            {
                var actionLink = Url.Action("Edit", "Claim", new { claim.ClaimId, discussion.ProjectId });
                return new RedirectResult(actionLink + extra);
            }
            var forumThread = discussion.GetForumThread();
            if (forumThread != null)
            {
                var actionLink = Url.Action("ViewThread", new { discussion.ProjectId, forumThread.ForumThreadId });
                return new RedirectResult(actionLink + extra);
            }
            return new NotFoundResult();
        }
    }
}

using JoinRpg.DataModel;
using JoinRpg.Domain;
using Microsoft.AspNetCore.Mvc;

namespace JoinRpg.Portal.Controllers.Comments
{
    internal static class CommentRedirectHelper
    {
        public static ActionResult RedirectToDiscussion(IUrlHelper Url, CommentDiscussion discussion, int? commentId = null)
        {
            var extra = commentId != null ? $"#comment{commentId}" : null;
            var claim = discussion.GetClaim();
            if (claim != null)
            {
                var actionLink = Url.Action("Edit", "Claim", new { claim.ClaimId, discussion.ProjectId });
                return new RedirectResult(actionLink + extra);
            }
            var forumThread = discussion.GetForumThread();
            if (forumThread != null)
            {
                var actionLink = Url.Action("ViewThread", "Forum", new { discussion.ProjectId, forumThread.ForumThreadId });
                return new RedirectResult(actionLink + extra);
            }
            return new NotFoundResult();
        }
    }
}

Fix bug about not redirecting to forums

Fix bug about not redirecting to forums


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

using System.Reflection;
using System.Resources;

[assembly: AssemblyTitle("Microsoft Azure Cognitive Services Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Cognitive Services management functions for managing Microsoft Azure Cognitive Services accounts.")]

[assembly: AssemblyVersion("0.2.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

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

using System.Reflection;
using System.Resources;

[assembly: AssemblyTitle("Microsoft Azure Cognitive Services Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Cognitive Services management functions for managing Microsoft Azure Cognitive Services accounts.")]

[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

Revert assembly version and assembly file version back to 0.2.0.0

Revert assembly version and assembly file version back to 0.2.0.0 as
suggested.


using Newtonsoft.Json;

namespace Nest
{
	[JsonObject]
	public class AnalyzeToken
	{
		[JsonProperty(PropertyName = "token")]
		public string Token { get; internal set; }

		[JsonProperty(PropertyName = "type")]
		public string Type { get; internal set; }

		//TODO change to long in 6.0
		[JsonProperty(PropertyName = "start_offset")]
		public int StartOffset { get; internal set; }

		[JsonProperty(PropertyName = "end_offset")]
		public int EndPostion { get; internal set; }

		[JsonProperty(PropertyName = "position")]
		public int Position { get; internal set; }

		[JsonProperty(PropertyName = "position_length")]
		public long? PositionLength { get; internal set; }

	}
}

using System;
using Newtonsoft.Json;

namespace Nest
{
	[JsonObject]
	public class AnalyzeToken
	{
		[JsonProperty("token")]
		public string Token { get; internal set; }

		[JsonProperty("type")]
		public string Type { get; internal set; }

		//TODO change to long in 6.0... RC: (this is int in Elasticsearch codebase)
		[JsonProperty("start_offset")]
		public int StartOffset { get; internal set; }

		[JsonProperty("end_offset")]
		public int EndOffset { get; internal set; }

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

		[JsonProperty("position_length")]
		public long? PositionLength { get; internal set; }
	}
}

Introduce EndOffset to Analyze token

Introduce EndOffset to Analyze token

remove misspelt EndPostion

(cherry picked from commit 5e4e0e5f357edbc5c8cef3630d2f4fb40a9066d6)


using System;
using System.Linq;
using FluentValidation;
using SFA.DAS.CommitmentsV2.Models;

namespace SFA.DAS.CommitmentsV2.Application.Queries.GetApprenticeships
{
    public class GetApprenticeshipsQueryValidator : AbstractValidator<GetApprenticeshipsQuery>
    {
        public GetApprenticeshipsQueryValidator()
        {
            Unless(request => request.EmployerAccountId.HasValue && request.EmployerAccountId.Value > 0, () =>
            {
                RuleFor(request => request.ProviderId)
                    .Must(id => id.HasValue && id.Value > 0)
                    .WithMessage("The provider id must be set");
            });

            Unless(request => request.ProviderId.HasValue && request.ProviderId.Value > 0, () =>
            {
                RuleFor(request => request.EmployerAccountId)
                    .Must(id => id.HasValue && id.Value > 0)
                    .WithMessage("The employer account id must be set");
            });

            When(request => request.ProviderId.HasValue && request.EmployerAccountId.HasValue, () =>
            {
                Unless(request => request.EmployerAccountId.Value == 0, () =>
                {
                    RuleFor(request => request.ProviderId)
                        .Must(id => id.Value == 0)
                        .WithMessage("The provider id must be zero if employer account id is set");
                });

                Unless(request => request.ProviderId.Value == 0, () =>
                {
                    RuleFor(request => request.EmployerAccountId)
                        .Must(id => id.Value == 0)
                        .WithMessage("The employer account id must be zero if provider id is set");
                });
            });

            RuleFor(request => request.SortField)
                .Must(field => string.IsNullOrEmpty(field) ||
                               typeof(Apprenticeship).GetProperties().Select(c => c.Name).Contains(field) ||
                               typeof(Cohort).GetProperties().Select(c => c.Name).Contains(field) ||
                               typeof(AccountLegalEntity).GetProperties().Select(c => c.Name).Contains(field) ||
                               field.Equals("ProviderName", StringComparison.CurrentCultureIgnoreCase))
                .WithMessage("Sort field must be empty or property on Apprenticeship ");
        }
    }
}

using System;
using System.Linq;
using FluentValidation;
using SFA.DAS.CommitmentsV2.Models;

namespace SFA.DAS.CommitmentsV2.Application.Queries.GetApprenticeships
{
    public class GetApprenticeshipsQueryValidator : AbstractValidator<GetApprenticeshipsQuery>
    {
        public GetApprenticeshipsQueryValidator()
        {
            RuleFor(request => request.SortField)
                .Must(field => string.IsNullOrEmpty(field) ||
                               typeof(Apprenticeship).GetProperties().Select(c => c.Name).Contains(field) ||
                               typeof(Cohort).GetProperties().Select(c => c.Name).Contains(field) ||
                               typeof(AccountLegalEntity).GetProperties().Select(c => c.Name).Contains(field) ||
                               field.Equals("ProviderName", StringComparison.CurrentCultureIgnoreCase))
                .WithMessage("Sort field must be empty or property on Apprenticeship ");
        }
    }
}

Remove Restrictions on search endpoint

Remove Restrictions on search endpoint


@model Portal.CMS.Web.Areas.Builder.ViewModels.Container.EditViewModel
@{
    Layout = "";
}

@using (Html.BeginForm("Edit", "Container", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    @Html.HiddenFor(x => x.PageSectionId)
    @Html.HiddenFor(x => x.ContainerElementId)

        <button class="btn primary">Save</button>
        Delete
        <button class="btn" data-dismiss="modal">Cancel</button>

}

@model Portal.CMS.Web.Areas.Builder.ViewModels.Container.EditViewModel
@{
    Layout = "";
}

        Delete
        <button class="btn" data-dismiss="modal">Cancel</button>

Remove form Fields from Container Edit

Remove form Fields from Container Edit


using UnityEngine;
using System.Collections.Generic;

public class PlayerMovement
{
    private const float Gravity = -1.0f;

    public bool IsOnGround { get; set; }

    public Vector3 Update()
    {
        if (IsOnGround)
        {
            return Vector2.zero;
        }
        return new Vector3(0.0f, Gravity);
    }
}

using UnityEngine;
using System.Collections.Generic;

public class PlayerMovement
{
    private const float Gravity = -1.0f;

    public bool IsOnGround { get; set; }

    private Vector3 currentVelocity;

    public Vector3 Update()
    {
        if (IsOnGround)
        {
            return Vector2.zero;
        }
        currentVelocity += new Vector3(0.0f, Gravity);
        return currentVelocity;
    }
}

Test for accelerating whilst falling now passes


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

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle ("Eve.NET.Net4")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CIR 2000")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("nicola")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]

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

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

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

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

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

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle ("Eve.NET.Net4")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CIR 2000")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("nicola")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]

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

[assembly: AssemblyVersion("0.1.0.1")]
[assembly: AssemblyFileVersion("0.1.0.1")]

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

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

Align .NET4 assembly version with main project


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

#nullable disable

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Localisation;

namespace osu.Game.Screens.Edit.Setup
{
    internal class ColoursSection : SetupSection
    {
        public override LocalisableString Title => EditorSetupStrings.ColoursHeader;

        private LabelledColourPalette comboColours;

        [BackgroundDependencyLoader]
        private void load()
        {
            Children = new Drawable[]
            {
                comboColours = new LabelledColourPalette
                {
                    Label = EditorSetupStrings.HitcircleSliderCombos,
                    FixedLabelWidth = LABEL_WIDTH,
                    ColourNamePrefix = EditorSetupStrings.ComboColourPrefix }
            };

            if (Beatmap.BeatmapSkin != null)
                comboColours.Colours.BindTo(Beatmap.BeatmapSkin.ComboColours);
        }
    }
}

Fix code quality for CI

Fix code quality for CI


using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using NUnit.Framework;
using RoslynNUnitLight;
using UnityEngineAnalyzer.Coroutines;

namespace UnityEngineAnalyzer.Test.Coroutines
{
    [TestFixture]
    sealed class DoNotUseCoroutinesAnalyzerTests : AnalyzerTestFixture
    {
        protected override string LanguageName => LanguageNames.CSharp;
        protected override DiagnosticAnalyzer CreateAnalyzer() => new DoNotUseCoroutinesAnalyzer();

        [Test]
        public void StartCoroutineUsedInMonoBehaviourClass()
        {
            const string code = @"
using UnityEngine;

class C : MonoBehaviour
{
    void M()
    {
        [|StartCoroutine("")|];
    }
}";
            Document document;
            TextSpan span;
            TestHelpers.TryGetDocumentAndSpanFromMarkup(code, LanguageName, MetadataReferenceHelper.UsingUnityEngine, out document, out span);

            HasDiagnostic(document, span, DiagnosticIDs.EmptyMonoBehaviourMethod);
        }

        [Test]
        public void StartCoroutineUsedByMonoBehaviourClass()
        {
            const string code = @"
using UnityEngine;

class CC : MonoBehaviour { }

class C : MonoBehaviour
{
    private CC cc;
    void M()
    {
        cc.[|StartCoroutine("")|];
    }
}";
            Document document;
            TextSpan span;
            TestHelpers.TryGetDocumentAndSpanFromMarkup(code, LanguageName, MetadataReferenceHelper.UsingUnityEngine, out document, out span);

            HasDiagnostic(document, span, DiagnosticIDs.EmptyMonoBehaviourMethod);
        }
    }
}

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using NUnit.Framework;
using RoslynNUnitLight;
using UnityEngineAnalyzer.Coroutines;

namespace UnityEngineAnalyzer.Test.Coroutines
{
    [TestFixture]
    sealed class DoNotUseCoroutinesAnalyzerTests : AnalyzerTestFixture
    {
        protected override string LanguageName => LanguageNames.CSharp;
        protected override DiagnosticAnalyzer CreateAnalyzer() => new DoNotUseCoroutinesAnalyzer();

        [Test]
        public void StartCoroutineUsedInMonoBehaviourClass()
        {
            const string code = @"
using UnityEngine;

class C : MonoBehaviour
{
    void M()
    {
        [|StartCoroutine("")|];
    }
}";
            Document document;
            TextSpan span;
            TestHelpers.TryGetDocumentAndSpanFromMarkup(code, LanguageName, MetadataReferenceHelper.UsingUnityEngine, out document, out span);

            HasDiagnostic(document, span, DiagnosticIDs.DoNotUseCoroutines);
        }

        [Test]
        public void StartCoroutineUsedByMonoBehaviourClass()
        {
            const string code = @"
using UnityEngine;

class CC : MonoBehaviour { }

class C : MonoBehaviour
{
    private CC cc;
    void M()
    {
        cc.[|StartCoroutine("")|];
    }
}";
            Document document;
            TextSpan span;
            TestHelpers.TryGetDocumentAndSpanFromMarkup(code, LanguageName, MetadataReferenceHelper.UsingUnityEngine, out document, out span);

            HasDiagnostic(document, span, DiagnosticIDs.DoNotUseCoroutines);
        }
    }
}

Fix wrong id used in DoNotUseCoroutines test


using IdentityModel.Client;
using System;
using System.Collections.Generic;

namespace eShopOnContainers.Core.Services.Identity
{
    public class IdentityService : IIdentityService
    {
        public string CreateAuthorizationRequest()
        {
            // Create URI to authorization endpoint
            var authorizeRequest = new AuthorizeRequest(GlobalSetting.Instance.IdentityEndpoint);

            // Dictionary with values for the authorize request
            var dic = new Dictionary<string, string>();
            dic.Add("client_id", "xamarin");
            dic.Add("client_secret", "secret");
            dic.Add("response_type", "code id_token token");
            dic.Add("scope", "openid profile basket orders offline_access");

            dic.Add("redirect_uri", GlobalSetting.Instance.IdentityCallback);
            dic.Add("nonce", Guid.NewGuid().ToString("N"));

            // Add CSRF token to protect against cross-site request forgery attacks.
            var currentCSRFToken = Guid.NewGuid().ToString("N");
            dic.Add("state", currentCSRFToken);

            var authorizeUri = authorizeRequest.Create(dic);
            return authorizeUri;
        }

        public string CreateLogoutRequest(string token)
        {
            if(string.IsNullOrEmpty(token))
            {
                return string.Empty;
            }

            return string.Format("{0}?id_token_hint={1}&post_logout_redirect_uri={2}",
                GlobalSetting.Instance.LogoutEndpoint,
                token,
                GlobalSetting.Instance.LogoutCallback);
        }
    }
}

using IdentityModel.Client;
using System;
using System.Collections.Generic;

namespace eShopOnContainers.Core.Services.Identity
{
    public class IdentityService : IIdentityService
    {
        public string CreateAuthorizationRequest()
        {
            // Create URI to authorization endpoint
            var authorizeRequest = new AuthorizeRequest(GlobalSetting.Instance.IdentityEndpoint);

            // Dictionary with values for the authorize request
            var dic = new Dictionary<string, string>();
            dic.Add("client_id", "xamarin");
            dic.Add("client_secret", "secret");
            dic.Add("response_type", "code id_token token");
            dic.Add("scope", "openid profile basket orders locations offline_access");

            dic.Add("redirect_uri", GlobalSetting.Instance.IdentityCallback);
            dic.Add("nonce", Guid.NewGuid().ToString("N"));

            // Add CSRF token to protect against cross-site request forgery attacks.
            var currentCSRFToken = Guid.NewGuid().ToString("N");
            dic.Add("state", currentCSRFToken);

            var authorizeUri = authorizeRequest.Create(dic);
            return authorizeUri;
        }

        public string CreateLogoutRequest(string token)
        {
            if(string.IsNullOrEmpty(token))
            {
                return string.Empty;
            }

            return string.Format("{0}?id_token_hint={1}&post_logout_redirect_uri={2}",
                GlobalSetting.Instance.LogoutEndpoint,
                token,
                GlobalSetting.Instance.LogoutCallback);
        }
    }
}

Add locations to allow scopes to dictionary


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

using UnityEngine;

namespace Engine.Game.Actor {

    public class NavMeshAgentFollowController : MonoBehaviour {
        public NavMeshAgent agent;
        public Transform targetFollow;

        // Use this for initialization
        private void Start() {
            agent = GetComponent<NavMeshAgent>();
            NavigateToDestination();
        }

        public void NavigateToDestination() {
            if (agent != null) {
                if (targetFollow != null) {
                    float distance = Vector3.Distance(agent.destination, targetFollow.position);

                    if (distance < 5) {
                        agent.Stop();
                    }
                    else {
                        agent.destination = targetFollow.position;
                    }
                }
            }
        }

        // Update is called once per frame
        private void Update() {
            if (agent != null) {
                if (agent.remainingDistance == 0 || agent.isPathStale) {
                    NavigateToDestination();
                }
            }
        }
    }
}

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

using UnityEngine;

namespace Engine.Game.Actor {

    public class NavMeshAgentFollowController : MonoBehaviour {
        public NavMeshAgent agent;
        public Transform targetFollow;

        // Use this for initialization
        private void Start() {
            agent = GetComponent<NavMeshAgent>();
            NavigateToDestination();
        }

        public void NavigateToDestination() {
            if (agent != null) {
                if (targetFollow != null) {
                    float distance = Vector3.Distance(agent.destination, targetFollow.position);

                    if (distance < 5) {
                        agent.Stop();
                    }
                    else {
                        agent.destination = targetFollow.position;
                    }
                }
            }
        }

        // Update is called once per frame
        private void Update() {

            if(!GameConfigs.isGameRunning) {

                if (agent != null) {
                   agent.Stop();
                }
                return;
            }

            if (agent != null) {
                if (agent.remainingDistance == 0 || agent.isPathStale) {
                    NavigateToDestination();
                }
            }
        }
    }
}

Update ai/navmesh agents to stop pursuing during content display state.


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

namespace MediaManager
{
    public abstract class NotificationManagerBase : INotificationManager
    {
        protected NotificationManagerBase()
        {
            Enabled = true;
        }

        private bool _enabled = true;
        private bool _showPlayPauseControls = true;
        private bool _showNavigationControls = true;

        public virtual bool Enabled
        {
            get => _enabled;
            set
            {
                _enabled = value;
                UpdateNotification();
            }
        }

        public virtual bool ShowPlayPauseControls
        {
            get => _showPlayPauseControls;
            set
            {
                _showPlayPauseControls = value;
                UpdateNotification();
            }
        }

        public virtual bool ShowNavigationControls
        {
            get => _showNavigationControls;
            set
            {
                _showNavigationControls = value;
                UpdateNotification();
            }
        }

        public abstract void UpdateNotification();
    }
}

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

namespace MediaManager
{
    public abstract class NotificationManagerBase : INotificationManager
    {
        protected NotificationManagerBase()
        {
            Enabled = true;
            ShowPlayPauseControls = true;
            ShowNavigationControls = true;
        }

        private bool _enabled;
        private bool _showPlayPauseControls;
        private bool _showNavigationControls;

        public virtual bool Enabled
        {
            get => _enabled;
            set
            {
                _enabled = value;
                UpdateNotification();
            }
        }

        public virtual bool ShowPlayPauseControls
        {
            get => _showPlayPauseControls;
            set
            {
                _showPlayPauseControls = value;
                UpdateNotification();
            }
        }

        public virtual bool ShowNavigationControls
        {
            get => _showNavigationControls;
            set
            {
                _showNavigationControls = value;
                UpdateNotification();
            }
        }

        public abstract void UpdateNotification();
    }
}

Call ShowPlayPauseControls and ShowNavigationControls setters in base constructor


using LearnWordsFast.API.Exceptions;
using LearnWordsFast.API.Services;
using LearnWordsFast.API.ViewModels.TrainingController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace LearnWordsFast.API.Controllers
{
    [Route("api/Training")]
    [Authorize]
    public class TrainingController : ApiController
    {
        private readonly ITrainingService _trainingService;
        private readonly ILogger<TrainingController> _log;

        public TrainingController(
            ITrainingService trainingService,
            ILogger<TrainingController> log)
        {
            _trainingService = trainingService;
            _log = log;
        }

        [HttpGet]
        public IActionResult Get()
        {
            _log.LogInformation("Get next training");
            var training = _trainingService.CreateTraining(UserId);
            if (training == null)
            {
                return NotFound();
            }

            return Ok(training);
        }

        [HttpPost]
        public IActionResult Finish([FromBody]TrainingResultViewModel[] results)
        {
            _log.LogInformation("Finish training");
            foreach (var result in results)
            {
                try
                {
                    _trainingService.FinishTraining(UserId, result);
                }
                catch (NotFoundException)
                {
                    return NotFound(result.WordId);
                }
            }

            return Ok();
        }
    }
}

using LearnWordsFast.API.Exceptions;
using LearnWordsFast.API.Services;
using LearnWordsFast.API.ViewModels.TrainingController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace LearnWordsFast.API.Controllers
{
    [Route("api/Training")]
    [Authorize("Bearer")]
    public class TrainingController : ApiController
    {
        private readonly ITrainingService _trainingService;
        private readonly ILogger<TrainingController> _log;

        public TrainingController(
            ITrainingService trainingService,
            ILogger<TrainingController> log)
        {
            _trainingService = trainingService;
            _log = log;
        }

        [HttpGet]
        public IActionResult Get()
        {
            _log.LogInformation("Get next training");
            var training = _trainingService.CreateTraining(UserId);
            if (training == null)
            {
                return NotFound();
            }

            return Ok(training);
        }

        [HttpPost]
        public IActionResult Finish([FromBody]TrainingResultViewModel[] results)
        {
            _log.LogInformation("Finish training");
            foreach (var result in results)
            {
                try
                {
                    _trainingService.FinishTraining(UserId, result);
                }
                catch (NotFoundException)
                {
                    return NotFound(result.WordId);
                }
            }

            return Ok();
        }
    }
}

Update Authorize attribute to use Bearer policy


using System;
using System.Collections.Generic;

namespace WinRSJS
{
    public sealed class Collections
    {
        static public object /* IMap<?, ?> */ createMap(string keyTypeName, string valTypeName)
        {
            Type typeKey = Type.GetType(keyTypeName);
            if (typeKey == null)
            {
                throw new ArgumentException("Key type name `" + keyTypeName + "` is invalid.");
            }

            Type typeVal = Type.GetType(valTypeName);
            if (typeVal == null)
            {
                throw new ArgumentException("Value type name `" + valTypeName + "` is invalid.");
            }

            Type typeDict = typeof(Dictionary<,>).MakeGenericType(new Type[] { typeKey, typeVal });
            return Activator.CreateInstance(typeDict);
        }
    }
}

using System;
using System.Collections.Generic;

namespace WinRSJS
{
    public sealed class Collections
    {
        static public object /* IMap<?, ?> */ CreateMap(string keyTypeName, string valTypeName)
        {
            Type typeKey = Type.GetType(keyTypeName);
            if (typeKey == null)
            {
                throw new ArgumentException("Key type name `" + keyTypeName + "` is invalid.");
            }

            Type typeVal = Type.GetType(valTypeName);
            if (typeVal == null)
            {
                throw new ArgumentException("Value type name `" + valTypeName + "` is invalid.");
            }

            Type typeDict = typeof(Dictionary<,>).MakeGenericType(new Type[] { typeKey, typeVal });
            return Activator.CreateInstance(typeDict);
        }
    }
}

Use Pascal casing for method name

Use Pascal casing for method name


using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using NuGetPackageExplorer.Types;

namespace PackageExplorer {
    [PackageContentViewerMetadata(99, ".jpg", ".gif", ".png", ".tif")]
    internal class ImageFileViewer : IPackageContentViewer {
        public object GetView(string extension, Stream stream) {
            var source = new BitmapImage();
            source.BeginInit();
            source.CacheOption = BitmapCacheOption.OnLoad;
            source.StreamSource = stream;
            source.EndInit();

            return new Image {
                Source = source,
                Width = source.Width,
                Height = source.Height
            };
        }
    }
}

using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using NuGetPackageExplorer.Types;

namespace PackageExplorer {
    [PackageContentViewerMetadata(99, ".jpg", ".gif", ".png", ".tif", ".bmp", ".ico")]
    internal class ImageFileViewer : IPackageContentViewer {
        public object GetView(string extension, Stream stream) {
            var source = new BitmapImage();
            source.BeginInit();
            source.CacheOption = BitmapCacheOption.OnLoad;
            source.StreamSource = stream;
            source.EndInit();

            return new Image {
                Source = source,
                Width = source.Width,
                Height = source.Height
            };
        }
    }
}

Add more supported image extensions to the image viewer plugin.


using AnimalHope.Web.Infrastructure.Mapping;
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 AnimalHope.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AutoMapperConfig.Execute();

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

using AnimalHope.Web.Infrastructure.Mapping;
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 AnimalHope.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            AutoMapperConfig.Execute();

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Clear all view engines and add only Razor view engine (performance)


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

namespace Archaius
{
    public class EnvironmentConfiguration : DictionaryConfiguration
    {
        public EnvironmentConfiguration()
            : base(GetEnvironmentVariables())
        {
        }

        public override void AddProperty(string key, object value)
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        public override void SetProperty(string key, object value)
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        public override void ClearProperty(string key)
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        public override void Clear()
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        private static IDictionary<string, object> GetEnvironmentVariables()
        {
            return Environment.GetEnvironmentVariables()
                    .Cast<DictionaryEntry>()
                    .ToDictionary(variable => (string)variable.Key, variable => variable.Value);
        }
    }
}

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

namespace Archaius
{
    public class EnvironmentConfiguration : DictionaryConfiguration
    {
        public EnvironmentConfiguration()
            : base(GetEnvironmentVariables())
        {
        }

        public override void AddProperty(string key, object value)
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        public override void SetProperty(string key, object value)
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        public override void ClearProperty(string key)
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        public override void Clear()
        {
            throw new NotSupportedException("EnvironmentConfiguration is readonly.");
        }

        private static IDictionary<string, object> GetEnvironmentVariables()
        {
            var variables = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)
                                       .Cast<DictionaryEntry>()
                                       .ToDictionary(variable => (string)variable.Key, variable => variable.Value);
            foreach (DictionaryEntry userVariable in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User))
            {
                if (!variables.ContainsKey((string)userVariable.Key))
                {
                    variables.Add((string)userVariable.Key, userVariable.Value);
                }
            }
            foreach (DictionaryEntry machineVariable in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine))
            {
                if (!variables.ContainsKey((string)machineVariable.Key))
                {
                    variables.Add((string)machineVariable.Key, machineVariable.Value);
                }
            }
            return variables;
        }
    }
}

Load environment variables from different targets to support ASP.Net applications.


// 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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Skinning.Legacy;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;

namespace osu.Game.Rulesets.Catch.Tests
{
    [TestFixture]
    public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
    {
        [Test]
        public void TestUsingLegacySkin()
        {
            // check for the existence of a random legacy component to ensure using legacy skin.
            // this should exist in LegacySkinPlayerTestScene but the weird transformer logic below needs to be "fixed" or otherwise first.
            AddAssert("using legacy skin", () => this.ChildrenOfType<LegacyScoreCounter>().Any());
        }

        protected override Ruleset CreatePlayerRuleset() => new TestCatchRuleset();

        private class TestCatchRuleset : CatchRuleset
        {
            public override ISkin CreateLegacySkinProvider(ISkinSource source, IBeatmap beatmap) => new TestCatchLegacySkinTransformer(source);
        }

        private class TestCatchLegacySkinTransformer : CatchLegacySkinTransformer
        {
            public TestCatchLegacySkinTransformer(ISkinSource source)
                : base(source)
            {
            }

            public override Drawable GetDrawableComponent(ISkinComponent component)
            {
                var drawable = base.GetDrawableComponent(component);
                if (drawable != null)
                    return drawable;

                // it shouldn't really matter whether to return null or return this,
                // but returning null skips over the beatmap skin, so this needs to exist to test things properly.
                return Source.GetDrawableComponent(component);
            }
        }
    }
}

// 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.Game.Tests.Visual;

namespace osu.Game.Rulesets.Catch.Tests
{
    [TestFixture]
    public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
    {
        protected override Ruleset CreatePlayerRuleset() => new CatchRuleset();
    }
}

Revert "Add failing test case"

Revert "Add failing test case"

This reverts commit ec89a149dd752d242e1675a4462c8af4e360eb3e.


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

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

namespace osu.Game.Rulesets.Catch.UI
{
    public class CatchPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
    {
        protected override Container<Drawable> Content => content;
        private readonly Container content;

        public CatchPlayfieldAdjustmentContainer()
        {
            Anchor = Anchor.TopCentre;
            Origin = Anchor.TopCentre;

            Size = new Vector2(0.86f); // matches stable's vertical offset for catcher plate

            InternalChild = new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                RelativeSizeAxes = Axes.Both,
                FillMode = FillMode.Fit,
                FillAspectRatio = 4f / 3,
                Child = content = new ScalingContainer { RelativeSizeAxes = Axes.Both }
            };
        }

        /// <summary>
        /// A <see cref="Container"/> which scales its content relative to a target width.
        /// </summary>
        private class ScalingContainer : Container
        {
            protected override void Update()
            {
                base.Update();

                Scale = new Vector2(Parent.ChildSize.X / CatchPlayfield.WIDTH);
                Size = Vector2.Divide(Vector2.One, Scale);
            }
        }
    }
}

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

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

namespace osu.Game.Rulesets.Catch.UI
{
    public class CatchPlayfieldAdjustmentContainer : PlayfieldAdjustmentContainer
    {
        private const float playfield_size_adjust = 0.8f;

        protected override Container<Drawable> Content => content;
        private readonly Container content;

        public CatchPlayfieldAdjustmentContainer()
        {
            Anchor = Anchor.TopCentre;
            Origin = Anchor.TopCentre;

            Size = new Vector2(playfield_size_adjust);

            InternalChild = new Container
            {
                Anchor = Anchor.Centre,
                Origin = Anchor.Centre,
                RelativeSizeAxes = Axes.Both,
                FillMode = FillMode.Fit,
                FillAspectRatio = 4f / 3,
                Child = content = new ScalingContainer { RelativeSizeAxes = Axes.Both }
            };
        }

        /// <summary>
        /// A <see cref="Container"/> which scales its content relative to a target width.
        /// </summary>
        private class ScalingContainer : Container
        {
            protected override void Update()
            {
                base.Update();

                Scale = new Vector2(Parent.ChildSize.X / CatchPlayfield.WIDTH);
                Size = Vector2.Divide(Vector2.One, Scale);
            }
        }
    }
}

Use correct width adjust for osu!catch playfield


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGameUtils.Drawing
{
    /// <summary>
    /// Various useful utility methods that don't obviously go elsewhere.
    /// </summary>
    public static class Utilities
    {
        /// <summary>
        /// Draw the provided model in the world, given the provided matrices.
        /// </summary>
        /// <param name="model">The model to draw.</param>
        /// <param name="world">The world matrix that the model should be drawn in.</param>
        /// <param name="view">The view matrix that the model should be drawn in.</param>
        /// <param name="projection">The projection matrix that the model should be drawn in.</param>
       public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
        {
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = world;
                    effect.View = view;
                    effect.Projection = projection;
                }

                mesh.Draw();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGameUtils.Drawing
{
    /// <summary>
    /// Various useful utility methods that don't obviously go elsewhere.
    /// </summary>
    public static class Utilities
    {
        /// <summary>
        /// Draw the provided model in the world, given the provided matrices.
        /// </summary>
        /// <param name="model">The model to draw.</param>
        /// <param name="world">The world matrix that the model should be drawn in.</param>
        /// <param name="view">The view matrix that the model should be drawn in.</param>
        /// <param name="projection">The projection matrix that the model should be drawn in.</param>
       public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
        {
           Contract.Requires(model != null);
           Contract.Requires(world != null);
           Contract.Requires(view != null);
           Contract.Requires(projection != null);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = world;
                    effect.View = view;
                    effect.Projection = projection;
                }

                mesh.Draw();
            }
        }
    }
}

Add contracts to verifty the DrawModel() method doesn't receive null data.


using System.Collections.Generic;
using LinqToTTreeInterfacesLib;
namespace LINQToTTreeLib.Statements
{
    /// <summary>
    /// Sits inside a loop and records the integer that it is given on each call by pushing it onto a vector. It *does not*
    /// check for uniqueness.
    /// </summary>
    class StatementRecordIndicies : IStatement
    {
        private LinqToTTreeInterfacesLib.IValue iValue;
        private Variables.VarArray arrayRecord;

        /// <summary>
        /// Create a statement that will record this index into this array each time through.
        /// </summary>
        /// <param name="iValue"></param>
        /// <param name="arrayRecord"></param>
        public StatementRecordIndicies(IValue iValue, Variables.VarArray arrayRecord)
        {
            // TODO: Complete member initialization
            this.iValue = iValue;
            this.arrayRecord = arrayRecord;
        }

        /// <summary>
        /// Returns a IValue that represents
        /// </summary>
        public IValue HolderArray { get; private set; }

        /// <summary>
        /// Return the code for this statement.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> CodeItUp()
        {
            yield return string.Format("{0}.push_back({1});", arrayRecord.RawValue, iValue.RawValue);
        }
    }
}

using System.Collections.Generic;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Variables;
namespace LINQToTTreeLib.Statements
{
    /// <summary>
    /// Sits inside a loop and records the integer that it is given on each call by pushing it onto a vector. It *does not*
    /// check for uniqueness of that integer that is pushed on - this is pretty simple. The vector it is pushing onto should
    /// be declared at an outter level to be of any use. :-)
    /// </summary>
    class StatementRecordIndicies : IStatement
    {
        /// <summary>
        /// The integer to record
        /// </summary>
        private IValue _intToRecord;

        /// <summary>
        /// The array to be storing things in
        /// </summary>
        private Variables.VarArray _storageArray;

        /// <summary>
        /// Create a statement that will record this index into this array each time through.
        /// </summary>
        /// <param name="intToRecord">Integer that should be cached on each time through</param>
        /// <param name="storageArray">The array where the indicies should be written</param>
        public StatementRecordIndicies(IValue intToRecord, VarArray storageArray)
        {
            _intToRecord = intToRecord;
            _storageArray = storageArray;
        }

        /// <summary>
        /// Returns a IValue that represents
        /// </summary>
        public IValue HolderArray { get; private set; }

        /// <summary>
        /// Return the code for this statement.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> CodeItUp()
        {
            yield return string.Format("{0}.push_back({1});", _storageArray.RawValue, _intToRecord.RawValue);
        }
    }
}

Clean up and add comments

Clean up and add comments


using Android.Widget;
using FFImageLoading.Work;

namespace FFImageLoading.Extensions
{
	public static class ImageViewExtensions
	{
		/// <summary>
		/// Retrieve the currently active work task (if any) associated with this imageView.
		/// </summary>
		/// <param name="imageView"></param>
		/// <returns></returns>
		public static ImageLoaderTask GetImageLoaderTask(this ImageView imageView)
		{
			if (imageView == null)
				return null;

			var drawable = imageView.Drawable;

			var asyncDrawable = drawable as AsyncDrawable;
			if (asyncDrawable != null)
			{
				return asyncDrawable.GetImageLoaderTask();
			}

			return null;
		}
	}
}

using Android.Widget;
using FFImageLoading.Work;
using System;

namespace FFImageLoading.Extensions
{
	public static class ImageViewExtensions
	{
		/// <summary>
		/// Retrieve the currently active work task (if any) associated with this imageView.
		/// </summary>
		/// <param name="imageView"></param>
		/// <returns></returns>
		public static ImageLoaderTask GetImageLoaderTask(this ImageView imageView)
		{
			if (imageView == null || imageView.Handle == IntPtr.Zero)
				return null;

			var drawable = imageView.Drawable;

			var asyncDrawable = drawable as AsyncDrawable;
			if (asyncDrawable != null)
			{
				return asyncDrawable.GetImageLoaderTask();
			}

			return null;
		}
	}
}

Check validity if the ImageView before trying to access its Drawable


using System.IO;
using System.Reflection;
using Cake.Core;
using Cake.Core.Annotations;
using Nerdbank.GitVersioning;

namespace Cake.GitVersioning
{
    /// <summary>
    /// Contains functionality for using Nerdbank.GitVersioning.
    /// </summary>
    [CakeAliasCategory("Git Versioning")]
    public static class GitVersioningAliases
    {
        /// <summary>
        /// Gets the Git Versioning version from the current repo.
        /// </summary>
        /// <example>
        /// Task("GetVersion")
        ///     .Does(() =>
        /// {
        ///     Information(GetVersioningGetVersion().SemVer2)
        /// });
        /// </example>
        /// <param name="context">The context.</param>
        /// <param name="projectDirectory">Directory to start the search for version.json.</param>
        /// <returns>The version information from Git Versioning.</returns>
        [CakeMethodAlias]
        public static VersionOracle GitVersioningGetVersion(this ICakeContext context, string projectDirectory = ".")
        {
            GitExtensions.HelpFindLibGit2NativeBinaries(Path.GetDirectoryName(Assembly.GetAssembly(typeof(GitVersioningAliases)).Location));

            return VersionOracle.Create(projectDirectory, null, CloudBuild.Active);
        }
    }
}

using System.IO;
using System.Reflection;
using Cake.Core;
using Cake.Core.Annotations;
using Nerdbank.GitVersioning;

namespace Cake.GitVersioning
{
    /// <summary>
    /// Contains functionality for using Nerdbank.GitVersioning.
    /// </summary>
    [CakeAliasCategory("Git Versioning")]
    public static class GitVersioningAliases
    {
        /// <summary>
        /// Gets the Git Versioning version from the current repo.
        /// </summary>
        /// <example>
        /// Task("GetVersion")
        ///     .Does(() =>
        /// {
        ///     Information(GetVersioningGetVersion().SemVer2)
        /// });
        /// </example>
        /// <param name="context">The context.</param>
        /// <param name="projectDirectory">Directory to start the search for version.json.</param>
        /// <returns>The version information from Git Versioning.</returns>
        [CakeMethodAlias]
        public static VersionOracle GitVersioningGetVersion(this ICakeContext context, string projectDirectory = ".")
        {
            var fullProjectDirectory = (new DirectoryInfo(projectDirectory)).FullName;

            GitExtensions.HelpFindLibGit2NativeBinaries(Path.GetDirectoryName(Assembly.GetAssembly(typeof(GitVersioningAliases)).Location));

            return VersionOracle.Create(fullProjectDirectory, null, CloudBuild.Active);
        }
    }
}

Convert relative path into full path

Convert relative path into full path


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

namespace Umbraco.Web.Models.ContentEditing
{
    [DataContract(Name = "propertyGroup", Namespace = "")]
    public class PropertyGroupDisplay
    {
        public PropertyGroupDisplay()
        {
            Properties = new List<PropertyTypeDisplay>();
        }

        [DataMember(Name = "id")]
        public int Id { get; set; }

        [DataMember(Name = "parentGroupId")]
        public int ParentGroupId { get; set; }

        [DataMember(Name = "sortOrder")]
        public int SortOrder { get; set; }

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

        [DataMember(Name = "properties")]
        public IEnumerable<PropertyTypeDisplay> Properties { get; set; }

        //Indicate if this tab was inherited
        [DataMember(Name = "inherited")]
        public bool Inherited { get; set; }

        [DataMember(Name = "contentTypeId")]
        public int ContentTypeId { get; set; }

        [DataMember(Name = "parentTabContentTypes")]
        public IEnumerable<int> ParentTabContentTypes { get; set; }

        [DataMember(Name = "parentTabContentTypeNames")]
        public IEnumerable<string> ParentTabContentTypeNames { get; set; }
    }
}

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

namespace Umbraco.Web.Models.ContentEditing
{
    [DataContract(Name = "propertyGroup", Namespace = "")]
    public class PropertyGroupDisplay
    {
        public PropertyGroupDisplay()
        {
            Properties = new List<PropertyTypeDisplay>();
            ParentTabContentTypeNames = new List<string>();
            ParentTabContentTypes = new List<int>();
        }

        [DataMember(Name = "id")]
        public int Id { get; set; }

        [DataMember(Name = "parentGroupId")]
        public int ParentGroupId { get; set; }

        [DataMember(Name = "sortOrder")]
        public int SortOrder { get; set; }

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

        [DataMember(Name = "properties")]
        public IEnumerable<PropertyTypeDisplay> Properties { get; set; }

        //Indicate if this tab was inherited
        [DataMember(Name = "inherited")]
        public bool Inherited { get; set; }

        [DataMember(Name = "contentTypeId")]
        public int ContentTypeId { get; set; }

        [DataMember(Name = "parentTabContentTypes")]
        public IEnumerable<int> ParentTabContentTypes { get; set; }

        [DataMember(Name = "parentTabContentTypeNames")]
        public IEnumerable<string> ParentTabContentTypeNames { get; set; }
    }
}

Set collections on property groups

Set collections on property groups


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

#nullable disable

using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;

namespace osu.Game.Graphics.Containers
{
    public abstract class OsuRearrangeableListContainer<TModel> : RearrangeableListContainer<TModel>
    {
        /// <summary>
        /// Whether any item is currently being dragged. Used to hide other items' drag handles.
        /// </summary>
        protected readonly BindableBool DragActive = new BindableBool();

        protected override ScrollContainer<Drawable> CreateScrollContainer() => new OsuScrollContainer();

        protected sealed override RearrangeableListItem<TModel> CreateDrawable(TModel item) => CreateOsuDrawable(item).With(d =>
        {
            d.DragActive.BindTo(DragActive);
        });

        protected abstract OsuRearrangeableListItem<TModel> CreateOsuDrawable(TModel item);
    }
}

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

#nullable disable

using System.Collections.Specialized;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;

namespace osu.Game.Graphics.Containers
{
    public abstract class OsuRearrangeableListContainer<TModel> : RearrangeableListContainer<TModel>
    {
        /// <summary>
        /// Whether any item is currently being dragged. Used to hide other items' drag handles.
        /// </summary>
        protected readonly BindableBool DragActive = new BindableBool();

        protected override ScrollContainer<Drawable> CreateScrollContainer() => new OsuScrollContainer();

        private Sample sampleSwap;
        private double sampleLastPlaybackTime;

        protected sealed override RearrangeableListItem<TModel> CreateDrawable(TModel item) => CreateOsuDrawable(item).With(d =>
        {
            d.DragActive.BindTo(DragActive);
        });

        protected abstract OsuRearrangeableListItem<TModel> CreateOsuDrawable(TModel item);

        protected OsuRearrangeableListContainer()
        {
            Items.CollectionChanged += (_, args) =>
            {
                if (args.Action == NotifyCollectionChangedAction.Move)
                    playSwapSample();
            };
        }

        private void playSwapSample()
        {
            if (Time.Current - sampleLastPlaybackTime <= 35)
                return;

            var channel = sampleSwap?.GetChannel();
            if (channel == null)
                return;

            channel.Frequency.Value = 0.96 + RNG.NextDouble(0.08);
            channel.Play();
            sampleLastPlaybackTime = Time.Current;
        }

        [BackgroundDependencyLoader]
        private void load(AudioManager audio)
        {
            sampleSwap = audio.Samples.Get(@"UI/item-swap");
            sampleLastPlaybackTime = Time.Current;
        }
    }
}

Add audio feedback for rearranging list items


using Microsoft.Xunit.Performance;
using Xunit;

namespace DNXLibrary
{
    // This project can output the Class library as a NuGet Package.
    // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
    public class DNXSampleTests
    {
        [Fact]
        public void AlwaysPass()
        {
            Assert.True(true);
        }

        [Fact]
        public void AlwaysFail()
        {
            Assert.True(false);
        }

        [Benchmark]
        public void Benchmark1()
        {
        }

        [Benchmark]
        [InlineData(1)]
        [InlineData(2)]
        [InlineData(3)]
        public void Benchmark2(int x)
        {
        }
    }
}

using Microsoft.Xunit.Performance;
using Xunit;

namespace DNXLibrary
{
    // This project can output the Class library as a NuGet Package.
    // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
    public class DNXSampleTests
    {
        [Fact]
        public void AlwaysPass()
        {
            Assert.True(true);
        }

        [Fact]
        public void AlwaysFail()
        {
            Assert.True(false);
        }

        [Benchmark]
        public void Benchmark1()
        {
            Benchmark.Iterate(() => { });
        }

        [Benchmark]
        [InlineData(1)]
        [InlineData(2)]
        [InlineData(3)]
        public void Benchmark2(int x)
        {
            Benchmark.Iterate(() => { });
        }
    }
}

Update benchmarks to new format

Update benchmarks to new format


@model JoinRpg.DataModel.MarkdownString
@{
  var requiredMsg = new MvcHtmlString("");
    var validation = false;
  foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
  {
      if (attr.Key == "data-val-required")
      {
          requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
          validation = true;
      }
  }
}

    Можно использовать MarkDown (**полужирный**, _курсив_)

    <textarea
        class="form-control"
        cols="100"
        id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents"
        name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents"
        @requiredMsg @(validation ? "data-val=true" : "")
        rows="4">@(Model == null ? "" : Model.Contents)</textarea>

@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}

Make Markdown help open in another window


// WhistTest.cs
// <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright>
using System;
using CardGames.Whist;

namespace ConsoleTesting
{
    /// <summary>
    /// The whist test class
    /// </summary>
    public class WhistTest : IGameTest
    {
        /// <summary>
        /// Run the test
        /// </summary>
        public void RunTest()
        {
            Whist whist = new Whist();

            ConsolePlayer p1 = new ConsolePlayer();
            ConsolePlayer p2 = new ConsolePlayer();
            ConsolePlayer p3 = new ConsolePlayer();

            whist.AddPlayer(p1);
            whist.AddPlayer(p2);
            whist.AddPlayer(p3);

            whist.Start();
        }

        public void RunWithAi()
        {
            Console.WriteLine("Es gibt kein AI");
        }
    }
}

// WhistTest.cs
// <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright>
using System;
using CardGames.Whist;

namespace ConsoleTesting
{
    /// <summary>
    /// The whist test class
    /// </summary>
    public class WhistTest : IGameTest
    {
        /// <summary>
        /// Run the test
        /// </summary>
        public void RunTest()
        {
            Whist whist = new Whist();

            ConsolePlayer p1 = new ConsolePlayer();
            ConsolePlayer p2 = new ConsolePlayer();
            ConsolePlayer p3 = new ConsolePlayer();

            whist.AddPlayer(p1);
            whist.AddPlayer(p2);
            whist.AddPlayer(p3);

            whist.Start();
        }

        public void RunWithAi()
        {
            Console.WriteLine("Es gibt kein AI");
            Console.WriteLine("There is no AI")
        }
    }
}

Add english as well as german

Add english as well as german


using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            var searchText = SearchText;
            SearchText = string.Empty;
            try
            {
                Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");
            }
            catch
            {
                // ignored
            }
            if (Settings.HideOnSearch)
                _id.GetView()?.HideUI();
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;

namespace DesktopWidgets.Widgets.Search
{
    public class ViewModel : WidgetViewModelBase
    {
        private string _searchText;

        public ViewModel(WidgetId id) : base(id)
        {
            Settings = id.GetSettings() as Settings;
            if (Settings == null)
                return;
            Go = new RelayCommand(GoExecute);
            OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
        }

        public Settings Settings { get; }

        public ICommand Go { get; set; }
        public ICommand OnKeyUp { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    RaisePropertyChanged(nameof(SearchText));
                }
            }
        }

        private void GoExecute()
        {
            var searchText = SearchText;
            SearchText = string.Empty;
            Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");
            if (Settings.HideOnSearch)
                _id.GetView()?.HideUI();
        }

        private void OnKeyUpExecute(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                GoExecute();
        }
    }
}

Fix "Search" widget ignoring search errors


// 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.IO.Stores;
using osu.Game.Rulesets;
using osu.Game.Skinning;

namespace osu.Game.Tests.Visual
{
    [TestFixture]
    public abstract class LegacySkinPlayerTestScene : PlayerTestScene
    {
        protected LegacySkin LegacySkin { get; private set; }

        private ISkinSource legacySkinSource;

        protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource);

        [BackgroundDependencyLoader]
        private void load(OsuGameBase game, SkinManager skins)
        {
            LegacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins);
            legacySkinSource = new SkinProvidingContainer(LegacySkin);
        }

        public class SkinProvidingPlayer : TestPlayer
        {
            [Cached(typeof(ISkinSource))]
            private readonly ISkinSource skinSource;

            public SkinProvidingPlayer(ISkinSource skinSource)
            {
                this.skinSource = skinSource;
            }
        }
    }
}

// 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.Extensions.IEnumerableExtensions;
using osu.Framework.IO.Stores;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Skinning;

namespace osu.Game.Tests.Visual
{
    [TestFixture]
    public abstract class LegacySkinPlayerTestScene : PlayerTestScene
    {
        protected LegacySkin LegacySkin { get; private set; }

        private ISkinSource legacySkinSource;

        protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource);

        [BackgroundDependencyLoader]
        private void load(OsuGameBase game, SkinManager skins)
        {
            LegacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins);
            legacySkinSource = new SkinProvidingContainer(LegacySkin);
        }

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

        [TearDownSteps]
        public override void TearDownSteps()
        {
            addResetTargetsStep();
            base.TearDownSteps();
        }

        private void addResetTargetsStep()
        {
            AddStep("reset targets", () => this.ChildrenOfType<SkinnableTargetContainer>().ForEach(t =>
            {
                LegacySkin.ResetDrawableTarget(t);
                t.Reload();
            }));
        }

        public class SkinProvidingPlayer : TestPlayer
        {
            [Cached(typeof(ISkinSource))]
            private readonly ISkinSource skinSource;

            public SkinProvidingPlayer(ISkinSource skinSource)
            {
                this.skinSource = skinSource;
            }
        }
    }
}

Add skin traget resetting on setup/teardown steps


namespace pinboard.net.Models
{
    public class LastUpdate
    {
    }
}

using Newtonsoft.Json;
using System;

namespace pinboard.net.Models
{
    public class LastUpdate
    {
        [JsonProperty("update_time")]
        public DateTimeOffset UpdateTime { get; set; }
    }
}

Implement last update model, had forgotten, hehe


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

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

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

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

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

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

Align assembly version with package version


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

using osu.Framework.Bindables;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using System.Linq;
using osu.Framework.Allocation;

namespace osu.Game.Overlays.BeatmapSet
{
    public class BeatmapRulesetSelector : OverlayRulesetSelector
    {
        protected override bool SelectInitialRuleset => false;

        private readonly Bindable<BeatmapSetInfo> beatmapSet = new Bindable<BeatmapSetInfo>();

        public BeatmapSetInfo BeatmapSet
        {
            get => beatmapSet.Value;
            set
            {
                // propagate value to tab items first to enable only available rulesets.
                beatmapSet.Value = value;

                SelectTab(TabContainer.TabItems.FirstOrDefault(t => t.Enabled.Value));
            }
        }

        protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new BeatmapRulesetTabItem(value)
        {
            BeatmapSet = { BindTarget = beatmapSet }
        };
    }
}

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

using osu.Framework.Bindables;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using System.Linq;

namespace osu.Game.Overlays.BeatmapSet
{
    public class BeatmapRulesetSelector : OverlayRulesetSelector
    {
        protected override bool SelectInitialRuleset => false;

        private readonly Bindable<BeatmapSetInfo> beatmapSet = new Bindable<BeatmapSetInfo>();

        public BeatmapSetInfo BeatmapSet
        {
            get => beatmapSet.Value;
            set
            {
                // propagate value to tab items first to enable only available rulesets.
                beatmapSet.Value = value;

                SelectTab(TabContainer.TabItems.FirstOrDefault(t => t.Enabled.Value));
            }
        }

        protected override TabItem<RulesetInfo> CreateTabItem(RulesetInfo value) => new BeatmapRulesetTabItem(value)
        {
            BeatmapSet = { BindTarget = beatmapSet }
        };
    }
}

Remove unused using embedded in reverted changes