Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add room name to settings
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Game.Online.API; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings> { public int? BeatmapID { get; set; } public int? RulesetID { get; set; } [NotNull] public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>(); public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID; public override string ToString() => $"Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using osu.Game.Online.API; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings> { public int? BeatmapID { get; set; } public int? RulesetID { get; set; } public string Name { get; set; } = "Unnamed room"; [NotNull] public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>(); public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal); public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}"; } }
Add missing bootstrap reference (after removing bootswatch)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Calendar Proxy</title> <link href="~/Content/iCalStyles.min.css" rel="stylesheet" /> <link href="~/Content/timer.min.css" rel="stylesheet" /> <link href="~/Content/calendar-proxy-form.css" rel="stylesheet" /> <link href="~/Content/texteffects.min.css" rel="stylesheet" /> </head> <body> <div class="navbar fixed-top navbar-dark bg-primary"> <div class="container"> <div class="navbar-header"> @Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> </div> </div> <div class="body-content"> <div class="container"> @RenderBody() </div> </div> <script src="~/Scripts/ical.min.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <script src="~/Scripts/icalrender.min.js"></script> <script src="~/Scripts/calendar-proxy-form.min.js"></script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Calendar Proxy</title> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/iCalStyles.min.css" rel="stylesheet" /> <link href="~/Content/timer.min.css" rel="stylesheet" /> <link href="~/Content/calendar-proxy-form.css" rel="stylesheet" /> <link href="~/Content/texteffects.min.css" rel="stylesheet" /> </head> <body> <div class="navbar fixed-top navbar-dark bg-primary"> <div class="container"> <div class="navbar-header"> @Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> </div> </div> <div class="body-content"> <div class="container"> @RenderBody() </div> </div> <script src="~/Scripts/ical.min.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <script src="~/Scripts/icalrender.min.js"></script> <script src="~/Scripts/calendar-proxy-form.min.js"></script> </body> </html>
Add Cygwin path replacement for Rename/Override
namespace OmniSharp.Rename { public class ModifiedFileResponse { public ModifiedFileResponse() {} public ModifiedFileResponse(string fileName, string buffer) { this.FileName = fileName; this.Buffer = buffer; } public string FileName { get; set; } public string Buffer { get; set; } } }
using OmniSharp.Solution; namespace OmniSharp.Rename { public class ModifiedFileResponse { private string _fileName; public ModifiedFileResponse() {} public ModifiedFileResponse(string fileName, string buffer) { this.FileName = fileName; this.Buffer = buffer; } public string FileName { get { return _fileName; } set { _fileName = value.ApplyPathReplacementsForClient(); } } public string Buffer { get; set; } } }
Revert "Added 5 tests for Length and a test for Time"
namespace Gu.Units.Tests { using NUnit.Framework; public class UnitParserTests { [TestCase("1m", 1)] [TestCase("-1m", -1)] [TestCase("1e3m", 1e3)] [TestCase("1e+3m", 1e+3)] [TestCase("-1e+3m", -1e+3)] [TestCase("1e-3m", 1e-3)] [TestCase("-1e-3m", -1e-3)] [TestCase(" 1m", 1)] [TestCase("1m ", 1)] [TestCase("1 m", 1)] [TestCase("1 m ", 1)] [TestCase("1 m", 1)] [TestCase("1m ", 1)] public void ParseLength(string s, double expected) { var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From); Assert.AreEqual(expected, length.Meters); } [TestCase("1s", 1)] public void ParseTime(string s, double expected) { var time = UnitParser.Parse<ITimeUnit, Time>(s, Time.From); Assert.AreEqual(expected, time.Seconds); } } }
namespace Gu.Units.Tests { using NUnit.Framework; public class UnitParserTests { [TestCase("1m", 1)] [TestCase("-1m", 1)] [TestCase("1e3m", 1e3)] [TestCase("1e+3m", 1e+3)] [TestCase("1e-3m", 1e-3)] [TestCase(" 1m", 1)] [TestCase("1 m", 1)] [TestCase("1m ", 1)] public void ParseLength(string s, double expected) { var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From); Assert.AreEqual(expected, length.Meters); } } }
Rework login partial to BS4
@using Microsoft.AspNetCore.Identity @using mvc_individual_authentication.Models @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager @if (SignInManager.IsSignedIn(User)) { <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right"> <ul class="nav navbar-nav navbar-right"> <li> <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a> </li> <li> <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button> </li> </ul> </form> } else { <ul class="nav navbar-nav navbar-right"> <li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li> <li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li> </ul> }
@using Microsoft.AspNetCore.Identity @using mvc_individual_authentication.Models @inject SignInManager<ApplicationUser> SignInManager @inject UserManager<ApplicationUser> UserManager @if (SignInManager.IsSignedIn(User)) { <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" class="form-inline"> <ul class="navbar-nav"> <li> <a class="btn btn-link nav-link" asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a> </li> <li> <button type="submit" class="btn btn-link nav-link">Log out</button> </li> </ul> </form> } else { <ul class="navbar-nav"> <li><a class="nav-link" asp-area="" asp-controller="Account" asp-action="Register">Register</a></li> <li><a class="nav-link" asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li> </ul> }
Set specific version for Microsoft.DirectX.dll.
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. using System; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft.DirectX")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("alesliehughes")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. using System; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft.DirectX")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("alesliehughes")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.2902.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)]
Use ToString instead of Enum.GetName
// Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 649 using System; using Newtonsoft.Json; namespace Yeena.PathOfExile { [JsonObject] class PoEItemSocket { [JsonProperty("group")] private readonly int _group; [JsonProperty("attr")] private readonly string _attr; public int Group { get { return _group; } } public PoESocketColor Color { get { return PoESocketColorUtilities.Parse(_attr); } } public override string ToString() { return Enum.GetName(typeof(PoESocketColor), Color); } } }
// Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 649 using Newtonsoft.Json; namespace Yeena.PathOfExile { [JsonObject] class PoEItemSocket { [JsonProperty("group")] private readonly int _group; [JsonProperty("attr")] private readonly string _attr; public int Group { get { return _group; } } public PoESocketColor Color { get { return PoESocketColorUtilities.Parse(_attr); } } public override string ToString() { return Color.ToString(); } } }
Add a bunch of junk you might find in a top-level program
using System; Console.WriteLine("Hello World!");
using System; using System.Linq.Expressions; using ExpressionToCodeLib; const int SomeConst = 27; var myVariable = "implicitly closed over"; var withImplicitType = new { A = "ImplicitTypeMember", }; Console.WriteLine(ExpressionToCode.ToCode(() => myVariable)); new InnerClass().DoIt(); LocalFunction(123); void LocalFunction(int arg) { var inLocalFunction = 42; Expression<Func<int>> expression1 = () => inLocalFunction + myVariable.Length - arg - withImplicitType.A.Length * SomeConst; Console.WriteLine(ExpressionToCode.ToCode(expression1)); } sealed class InnerClass { public static int StaticInt = 37; public int InstanceInt = 12; public void DoIt() => Console.WriteLine(ExpressionToCode.ToCode(() => StaticInt + InstanceInt)); }
Remove unused depedency from test
using System.Threading.Tasks; using Moq; using NUnit.Framework; using Ploeh.AutoFixture.NUnit3; using SlackConnector.Connections; using SlackConnector.Connections.Clients.Channel; using SlackConnector.Connections.Models; using SlackConnector.Connections.Sockets; using SlackConnector.Connections.Sockets.Messages.Outbound; using SlackConnector.Models; namespace SlackConnector.Tests.Unit.SlackConnectionTests { internal class PingTests { [Test, AutoMoqData] public async Task should_return_expected_slack_hub([Frozen]Mock<IConnectionFactory> connectionFactory, Mock<IChannelClient> channelClient, Mock<IWebSocketClient> webSocket, SlackConnection slackConnection) { // given const string slackKey = "key-yay"; const string userId = "some-id"; var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey }; await slackConnection.Initialise(connectionInfo); connectionFactory .Setup(x => x.CreateChannelClient()) .Returns(channelClient.Object); var returnChannel = new Channel { Id = "super-id", Name = "dm-channel" }; channelClient .Setup(x => x.JoinDirectMessageChannel(slackKey, userId)) .ReturnsAsync(returnChannel); // when await slackConnection.Ping(); // then webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>())); } } }
using System.Threading.Tasks; using Moq; using NUnit.Framework; using Ploeh.AutoFixture.NUnit3; using SlackConnector.Connections; using SlackConnector.Connections.Sockets; using SlackConnector.Connections.Sockets.Messages.Outbound; using SlackConnector.Models; namespace SlackConnector.Tests.Unit.SlackConnectionTests { internal class PingTests { [Test, AutoMoqData] public async Task should_send_ping([Frozen]Mock<IConnectionFactory> connectionFactory, Mock<IWebSocketClient> webSocket, SlackConnection slackConnection) { // given const string slackKey = "key-yay"; var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey }; await slackConnection.Initialise(connectionInfo); // when await slackConnection.Ping(); // then webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>())); } } }
Expand interface to be more testable. So methods must have a session (i.e. not null) and add a generic for session when no session is needed.
using System.Collections.Generic; using System.Threading.Tasks; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public interface IRepository<TEntity, TPk> where TEntity : class { TEntity GetKey(TPk key, ISession session); Task<TEntity> GetKeyAsync(TPk key, ISession session ); TEntity Get(TEntity entity, ISession session); Task<TEntity> GetAsync(TEntity entity, ISession session); IEnumerable<TEntity> GetAll(ISession session); Task<IEnumerable<TEntity>> GetAllAsync(ISession session); TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow); Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow); } }
using System.Collections.Generic; using System.Threading.Tasks; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public interface IRepository<TEntity, TPk> where TEntity : class { TEntity GetKey(TPk key, ISession session); TEntity GetKey<TSesssion>(TPk key) where TSesssion : class, ISession; Task<TEntity> GetKeyAsync(TPk key, ISession session); Task<TEntity> GetKeyAsync<TSesssion>(TPk key) where TSesssion : class, ISession; TEntity Get(TEntity entity, ISession session); TEntity Get<TSesssion>(TEntity entity) where TSesssion : class, ISession; Task<TEntity> GetAsync(TEntity entity, ISession session); Task<TEntity> GetAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession; IEnumerable<TEntity> GetAll(ISession session); IEnumerable<TEntity> GetAll<TSesssion>() where TSesssion : class, ISession; Task<IEnumerable<TEntity>> GetAllAsync(ISession session); Task<IEnumerable<TEntity>> GetAllAsync<TSesssion>() where TSesssion : class, ISession; TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow); TPk SaveOrUpdate<TSesssion>(TEntity entity) where TSesssion : class, ISession; Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow); Task<TPk> SaveOrUpdateAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession; } }
Convert FormattingKeyword enum to it class name counterparts
namespace Glimpse.Core.Plugin.Assist { public static class FormattingKeywords { public const string Error = "error"; public const string Fail = "fail"; public const string Info = "info"; public const string Loading = "loading"; public const string Ms = "ms"; public const string Quiet = "quiet"; public const string Selected = "selected"; public const string Warn = "warn"; } }
namespace Glimpse.Core.Plugin.Assist { public static class FormattingKeywords { public const string Error = "error"; public const string Fail = "fail"; public const string Info = "info"; public const string Loading = "loading"; public const string Ms = "ms"; public const string Quiet = "quiet"; public const string Selected = "selected"; public const string Warn = "warn"; public static string Convert(FormattingKeywordEnum keyword) { switch (keyword) { case FormattingKeywordEnum.Error: return Error; case FormattingKeywordEnum.Fail: return Fail; case FormattingKeywordEnum.Info: return Info; case FormattingKeywordEnum.Loading: return Loading; case FormattingKeywordEnum.Quite: return Quiet; case FormattingKeywordEnum.Selected: return Selected; case FormattingKeywordEnum.System: return Ms; case FormattingKeywordEnum.Warn: return Warn; default: return null; } } } }
Load OIDC configuration from root of Authority
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace Auth0.AuthenticationApi { internal class OpenIdConfigurationCache { private static volatile OpenIdConfigurationCache _instance; private static readonly object SyncRoot = new object(); private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>(); private OpenIdConfigurationCache() {} public static OpenIdConfigurationCache Instance { get { if (_instance == null) { lock (SyncRoot) { if (_instance == null) _instance = new OpenIdConfigurationCache(); } } return _instance; } } public async Task<OpenIdConnectConfiguration> GetAsync(string domain) { _innerCache.TryGetValue(domain, out var configuration); if (configuration == null) { var uri = new Uri(domain); IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{uri.AbsoluteUri}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None); _innerCache[domain] = configuration; } return configuration; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace Auth0.AuthenticationApi { internal class OpenIdConfigurationCache { private static volatile OpenIdConfigurationCache _instance; private static readonly object SyncRoot = new object(); private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>(); private OpenIdConfigurationCache() {} public static OpenIdConfigurationCache Instance { get { if (_instance == null) { lock (SyncRoot) { if (_instance == null) _instance = new OpenIdConfigurationCache(); } } return _instance; } } public async Task<OpenIdConnectConfiguration> GetAsync(string domain) { _innerCache.TryGetValue(domain, out var configuration); if (configuration == null) { var uri = new Uri(domain); IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>( $"{uri.Scheme}://{uri.Authority}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None); _innerCache[domain] = configuration; } return configuration; } } }
Fix OsuGame test case not working
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Screens; using osu.Game.Screens; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseOsuGame : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), }; public TestCaseOsuGame() { Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, new ScreenStack(new Loader()) { RelativeSizeAxes = Axes.Both, } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Platform; using osu.Game.Screens.Menu; using osuTK.Graphics; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseOsuGame : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), }; [BackgroundDependencyLoader] private void load(GameHost host) { OsuGame game = new OsuGame(); game.SetHost(host); Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, game }; } } }
Fix TryGetRawMetadata to return false when the assembly is not a RuntimeAssembly
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace System.Reflection.Metadata { public static class AssemblyExtensions { [DllImport(JitHelpers.QCall)] [SecurityCritical] // unsafe method [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length); // Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader. // - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET // native images, etc. // - Callers should not write to the metadata blob // - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is // associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the // metadata blob. [CLSCompliant(false)] // out byte* blob [SecurityCritical] // unsafe method public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length) { if (assembly == null) { throw new ArgumentNullException("assembly"); } blob = null; length = 0; return InternalTryGetRawMetadata((RuntimeAssembly)assembly, ref blob, ref length); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; namespace System.Reflection.Metadata { public static class AssemblyExtensions { [DllImport(JitHelpers.QCall)] [SecurityCritical] // unsafe method [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length); // Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader. // - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET // native images, etc. // - Callers should not write to the metadata blob // - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is // associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the // metadata blob. [CLSCompliant(false)] // out byte* blob [SecurityCritical] // unsafe method public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length) { if (assembly == null) { throw new ArgumentNullException("assembly"); } blob = null; length = 0; var runtimeAssembly = assembly as RuntimeAssembly; if (runtimeAssembly == null) { return false; } return InternalTryGetRawMetadata(runtimeAssembly, ref blob, ref length); } } }
Test parsing valid absolute URI
using System; using Xunit; namespace FromString.Tests { public class ParsedTTests { [Fact] public void CanParseAnInt() { var parsedInt = new Parsed<int>("123"); Assert.True(parsedInt.HasValue); Assert.Equal(123, parsedInt.Value); } [Fact] public void AnInvalidStringSetsHasValueFalse() { var parsedInt = new Parsed<int>("this is not a string"); Assert.False(parsedInt.HasValue); } [Fact] public void AnInvalidStringThrowsExceptionWhenAccessingValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Throws<InvalidOperationException>(() => parsedInt.Value); } [Fact] public void CanGetBackRawValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Equal("this is not a string", parsedInt.RawValue); } [Fact] public void CanAssignValueDirectly() { Parsed<decimal> directDecimal = 123.45m; Assert.True(directDecimal.HasValue); Assert.Equal(123.45m, directDecimal.Value); } [Fact] public void ParsingInvalidUriFails() { var parsedUri = new Parsed<Uri>("this is not an URI"); Assert.False(parsedUri.HasValue); } } }
using System; using Xunit; namespace FromString.Tests { public class ParsedTTests { [Fact] public void CanParseAnInt() { var parsedInt = new Parsed<int>("123"); Assert.True(parsedInt.HasValue); Assert.Equal(123, parsedInt.Value); } [Fact] public void AnInvalidStringSetsHasValueFalse() { var parsedInt = new Parsed<int>("this is not a string"); Assert.False(parsedInt.HasValue); } [Fact] public void AnInvalidStringThrowsExceptionWhenAccessingValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Throws<InvalidOperationException>(() => parsedInt.Value); } [Fact] public void CanGetBackRawValue() { var parsedInt = new Parsed<int>("this is not a string"); Assert.Equal("this is not a string", parsedInt.RawValue); } [Fact] public void CanAssignValueDirectly() { Parsed<decimal> directDecimal = 123.45m; Assert.True(directDecimal.HasValue); Assert.Equal(123.45m, directDecimal.Value); } [Fact] public void ParsingInvalidUriFails() { var parsedUri = new Parsed<Uri>("this is not an URI"); Assert.False(parsedUri.HasValue); } [Fact] public void ParsingValidAbsoluteUriSucceeds() { var parsedUri = new Parsed<Uri>("https://github.com/"); Assert.True(parsedUri.HasValue); Assert.Equal(new Uri("https://github.com/"), parsedUri.Value); } } }
Remove running benchmarks on .NET Core 2.1
using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Running; using SwissArmyKnife.Benchmarks.Benches.Extensions; using System; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Toolchains.CsProj; namespace SwissArmyKnife.Benchmarks { class Program { private static void Main(string[] args) { var config = GetConfig(); var benchmarks = GetBenchmarks(); for (var i = 0; i < benchmarks.Length; i++) { var typeToRun = benchmarks[i]; BenchmarkRunner.Run(typeToRun, config); } //BenchmarkRunner.Run<StringExtensionsBenchmarks>(config); } private static Type[] GetBenchmarks() { var result = new Type[] { // Extensions typeof(ObjectExtensionsBenchmarks), typeof(IComparableExtensionsBenchmarks), typeof(StringBuilderExtensionsBenchmarks), typeof(StringExtensionsBenchmarks), typeof(IntExtensionsBenchmarks), }; return result; } private static IConfig GetConfig() { var config = ManualConfig.Create(DefaultConfig.Instance); config .AddDiagnoser(MemoryDiagnoser.Default); config.AddJob( Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(), Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp21), Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48) ); return config; } } }
using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Running; using SwissArmyKnife.Benchmarks.Benches.Extensions; using System; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Toolchains.CsProj; namespace SwissArmyKnife.Benchmarks { class Program { private static void Main(string[] args) { var config = GetConfig(); var benchmarks = GetBenchmarks(); for (var i = 0; i < benchmarks.Length; i++) { var typeToRun = benchmarks[i]; BenchmarkRunner.Run(typeToRun, config); } //BenchmarkRunner.Run<StringExtensionsBenchmarks>(config); } private static Type[] GetBenchmarks() { var result = new Type[] { // Extensions typeof(ObjectExtensionsBenchmarks), typeof(IComparableExtensionsBenchmarks), typeof(StringBuilderExtensionsBenchmarks), typeof(StringExtensionsBenchmarks), typeof(IntExtensionsBenchmarks), }; return result; } private static IConfig GetConfig() { var config = ManualConfig.Create(DefaultConfig.Instance); config .AddDiagnoser(MemoryDiagnoser.Default); config.AddJob( Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(), Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48) ); return config; } } }
Fix labels not appearing on BucketMonitorWidget
using System; using BudgetAnalyser.Engine.Annotations; namespace BudgetAnalyser.Engine.Widgets { public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget { private readonly string disabledToolTip; private string doNotUseId; public BudgetBucketMonitorWidget() { this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated."; } public string Id { get { return this.doNotUseId; } set { this.doNotUseId = value; OnPropertyChanged(); BucketCode = Id; } } public Type WidgetType => GetType(); public void Initialise(MultiInstanceWidgetState state, ILogger logger) { } public override void Update([NotNull] params object[] input) { base.Update(input); if (!Enabled) { ToolTip = this.disabledToolTip; } } } }
using System; using BudgetAnalyser.Engine.Annotations; namespace BudgetAnalyser.Engine.Widgets { public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget { private readonly string disabledToolTip; private string doNotUseId; public BudgetBucketMonitorWidget() { this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated."; } public string Id { get { return this.doNotUseId; } set { this.doNotUseId = value; OnPropertyChanged(); BucketCode = Id; } } public Type WidgetType => GetType(); public void Initialise(MultiInstanceWidgetState state, ILogger logger) { } public override void Update([NotNull] params object[] input) { base.Update(input); DetailedText = BucketCode; if (!Enabled) { ToolTip = this.disabledToolTip; } } } }
Add missing Commit, when game starts.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TicTacToe.Core; using TicTacToe.Web.Data; using TicTacToe.Web.ViewModels; namespace TicTacToe.Controllers { public class GameController : Controller { private ApplicationDbContext context; public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext()); public ActionResult Index() { //var context = new ApplicationDbContext(); //var game = new Game {Player = "123"}; //var field = new Field() {Game = game}; //game.Field = field; //context.Games.Add(game); //context.Commit(); //context.Dispose(); return View(); } public ActionResult Play(string playerName) { if (string.IsNullOrEmpty(playerName)) return View("Index"); var game = new Game(); game.CreateField(); game.Player = playerName; Context.Games.Add(game); return View(game); } public JsonResult Turn(TurnClientViewModel turn) { return Json(turn); } public ActionResult About() { var context = new ApplicationDbContext(); var games = context.Games.ToArray(); context.Dispose(); ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } protected override void Dispose(bool disposing) { context?.Dispose(); base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TicTacToe.Core; using TicTacToe.Web.Data; using TicTacToe.Web.ViewModels; namespace TicTacToe.Controllers { public class GameController : Controller { private ApplicationDbContext context; public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext()); public ActionResult Index() { //var context = new ApplicationDbContext(); //var game = new Game {Player = "123"}; //var field = new Field() {Game = game}; //game.Field = field; //context.Games.Add(game); //context.Commit(); //context.Dispose(); return View(); } public ActionResult Play(string playerName) { if (string.IsNullOrEmpty(playerName)) return View("Index"); var game = new Game(); game.CreateField(); game.Player = playerName; Context.Games.Add(game); Context.Commit(); return View(game); } public JsonResult Turn(TurnClientViewModel turn) { return Json(turn); } public ActionResult About() { var context = new ApplicationDbContext(); var games = context.Games.ToArray(); context.Dispose(); ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } protected override void Dispose(bool disposing) { context?.Dispose(); base.Dispose(disposing); } } }
Add negative test for the registration source.
using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Autofac.Test.Features.OpenGenerics { public class OpenGenericDelegateTests { private interface IInterfaceA<T> { } private class ImplementationA<T> : IInterfaceA<T> { } [Fact] public void CanResolveByGenericInterface() { var builder = new ContainerBuilder(); builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types))) .As(typeof(IInterfaceA<>)); var container = builder.Build(); var instance = container.Resolve<IInterfaceA<string>>(); var implementedType = instance.GetType().GetGenericTypeDefinition(); Assert.Equal(typeof(ImplementationA<>), implementedType); } } }
using System; using System.Collections.Generic; using System.Text; using Autofac.Core; using Autofac.Core.Registration; using Xunit; namespace Autofac.Test.Features.OpenGenerics { public class OpenGenericDelegateTests { private interface IInterfaceA<T> { } private interface IInterfaceB<T> { } private class ImplementationA<T> : IInterfaceA<T> { } [Fact] public void CanResolveByGenericInterface() { var builder = new ContainerBuilder(); builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types))) .As(typeof(IInterfaceA<>)); var container = builder.Build(); var instance = container.Resolve<IInterfaceA<string>>(); var implementedType = instance.GetType().GetGenericTypeDefinition(); Assert.Equal(typeof(ImplementationA<>), implementedType); } [Fact] public void DoesNotResolveForDifferentGenericService() { var builder = new ContainerBuilder(); builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types))) .As(typeof(IInterfaceA<>)); var container = builder.Build(); Assert.Throws<ComponentNotRegisteredException>(() => container.Resolve<IInterfaceB<string>>()); } } }
Test coverage for unparseable string -> DateTime conversion
namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion { using System; using TestClasses; using Xunit; public class WhenMappingToDateTimes { [Fact] public void ShouldMapANullableDateTimeToADateTime() { var source = new PublicProperty<DateTime?> { Value = DateTime.Today }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(DateTime.Today); } [Fact] public void ShouldMapAYearMonthDayStringToADateTime() { var source = new PublicProperty<string> { Value = "2016/06/08" }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(new DateTime(2016, 06, 08)); } } }
namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion { using System; using Shouldly; using TestClasses; using Xunit; public class WhenMappingToDateTimes { [Fact] public void ShouldMapANullableDateTimeToADateTime() { var source = new PublicProperty<DateTime?> { Value = DateTime.Today }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(DateTime.Today); } [Fact] public void ShouldMapAYearMonthDayStringToADateTime() { var source = new PublicProperty<string> { Value = "2016/06/08" }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>(); result.Value.ShouldBe(new DateTime(2016, 06, 08)); } [Fact] public void ShouldMapAnUnparseableStringToANullableDateTime() { var source = new PublicProperty<string> { Value = "OOH OOH OOH" }; var result = Mapper.Map(source).ToNew<PublicProperty<DateTime?>>(); result.Value.ShouldBeNull(); } } }
Use Count instead of Count()
using System; using System.Collections.Generic; using System.Linq; using WalletWasabi.Bases; using WalletWasabi.Coins; namespace WalletWasabi.BlockchainAnalysis { public class Cluster : NotifyPropertyChangedBase { private List<SmartCoin> Coins { get; set; } private string _labels; public Cluster(params SmartCoin[] coins) : this(coins as IEnumerable<SmartCoin>) { } public Cluster(IEnumerable<SmartCoin> coins) { Coins = coins.ToList(); Labels = string.Join(", ", KnownBy); } public string Labels { get => _labels; private set => RaiseAndSetIfChanged(ref _labels, value); } public int Size => Coins.Count(); public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase); public void Merge(Cluster clusters) => Merge(clusters.Coins); public void Merge(IEnumerable<SmartCoin> coins) { var insertPosition = 0; foreach (var coin in coins.ToList()) { if (!Coins.Contains(coin)) { Coins.Insert(insertPosition++, coin); } coin.Clusters = this; } if (insertPosition > 0) // at least one element was inserted { Labels = string.Join(", ", KnownBy); } } } }
using System; using System.Collections.Generic; using System.Linq; using WalletWasabi.Bases; using WalletWasabi.Coins; namespace WalletWasabi.BlockchainAnalysis { public class Cluster : NotifyPropertyChangedBase { private List<SmartCoin> Coins { get; set; } private string _labels; public Cluster(params SmartCoin[] coins) : this(coins as IEnumerable<SmartCoin>) { } public Cluster(IEnumerable<SmartCoin> coins) { Coins = coins.ToList(); Labels = string.Join(", ", KnownBy); } public string Labels { get => _labels; private set => RaiseAndSetIfChanged(ref _labels, value); } public int Size => Coins.Count; public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase); public void Merge(Cluster clusters) => Merge(clusters.Coins); public void Merge(IEnumerable<SmartCoin> coins) { var insertPosition = 0; foreach (var coin in coins.ToList()) { if (!Coins.Contains(coin)) { Coins.Insert(insertPosition++, coin); } coin.Clusters = this; } if (insertPosition > 0) // at least one element was inserted { Labels = string.Join(", ", KnownBy); } } } }
Update server side API for single multiple answer question
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
Fix a build warning for missing blank line at end of file
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace NOpenCL.Test { internal static class TestCategories { public const string RequireGpu = nameof(RequireGpu); } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace NOpenCL.Test { internal static class TestCategories { public const string RequireGpu = nameof(RequireGpu); } }
Replace another Task.Yield with Task.CompletedTask.
using System.Threading.Tasks; using Windows.ApplicationModel.Activation; namespace Sample { sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); } public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); await Task.Yield(); } } }
using System.Threading.Tasks; using Windows.ApplicationModel.Activation; namespace Sample { sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); } public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); return Task.CompletedTask; } } }
Change text from favorites to "My Agenda"
@page "{id}" @model SessionModel <ol class="breadcrumb"> <li><a asp-page="/Index">Agenda</a></li> <li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li> <li class="active">@Model.Session.Title</li> </ol> <h1>@Model.Session.Title</h1> <span class="label label-default">@Model.Session.Track?.Name</span> @foreach (var speaker in Model.Session.Speakers) { <em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em> } <p>@Html.Raw(Model.Session.Abstract)</p> <form method="post"> <input type="hidden" name="sessionId" value="@Model.Session.ID" /> <p> <a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a> @if (Model.IsFavorite) { <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from Favorites</button> } else { <button authz="true" type="submit" class="btn btn-primary">Add to Favorites</button> } </p> </form>
@page "{id}" @model SessionModel <ol class="breadcrumb"> <li><a asp-page="/Index">Agenda</a></li> <li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li> <li class="active">@Model.Session.Title</li> </ol> <h1>@Model.Session.Title</h1> <span class="label label-default">@Model.Session.Track?.Name</span> @foreach (var speaker in Model.Session.Speakers) { <em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em> } <p>@Html.Raw(Model.Session.Abstract)</p> <form method="post"> <input type="hidden" name="sessionId" value="@Model.Session.ID" /> <p> <a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a> @if (Model.IsFavorite) { <button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from My Agenda</button> } else { <button authz="true" type="submit" class="btn btn-primary">Add to My Agenda</button> } </p> </form>
Remove interface mapping from role mapper
using System; using System.Collections.Generic; using System.Linq; using Affecto.IdentityManagement.ApplicationServices.Model; using Affecto.IdentityManagement.Interfaces.Model; using Affecto.Mapping.AutoMapper; using AutoMapper; namespace Affecto.IdentityManagement.ApplicationServices.Mapping { internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role> { protected override void ConfigureMaps() { Func<Querying.Data.Permission, IPermission> permissionCreator = o => new Permission(); Mapper.CreateMap<Querying.Data.Permission, IPermission>().ConvertUsing(permissionCreator); Mapper.CreateMap<Querying.Data.Permission, Permission>(); Mapper.CreateMap<Querying.Data.Role, Role>() .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<IPermission>>(c.Permissions.ToList()))); } } }
using System.Collections.Generic; using System.Linq; using Affecto.IdentityManagement.ApplicationServices.Model; using Affecto.Mapping.AutoMapper; using AutoMapper; namespace Affecto.IdentityManagement.ApplicationServices.Mapping { internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role> { protected override void ConfigureMaps() { Mapper.CreateMap<Querying.Data.Permission, Permission>(); Mapper.CreateMap<Querying.Data.Role, Role>() .ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<Permission>>(c.Permissions.ToList()))); } } }
Fix Autofac crash due to linker stripping out a function used by reflection only
using System; using Autofac; namespace AGS.Engine.IOS { public class AGSEngineIOS { private static IOSAssemblies _assembly; public static void Init() { OpenTK.Toolkit.Init(); var device = new IOSDevice(_assembly); AGSGame.Device = device; //Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>()); Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>()); } public static void SetAssembly() { _assembly = new IOSAssemblies(); } } }
using System; using Autofac; namespace AGS.Engine.IOS { public class AGSEngineIOS { private static IOSAssemblies _assembly; public static void Init() { // On IOS, when the mono linker is enabled (and it's enabled by default) it strips out all parts of // the framework which are not in use. The linker does not support reflection, however, therefore it // does not recognize the call to 'GetRuntimeMethod(nameof(Convert.ChangeType)' (which is called from // a method in this Autofac in ConstructorParameterBinding class, ConvertPrimitiveType method) // as using the 'Convert.ChangeType' method and strips it away unless it's // explicitly used somewhere else, crashing Autofac if that method is called. // Therefore, by explicitly calling it here, we're playing nicely with the linker and making sure // Autofac works on IOS. Convert.ChangeType((object)1234f, typeof(float)); OpenTK.Toolkit.Init(); var device = new IOSDevice(_assembly); AGSGame.Device = device; //Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>()); Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>()); } public static void SetAssembly() { _assembly = new IOSAssemblies(); } } }
Make sure we read the backing store name properly.
using System; using System.IO; using Newtonsoft.Json; namespace Scanner { using System.Collections.Generic; public class BackingStore { private string backingStoreName; public BackingStore(string backingStoreName) { this.backingStoreName = backingStoreName; } public IEnumerable<Child> GetAll() { string json = File.ReadAllText(GetBackingStoreFilename()); return JsonConvert.DeserializeObject<IEnumerable<Child>>(json); } public void SaveAll(IEnumerable<Child> children) { string json = JsonConvert.SerializeObject(children); var applicationFile = GetBackingStoreFilename(); File.WriteAllText(applicationFile, json); } private static string GetBackingStoreFilename() { var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner"); Directory.CreateDirectory(applicationFolder); var applicationFile = Path.Combine(applicationFolder, "children.json"); return applicationFile; } } }
using System; using System.IO; using Newtonsoft.Json; namespace Scanner { using System.Collections.Generic; public class BackingStore { private string backingStoreName; public BackingStore(string backingStoreName) { this.backingStoreName = backingStoreName; } public IEnumerable<Child> GetAll() { string json = File.ReadAllText(GetBackingStoreFilename()); return JsonConvert.DeserializeObject<IEnumerable<Child>>(json); } public void SaveAll(IEnumerable<Child> children) { string json = JsonConvert.SerializeObject(children); var applicationFile = GetBackingStoreFilename(); File.WriteAllText(applicationFile, json); } private string GetBackingStoreFilename() { var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner"); Directory.CreateDirectory(applicationFolder); var applicationFile = Path.Combine(applicationFolder, string.Format("{0}.json", backingStoreName)); return applicationFile; } } }
Add 0.6 seconds preview time for spells
using System.Collections; using System.Collections.Generic; using HarryPotterUnity.Tween; using HarryPotterUnity.Utils; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.Generic { public abstract class GenericSpell : GenericCard { private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f); protected sealed override void OnClickAction(List<GenericCard> targets) { Enable(); PreviewSpell(); Player.Hand.Remove(this); Player.Discard.Add(this); SpellAction(targets); } protected abstract void SpellAction(List<GenericCard> targets); private void PreviewSpell() { State = CardStates.Discarded; var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate; UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State)); } } }
using System.Collections; using System.Collections.Generic; using HarryPotterUnity.Tween; using HarryPotterUnity.Utils; using JetBrains.Annotations; using UnityEngine; namespace HarryPotterUnity.Cards.Generic { public abstract class GenericSpell : GenericCard { private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f); protected sealed override void OnClickAction(List<GenericCard> targets) { Enable(); PreviewSpell(); Player.Hand.Remove(this); Player.Discard.Add(this); SpellAction(targets); } protected abstract void SpellAction(List<GenericCard> targets); private void PreviewSpell() { State = CardStates.Discarded; var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate; UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State, 0.6f)); } } }
Add message id to storage convert process
using Microsoft.Azure.ServiceBus; using System; using System.Collections.Generic; using QueueMessage = Storage.Net.Messaging.QueueMessage; namespace Storage.Net.Microsoft.Azure.ServiceBus { static class Converter { public static Message ToMessage(QueueMessage message) { if(message == null) throw new ArgumentNullException(nameof(message)); var result = new Message(message.Content); if(message.Properties != null && message.Properties.Count > 0) { foreach(KeyValuePair<string, string> prop in message.Properties) { result.UserProperties.Add(prop.Key, prop.Value); } } return result; } public static QueueMessage ToQueueMessage(Message message) { string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString(); var result = new QueueMessage(id, message.Body); result.DequeueCount = message.SystemProperties.DeliveryCount; if(message.UserProperties != null && message.UserProperties.Count > 0) { foreach(KeyValuePair<string, object> pair in message.UserProperties) { result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString(); } } return result; } } }
using Microsoft.Azure.ServiceBus; using System; using System.Collections.Generic; using QueueMessage = Storage.Net.Messaging.QueueMessage; namespace Storage.Net.Microsoft.Azure.ServiceBus { static class Converter { public static Message ToMessage(QueueMessage message) { if(message == null) throw new ArgumentNullException(nameof(message)); var result = new Message(message.Content) { MessageId = message.Id }; if(message.Properties != null && message.Properties.Count > 0) { foreach(KeyValuePair<string, string> prop in message.Properties) { result.UserProperties.Add(prop.Key, prop.Value); } } return result; } public static QueueMessage ToQueueMessage(Message message) { string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString(); var result = new QueueMessage(id, message.Body); result.DequeueCount = message.SystemProperties.DeliveryCount; if(message.UserProperties != null && message.UserProperties.Count > 0) { foreach(KeyValuePair<string, object> pair in message.UserProperties) { result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString(); } } return result; } } }
Switch to StringBuilder for speed.
using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using ClientSamples.CachingTools; namespace Tavis.PrivateCache { public class CacheEntry { public PrimaryCacheKey Key { get; private set; } public HttpHeaderValueCollection<string> VaryHeaders { get; private set; } internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders) { Key = key; VaryHeaders = varyHeaders; } public string CreateSecondaryKey(HttpRequestMessage request) { var key = ""; foreach (var h in VaryHeaders.OrderBy(v => v)) // Sort the vary headers so that ordering doesn't generate different stored variants { if (h != "*") { key += h + ":" + String.Join(",", request.Headers.GetValues(h)); } else { key += "*"; } } return key.ToLower(); } public CacheContent CreateContent(HttpResponseMessage response) { return new CacheContent() { CacheEntry = this, Key = CreateSecondaryKey(response.RequestMessage), HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null), Expires = HttpCache.GetExpireDate(response), CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(), Response = response, }; } } }
using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using ClientSamples.CachingTools; namespace Tavis.PrivateCache { public class CacheEntry { public PrimaryCacheKey Key { get; private set; } public HttpHeaderValueCollection<string> VaryHeaders { get; private set; } internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders) { Key = key; VaryHeaders = varyHeaders; } public string CreateSecondaryKey(HttpRequestMessage request) { var key = new StringBuilder(); foreach (var h in VaryHeaders.OrderBy(v => v)) // Sort the vary headers so that ordering doesn't generate different stored variants { if (h != "*") { key.Append(h).Append(':'); bool addedOne = false; foreach (var val in request.Headers.GetValues(h)) { key.Append(val).Append(','); addedOne = true; } if (addedOne) { key.Length--; // truncate trailing comma. } } else { key.Append('*'); } } return key.ToString().ToLowerInvariant(); } public CacheContent CreateContent(HttpResponseMessage response) { return new CacheContent() { CacheEntry = this, Key = CreateSecondaryKey(response.RequestMessage), HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null), Expires = HttpCache.GetExpireDate(response), CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(), Response = response, }; } } }
Fix some xml parsing issues
using NBi.Core.Evaluate; using NBi.Core.ResultSet; using NBi.Core.Transformation; using NBi.Xml.Variables; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace NBi.Xml.Items.Calculation { [XmlType("")] public class ExpressionXml: IColumnExpression { [Obsolete("Use the attribute Script in place of Value")] [XmlText()] public string Value { get => ShouldSerializeValue() ? Script.Code : null; set => Script = new ScriptXml() { Language = LanguageType.NCalc, Code = value }; } public bool ShouldSerializeValue() => Script?.Language == LanguageType.NCalc; [XmlElement("script")] public ScriptXml Script { get; set; } public bool ShouldSerializeScript() => Script?.Language != LanguageType.NCalc; [XmlIgnore()] public LanguageType Language { get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("column-index")] [DefaultValue(0)] public int Column { get; set; } [XmlAttribute("type")] [DefaultValue(ColumnType.Text)] public ColumnType Type { get; set; } [XmlAttribute("tolerance")] [DefaultValue("")] public string Tolerance { get; set; } } }
using NBi.Core.Evaluate; using NBi.Core.ResultSet; using NBi.Core.Transformation; using NBi.Xml.Variables; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace NBi.Xml.Items.Calculation { [XmlType("")] public class ExpressionXml: IColumnExpression { [XmlText()] public string Value { get => Script.Code; set => Script.Code = value; } public bool ShouldSerializeValue() => Script.Language == LanguageType.NCalc; [XmlElement("script")] public ScriptXml Script { get; set; } public bool ShouldSerializeScript() => Script.Language != LanguageType.NCalc; [XmlIgnore()] public LanguageType Language { get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("column-index")] [DefaultValue(0)] public int Column { get; set; } [XmlAttribute("type")] [DefaultValue(ColumnType.Text)] public ColumnType Type { get; set; } [XmlAttribute("tolerance")] [DefaultValue("")] public string Tolerance { get; set; } public ExpressionXml() { Script = new ScriptXml() { Language = LanguageType.NCalc }; } } }
Update new test to use UsePerRequestServices
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Builder; using Microsoft.Framework.DependencyInjection; namespace TagHelpersWebSite { public class Startup { public void Configure(IApplicationBuilder app) { var configuration = app.GetTestConfiguration(); app.UseServices(services => { services.AddMvc(configuration); }); app.UseMvc(); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Builder; using Microsoft.Framework.DependencyInjection; namespace TagHelpersWebSite { public class Startup { public void Configure(IApplicationBuilder app) { var configuration = app.GetTestConfiguration(); app.UsePerRequestServices(services => { services.AddMvc(configuration); }); app.UseMvc(); } } }
Reduce information displayed in about box
using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }
using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { var version = Assembly.GetExecutingAssembly().GetName().Version; return $"{version.Major}.{version.Minor}.{version.Revision}"; } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }
Fix wrong attribute for about box
using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { var version = Assembly.GetExecutingAssembly().GetName().Version; return $"{version.Major}.{version.Minor}.{version.Revision}"; } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }
using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = $"About {AssemblyTitle}"; labelProductName.Text = AssemblyTitle; labelVersion.Text = AssemblyVersion; lastUpdatedBox.Text = LastUpdatedDate.ToString(); linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } public static string AssemblyTitle { get; } = "Vigilant Cupcake"; public static string AssemblyVersion { get { var version = Assembly.GetExecutingAssembly().GetName().Version; return $"{version.Major}.{version.Minor}.{version.Build}"; } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }
Add license info in assembly.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Digital Color Meter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Digital Color Meter")] [assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ca199dd4-2017-4ee7-808c-3747101e04b1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Digital Color Meter")] [assembly: AssemblyDescription("Released under the MIT License")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Digital Color Meter")] [assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ca199dd4-2017-4ee7-808c-3747101e04b1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Use the correct Accept type for json requests
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using Newtonsoft.Json; namespace osu.Framework.IO.Network { /// <summary> /// A web request with a specific JSON response format. /// </summary> /// <typeparam name="T">the response format.</typeparam> public class JsonWebRequest<T> : WebRequest { public JsonWebRequest(string url = null, params object[] args) : base(url, args) { base.Finished += finished; } private void finished(WebRequest request, Exception e) { try { deserialisedResponse = JsonConvert.DeserializeObject<T>(ResponseString); } catch (Exception se) { e = e == null ? se : new AggregateException(e, se); } Finished?.Invoke(this, e); } private T deserialisedResponse; public T ResponseObject => deserialisedResponse; /// <summary> /// Request has finished with success or failure. Check exception == null for success. /// </summary> public new event RequestCompleteHandler<T> Finished; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Net; using Newtonsoft.Json; namespace osu.Framework.IO.Network { /// <summary> /// A web request with a specific JSON response format. /// </summary> /// <typeparam name="T">the response format.</typeparam> public class JsonWebRequest<T> : WebRequest { public JsonWebRequest(string url = null, params object[] args) : base(url, args) { base.Finished += finished; } protected override HttpWebRequest CreateWebRequest(string requestString = null) { var req = base.CreateWebRequest(requestString); req.Accept = @"application/json"; return req; } private void finished(WebRequest request, Exception e) { try { deserialisedResponse = JsonConvert.DeserializeObject<T>(ResponseString); } catch (Exception se) { e = e == null ? se : new AggregateException(e, se); } Finished?.Invoke(this, e); } private T deserialisedResponse; public T ResponseObject => deserialisedResponse; /// <summary> /// Request has finished with success or failure. Check exception == null for success. /// </summary> public new event RequestCompleteHandler<T> Finished; } }
Add TLS change to make the call to the Audit api work
using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Api.Startup))] namespace SFA.DAS.EmployerUsers.Api { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
using System.Net; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(SFA.DAS.EmployerUsers.Api.Startup))] namespace SFA.DAS.EmployerUsers.Api { public partial class Startup { public void Configuration(IAppBuilder app) { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; ConfigureAuth(app); } } }
Revert "keep username only in sinin cookie"
using Microsoft.AspNetCore.Http; using Obsidian.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Authentication; using Obsidian.Application.OAuth20; namespace Obsidian.Services { public class SignInService : ISignInService { private readonly IHttpContextAccessor _accessor; const string Scheme = "Obsidian.Cookie"; public SignInService(IHttpContextAccessor accessor) { _accessor = accessor; } public async Task CookieSignInAsync(User user, bool isPersistent) { await CookieSignOutCurrentUserAsync(); var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.UserName) }; var identity = new ClaimsIdentity(claims); var principal = new ClaimsPrincipal(identity); var context = _accessor.HttpContext; var props = new AuthenticationProperties{ IsPersistent = isPersistent }; await context.Authentication.SignInAsync(Scheme, principal, props); } public async Task CookieSignOutCurrentUserAsync() => await _accessor.HttpContext.Authentication.SignOutAsync(Scheme); } }
using Microsoft.AspNetCore.Http; using Obsidian.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Authentication; using Obsidian.Application.OAuth20; namespace Obsidian.Services { public class SignInService : ISignInService { private readonly IHttpContextAccessor _accessor; const string Scheme = "Obsidian.Cookie"; public SignInService(IHttpContextAccessor accessor) { _accessor = accessor; } public async Task CookieSignInAsync(User user, bool isPersistent) { await CookieSignOutCurrentUserAsync(); var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; var identity = new ClaimsIdentity(claims); var principal = new ClaimsPrincipal(identity); var context = _accessor.HttpContext; var props = new AuthenticationProperties{ IsPersistent = isPersistent }; await context.Authentication.SignInAsync(Scheme, principal, props); } public async Task CookieSignOutCurrentUserAsync() => await _accessor.HttpContext.Authentication.SignOutAsync(Scheme); } }
Improve naming of tests to clearly indicate the feature to be tested
#region Copyright and license // // <copyright file="AlwaysTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // 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. // // </license> #endregion namespace Delizious.Filtering { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class AlwaysTests { [TestMethod] public void Succeed__When_Value_Is_Null() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(null)); } [TestMethod] public void Succeed__When_Value_Is_An_Instance() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(new GenericParameterHelper())); } } }
#region Copyright and license // // <copyright file="AlwaysTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // 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. // // </license> #endregion namespace Delizious.Filtering { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class AlwaysTests { [TestMethod] public void Match_Succeeds_When_Value_To_Match_Is_Null() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(null)); } [TestMethod] public void Match_Succeeds_When_Value_To_Match_Is_An_Instance() { Assert.IsTrue(Match.Always<GenericParameterHelper>().Matches(new GenericParameterHelper())); } } }
Reduce concurrency (not eliminate) in integration tests so that starting up a test suite run doesn't soak up all the threads in our thread pool.
using NUnit.Framework; [assembly: Category("IntegrationTest")] [assembly: Parallelizable(ParallelScope.Fixtures)] [assembly: LevelOfParallelism(32)]
using NUnit.Framework; [assembly: Category("IntegrationTest")] [assembly: Parallelizable(ParallelScope.Fixtures)] [assembly: LevelOfParallelism(2)]
Use same url Facebook uses to download bits
void DownloadAudienceNetwork (Artifact artifact) { var podSpec = artifact.PodSpecs [0]; var id = podSpec.Name; var version = podSpec.Version; var url = $"https://origincache.facebook.com/developers/resources/?id={id}-{version}.zip"; var basePath = $"./externals/{id}"; DownloadFile (url, $"{basePath}.zip", new Cake.Xamarin.Build.DownloadFileSettings { UserAgent = "curl/7.43.0" }); Unzip ($"{basePath}.zip", $"{basePath}"); CopyDirectory ($"{basePath}/Dynamic/{id}.framework", $"./externals/{id}.framework"); }
void DownloadAudienceNetwork (Artifact artifact) { var podSpec = artifact.PodSpecs [0]; var id = podSpec.Name; var version = podSpec.Version; var url = $"https://developers.facebook.com/resources/{id}-{version}.zip"; var basePath = $"./externals/{id}"; DownloadFile (url, $"{basePath}.zip", new Cake.Xamarin.Build.DownloadFileSettings { UserAgent = "curl/7.43.0" }); Unzip ($"{basePath}.zip", $"{basePath}"); CopyDirectory ($"{basePath}/Dynamic/{id}.framework", $"./externals/{id}.framework"); }
Fix check so file extension is preserved
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using NuGet.Packaging; namespace PackageExplorerViewModel.Utilities { public class TemporaryFile : IDisposable { public TemporaryFile(Stream stream, string extension) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (!string.IsNullOrWhiteSpace(extension) || extension[0] != '.') { extension = string.Empty; } FileName = Path.GetTempFileName() + extension; stream.CopyToFile(FileName); } public string FileName { get; } bool disposed; public void Dispose() { if (!disposed) { disposed = true; try { File.Delete(FileName); } catch // best effort { } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using NuGet.Packaging; namespace PackageExplorerViewModel.Utilities { public class TemporaryFile : IDisposable { public TemporaryFile(Stream stream, string extension) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (string.IsNullOrWhiteSpace(extension) || extension[0] != '.') { extension = string.Empty; } FileName = Path.GetTempFileName() + extension; stream.CopyToFile(FileName); } public string FileName { get; } bool disposed; public void Dispose() { if (!disposed) { disposed = true; try { File.Delete(FileName); } catch // best effort { } } } } }
Add message to press enter when sample App execution is complete
using System.Threading; using System.Threading.Tasks; using Console = System.Console; namespace ConsoleWritePrettyOneDay.App { class Program { static void Main(string[] args) { Spinner.Wait(() => Thread.Sleep(5000), "waiting for sleep"); var task = Task.Run(() => Thread.Sleep(4000)); Spinner.Wait(task, "waiting for task"); Console.ReadLine(); } } }
using System.Threading; using System.Threading.Tasks; using Console = System.Console; namespace ConsoleWritePrettyOneDay.App { class Program { static void Main(string[] args) { Spinner.Wait(() => Thread.Sleep(5000), "waiting for sleep"); var task = Task.Run(() => Thread.Sleep(4000)); Spinner.Wait(task, "waiting for task"); Console.WriteLine(); Console.WriteLine("Press [enter] to exit."); Console.ReadLine(); } } }
Add config to the dependency flags.
using System; namespace uSync8.Core.Dependency { [Flags] public enum DependencyFlags { None = 0, IncludeChildren = 2, IncludeAncestors = 4, IncludeDependencies = 8, IncludeViews = 16, IncludeMedia = 32, IncludeLinked = 64, IncludeMediaFiles = 128 } }
using System; namespace uSync8.Core.Dependency { [Flags] public enum DependencyFlags { None = 0, IncludeChildren = 2, IncludeAncestors = 4, IncludeDependencies = 8, IncludeViews = 16, IncludeMedia = 32, IncludeLinked = 64, IncludeMediaFiles = 128, IncludeConfig = 256 } }
Handle paths on Windows properly
using System; namespace Mammoth.Couscous.java.net { internal class URI { private readonly Uri _uri; internal URI(string uri) { try { _uri = new Uri(uri, UriKind.RelativeOrAbsolute); } catch (UriFormatException exception) { throw new URISyntaxException(exception.Message); } } internal URI(Uri uri) { _uri = uri; } internal bool isAbsolute() { return _uri.IsAbsoluteUri; } internal URL toURL() { return new URL(_uri.ToString()); } internal URI resolve(string relativeUri) { if (new URI(relativeUri).isAbsolute()) { return new URI(relativeUri); } else if (_uri.IsAbsoluteUri) { return new URI(new Uri(_uri, relativeUri)); } else { var path = _uri.ToString(); var lastSlashIndex = path.LastIndexOf("/"); var basePath = lastSlashIndex == -1 ? "." : path.Substring(0, lastSlashIndex + 1); return new URI(basePath + relativeUri); } } } }
using System; namespace Mammoth.Couscous.java.net { internal class URI { private readonly Uri _uri; internal URI(string uri) { try { _uri = new Uri(uri, UriKind.RelativeOrAbsolute); } catch (UriFormatException exception) { throw new URISyntaxException(exception.Message); } } internal URI(Uri uri) { _uri = uri; } internal bool isAbsolute() { return _uri.IsAbsoluteUri; } internal URL toURL() { return new URL(_uri.ToString()); } internal URI resolve(string relativeUri) { if (new URI(relativeUri).isAbsolute()) { return new URI(relativeUri); } else if (_uri.IsAbsoluteUri) { return new URI(new Uri(_uri, relativeUri)); } else { var path = _uri.ToString(); var basePath = System.IO.Path.GetDirectoryName(path); return new URI(System.IO.Path.Combine(basePath, relativeUri)); } } } }
Debug mode: Show the number of garbage collections
// Copyright (c) the authors of nanoGames. All rights reserved. // Licensed under the MIT license. See LICENSE.txt in the project root. using NanoGames.Engine; using System.Collections.Generic; using System.Diagnostics; namespace NanoGames.Application { /// <summary> /// A view that measures and draws the current frames per second. /// </summary> internal sealed class FpsView : IView { private readonly Queue<long> _times = new Queue<long>(); /// <inheritdoc/> public void Update(Terminal terminal) { var fontSize = 6; var color = new Color(0.60, 0.35, 0.05); if (DebugMode.IsEnabled) { terminal.Graphics.Print(color, fontSize, new Vector(0, 0), "DEBUG"); } var time = Stopwatch.GetTimestamp(); if (Settings.Instance.ShowFps && _times.Count > 0) { var fps = (double)Stopwatch.Frequency * _times.Count / (time - _times.Peek()); var fpsString = ((int)(fps + 0.5)).ToString("D2"); terminal.Graphics.Print(color, fontSize, new Vector(GraphicsConstants.Width - fpsString.Length * fontSize, 0), fpsString); } if (_times.Count > 128) { _times.Dequeue(); } _times.Enqueue(time); } } }
// Copyright (c) the authors of nanoGames. All rights reserved. // Licensed under the MIT license. See LICENSE.txt in the project root. using NanoGames.Engine; using System.Collections.Generic; using System.Diagnostics; namespace NanoGames.Application { /// <summary> /// A view that measures and draws the current frames per second. /// </summary> internal sealed class FpsView : IView { private readonly Queue<long> _times = new Queue<long>(); /// <inheritdoc/> public void Update(Terminal terminal) { var fontSize = 6; var color = new Color(0.60, 0.35, 0.05); if (DebugMode.IsEnabled) { terminal.Graphics.Print(color, fontSize, new Vector(0, 0), "DEBUG"); for (int i = 0; i <= System.GC.MaxGeneration; ++i) { terminal.Graphics.Print(color, fontSize, new Vector(0, (i + 1) * fontSize), string.Format("GC{0}: {1}", i, System.GC.CollectionCount(i))); } } var time = Stopwatch.GetTimestamp(); if (Settings.Instance.ShowFps && _times.Count > 0) { var fps = (double)Stopwatch.Frequency * _times.Count / (time - _times.Peek()); var fpsString = ((int)(fps + 0.5)).ToString("D2"); terminal.Graphics.Print(color, fontSize, new Vector(GraphicsConstants.Width - fpsString.Length * fontSize, 0), fpsString); } if (_times.Count > 128) { _times.Dequeue(); } _times.Enqueue(time); } } }
Fix rounding error in numbers exercise
public static class AssemblyLine { private const int ProductionRatePerHourForDefaultSpeed = 221; public static double ProductionRatePerHour(int speed) => ProductionRatePerHourForSpeed(speed) * SuccessRate(speed); private static int ProductionRatePerHourForSpeed(int speed) => ProductionRatePerHourForDefaultSpeed * speed; public static int WorkingItemsPerMinute(int speed) => (int)ProductionRatePerHour(speed) / 60; private static double SuccessRate(int speed) { if (speed == 0) return 0.0; if (speed >= 9) return 0.77; if (speed < 5) return 1.0; return 0.9; } }
public static class AssemblyLine { private const int ProductionRatePerHourForDefaultSpeed = 221; public static double ProductionRatePerHour(int speed) => ProductionRatePerHourForSpeed(speed) * SuccessRate(speed); private static int ProductionRatePerHourForSpeed(int speed) => ProductionRatePerHourForDefaultSpeed * speed; public static int WorkingItemsPerMinute(int speed) => (int)(ProductionRatePerHour(speed) / 60); private static double SuccessRate(int speed) { if (speed == 0) return 0.0; if (speed >= 9) return 0.77; if (speed < 5) return 1.0; return 0.9; } }
Fix explosion reading out time values from wrong clock
// 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.Rulesets.Catch.Skinning.Default; using osu.Game.Rulesets.Objects.Pooling; using osu.Game.Skinning; namespace osu.Game.Rulesets.Catch.UI { public class HitExplosion : PoolableDrawableWithLifetime<HitExplosionEntry> { private SkinnableDrawable skinnableExplosion; public HitExplosion() { RelativeSizeAxes = Axes.Both; Anchor = Anchor.BottomCentre; Origin = Anchor.BottomCentre; } [BackgroundDependencyLoader] private void load() { InternalChild = skinnableExplosion = new SkinnableDrawable(new CatchSkinComponent(CatchSkinComponents.HitExplosion), _ => new DefaultHitExplosion()) { CentreComponent = false, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre }; } protected override void OnApply(HitExplosionEntry entry) { base.OnApply(entry); ApplyTransformsAt(double.MinValue, true); ClearTransforms(true); (skinnableExplosion.Drawable as IHitExplosion)?.Animate(entry); LifetimeEnd = skinnableExplosion.Drawable.LatestTransformEndTime; } } }
// 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.Rulesets.Catch.Skinning.Default; using osu.Game.Rulesets.Objects.Pooling; using osu.Game.Skinning; namespace osu.Game.Rulesets.Catch.UI { public class HitExplosion : PoolableDrawableWithLifetime<HitExplosionEntry> { private SkinnableDrawable skinnableExplosion; public HitExplosion() { RelativeSizeAxes = Axes.Both; Anchor = Anchor.BottomCentre; Origin = Anchor.BottomCentre; } [BackgroundDependencyLoader] private void load() { InternalChild = skinnableExplosion = new SkinnableDrawable(new CatchSkinComponent(CatchSkinComponents.HitExplosion), _ => new DefaultHitExplosion()) { CentreComponent = false, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre }; } protected override void OnApply(HitExplosionEntry entry) { base.OnApply(entry); if (IsLoaded) apply(entry); } protected override void LoadComplete() { base.LoadComplete(); apply(Entry); } private void apply(HitExplosionEntry entry) { ApplyTransformsAt(double.MinValue, true); ClearTransforms(true); (skinnableExplosion.Drawable as IHitExplosion)?.Animate(entry); LifetimeEnd = skinnableExplosion.Drawable.LatestTransformEndTime; } } }
Switch Guid implementation temporarily to avoid compile time error
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Input.Bindings; using osu.Game.Database; using Realms; namespace osu.Game.Input.Bindings { [MapTo(nameof(KeyBinding))] public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding { [PrimaryKey] public Guid ID { get; set; } public int? RulesetID { get; set; } public int? Variant { get; set; } public KeyCombination KeyCombination { get => KeyCombinationString; set => KeyCombinationString = value.ToString(); } public object Action { get => ActionInt; set => ActionInt = (int)value; } [MapTo(nameof(Action))] public int ActionInt { get; set; } [MapTo(nameof(KeyCombination))] public string KeyCombinationString { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Input.Bindings; using osu.Game.Database; using Realms; namespace osu.Game.Input.Bindings { [MapTo(nameof(KeyBinding))] public class RealmKeyBinding : RealmObject, IHasGuidPrimaryKey, IKeyBinding { [PrimaryKey] public string StringGuid { get; set; } [Ignored] public Guid ID { get => Guid.Parse(StringGuid); set => StringGuid = value.ToString(); } public int? RulesetID { get; set; } public int? Variant { get; set; } public KeyCombination KeyCombination { get => KeyCombinationString; set => KeyCombinationString = value.ToString(); } public object Action { get => ActionInt; set => ActionInt = (int)value; } [MapTo(nameof(Action))] public int ActionInt { get; set; } [MapTo(nameof(KeyCombination))] public string KeyCombinationString { get; set; } } }
Fix ordering bug when chaining Tweens
using UnityEngine; using System.Collections; using System; public class AnimateToPoint : MonoBehaviour { private SimpleTween tween; private Vector3 sourcePos; private Vector3 targetPos; private Action onComplete; private float timeScale; private float timer; public void Trigger(SimpleTween tween, Vector3 point) { Trigger(tween, point, () => {}); } public void Trigger(SimpleTween tween, Vector3 point, Action onComplete) { this.tween = tween; this.onComplete = onComplete; sourcePos = transform.position; targetPos = point; timeScale = 1.0f / tween.Duration; timer = 0.0f; } private void Update() { if (tween != null) { if (timer > 1.0f) { transform.position = targetPos; onComplete(); tween = null; } else { transform.position = tween.Evaluate(sourcePos, targetPos, timer); } timer += timeScale * Time.deltaTime; } } }
using UnityEngine; using System.Collections; using System; public class AnimateToPoint : MonoBehaviour { private SimpleTween tween; private Vector3 sourcePos; private Vector3 targetPos; private Action onComplete; private float timeScale; private float timer; public void Trigger(SimpleTween tween, Vector3 point) { Trigger(tween, point, () => {}); } public void Trigger(SimpleTween tween, Vector3 point, Action onComplete) { this.tween = tween; this.onComplete = onComplete; sourcePos = transform.position; targetPos = point; timeScale = 1.0f / tween.Duration; timer = 0.0f; } private void Update() { if (tween != null) { if (timer > 1.0f) { tween = null; transform.position = targetPos; onComplete(); } else { transform.position = tween.Evaluate(sourcePos, targetPos, timer); } timer += timeScale * Time.deltaTime; } } }
Change message to indicate player is freed from track
using UnityEngine; using System.Collections; public class AdminModeMessageWindow : MonoBehaviour { private const float WINDOW_WIDTH = 300; private const float WINDOW_HEIGHT = 120; private const float MESSAGE_HEIGHT = 60; private const float BUTTON_HEIGHT = 30; private const float BUTTON_WIDTH = 40; private string Message; public void Initialize() { Message = "Could not sync player records to server.\nReason \"Player " + PlayerOptions.Name + " log corrupted\".\nAdmin mode enabled"; } void OnGUI () { GUI.Window(0, WindowRect, MessageWindow, "Error"); } void MessageWindow(int windowID) { GUI.Label(LabelRect, Message); if (GUI.Button(ButtonRect, "OK")) { enabled = false; } } private Rect WindowRect { get { var anchor = TransformToGuiFinder.Find(transform); return new Rect(anchor.x - WINDOW_WIDTH / 2, anchor.y - WINDOW_HEIGHT / 2, WINDOW_WIDTH, WINDOW_HEIGHT); } } private Rect LabelRect { get { return new Rect(10, 20, WINDOW_WIDTH, MESSAGE_HEIGHT); } } private Rect ButtonRect { get { return new Rect((WINDOW_WIDTH / 2) - (BUTTON_WIDTH / 2), 20 + MESSAGE_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); } } }
using UnityEngine; using System.Collections; public class AdminModeMessageWindow : MonoBehaviour { private const float WINDOW_WIDTH = 300; private const float WINDOW_HEIGHT = 120; private const float MESSAGE_HEIGHT = 60; private const float BUTTON_HEIGHT = 30; private const float BUTTON_WIDTH = 40; private string Message; public void Initialize() { Message = "Could not sync player records to server.\nReason \"Player " + PlayerOptions.Name + " log corrupted\".\nAdmin mode enabled and player freed from track."; } void OnGUI () { GUI.Window(0, WindowRect, MessageWindow, "Error"); } void MessageWindow(int windowID) { GUI.Label(LabelRect, Message); if (GUI.Button(ButtonRect, "OK")) { enabled = false; } } private Rect WindowRect { get { var anchor = TransformToGuiFinder.Find(transform); return new Rect(anchor.x - WINDOW_WIDTH / 2, anchor.y - WINDOW_HEIGHT / 2, WINDOW_WIDTH, WINDOW_HEIGHT); } } private Rect LabelRect { get { return new Rect(10, 20, WINDOW_WIDTH, MESSAGE_HEIGHT); } } private Rect ButtonRect { get { return new Rect((WINDOW_WIDTH / 2) - (BUTTON_WIDTH / 2), 20 + MESSAGE_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); } } }
Handle optional version and fallback
using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public interface IGetMetrics { IEnumerable<Metric> Deserialize(string response); } public class GetMetrics : IGetMetrics { public IEnumerable<Metric> Deserialize(string response) { var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response); return deserializeObject .Select(x => new Metric { Name = x.Key, Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(), WindowSize = x.Value.windowSize.ToObject<float>() }); } } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public interface IGetMetrics { IEnumerable<Metric> Deserialize(string response); } public class GetMetrics : IGetMetrics { public IEnumerable<Metric> Deserialize(string response) { var jObject = JObject.Parse(response); JToken versionToken; jObject.TryGetValue("version", out versionToken); var version = "0"; if (versionToken != null && versionToken.HasValues) { version = versionToken.Value<string>(); } if (version.Equals("0", StringComparison.OrdinalIgnoreCase)) { var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response); return deserializeObject .Select(x => new Metric { Name = x.Key, Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(), WindowSize = x.Value.windowSize.ToObject<float>() }); } return Enumerable.Empty<Metric>(); } } }
Fix the query string stuff
// ========================================================================== // SingleUrlsMiddleware.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Squidex.Pipeline { public sealed class SingleUrlsMiddleware { private readonly RequestDelegate next; private readonly ILogger<SingleUrlsMiddleware> logger; public SingleUrlsMiddleware(RequestDelegate next, ILoggerFactory factory) { this.next = next; logger = factory.CreateLogger<SingleUrlsMiddleware>(); } public async Task Invoke(HttpContext context) { var currentUrl = string.Concat(context.Request.Scheme, "://", context.Request.Host, context.Request.Path); var hostName = context.Request.Host.ToString().ToLowerInvariant(); if (hostName.StartsWith("www")) { hostName = hostName.Substring(3); } var requestPath = context.Request.Path.ToString(); if (!requestPath.EndsWith("/") && !requestPath.Contains(".")) { requestPath = requestPath + "/"; } var newUrl = string.Concat("https://", hostName, requestPath); if (!string.Equals(newUrl, currentUrl, StringComparison.OrdinalIgnoreCase)) { logger.LogError("Invalid url: {0} instead {1}", currentUrl, newUrl); context.Response.Redirect(newUrl, true); } else { await next(context); } } } }
// ========================================================================== // SingleUrlsMiddleware.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Squidex.Pipeline { public sealed class SingleUrlsMiddleware { private readonly RequestDelegate next; private readonly ILogger<SingleUrlsMiddleware> logger; public SingleUrlsMiddleware(RequestDelegate next, ILoggerFactory factory) { this.next = next; logger = factory.CreateLogger<SingleUrlsMiddleware>(); } public async Task Invoke(HttpContext context) { var currentUrl = string.Concat(context.Request.Scheme, "://", context.Request.Host, context.Request.Path); var hostName = context.Request.Host.ToString().ToLowerInvariant(); if (hostName.StartsWith("www")) { hostName = hostName.Substring(3); } var requestPath = context.Request.Path.ToString(); if (!requestPath.EndsWith("/") && !requestPath.Contains(".")) { requestPath = requestPath + "/"; } var newUrl = string.Concat("https://", hostName, requestPath); if (!string.Equals(newUrl, currentUrl, StringComparison.OrdinalIgnoreCase)) { logger.LogError("Invalid url: {0} instead {1}", currentUrl, newUrl); context.Response.Redirect(newUrl + context.Request.QueryString, true); } else { await next(context); } } } }
Fix Fault; Incorrect check in ctor
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SceneJect.Common { public abstract class DepedencyInjectionFactoryService { /// <summary> /// Service for resolving dependencies. /// </summary> protected IResolver resolverService { get; } /// <summary> /// Strategy for injection. /// </summary> protected IInjectionStrategy injectionStrategy { get; } public DepedencyInjectionFactoryService(IResolver resolver, IInjectionStrategy injectionStrat) { if (resolver == null) throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null."); if (injectionStrategy == null) throw new ArgumentNullException(nameof(injectionStrategy), $"Provided {nameof(IInjectionStrategy)} service provided is null."); injectionStrategy = injectionStrat; resolverService = resolver; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SceneJect.Common { public abstract class DepedencyInjectionFactoryService { /// <summary> /// Service for resolving dependencies. /// </summary> protected IResolver resolverService { get; } /// <summary> /// Strategy for injection. /// </summary> protected IInjectionStrategy injectionStrategy { get; } public DepedencyInjectionFactoryService(IResolver resolver, IInjectionStrategy injectionStrat) { if (resolver == null) throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null."); if (injectionStrat == null) throw new ArgumentNullException(nameof(injectionStrat), $"Provided {nameof(IInjectionStrategy)} service provided is null."); injectionStrategy = injectionStrat; resolverService = resolver; } } }
Fix logic to use the new task based async pattern
using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace WootzJs.Mvc { public class ControllerActionInvoker : IActionInvoker { public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action) { var parameters = action.GetParameters(); var args = new object[parameters.Length]; var lastParameter = parameters.LastOrDefault(); // If async if (lastParameter != null && lastParameter.ParameterType == typeof(Action<ActionResult>)) { return (Task<ActionResult>)action.Invoke(context.Controller, args); } // If synchronous else { var actionResult = (ActionResult)action.Invoke(context.Controller, args); return Task.FromResult(actionResult); } } } }
using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace WootzJs.Mvc { public class ControllerActionInvoker : IActionInvoker { public Task<ActionResult> InvokeAction(ControllerContext context, MethodInfo action) { var parameters = action.GetParameters(); var args = new object[parameters.Length]; // If async if (action.ReturnType == typeof(Task<ActionResult>)) { return (Task<ActionResult>)action.Invoke(context.Controller, args); } // If synchronous else { var actionResult = (ActionResult)action.Invoke(context.Controller, args); return Task.FromResult(actionResult); } } } }
Fix registration to send nightly
using FluentScheduler; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using System; namespace BatteryCommander.Web.Jobs { internal static class JobHandler { public static void WithScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger(typeof(JobHandler)); JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name); JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration); JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name); JobManager.UseUtcTime(); JobManager.JobFactory = new JobFactory(app.ApplicationServices); var registry = new Registry(); registry.Schedule<SqliteBackupJob>().ToRunNow().AndEvery(1).Days().At(hours: 12, minutes: 0); JobManager.Initialize(registry); } private class JobFactory : IJobFactory { private readonly IServiceProvider serviceProvider; public JobFactory(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public IJob GetJobInstance<T>() where T : IJob { return serviceProvider.GetService(typeof(T)) as IJob; } } } }
using FluentScheduler; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; using System; namespace BatteryCommander.Web.Jobs { internal static class JobHandler { public static void WithScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger(typeof(JobHandler)); JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name); JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration); JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name); JobManager.UseUtcTime(); JobManager.JobFactory = new JobFactory(app.ApplicationServices); var registry = new Registry(); registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 12, minutes: 0); JobManager.Initialize(registry); } private class JobFactory : IJobFactory { private readonly IServiceProvider serviceProvider; public JobFactory(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public IJob GetJobInstance<T>() where T : IJob { return serviceProvider.GetService(typeof(T)) as IJob; } } } }
Fix code coverage - exclude remote-only class
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ namespace Apache.Ignite.Core.Tests.TestDll { using System.Linq; /// <summary> /// Extension methods for tests. /// </summary> public static class TestExtensions { /// <summary> /// Reverses the string. /// </summary> public static string ReverseString(this string str) { return new string(str.Reverse().ToArray()); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ namespace Apache.Ignite.Core.Tests.TestDll { using System.Diagnostics.CodeAnalysis; using System.Linq; /// <summary> /// Extension methods for tests. /// </summary> [ExcludeFromCodeCoverage] public static class TestExtensions { /// <summary> /// Reverses the string. /// </summary> public static string ReverseString(this string str) { return new string(str.Reverse().ToArray()); } } }
Revert "added try catch, test commit"
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { try { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } catch (Exception) { throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } } }
Apply hang mitigating timeout in VerifyOpen and VerifyClosed
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class Dialog_OutOfProc : OutOfProcComponent { public Dialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void VerifyOpen(string dialogName) { // FindDialog will wait until the dialog is open, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: true, CancellationToken.None); // Wait for application idle to ensure the dialog is fully initialized VisualStudioInstance.WaitForApplicationIdle(CancellationToken.None); } public void VerifyClosed(string dialogName) { // FindDialog will wait until the dialog is closed, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: false, CancellationToken.None); } public void Click(string dialogName, string buttonName) => DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), dialogName, buttonName); private IntPtr GetMainWindowHWnd() => VisualStudioInstance.Shell.GetHWnd(); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class Dialog_OutOfProc : OutOfProcComponent { public Dialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void VerifyOpen(string dialogName) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); // FindDialog will wait until the dialog is open, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: true, cancellationTokenSource.Token); // Wait for application idle to ensure the dialog is fully initialized VisualStudioInstance.WaitForApplicationIdle(cancellationTokenSource.Token); } public void VerifyClosed(string dialogName) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); // FindDialog will wait until the dialog is closed, so the return value is unused. DialogHelpers.FindDialogByName(GetMainWindowHWnd(), dialogName, isOpen: false, cancellationTokenSource.Token); } public void Click(string dialogName, string buttonName) => DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), dialogName, buttonName); private IntPtr GetMainWindowHWnd() => VisualStudioInstance.Shell.GetHWnd(); } }
Update history list to also sort by gameplay order
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osuTK; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist { /// <summary> /// A historically-ordered list of <see cref="DrawableRoomPlaylistItem"/>s. /// </summary> public class MultiplayerHistoryList : DrawableRoomPlaylist { public MultiplayerHistoryList() : base(false, false, true) { } protected override FillFlowContainer<RearrangeableListItem<PlaylistItem>> CreateListFillFlowContainer() => new HistoryFillFlowContainer { Spacing = new Vector2(0, 2) }; private class HistoryFillFlowContainer : FillFlowContainer<RearrangeableListItem<PlaylistItem>> { public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.Reverse(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osuTK; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist { /// <summary> /// A historically-ordered list of <see cref="DrawableRoomPlaylistItem"/>s. /// </summary> public class MultiplayerHistoryList : DrawableRoomPlaylist { public MultiplayerHistoryList() : base(false, false, true) { } protected override FillFlowContainer<RearrangeableListItem<PlaylistItem>> CreateListFillFlowContainer() => new HistoryFillFlowContainer { Spacing = new Vector2(0, 2) }; private class HistoryFillFlowContainer : FillFlowContainer<RearrangeableListItem<PlaylistItem>> { public override IEnumerable<Drawable> FlowingChildren => base.FlowingChildren.OfType<RearrangeableListItem<PlaylistItem>>().OrderByDescending(item => item.Model.GameplayOrder); } } }
Comment out batchSize for now as not used
using System; using System.Data; using NHibernate.Engine; namespace NHibernate.Impl { /// <summary> /// Summary description for BatchingBatcher. /// </summary> internal class BatchingBatcher : BatcherImpl { private int batchSize; private int[] expectedRowCounts; /// <summary> /// /// </summary> /// <param name="session"></param> public BatchingBatcher( ISessionImplementor session ) : base( session ) { expectedRowCounts = new int[ Factory.BatchSize ]; } /// <summary> /// /// </summary> /// <param name="expectedRowCount"></param> public override void AddToBatch( int expectedRowCount ) { throw new NotImplementedException( "Batching not implemented yet" ); /* log.Info( "Adding to batch" ); IDbCommand batchUpdate = CurrentStatment; */ } /// <summary> /// /// </summary> /// <param name="ps"></param> protected override void DoExecuteBatch( IDbCommand ps ) { throw new NotImplementedException( "Batching not implemented yet" ); } } }
using System; using System.Data; using NHibernate.Engine; namespace NHibernate.Impl { /// <summary> /// Summary description for BatchingBatcher. /// </summary> internal class BatchingBatcher : BatcherImpl { //private int batchSize; private int[] expectedRowCounts; /// <summary> /// /// </summary> /// <param name="session"></param> public BatchingBatcher( ISessionImplementor session ) : base( session ) { expectedRowCounts = new int[ Factory.BatchSize ]; } /// <summary> /// /// </summary> /// <param name="expectedRowCount"></param> public override void AddToBatch( int expectedRowCount ) { throw new NotImplementedException( "Batching not implemented yet" ); /* log.Info( "Adding to batch" ); IDbCommand batchUpdate = CurrentStatment; */ } /// <summary> /// /// </summary> /// <param name="ps"></param> protected override void DoExecuteBatch( IDbCommand ps ) { throw new NotImplementedException( "Batching not implemented yet" ); } } }
Fix the sample to await when writing directly to the output stream in a controller.
using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using MvcSample.Web.Models; namespace MvcSample.Web.RandomNameSpace { public class Home2Controller { private User _user = new User() { Name = "User Name", Address = "Home Address" }; [Activate] public HttpResponse Response { get; set; } public ActionContext ActionContext { get; set; } public string Index() { return "Hello World: my namespace is " + this.GetType().Namespace; } public ActionResult Something() { return new ContentResult { Content = "Hello World From Content" }; } public ActionResult Hello() { return new ContentResult { Content = "Hello World", }; } public void Raw() { Response.WriteAsync("Hello World raw"); } public ActionResult UserJson() { var jsonResult = new JsonResult(_user); return jsonResult; } public User User() { return _user; } } }
using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using MvcSample.Web.Models; namespace MvcSample.Web.RandomNameSpace { public class Home2Controller { private User _user = new User() { Name = "User Name", Address = "Home Address" }; [Activate] public HttpResponse Response { get; set; } public ActionContext ActionContext { get; set; } public string Index() { return "Hello World: my namespace is " + this.GetType().Namespace; } public ActionResult Something() { return new ContentResult { Content = "Hello World From Content" }; } public ActionResult Hello() { return new ContentResult { Content = "Hello World", }; } public async Task Raw() { await Response.WriteAsync("Hello World raw"); } public ActionResult UserJson() { var jsonResult = new JsonResult(_user); return jsonResult; } public User User() { return _user; } } }
Validate existence of x-pack-core for 6.2.4+
using System; using System.Linq; using Nest; using Tests.Framework.ManagedElasticsearch.Nodes; using Tests.Framework.ManagedElasticsearch.Plugins; namespace Tests.Framework.ManagedElasticsearch.Tasks.ValidationTasks { public class ValidatePluginsTask : NodeValidationTaskBase { public override void Validate(IElasticClient client, NodeConfiguration configuration) { var v = configuration.ElasticsearchVersion; var requiredMonikers = ElasticsearchPluginCollection.Supported .Where(plugin => plugin.IsValid(v) && configuration.RequiredPlugins.Contains(plugin.Plugin)) .Select(plugin => plugin.Moniker) .ToList(); if (!requiredMonikers.Any()) return; var checkPlugins = client.CatPlugins(); if (!checkPlugins.IsValid) throw new Exception($"Failed to check plugins: {checkPlugins.DebugInformation}."); var missingPlugins = requiredMonikers .Except((checkPlugins.Records ?? Enumerable.Empty<CatPluginsRecord>()).Select(r => r.Component)) .ToList(); if (!missingPlugins.Any()) return; var pluginsString = string.Join(", ", missingPlugins); throw new Exception($"Already running elasticsearch missed the following plugin(s): {pluginsString}."); } } }
using System; using System.Linq; using Nest; using Tests.Document.Multiple.UpdateByQuery; using Tests.Framework.ManagedElasticsearch.Nodes; using Tests.Framework.ManagedElasticsearch.Plugins; namespace Tests.Framework.ManagedElasticsearch.Tasks.ValidationTasks { public class ValidatePluginsTask : NodeValidationTaskBase { public override void Validate(IElasticClient client, NodeConfiguration configuration) { var v = configuration.ElasticsearchVersion; var requiredMonikers = ElasticsearchPluginCollection.Supported .Where(plugin => plugin.IsValid(v) && configuration.RequiredPlugins.Contains(plugin.Plugin)) .Select(plugin => plugin.Moniker) .ToList(); if (!requiredMonikers.Any()) return; // 6.2.4 splits out X-Pack into separate plugin names if (requiredMonikers.Contains(ElasticsearchPlugin.XPack.Moniker()) && TestClient.VersionUnderTestSatisfiedBy(">=6.2.4")) { requiredMonikers.Remove(ElasticsearchPlugin.XPack.Moniker()); requiredMonikers.Add(ElasticsearchPlugin.XPack.Moniker() + "-core"); } var checkPlugins = client.CatPlugins(); if (!checkPlugins.IsValid) throw new Exception($"Failed to check plugins: {checkPlugins.DebugInformation}."); var missingPlugins = requiredMonikers .Except((checkPlugins.Records ?? Enumerable.Empty<CatPluginsRecord>()).Select(r => r.Component)) .ToList(); if (!missingPlugins.Any()) return; var pluginsString = string.Join(", ", missingPlugins); throw new Exception($"Already running elasticsearch missed the following plugin(s): {pluginsString}."); } } }
Rewrite with expression bodies properties syntax.
using System.Reflection; using P2E.Interfaces.DataObjects; namespace P2E.DataObjects { public class ApplicationInformation : IApplicationInformation { public string Name { get; } public string Version { get; } public ApplicationInformation() { Name = Assembly.GetEntryAssembly().GetName().Name; Version = Assembly.GetEntryAssembly().GetName().Version.ToString(); } } }
using System.Reflection; using P2E.Interfaces.DataObjects; namespace P2E.DataObjects { public class ApplicationInformation : IApplicationInformation { public string Name => Assembly.GetEntryAssembly().GetName().Name; public string Version => Assembly.GetEntryAssembly().GetName().Version.ToString(); } }
Use correct URL for help
using System; using System.Collections.Generic; using System.Text; namespace BitDiffer.Common.Misc { public class Constants { public const string ProductName = "BitDiffer"; public const string ProductSubTitle = "Assembly Comparison Tool"; public const string HelpUrl = "https://github.com/grennis/bitdiffer/wiki"; public const string ExtractionDomainPrefix = "Temp App Domain"; public const string ComparisonEmailSubject = "BitDiffer Assembly Comparison Report"; } }
using System; using System.Collections.Generic; using System.Text; namespace BitDiffer.Common.Misc { public class Constants { public const string ProductName = "BitDiffer"; public const string ProductSubTitle = "Assembly Comparison Tool"; public const string HelpUrl = "https://github.com/bitdiffer/bitdiffer/wiki"; public const string ExtractionDomainPrefix = "Temp App Domain"; public const string ComparisonEmailSubject = "BitDiffer Assembly Comparison Report"; } }
Bump assembly info for 1.3.0 release
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("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.3.0")] [assembly: AssemblyFileVersion("1.2.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
Add checks in product rating service
using ZobShop.Data.Contracts; using ZobShop.Factories; using ZobShop.Models; using ZobShop.Services.Contracts; namespace ZobShop.Services { public class ProductRatingService : IProductRatingService { private readonly IRepository<User> userRepository; private readonly IRepository<ProductRating> productRatingRepository; private readonly IRepository<Product> productRepository; private readonly IUnitOfWork unitOfWork; private readonly IProductRatingFactory factory; public ProductRatingService(IRepository<User> userRepository, IRepository<Product> productRepository, IRepository<ProductRating> productRatingRepository, IUnitOfWork unitOfWork, IProductRatingFactory factory) { this.userRepository = userRepository; this.productRepository = productRepository; this.productRatingRepository = productRatingRepository; this.unitOfWork = unitOfWork; this.factory = factory; } public ProductRating CreateProductRating(int rating, string content, int productId, string userId) { var product = this.productRepository.GetById(productId); var user = this.userRepository.GetById(userId); var newRating = this.factory.CreateProductRating(rating, content, product, user); this.productRatingRepository.Add(newRating); this.unitOfWork.Commit(); return newRating; } } }
using System; using ZobShop.Data.Contracts; using ZobShop.Factories; using ZobShop.Models; using ZobShop.Services.Contracts; namespace ZobShop.Services { public class ProductRatingService : IProductRatingService { private readonly IRepository<User> userRepository; private readonly IRepository<ProductRating> productRatingRepository; private readonly IRepository<Product> productRepository; private readonly IUnitOfWork unitOfWork; private readonly IProductRatingFactory factory; public ProductRatingService(IRepository<User> userRepository, IRepository<Product> productRepository, IRepository<ProductRating> productRatingRepository, IUnitOfWork unitOfWork, IProductRatingFactory factory) { if (userRepository == null) { throw new ArgumentNullException("user repository cannot be null"); } if (productRepository == null) { throw new ArgumentNullException("product repository cannot be null"); } if (productRatingRepository == null) { throw new ArgumentNullException("product rating repository cannot be null"); } if (unitOfWork == null) { throw new ArgumentNullException("unit of work repository cannot be null"); } if (factory == null) { throw new ArgumentNullException("factory repository cannot be null"); } this.userRepository = userRepository; this.productRepository = productRepository; this.productRatingRepository = productRatingRepository; this.unitOfWork = unitOfWork; this.factory = factory; } public ProductRating CreateProductRating(int rating, string content, int productId, string userId) { var product = this.productRepository.GetById(productId); var user = this.userRepository.GetById(userId); var newRating = this.factory.CreateProductRating(rating, content, product, user); this.productRatingRepository.Add(newRating); this.unitOfWork.Commit(); return newRating; } } }
Improve translation when removing strings from names!
 namespace LINQToTreeHelpers { public static class Utils { /// <summary> /// Write out an object. Eventually, with ROOTNET improvements this will work better and perahps /// won't be needed! /// </summary> /// <param name="obj"></param> /// <param name="dir"></param> internal static void InternalWriteObject(this ROOTNET.Interface.NTObject obj, ROOTNET.Interface.NTDirectory dir) { var h = obj as ROOTNET.Interface.NTH1; if (h != null) { var copy = h.Clone(); dir.WriteTObject(copy); // Ugly from a memory pov, but... copy.SetNull(); } else { dir.WriteTObject(obj); obj.SetNull(); } } /// <summary> /// Take a string and "sanatize" it for a root name. /// </summary> /// <param name="name">Text name to be used as a ROOT name</param> /// <returns>argument name with spaces removes, as well as other characters</returns> public static string FixupForROOTName(this string name) { var result = name.Replace(" ", ""); result = result.Replace("_{", ""); result = result.Replace("{", ""); result = result.Replace("}", ""); result = result.Replace("-", ""); result = result.Replace("\\", ""); result = result.Replace("%", ""); result = result.Replace("<", ""); result = result.Replace(">", ""); return result; } } }
 namespace LINQToTreeHelpers { public static class Utils { /// <summary> /// Write out an object. Eventually, with ROOTNET improvements this will work better and perahps /// won't be needed! /// </summary> /// <param name="obj"></param> /// <param name="dir"></param> internal static void InternalWriteObject(this ROOTNET.Interface.NTObject obj, ROOTNET.Interface.NTDirectory dir) { var h = obj as ROOTNET.Interface.NTH1; if (h != null) { var copy = h.Clone(); dir.WriteTObject(copy); // Ugly from a memory pov, but... copy.SetNull(); } else { dir.WriteTObject(obj); obj.SetNull(); } } /// <summary> /// Take a string and "sanatize" it for a root name. /// </summary> /// <param name="name">Text name to be used as a ROOT name</param> /// <returns>argument name with spaces removes, as well as other characters</returns> public static string FixupForROOTName(this string name) { var result = name.Replace(" ", ""); result = result.Replace("_{", ""); result = result.Replace("{", ""); result = result.Replace("}", ""); result = result.Replace("-", ""); result = result.Replace("\\", ""); result = result.Replace("%", ""); result = result.Replace("<", "lt"); result = result.Replace(">", "gt"); return result; } } }
Make sure NONEXISTENT_CELLS is serialized into nonexistentCells
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2014 SmartsheetClient // %% // 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. // %[license] using System.Runtime.Serialization; namespace Smartsheet.Api.Models { /// <summary> /// Represents specific objects that can be excluded in some responses. /// </summary> public enum ObjectExclusion { /// <summary> /// The discussions /// </summary> [EnumMember(Value = "nonexistentCells")] NONEXISTENT_CELLS } }
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2014 SmartsheetClient // %% // 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. // %[license] using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; namespace Smartsheet.Api.Models { /// <summary> /// Represents specific objects that can be excluded in some responses. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ObjectExclusion { /// <summary> /// The discussions /// </summary> [EnumMember(Value = "nonexistentCells")] NONEXISTENT_CELLS } }
Revert "remove unused private setters"
using System; namespace FilterLists.Agent.Entities { public class ListInfo { public int Id { get; } public Uri ViewUrl { get; } } }
using System; namespace FilterLists.Agent.Entities { public class ListInfo { public int Id { get; private set; } public Uri ViewUrl { get; private set; } } }
Destroy bullets on trigger event
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { public int bulletSpeed = 715; void Start () { GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * bulletSpeed); } }
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { public int bulletSpeed = 715; void Start() { GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * bulletSpeed); } void OnTriggerEnter(Collider other) { Destroy(gameObject); } }
Apply force unbold to dropdown options
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DropdownLanguageFontUpdater : MonoBehaviour { [SerializeField] private Text textComponent; void Start () { Font overrideFont = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1].overrideFont; if (overrideFont != null) textComponent.font = overrideFont; } void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DropdownLanguageFontUpdater : MonoBehaviour { [SerializeField] private Text textComponent; void Start () { var language = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1]; if (language.overrideFont != null) { textComponent.font = language.overrideFont; if (language.forceUnbold) textComponent.fontStyle = FontStyle.Normal; } } void Update () { } }
Load the precompilation type from the loaded assembly
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Reflection; using System.Runtime.Loader; using Microsoft.AspNetCore.Mvc.ApplicationParts; namespace Microsoft.AspNetCore.Mvc.Razor.Compilation { public static class CompiledViewManfiest { public static readonly string PrecompiledViewsAssemblySuffix = ".PrecompiledViews"; public static Type GetManifestType(AssemblyPart assemblyPart, string typeName) { EnsureFeatureAssembly(assemblyPart); var precompiledAssemblyName = new AssemblyName(assemblyPart.Assembly.FullName); precompiledAssemblyName.Name = precompiledAssemblyName.Name + PrecompiledViewsAssemblySuffix; return Type.GetType($"{typeName},{precompiledAssemblyName}"); } private static void EnsureFeatureAssembly(AssemblyPart assemblyPart) { if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty(assemblyPart.Assembly.Location)) { return; } var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name + PrecompiledViewsAssemblySuffix + ".dll"; var precompiledAssemblyFilePath = Path.Combine( Path.GetDirectoryName(assemblyPart.Assembly.Location), precompiledAssemblyFileName); if (File.Exists(precompiledAssemblyFilePath)) { try { Assembly.LoadFile(precompiledAssemblyFilePath); } catch (FileLoadException) { // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly. } } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Reflection; using System.Runtime.Loader; using Microsoft.AspNetCore.Mvc.ApplicationParts; namespace Microsoft.AspNetCore.Mvc.Razor.Compilation { public static class CompiledViewManfiest { public static readonly string PrecompiledViewsAssemblySuffix = ".PrecompiledViews"; public static Type GetManifestType(AssemblyPart assemblyPart, string typeName) { var assembly = GetFeatureAssembly(assemblyPart); return assembly?.GetType(typeName); } private static Assembly GetFeatureAssembly(AssemblyPart assemblyPart) { if (assemblyPart.Assembly.IsDynamic || string.IsNullOrEmpty(assemblyPart.Assembly.Location)) { return null; } var precompiledAssemblyFileName = assemblyPart.Assembly.GetName().Name + PrecompiledViewsAssemblySuffix + ".dll"; var precompiledAssemblyFilePath = Path.Combine( Path.GetDirectoryName(assemblyPart.Assembly.Location), precompiledAssemblyFileName); if (File.Exists(precompiledAssemblyFilePath)) { try { return Assembly.LoadFile(precompiledAssemblyFilePath); } catch (FileLoadException) { // Don't throw if assembly cannot be loaded. This can happen if the file is not a managed assembly. } } return null; } } }
Remove empty method checked in by mistake
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Elasticsearch.Net; using FluentAssertions; using Nest; using Nest.Tests.MockData.Domain; using NUnit.Framework; namespace Nest.Tests.Unit.ObjectInitializer.Index { [TestFixture] public class IndexRequestTests : BaseJsonTests { private readonly IElasticsearchResponse _status; public IndexRequestTests() { var newProject = new ElasticsearchProject { Id = 15, Name = "Some awesome new elasticsearch project" }; var request = new IndexRequest<ElasticsearchProject>(newProject) { Replication = Replication.Async }; //TODO Index(request) does not work as expected var response = this._client.Index<ElasticsearchProject>(request); this._status = response.ConnectionStatus; } public void SettingsTest() { } [Test] public void Url() { this._status.RequestUrl.Should().EndWith("/nest_test_data/elasticsearchprojects/15?replication=async"); this._status.RequestMethod.Should().Be("PUT"); } [Test] public void IndexBody() { this.JsonEquals(this._status.Request, MethodBase.GetCurrentMethod()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Elasticsearch.Net; using FluentAssertions; using Nest; using Nest.Tests.MockData.Domain; using NUnit.Framework; namespace Nest.Tests.Unit.ObjectInitializer.Index { [TestFixture] public class IndexRequestTests : BaseJsonTests { private readonly IElasticsearchResponse _status; public IndexRequestTests() { var newProject = new ElasticsearchProject { Id = 15, Name = "Some awesome new elasticsearch project" }; var request = new IndexRequest<ElasticsearchProject>(newProject) { Replication = Replication.Async }; //TODO Index(request) does not work as expected var response = this._client.Index<ElasticsearchProject>(request); this._status = response.ConnectionStatus; } [Test] public void Url() { this._status.RequestUrl.Should().EndWith("/nest_test_data/elasticsearchprojects/15?replication=async"); this._status.RequestMethod.Should().Be("PUT"); } [Test] public void IndexBody() { this.JsonEquals(this._status.Request, MethodBase.GetCurrentMethod()); } } }
Fix wrong mapping for Translation, should be mapped as a property instead of Component
// Copyright 2017 by PeopleWare n.v.. // // 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 NHibernate.Mapping.ByCode.Conformist; using PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Models; namespace PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Mappers { public class PlaneMapper : ComponentMapping<Plane> { public PlaneMapper() { Component(p => p.Normal); Component(p => p.Translation); } } }
// Copyright 2017 by PeopleWare n.v.. // // 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 NHibernate.Mapping.ByCode.Conformist; using PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Models; namespace PPWCode.Vernacular.NHibernate.I.Tests.DictionariesAndLists.Mappers { public class PlaneMapper : ComponentMapping<Plane> { public PlaneMapper() { Component(p => p.Normal); Property(p => p.Translation); } } }
Fix check not accounting for mods not existing in certain rulesets
// 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.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets.Mods; namespace osu.Game.Tests.Visual.Gameplay { [HeadlessTest] public class TestSceneModValidity : TestSceneAllRulesetPlayers { protected override void AddCheckSteps() { AddStep("Check all mod acronyms are unique", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<string> acronyms = mods.Select(m => m.Acronym); Assert.That(acronyms, Is.Unique); }); AddStep("Check all mods are two-way incompatible", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<Mod> modInstances = mods.Select(mod => mod.CreateInstance()); foreach (var mod in modInstances) { var modIncompatibilities = mod.IncompatibleMods; foreach (var incompatibleModType in modIncompatibilities) { var incompatibleMod = modInstances.First(m => incompatibleModType.IsInstanceOfType(m)); Assert.That( incompatibleMod.IncompatibleMods.Any(m => m.IsInstanceOfType(mod)), $"{mod} has {incompatibleMod} in it's incompatible mods, but {incompatibleMod} does not have {mod} in it's incompatible mods." ); } } }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets.Mods; namespace osu.Game.Tests.Visual.Gameplay { [HeadlessTest] public class TestSceneModValidity : TestSceneAllRulesetPlayers { protected override void AddCheckSteps() { AddStep("Check all mod acronyms are unique", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<string> acronyms = mods.Select(m => m.Acronym); Assert.That(acronyms, Is.Unique); }); AddStep("Check all mods are two-way incompatible", () => { var mods = Ruleset.Value.CreateInstance().AllMods; IEnumerable<Mod> modInstances = mods.Select(mod => mod.CreateInstance()); foreach (var modToCheck in modInstances) { var incompatibleMods = modToCheck.IncompatibleMods; foreach (var incompatible in incompatibleMods) { foreach (var incompatibleMod in modInstances.Where(m => incompatible.IsInstanceOfType(m))) { Assert.That( incompatibleMod.IncompatibleMods.Any(m => m.IsInstanceOfType(modToCheck)), $"{modToCheck} has {incompatibleMod} in it's incompatible mods, but {incompatibleMod} does not have {modToCheck} in it's incompatible mods." ); } } } }); } } }
Enable debug by default in scenario tests
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Test.Utilities { using System.Management.Automation; using VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.Test.Tests.Utilities; [TestClass] public class PowerShellTest { protected PowerShell powershell; protected string[] modules; public PowerShellTest(params string[] modules) { this.modules = modules; } protected void AddScenarioScript(string script) { powershell.AddScript(Testing.GetTestResourceContents(script)); } [TestInitialize] public virtual void SetupTest() { powershell = PowerShell.Create(); foreach (string moduleName in modules) { powershell.AddScript(string.Format("Import-Module \"{0}\"", Testing.GetTestResourcePath(moduleName))); } powershell.AddScript("$verbosepreference='continue'"); } [TestCleanup] public virtual void TestCleanup() { powershell.Dispose(); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Test.Utilities { using System.Management.Automation; using VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.Test.Tests.Utilities; [TestClass] public class PowerShellTest { protected PowerShell powershell; protected string[] modules; public PowerShellTest(params string[] modules) { this.modules = modules; } protected void AddScenarioScript(string script) { powershell.AddScript(Testing.GetTestResourceContents(script)); } [TestInitialize] public virtual void SetupTest() { powershell = PowerShell.Create(); foreach (string moduleName in modules) { powershell.AddScript(string.Format("Import-Module \"{0}\"", Testing.GetTestResourcePath(moduleName))); } powershell.AddScript("$VerbosePreference='Continue'"); powershell.AddScript("$DebugPreference='Continue'"); } [TestCleanup] public virtual void TestCleanup() { powershell.Dispose(); } } }
Fix category of revision log RSS feeds.
<?xml version="1.0"?> <!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> --> <rss version="2.0"> <channel><?cs if:project.name_encoded ?> <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs else ?> <title>Revisions of <?cs var:log.path ?></title><?cs /if ?> <link><?cs var:base_host ?><?cs var:log.log_href ?></link> <description>Trac Log - Revisions of <?cs var:log.path ?></description> <language>en-us</language> <generator>Trac v<?cs var:trac.version ?></generator><?cs each:item = log.items ?><?cs with:change = log.changes[item.rev] ?> <item> <author><?cs var:change.author ?></author> <pubDate><?cs var:change.date ?></pubDate> <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title> <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link> <description><?cs var:change.message ?></description> <category>Report</category> </item><?cs /with ?><?cs /each ?> </channel> </rss>
<?xml version="1.0"?> <!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> --> <rss version="2.0"> <channel><?cs if:project.name_encoded ?> <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs else ?> <title>Revisions of <?cs var:log.path ?></title><?cs /if ?> <link><?cs var:base_host ?><?cs var:log.log_href ?></link> <description>Trac Log - Revisions of <?cs var:log.path ?></description> <language>en-us</language> <generator>Trac v<?cs var:trac.version ?></generator><?cs each:item = log.items ?><?cs with:change = log.changes[item.rev] ?> <item> <author><?cs var:change.author ?></author> <pubDate><?cs var:change.date ?></pubDate> <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title> <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link> <description><?cs var:change.message ?></description> <category>Log</category> </item><?cs /with ?><?cs /each ?> </channel> </rss>
Update spelling mistake in api types
using System.ComponentModel; namespace SFA.DAS.EAS.Account.Api.Types { public enum EmployerAgreementStatus { [Description("Not signed")] Pending = 1, [Description("Signed")] Signed = 2, [Description("Expired")] Expired = 3, [Description("Superceded")] Superceded = 4 } }
using System.ComponentModel; namespace SFA.DAS.EAS.Account.Api.Types { public enum EmployerAgreementStatus { [Description("Not signed")] Pending = 1, [Description("Signed")] Signed = 2, [Description("Expired")] Expired = 3, [Description("Superseded")] Superceded = 4 } }
Add a list focus call
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace Countdown.Views { internal class ScrollTo { public static void SetItem(UIElement element, object value) { element.SetValue(ItemProperty, value); } public static object GetItem(UIElement element) { return element.GetValue(ItemProperty); } public static readonly DependencyProperty ItemProperty = DependencyProperty.RegisterAttached("Item", typeof(object), typeof(ScrollTo), new FrameworkPropertyMetadata(OnScrollToItemPropertyChanged)); private static void OnScrollToItemPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { if ((e.NewValue is not null) && (source is ListBox list)) { list.SelectedItem = e.NewValue; if (list.IsGrouping) { // Work around a bug that stops ScrollIntoView() working on Net5.0 // see https://github.com/dotnet/wpf/issues/4797 _ = list.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => list.ScrollIntoView(e.NewValue))); } else { list.ScrollIntoView(e.NewValue); } } } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace Countdown.Views { internal class ScrollTo { public static void SetItem(UIElement element, object value) { element.SetValue(ItemProperty, value); } public static object GetItem(UIElement element) { return element.GetValue(ItemProperty); } public static readonly DependencyProperty ItemProperty = DependencyProperty.RegisterAttached("Item", typeof(object), typeof(ScrollTo), new FrameworkPropertyMetadata(OnScrollToItemPropertyChanged)); private static void OnScrollToItemPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { if ((e.NewValue is not null) && (source is ListBox list)) { list.SelectedItem = e.NewValue; if (list.IsGrouping) { // Work around a bug that stops ScrollIntoView() working on Net5.0 // see https://github.com/dotnet/wpf/issues/4797 _ = list.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => { list.ScrollIntoView(e.NewValue); _ = list.Focus(); })); } else { list.ScrollIntoView(e.NewValue); _ = list.Focus(); } } } } }
Make sure to take into account completed when looking at ALL
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => 0 <= _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 30).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => 30 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 60).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => 60 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 90).Count(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => !_.IsCompleted).Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsCompleted).Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => !_.IsCompleted).Where(_ => 0 <= _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 30).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => !_.IsCompleted).Where(_ => 30 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 60).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => !_.IsCompleted).Where(_ => 60 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 90).Count(); } }
Fix bug in the Sql Server implementation
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Luval.Common; namespace Luval.Orm { public class SqlServerLanguageProvider : AnsiSqlLanguageProvider { public SqlServerLanguageProvider() : this(DbConfiguration.Get<ISqlExpressionProvider>(), DbConfiguration.Get<IObjectAccesor>()) { } public SqlServerLanguageProvider(ISqlExpressionProvider expressionProvider, IObjectAccesor objectAccesor) : base(expressionProvider, new SqlServerDialectProvider(), objectAccesor) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Luval.Common; namespace Luval.Orm { public class SqlServerLanguageProvider : AnsiSqlLanguageProvider { public SqlServerLanguageProvider() : this(DbConfiguration.Get<ISqlExpressionProvider>(), DbConfiguration.Get<IObjectAccesor>()) { } public SqlServerLanguageProvider(ISqlExpressionProvider expressionProvider, IObjectAccesor objectAccesor) : base(expressionProvider, new SqlServerDialectProvider(), objectAccesor) { } public override string GetLastIdentityInsert() { return "SELECT SCOPE_IDENTITY()"; } } }
Use list-group instead of a table.
@model IEnumerable<Discord.WebSocket.SocketGuild> <table class="table"> <thead> <tr> <th> @Html.DisplayName("GuildId") </th> <th> @Html.DisplayName("GuildName") </th> <th></th> </tr> </thead> <tbody> @foreach(var guild in Model) { <tr> <td> @Html.DisplayFor(modelItem => guild.Id) </td> <td> @Html.DisplayFor(modelItem => guild.Name) </td> <td> <a asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">Details</a> </td> </tr> } </tbody> </table>
@model IEnumerable<Discord.WebSocket.SocketGuild> <div class="list-group"> @foreach(var guild in Model) { <a class="list-group-item list-group-item-action" asp-area="Guild" asp-controller="Stats" asp-action="Index" asp-route-guildId="@guild.Id">@guild.Name</a> } </div>
Throw HttpException when trying to resolve unknown controller
using System; using System.Web.Mvc; using System.Web.Routing; using Castle.MicroKernel; namespace SnittListan.IoC { public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel kernel; public WindsorControllerFactory(IKernel kernel) { this.kernel = kernel; } public override IController CreateController(RequestContext requestContext, string controllerName) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } try { return kernel.Resolve<IController>(controllerName + "controller"); } catch (ComponentNotFoundException ex) { throw new ApplicationException(string.Format("No controller with name '{0}' found", controllerName), ex); } } public override void ReleaseController(IController controller) { if (controller == null) { throw new ArgumentNullException("controller"); } kernel.ReleaseComponent(controller); } } }
using System; using System.Web.Mvc; using System.Web.Routing; using Castle.MicroKernel; using System.Web; namespace SnittListan.IoC { public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel kernel; public WindsorControllerFactory(IKernel kernel) { this.kernel = kernel; } public override IController CreateController(RequestContext requestContext, string controllerName) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } if (controllerName == null) { throw new HttpException(404, string.Format("The controller path '{0}' could not be found.", controllerName)); } try { return kernel.Resolve<IController>(controllerName + "controller"); } catch (ComponentNotFoundException ex) { throw new ApplicationException(string.Format("No controller with name '{0}' found", controllerName), ex); } } public override void ReleaseController(IController controller) { if (controller == null) { throw new ArgumentNullException("controller"); } kernel.ReleaseComponent(controller); } } }
Use collection of certificates to parse pkcs7
using System.Security.Cryptography.X509Certificates; using PeNet.Structures; namespace PeNet.Parser { internal class PKCS7Parser : SafeParser<X509Certificate2> { private readonly WIN_CERTIFICATE _winCertificate; internal PKCS7Parser(WIN_CERTIFICATE winCertificate) : base(null, 0) { _winCertificate = winCertificate; } protected override X509Certificate2 ParseTarget() { if (_winCertificate?.wCertificateType != (ushort) Constants.WinCertificateType.WIN_CERT_TYPE_PKCS_SIGNED_DATA) { return null; } var cert = _winCertificate.bCertificate; return new X509Certificate2(cert); } } }
using System.Security.Cryptography.X509Certificates; using PeNet.Structures; namespace PeNet.Parser { internal class PKCS7Parser : SafeParser<X509Certificate2> { private readonly WIN_CERTIFICATE _winCertificate; internal PKCS7Parser(WIN_CERTIFICATE winCertificate) : base(null, 0) { _winCertificate = winCertificate; } protected override X509Certificate2 ParseTarget() { if (_winCertificate?.wCertificateType != (ushort) Constants.WinCertificateType.WIN_CERT_TYPE_PKCS_SIGNED_DATA) { return null; } var pkcs7 = _winCertificate.bCertificate; var collection = new X509Certificate2Collection(); collection.Import(pkcs7); if (collection.Count == 0) return null; return collection[0]; } } }
Change return type of script engine
using System; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace ScriptSharp.ScriptEngine { public class CSharpScriptEngine { private static ScriptState<object> scriptState = null; public static object Execute(string code) { scriptState = scriptState == null ? CSharpScript.RunAsync(code).Result : scriptState.ContinueWithAsync(code).Result; if (scriptState.ReturnValue != null && !string.IsNullOrEmpty(scriptState.ReturnValue.ToString())) return scriptState.ReturnValue; return ""; } } }
using System; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace ScriptSharp.ScriptEngine { public class CSharpScriptEngine { private static ScriptState<object> scriptState = null; public static object Execute(string code) { scriptState = scriptState == null ? CSharpScript.RunAsync(code).Result : scriptState.ContinueWithAsync(code).Result; if (scriptState.ReturnValue != null && !string.IsNullOrEmpty(scriptState.ReturnValue.ToString())) return scriptState.ReturnValue; return null; } } }
Implement getting data for office details
using Starcounter; using System; namespace RealEstateAgencyFranchise.Controllers { internal class OfficeController { public Json Get(long officeObjectNo) { throw new NotImplementedException(); } } }
using RealEstateAgencyFranchise.Database; using Starcounter; using System.Linq; namespace RealEstateAgencyFranchise.Controllers { internal class OfficeController { public Json Get(ulong officeObjectNo) { return Db.Scope(() => { var offices = Db.SQL<Office>( "select o from Office o where o.ObjectNo = ?", officeObjectNo); if (offices == null || !offices.Any()) { return new Response() { StatusCode = 404, StatusDescription = "Office not found" }; } var office = offices.First; var json = new OfficeListJson { Data = office }; if (Session.Current == null) { Session.Current = new Session(SessionOptions.PatchVersioning); } json.Session = Session.Current; return json; }); } } }
Change time utils visibility from internal to public
using System; namespace Criteo.Profiling.Tracing.Utils { internal static class TimeUtils { private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime UtcNow { get { return HighResolutionDateTime.IsAvailable ? HighResolutionDateTime.UtcNow : DateTime.UtcNow; } } /// <summary> /// Create a UNIX timestamp from a UTC date time. Time is expressed in microseconds and not seconds. /// </summary> /// <see href="https://en.wikipedia.org/wiki/Unix_time"/> /// <param name="utcDateTime"></param> /// <returns></returns> public static long ToUnixTimestamp(DateTime utcDateTime) { return (long)(utcDateTime.Subtract(Epoch).TotalMilliseconds * 1000L); } } }
using System; namespace Criteo.Profiling.Tracing.Utils { public static class TimeUtils { private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime UtcNow { get { return HighResolutionDateTime.IsAvailable ? HighResolutionDateTime.UtcNow : DateTime.UtcNow; } } /// <summary> /// Create a UNIX timestamp from a UTC date time. Time is expressed in microseconds and not seconds. /// </summary> /// <see href="https://en.wikipedia.org/wiki/Unix_time"/> /// <param name="utcDateTime"></param> /// <returns></returns> public static long ToUnixTimestamp(DateTime utcDateTime) { return (long)(utcDateTime.Subtract(Epoch).TotalMilliseconds * 1000L); } } }
Fix bug with DFS when some vertices painted in gray twice
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SharpGraphEditor.Graph.Core.Elements; namespace SharpGraphEditor.Graph.Core.Algorithms { public class DepthFirstSearchAlgorithm : IAlgorithm { public string Name => "Depth first search"; public string Description => "Depth first search"; public void Run(IGraph graph, AlgorithmParameter p) { if (graph.Vertices.Count() == 0) { return; } graph.ChangeColor(graph.Vertices.ElementAt(0), VertexColor.Gray); var dfs = new Helpers.DepthFirstSearch(graph) { ProcessEdge = (v1, v2) => { graph.ChangeColor(v2, VertexColor.Gray); }, ProcessVertexLate = (v) => { graph.ChangeColor(v, VertexColor.Black); } }; dfs.Run(graph.Vertices.First()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SharpGraphEditor.Graph.Core.Elements; namespace SharpGraphEditor.Graph.Core.Algorithms { public class DepthFirstSearchAlgorithm : IAlgorithm { public string Name => "Depth first search"; public string Description => "Depth first search"; public void Run(IGraph graph, AlgorithmParameter p) { if (graph.Vertices.Count() == 0) { return; } graph.ChangeColor(graph.Vertices.ElementAt(0), VertexColor.Gray); var dfs = new Helpers.DepthFirstSearch(graph) { ProcessEdge = (v1, v2) => { if (v2.Color != VertexColor.Gray) { graph.ChangeColor(v2, VertexColor.Gray); } }, ProcessVertexLate = (v) => { graph.ChangeColor(v, VertexColor.Black); } }; dfs.Run(graph.Vertices.First()); } } }
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.AggregateService")] [assembly: AssemblyDescription("Autofac Aggregate Service Module")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.AggregateService")] [assembly: ComVisible(false)]
Change httpclientwrapper to return the content as string async.
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using NLog; using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration; using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HttpClientWrapper : IHttpClientWrapper { private readonly ILogger _logger; private readonly EmployerApprenticeshipsServiceConfiguration _configuration; public HttpClientWrapper(ILogger logger, EmployerApprenticeshipsServiceConfiguration configuration) { _logger = logger; _configuration = configuration; } public async Task<string> SendMessage<T>(T content, string url) { try { using (var httpClient = CreateHttpClient()) { var serializeObject = JsonConvert.SerializeObject(content); var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(serializeObject, Encoding.UTF8, "application/json") }); return response.Content.ToString(); } } catch (Exception ex) { _logger.Error(ex); } return null; } private HttpClient CreateHttpClient() { return new HttpClient { BaseAddress = new Uri(_configuration.Hmrc.BaseUrl) }; } } }
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using NLog; using SFA.DAS.EmployerApprenticeshipsService.Domain.Configuration; using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HttpClientWrapper : IHttpClientWrapper { private readonly ILogger _logger; private readonly EmployerApprenticeshipsServiceConfiguration _configuration; public HttpClientWrapper(ILogger logger, EmployerApprenticeshipsServiceConfiguration configuration) { _logger = logger; _configuration = configuration; } public async Task<string> SendMessage<T>(T content, string url) { try { using (var httpClient = CreateHttpClient()) { var serializeObject = JsonConvert.SerializeObject(content); var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(serializeObject, Encoding.UTF8, "application/json") }); return await response.Content.ReadAsStringAsync(); } } catch (Exception ex) { _logger.Error(ex); } return null; } private HttpClient CreateHttpClient() { return new HttpClient { BaseAddress = new Uri(_configuration.Hmrc.BaseUrl) }; } } }
Fix bug with double serialization
using System; using RestSharp; using Newtonsoft.Json; using RestSharp.Portable; using RestSharp.Portable.Authenticators; using RestSharp.Portable.HttpClient; namespace AsterNET.ARI.Middleware.Default { public class Command : IRestCommand { internal RestClient Client; internal RestRequest Request; public Command(StasisEndpoint info, string path) { Client = new RestClient(info.AriEndPoint) { Authenticator = new HttpBasicAuthenticator(info.Username, info.Password) }; Request = new RestRequest(path); } public string UniqueId { get; set; } public string Url { get; set; } public string Method { get { return Request.Method.ToString(); } set { Request.Method = (RestSharp.Portable.Method) Enum.Parse(typeof (RestSharp.Portable.Method), value); } } public string Body { get; private set; } public void AddUrlSegment(string segName, string value) { Request.AddUrlSegment(segName, value); } public void AddParameter(string name, object value, Middleware.ParameterType type) { if (type == ParameterType.RequestBody) { Request.Serializer = new RestSharp.Portable.Serializers.JsonSerializer(); Request.AddParameter(name, JsonConvert.SerializeObject(value), (RestSharp.Portable.ParameterType)Enum.Parse(typeof(RestSharp.Portable.ParameterType), type.ToString())); } else { Request.AddParameter(name, value, (RestSharp.Portable.ParameterType)Enum.Parse(typeof(RestSharp.Portable.ParameterType), type.ToString())); } } } }
using System; using RestSharp.Portable; using RestSharp.Portable.Authenticators; using RestSharp.Portable.HttpClient; namespace AsterNET.ARI.Middleware.Default { public class Command : IRestCommand { internal RestClient Client; internal RestRequest Request; public Command(StasisEndpoint info, string path) { Client = new RestClient(info.AriEndPoint) { Authenticator = new HttpBasicAuthenticator(info.Username, info.Password) }; Request = new RestRequest(path) {Serializer = new RestSharp.Portable.Serializers.JsonSerializer()}; } public string UniqueId { get; set; } public string Url { get; set; } public string Method { get { return Request.Method.ToString(); } set { Request.Method = (RestSharp.Portable.Method) Enum.Parse(typeof (RestSharp.Portable.Method), value); } } public string Body { get; private set; } public void AddUrlSegment(string segName, string value) { Request.AddUrlSegment(segName, value); } public void AddParameter(string name, object value, Middleware.ParameterType type) { Request.AddParameter(name, value, (RestSharp.Portable.ParameterType)Enum.Parse(typeof(RestSharp.Portable.ParameterType), type.ToString())); } } }
Remove unnecessary usings in example script
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; using Object = UnityEngine.Object; [CreateAssetMenu(fileName = "Example.asset", menuName = "New Example ScriptableObject")] public class ScriptableObjectExample : ScriptableObject { [EasyButtons.Button] public void SayHello() { Debug.Log("Hello"); } }
using UnityEngine; [CreateAssetMenu(fileName = "Example.asset", menuName = "New Example ScriptableObject")] public class ScriptableObjectExample : ScriptableObject { [EasyButtons.Button] public void SayHello() { Debug.Log("Hello"); } }
Rearrange test to better self-document what currently works and what does not.
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using ExpressionToCodeLib; using Xunit; namespace ExpressionToCodeTest { public class ValueTupleTests { [Fact] public void ExpressionCompileValueTupleEqualsWorks() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<bool>> expr = () => tuple.Equals(tuple2); Assert.True(expr.Compile()()); } [Fact] public void FastExpressionCompileValueTupleEqualsWorks() { var tuple = (1, 3); (int, int Length) tuple2 = (1, "123".Length); ValueTuple<int,int> x; var expr = FastExpressionCompiler.ExpressionCompiler.Compile(() => tuple.Equals(tuple2)); Assert.True(expr()); } [Fact] public void AssertingOnValueTupleEqualsWorks() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<bool>> expr = () => tuple.Equals(tuple2); Assert.True(expr.Compile()()); PAssert.That(() => tuple.Equals(tuple2)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using ExpressionToCodeLib; using Xunit; namespace ExpressionToCodeTest { public class ValueTupleTests { [Fact] public void ExpressionWithValueTupleEqualsCanCompile() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<int>> ok1 = () => tuple.Item1; Expression<Func<int>> ok2 = () => tuple.GetHashCode(); Expression<Func<Tuple<int, int>>> ok3 = () => tuple.ToTuple(); ok1.Compile(); ok2.Compile(); ok3.Compile(); Expression<Func<bool>> err1 = () => tuple.Equals(tuple2); Expression<Func<int>> err2 = () => tuple.CompareTo(tuple2); err1.Compile();//crash err2.Compile();//crash } [Fact] public void FastExpressionCompileValueTupleEqualsWorks() { var tuple = (1, 3); (int, int Length) tuple2 = (1, "123".Length); var expr = FastExpressionCompiler.ExpressionCompiler.Compile(() => tuple.Equals(tuple2)); Assert.True(expr()); } [Fact] public void AssertingOnValueTupleEqualsWorks() { var tuple = (1, 3); var tuple2 = (1, "123".Length); Expression<Func<bool>> expr = () => tuple.Equals(tuple2); Assert.True(expr.Compile()()); PAssert.That(() => tuple.Equals(tuple2)); } } }
Make spinners easier for now
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Objects.Types; using osu.Game.Database; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class Spinner : OsuHitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; /// <summary> /// Number of spins required to finish the spinner without miss. /// </summary> public int SpinsRequired { get; protected set; } = 1; public override bool NewCombo => true; public override void ApplyDefaults(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaults(controlPointInfo, difficulty); SpinsRequired = (int)(Duration / 1000 * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5)); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Objects.Types; using osu.Game.Database; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class Spinner : OsuHitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; /// <summary> /// Number of spins required to finish the spinner without miss. /// </summary> public int SpinsRequired { get; protected set; } = 1; public override bool NewCombo => true; public override void ApplyDefaults(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaults(controlPointInfo, difficulty); SpinsRequired = (int)(Duration / 1000 * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5)); // spinning doesn't match 1:1 with stable, so let's fudge them easier for the time being. SpinsRequired = (int)(SpinsRequired * 0.6); } } }
Clean up mac completion broker.
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Editor.Razor; using Microsoft.VisualStudio.Text.Editor; using MonoDevelop.Ide.CodeCompletion; namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor.Editor { internal class DefaultVisualStudioCompletionBroker : VisualStudioCompletionBroker { public override bool IsCompletionActive(ITextView textView) { if (textView == null) { throw new ArgumentNullException(nameof(textView)); } if (textView.HasAggregateFocus) { return CompletionWindowManager.IsVisible || (textView.Properties.TryGetProperty<bool>("RoslynCompletionPresenterSession.IsCompletionActive", out var visible) && visible); } // Text view does not have focus, if the completion window is visible it's for a different text view. return false; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Editor.Razor; using Microsoft.VisualStudio.Text.Editor; using MonoDevelop.Ide.CodeCompletion; namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor.Editor { internal class DefaultVisualStudioCompletionBroker : VisualStudioCompletionBroker { private const string IsCompletionActiveKey = "RoslynCompletionPresenterSession.IsCompletionActive"; public override bool IsCompletionActive(ITextView textView) { if (textView == null) { throw new ArgumentNullException(nameof(textView)); } if (!textView.HasAggregateFocus) { // Text view does not have focus, if the completion window is visible it's for a different text view. return false; } if (CompletionWindowManager.IsVisible) { return true; } if (textView.Properties.TryGetProperty<bool>(IsCompletionActiveKey, out var visible)) { return visible; } return false; } } }
Add null handling for editorinterface settings
using Contentful.Core.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { [JsonConverter(typeof(EditorInterfaceControlJsonConverter))] public class EditorInterfaceControl { public string FieldId { get; set; } public string WidgetId { get; set; } public EditorInterfaceControlSettings Settings { get; set; } } }
using Contentful.Core.Configuration; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Contentful.Core.Models.Management { [JsonConverter(typeof(EditorInterfaceControlJsonConverter))] public class EditorInterfaceControl { public string FieldId { get; set; } public string WidgetId { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public EditorInterfaceControlSettings Settings { get; set; } } }
Update mscorlib assembly name to match eventual module name
// AssemblyInfo.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("mscorlib")] [assembly: AssemblyDescription("Script# Core Assembly")] [assembly: ScriptAssembly("core")]
// AssemblyInfo.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("mscorlib")] [assembly: AssemblyDescription("Script# Core Assembly")] [assembly: ScriptAssembly("ss")]
Remove binding redirects for missing assemblies
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; // Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show // up in the Load context, which means that we can use ServiceHub and other nice things. [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.AngleSharp", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.9.9.0", NewVersion = "0.9.9.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "1.0.0.0", NewVersion = "1.0.0.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "1.0.0.0", NewVersion = "1.0.0.0")]
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; // Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show // up in the Load context, which means that we can use ServiceHub and other nice things. [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "1.0.0.0", NewVersion = "1.0.0.0")]