Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Allow specifying two sprites for legacy hit explosions
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Taiko.Skinning { public class LegacyHitExplosion : CompositeDrawable { public LegacyHitExplosion(Drawable sprite) { InternalChild = sprite; Anchor = Anchor.Centre; Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; } protected override void LoadComplete() { base.LoadComplete(); const double animation_time = 120; this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5); this.ScaleTo(0.6f) .Then().ScaleTo(1.1f, animation_time * 0.8) .Then().ScaleTo(0.9f, animation_time * 0.4) .Then().ScaleTo(1f, animation_time * 0.2); Expire(true); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Taiko.Skinning { public class LegacyHitExplosion : CompositeDrawable { private readonly Drawable sprite; private readonly Drawable strongSprite; /// <summary> /// Creates a new legacy hit explosion. /// </summary> /// <remarks> /// Contrary to stable's, this implementation doesn't require a frame-perfect hit /// for the strong sprite to be displayed. /// </remarks> /// <param name="sprite">The normal legacy explosion sprite.</param> /// <param name="strongSprite">The strong legacy explosion sprite.</param> public LegacyHitExplosion(Drawable sprite, Drawable strongSprite = null) { this.sprite = sprite; this.strongSprite = strongSprite; } [BackgroundDependencyLoader] private void load() { Anchor = Anchor.Centre; Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; AddInternal(sprite); if (strongSprite != null) AddInternal(strongSprite.With(s => s.Alpha = 0)); } protected override void LoadComplete() { base.LoadComplete(); const double animation_time = 120; this.FadeInFromZero(animation_time).Then().FadeOut(animation_time * 1.5); this.ScaleTo(0.6f) .Then().ScaleTo(1.1f, animation_time * 0.8) .Then().ScaleTo(0.9f, animation_time * 0.4) .Then().ScaleTo(1f, animation_time * 0.2); Expire(true); } } }
Use ImmutableArray for IList interface
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestEDITOR { /// <summary> /// /// </summary> internal class ProjectContractResolver : DefaultContractResolver { /// <summary> /// Use ObservableCollection for IList contract. /// </summary> /// <param name="type"></param> /// <returns></returns> public override JsonContract ResolveContract(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return base .ResolveContract(typeof(ObservableCollection<>) .MakeGenericType(type.GenericTypeArguments[0])); } else { return base.ResolveContract(type); } } /// <summary> /// Serialize only writable properties. /// </summary> /// <param name="type"></param> /// <param name="memberSerialization"></param> /// <returns></returns> protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization) { IList<JsonProperty> props = base.CreateProperties(type, memberSerialization); return props.Where(p => p.Writable).ToList(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestEDITOR { /// <summary> /// /// </summary> internal class ProjectContractResolver : DefaultContractResolver { /// <summary> /// Use ImmutableArray for IList contract. /// </summary> /// <param name="type"></param> /// <returns></returns> public override JsonContract ResolveContract(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return base .ResolveContract(typeof(ImmutableArray<>) .MakeGenericType(type.GenericTypeArguments[0])); } else { return base.ResolveContract(type); } } /// <summary> /// Serialize only writable properties. /// </summary> /// <param name="type"></param> /// <param name="memberSerialization"></param> /// <returns></returns> protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization) { IList<JsonProperty> props = base.CreateProperties(type, memberSerialization); return props.Where(p => p.Writable).ToList(); } } }
Add default values for lyric and pitch
namespace MusicXml.Domain { public class Note { internal Note() { Type = string.Empty; Duration = -1; Voice = -1; Staff = -1; IsChordTone = false; } public string Type { get; internal set; } public int Voice { get; internal set; } public int Duration { get; internal set; } public Lyric Lyric { get; internal set; } public Pitch Pitch { get; internal set; } public int Staff { get; internal set; } public bool IsChordTone { get; internal set; } } }
namespace MusicXml.Domain { public class Note { internal Note() { Type = string.Empty; Duration = -1; Voice = -1; Staff = -1; IsChordTone = false; Lyric = new Lyric(); Pitch = new Pitch(); } public string Type { get; internal set; } public int Voice { get; internal set; } public int Duration { get; internal set; } public Lyric Lyric { get; internal set; } public Pitch Pitch { get; internal set; } public int Staff { get; internal set; } public bool IsChordTone { get; internal set; } } }
Fix rust.BroadcastChat using wrong Broadcast method
using Oxide.Core.Libraries; namespace Oxide.Game.Rust.Libraries { public class Server : Library { #region Chat and Commands /// <summary> /// Broadcasts a chat message to all players /// </summary> /// <param name="message"></param> /// <param name="userId"></param> /// <param name="prefix"></param> public void Broadcast(string message, string prefix = null, ulong userId = 0) { ConsoleNetwork.BroadcastToAllClients("chat.add", userId, prefix != null ? $"{prefix} {message}" : message, 1.0); } /// <summary> /// Broadcasts a chat message to all players /// </summary> /// <param name="message"></param> /// <param name="userId"></param> /// <param name="prefix"></param> /// <param name="args"></param> public void Broadcast(string message, string prefix = null, ulong userId = 0, params object[] args) => Broadcast(string.Format(message, args), prefix, userId); /// <summary> /// Broadcasts a chat message to all players /// </summary> /// <param name="message"></param> /// <param name="prefix"></param> /// <param name="args"></param> public void Broadcast(string message, string prefix = null, params object[] args) => Broadcast(string.Format(message, args), prefix); /// <summary> /// Runs the specified server command /// </summary> /// <param name="command"></param> /// <param name="args"></param> public void Command(string command, params object[] args) => ConsoleSystem.Run(ConsoleSystem.Option.Server, command, args); #endregion } }
using Oxide.Core.Libraries; namespace Oxide.Game.Rust.Libraries { public class Server : Library { #region Chat and Commands /// <summary> /// Broadcasts a chat message to all players /// </summary> /// <param name="message"></param> /// <param name="userId"></param> /// <param name="prefix"></param> public void Broadcast(string message, string prefix = null, ulong userId = 0) { ConsoleNetwork.BroadcastToAllClients("chat.add", userId, prefix != null ? $"{prefix} {message}" : message, 1.0); } /// <summary> /// Broadcasts a chat message to all players /// </summary> /// <param name="message"></param> /// <param name="userId"></param> /// <param name="prefix"></param> /// <param name="args"></param> public void Broadcast(string message, string prefix = null, ulong userId = 0, params object[] args) => Broadcast(string.Format(message, args), prefix, userId); /// <summary> /// Runs the specified server command /// </summary> /// <param name="command"></param> /// <param name="args"></param> public void Command(string command, params object[] args) => ConsoleSystem.Run(ConsoleSystem.Option.Server, command, args); #endregion } }
Remove class constraint on AsNonNull()
// 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.Diagnostics.CodeAnalysis; namespace osu.Framework.Extensions.ObjectExtensions { /// <summary> /// Extensions that apply to all objects. /// </summary> public static class ObjectExtensions { /// <summary> /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>". /// </summary> /// <remarks> /// This should only be used when an assertion or other handling is not a reasonable alternative. /// </remarks> /// <param name="obj">The nullable object.</param> /// <typeparam name="T">The type of the object.</typeparam> /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns> public static T AsNonNull<T>(this T? obj) where T : class { return obj!; } /// <summary> /// If the given object is null. /// </summary> public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null); /// <summary> /// <c>true</c> if the given object is not null, <c>false</c> otherwise. /// </summary> public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null); } }
// 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.Diagnostics.CodeAnalysis; namespace osu.Framework.Extensions.ObjectExtensions { /// <summary> /// Extensions that apply to all objects. /// </summary> public static class ObjectExtensions { /// <summary> /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>". /// </summary> /// <remarks> /// This should only be used when an assertion or other handling is not a reasonable alternative. /// </remarks> /// <param name="obj">The nullable object.</param> /// <typeparam name="T">The type of the object.</typeparam> /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns> [return: NotNullIfNotNull("obj")] public static T AsNonNull<T>(this T? obj) => obj!; /// <summary> /// If the given object is null. /// </summary> public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null); /// <summary> /// <c>true</c> if the given object is not null, <c>false</c> otherwise. /// </summary> public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null); } }
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; using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.CommonServiceLocator")] [assembly: AssemblyDescription("Autofac Adapter for the Microsoft CommonServiceLocator")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.CommonServiceLocator")]
Write to log when retrying
using System; using System.Collections.Generic; namespace GitVersion.Helpers { internal class OperationWithExponentialBackoff<T> where T : Exception { private IThreadSleep ThreadSleep; private Action Operation; private int MaxRetries; public OperationWithExponentialBackoff(IThreadSleep threadSleep, Action operation, int maxRetries = 5) { if (threadSleep == null) throw new ArgumentNullException("threadSleep"); if (maxRetries < 0) throw new ArgumentOutOfRangeException("maxRetries"); this.ThreadSleep = threadSleep; this.Operation = operation; this.MaxRetries = maxRetries; } public void Execute() { var exceptions = new List<Exception>(); int tries = 0; int sleepMSec = 500; while (tries <= MaxRetries) { tries++; try { Operation(); break; } catch (T e) { exceptions.Add(e); if (tries > MaxRetries) { throw new AggregateException("Operation failed after maximum number of retries were exceeded.", exceptions); } } ThreadSleep.Sleep(sleepMSec); sleepMSec *= 2; } } } }
using System; using System.Collections.Generic; namespace GitVersion.Helpers { internal class OperationWithExponentialBackoff<T> where T : Exception { private IThreadSleep ThreadSleep; private Action Operation; private int MaxRetries; public OperationWithExponentialBackoff(IThreadSleep threadSleep, Action operation, int maxRetries = 5) { if (threadSleep == null) throw new ArgumentNullException("threadSleep"); if (maxRetries < 0) throw new ArgumentOutOfRangeException("maxRetries"); this.ThreadSleep = threadSleep; this.Operation = operation; this.MaxRetries = maxRetries; } public void Execute() { var exceptions = new List<Exception>(); int tries = 0; int sleepMSec = 500; while (tries <= MaxRetries) { tries++; try { Operation(); break; } catch (T e) { exceptions.Add(e); if (tries > MaxRetries) { throw new AggregateException("Operation failed after maximum number of retries were exceeded.", exceptions); } } Logger.WriteInfo(string.Format("Operation failed, retrying in {0} milliseconds.", sleepMSec)); ThreadSleep.Sleep(sleepMSec); sleepMSec *= 2; } } } }
Improve JS Snippet unit test
namespace Microsoft.Framework.DependencyInjection.Test { using Microsoft.ApplicationInsights.AspNetCore; using Microsoft.ApplicationInsights.Extensibility; using Xunit; public static class ApplicationInsightsJavaScriptTest { [Fact] public static void SnippetWillBeEmptyWhenInstrumentationKeyIsNotDefined() { var telemetryConfigurationWithNullKey = new TelemetryConfiguration(); var snippet = new JavaScriptSnippet(telemetryConfigurationWithNullKey); Assert.Equal(string.Empty, snippet.FullScript.ToString()); } [Fact] public static void SnippetWillBeEmptyWhenInstrumentationKeyIsEmpty() { var telemetryConfigurationWithEmptyKey = new TelemetryConfiguration { InstrumentationKey = string.Empty }; var snippet = new JavaScriptSnippet(telemetryConfigurationWithEmptyKey); Assert.Equal(string.Empty, snippet.FullScript.ToString()); } [Fact] public static void SnippetWillIncludeInstrumentationKeyAsSubstring() { string unittestkey = "unittestkey"; var telemetryConfiguration = new TelemetryConfiguration { InstrumentationKey = unittestkey }; var snippet = new JavaScriptSnippet(telemetryConfiguration); Assert.Contains("'" + unittestkey + "'", snippet.FullScript.ToString()); } } }
namespace Microsoft.Framework.DependencyInjection.Test { using Microsoft.ApplicationInsights.AspNetCore; using Microsoft.ApplicationInsights.Extensibility; using Xunit; public static class ApplicationInsightsJavaScriptTest { [Fact] public static void SnippetWillBeEmptyWhenInstrumentationKeyIsNotDefined() { var telemetryConfigurationWithNullKey = new TelemetryConfiguration(); var snippet = new JavaScriptSnippet(telemetryConfigurationWithNullKey); Assert.Equal(string.Empty, snippet.FullScript.ToString()); } [Fact] public static void SnippetWillBeEmptyWhenInstrumentationKeyIsEmpty() { var telemetryConfigurationWithEmptyKey = new TelemetryConfiguration { InstrumentationKey = string.Empty }; var snippet = new JavaScriptSnippet(telemetryConfigurationWithEmptyKey); Assert.Equal(string.Empty, snippet.FullScript.ToString()); } [Fact] public static void SnippetWillIncludeInstrumentationKeyAsSubstring() { string unittestkey = "unittestkey"; var telemetryConfiguration = new TelemetryConfiguration { InstrumentationKey = unittestkey }; var snippet = new JavaScriptSnippet(telemetryConfiguration); Assert.Contains("instrumentationKey: '" + unittestkey + "'", snippet.FullScript.ToString()); } } }
Fix migration by truncating rooms table
namespace Vaskelista.Migrations { using System; using System.Data.Entity.Migrations; public partial class RoomHouseholdRelation : DbMigration { public override void Up() { AddColumn("dbo.Rooms", "HouseHold_HouseholdId", c => c.Int(nullable: false)); CreateIndex("dbo.Rooms", "HouseHold_HouseholdId"); AddForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households", "HouseholdId", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households"); DropIndex("dbo.Rooms", new[] { "HouseHold_HouseholdId" }); DropColumn("dbo.Rooms", "HouseHold_HouseholdId"); } } }
namespace Vaskelista.Migrations { using System; using System.Data.Entity.Migrations; public partial class RoomHouseholdRelation : DbMigration { public override void Up() { Sql("TRUNCATE TABLE dbo.Rooms"); AddColumn("dbo.Rooms", "HouseHold_HouseholdId", c => c.Int(nullable: false)); CreateIndex("dbo.Rooms", "HouseHold_HouseholdId"); AddForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households", "HouseholdId", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.Rooms", "HouseHold_HouseholdId", "dbo.Households"); DropIndex("dbo.Rooms", new[] { "HouseHold_HouseholdId" }); DropColumn("dbo.Rooms", "HouseHold_HouseholdId"); } } }
Remove unnecessary cycle check from SynchroniseWithSystemClock
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb_core { public abstract class ClockedComponent { protected GameBoy _gb; protected ulong _lastUpdate; public ClockedComponent(GameBoy gameBoy) { _gb = gameBoy; } public void SynchroniseWithSystemClock() { // if we're up to date with the current timestamp there // is nothing for us to do if (_lastUpdate == _gb.Clock.Timestamp) { return; } ulong timestamp = _gb.Clock.Timestamp; uint cyclesToUpdate = (uint)(timestamp - _lastUpdate); _lastUpdate = timestamp; Update(cyclesToUpdate); } // Run this component for the required number of cycles public abstract void Update(uint cycleCount); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb_core { public abstract class ClockedComponent { protected GameBoy _gb; private SystemClock _clock; protected ulong _lastUpdate; public ClockedComponent(GameBoy gameBoy) { _gb = gameBoy; _clock = gameBoy.Clock; } public void SynchroniseWithSystemClock() { ulong timestamp = _clock.Timestamp; uint cyclesToUpdate = (uint)(timestamp - _lastUpdate); _lastUpdate = timestamp; Update(cyclesToUpdate); } // Run this component for the required number of cycles public abstract void Update(uint cycleCount); } }
Fix version number 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("Edument.CQRS.EntityFramework")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dynamic Generation Inc.")] [assembly: AssemblyProduct("Edument.CQRS.EntityFramework")] [assembly: AssemblyCopyright("Copyright © Dynamic Generation Inc. 2015")] [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("285a28c4-4564-4bb9-8cc2-afce371074a0")] // 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("Edument.CQRS.EntityFramework")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dynamic Generation Inc.")] [assembly: AssemblyProduct("Edument.CQRS.EntityFramework")] [assembly: AssemblyCopyright("Copyright © Dynamic Generation Inc. 2015")] [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("285a28c4-4564-4bb9-8cc2-afce371074a0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.1.0")] [assembly: AssemblyFileVersion("0.1.1.0")]
Fix Matt in name space
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; public class MattBobke : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Matt"; public string LastName => "Bobke"; public string ShortBioOrTagLine => "Desktop Support Specialist with admninistrative tendencies excited about PowerShell and automation."; public string StateOrRegion => "California, United States"; public string GravatarHash => "6f38a96cd055f95eacd1d3d102e309fa"; public string EmailAddress => "matt@mattbobke.com"; public string TwitterHandle => "MattBobke"; public string GitHubHandle => "mcbobke"; public GeoPosition Position => new GeoPosition(33.5676842, -117.7256083); public Uri WebSite => new Uri("https://mattbobke.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://mattbobke.com/feed"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } public string FeedLanguageCode => "en"; }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MattBobke : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Matt"; public string LastName => "Bobke"; public string ShortBioOrTagLine => "Desktop Support Specialist with admninistrative tendencies excited about PowerShell and automation."; public string StateOrRegion => "California, United States"; public string GravatarHash => "6f38a96cd055f95eacd1d3d102e309fa"; public string EmailAddress => "matt@mattbobke.com"; public string TwitterHandle => "MattBobke"; public string GitHubHandle => "mcbobke"; public GeoPosition Position => new GeoPosition(33.5676842, -117.7256083); public Uri WebSite => new Uri("https://mattbobke.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://mattbobke.com/feed"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } public string FeedLanguageCode => "en"; } }
Add model to change email view
@{ ViewBag.PageID = "page-change-email-address"; ViewBag.Title = "Change your email address"; } @if (!Model.Valid) { <div class="error-summary" role="group" tabindex="-1"> <h1 class="heading-medium error-summary-heading" id="error-summary-heading"> Errors to fix </h1> <p>Check the following details:</p> <ul class="error-summary-list"> </ul> </div> } <h1 class="heading-xlarge"> Change your email address </h1> <form method="post"> @Html.AntiForgeryToken() <fieldset> <legend class="visuallyhidden">New email address</legend> <div class="form-group"> <label class="form-label-bold" for="NewEmailAddress">New email address</label> <input autofocus="autofocus" aria-required="true" class="form-control" id="NewEmailAddress" name="NewEmailAddress"> </div> <div class="form-group"> <label class="form-label-bold" for="ConfirmEmailAddress">Re-type email addresss</label> <input aria-required="true" class="form-control" id="ConfirmEmailAddress" name="ConfirmEmailAddress"> </div> </fieldset> <button type="submit" class="button">Continue</button> </form>
 @model SFA.DAS.EmployerUsers.Web.Models.ChangeEmailViewModel @{ ViewBag.PageID = "page-change-email-address"; ViewBag.Title = "Change your email address"; } @if (!Model.Valid) { <div class="error-summary" role="group" tabindex="-1"> <h1 class="heading-medium error-summary-heading" id="error-summary-heading"> Errors to fix </h1> <p>Check the following details:</p> <ul class="error-summary-list"> </ul> </div> } <h1 class="heading-xlarge"> Change your email address </h1> <form method="post"> @Html.AntiForgeryToken() <fieldset> <legend class="visuallyhidden">New email address</legend> <div class="form-group"> <label class="form-label-bold" for="NewEmailAddress">New email address</label> <input autofocus="autofocus" aria-required="true" class="form-control" id="NewEmailAddress" name="NewEmailAddress"> </div> <div class="form-group"> <label class="form-label-bold" for="ConfirmEmailAddress">Re-type email addresss</label> <input aria-required="true" class="form-control" id="ConfirmEmailAddress" name="ConfirmEmailAddress"> </div> </fieldset> <button type="submit" class="button">Continue</button> </form>
Fix some flaky OData JSON tests using string comparison
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Linq; using Microsoft.TestCommon; namespace System.Web.Http.OData.Formatter { internal static class JsonAssert { public static void Equal(string expected, string actual) { // Due to a problem with one build system, don't assume source files use Environment.NewLine (they may just // use \n instead). Normalize the expected result to use Environment.NewLine. expected = expected.Replace(Environment.NewLine, "\n").Replace("\n", Environment.NewLine); // For now, simply compare the exact strings. Note that this approach requires whitespace to match exactly // (except for line endings). Assert.Equal(expected, actual); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using Microsoft.TestCommon; using Newtonsoft.Json.Linq; namespace System.Web.Http.OData.Formatter { internal static class JsonAssert { public static void Equal(string expected, string actual) { Assert.Equal(JToken.Parse(expected), JToken.Parse(actual), JToken.EqualityComparer); } } }
Fix asmdef analysers working on external files
using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Unity.JsonNew.Psi; using JetBrains.ReSharper.Plugins.Unity.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Tree; namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon { public abstract class AsmDefProblemAnalyzer<T> : ElementProblemAnalyzer<T> where T : ITreeNode { protected override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer) { // Run for visible documents and SWEA. Also run for "other", which is used by scoped quick fixes if (data.GetDaemonProcessKind() == DaemonProcessKind.GLOBAL_WARNINGS) return; if (data.SourceFile == null || !element.Language.Is<JsonNewLanguage>() || !data.SourceFile.IsAsmDef()) return; if (!element.GetProject().IsUnityProject()) return; Analyze(element, data, consumer); } protected abstract void Analyze(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer); } }
using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Unity.JsonNew.Psi; using JetBrains.ReSharper.Plugins.Unity.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Tree; namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Daemon { public abstract class AsmDefProblemAnalyzer<T> : ElementProblemAnalyzer<T> where T : ITreeNode { protected override void Run(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer) { // Run for visible documents and SWEA. Also run for "other", which is used by scoped quick fixes if (data.GetDaemonProcessKind() == DaemonProcessKind.GLOBAL_WARNINGS) return; if (data.SourceFile == null || !element.Language.Is<JsonNewLanguage>() || !data.SourceFile.IsAsmDef()) return; if (!element.GetSolution().HasUnityReference()) return; Analyze(element, data, consumer); } protected abstract void Analyze(T element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer); } }
Format code and remove wrong doc comment
using JetBrains.DocumentModel; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.Tree; using ReSharperExtensionsShared.Highlighting; using Roflcopter.Plugin.MismatchedFileNames; [assembly: RegisterConfigurableSeverity( MismatchedFileNameHighlighting.SeverityId, CompoundItemName: null, Group: HighlightingGroupIds.CodeSmell, Title: MismatchedFileNameHighlighting.Title, Description: MismatchedFileNameHighlighting.Description, DefaultSeverity: Severity.WARNING)] namespace Roflcopter.Plugin.MismatchedFileNames { /// <summary> /// Xml Doc highlighting for types / type members with specific accessibility. /// </summary> [ConfigurableSeverityHighlighting( SeverityId, CSharpLanguage.Name, OverlapResolve = OverlapResolveKind.NONE, ToolTipFormatString = Message)] public class MismatchedFileNameHighlighting : SimpleTreeNodeHighlightingBase<ITypeDeclaration> { public const string SeverityId = "MismatchedFileName"; public const string Title = "Mismatch between type and file name"; private const string Message = "Type doesn't match file name '{0}'"; public const string Description = Title; public MismatchedFileNameHighlighting(ITypeDeclaration declaration, string fileName) : base(declaration, string.Format(Message, fileName)) { } public override DocumentRange CalculateRange() { return TreeNode.GetNameDocumentRange(); } } }
using JetBrains.DocumentModel; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.Tree; using ReSharperExtensionsShared.Highlighting; using Roflcopter.Plugin.MismatchedFileNames; [assembly: RegisterConfigurableSeverity( MismatchedFileNameHighlighting.SeverityId, CompoundItemName: null, Group: HighlightingGroupIds.CodeSmell, Title: MismatchedFileNameHighlighting.Title, Description: MismatchedFileNameHighlighting.Description, DefaultSeverity: Severity.WARNING)] namespace Roflcopter.Plugin.MismatchedFileNames { [ConfigurableSeverityHighlighting( SeverityId, CSharpLanguage.Name, OverlapResolve = OverlapResolveKind.NONE, ToolTipFormatString = Message)] public class MismatchedFileNameHighlighting : SimpleTreeNodeHighlightingBase<ITypeDeclaration> { public const string SeverityId = "MismatchedFileName"; public const string Title = "Mismatch between type and file name"; private const string Message = "Type doesn't match file name '{0}'"; public const string Description = Title; public MismatchedFileNameHighlighting(ITypeDeclaration declaration, string fileName) : base(declaration, string.Format(Message, fileName)) { } public override DocumentRange CalculateRange() { return TreeNode.GetNameDocumentRange(); } } }
Fix issue that HRESULT returned by DWMAPI isn't converted.
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; namespace MetroRadiance.Interop.Win32 { public static class Dwmapi { [DllImport("Dwmapi.dll", ExactSpelling = true)] public static extern void DwmGetColorizationColor([Out] out uint pcrColorization, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfOpaqueBlend); [DllImport("Dwmapi.dll")] public static extern void DwmGetWindowAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE dwAttribute, [Out] out RECT pvAttribute, int cbAttribute); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; namespace MetroRadiance.Interop.Win32 { public static class Dwmapi { [DllImport("Dwmapi.dll", ExactSpelling = true, PreserveSig = false)] public static extern void DwmGetColorizationColor([Out] out uint pcrColorization, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfOpaqueBlend); [DllImport("Dwmapi.dll", ExactSpelling = true, PreserveSig = false)] public static extern void DwmGetWindowAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE dwAttribute, [Out] out RECT pvAttribute, int cbAttribute); } }
Disable with compiler constant instead.
using System; using System.Collections; using UnityEngine; //using DG.Tweening; public class EditorCoroutineTween { /* public static EditorCoroutine Run(Tween t) { EditorCoroutineTween ct = new EditorCoroutineTween(); return EditorCoroutine.Start(ct.UpdateTween(t)); } IEnumerator UpdateTween(Tween t) { #if UNITY_EDITOR float time = Time.realtimeSinceStartup; while (!t.IsComplete()) { t.fullPosition = Time.realtimeSinceStartup - time; yield return 0; } #else yield return null; #endif } */ }
#if !NO_DOTWEEN using System; using System.Collections; using UnityEngine; using DG.Tweening; public class EditorCoroutineTween { public static EditorCoroutine Run(Tween t) { EditorCoroutineTween ct = new EditorCoroutineTween(); return EditorCoroutine.Start(ct.UpdateTween(t)); } IEnumerator UpdateTween(Tween t) { #if UNITY_EDITOR float time = Time.realtimeSinceStartup; while (!t.IsComplete()) { t.fullPosition = Time.realtimeSinceStartup - time; yield return 0; } #else yield return null; #endif } } #endif
Add test for concurrent session factories.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace NHibernate.Caches.Redis.Tests { public class PerformanceTests : IntegrationTestBase { [Fact] async Task concurrent_reads_and_writes() { DisableLogging(); const int iterations = 1000; var sessionFactory = CreateSessionFactory(); var tasks = Enumerable.Range(0, iterations).Select(i => { return Task.Run(() => { object entityId = null; UsingSession(sessionFactory, session => { var entity = new Person("Foo", 1); entityId = session.Save(entity); session.Flush(); session.Clear(); entity = session.Load<Person>(entityId); entity.Name = Guid.NewGuid().ToString(); session.Flush(); }); }); }); await Task.WhenAll(tasks); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace NHibernate.Caches.Redis.Tests { public class PerformanceTests : IntegrationTestBase { [Fact] async Task concurrent_sessions_with_reads_and_writes() { DisableLogging(); const int iterations = 1000; var sessionFactory = CreateSessionFactory(); var tasks = Enumerable.Range(0, iterations).Select(i => { return Task.Run(() => { object entityId = null; UsingSession(sessionFactory, session => { var entity = new Person("Foo", 1); entityId = session.Save(entity); session.Flush(); session.Clear(); entity = session.Load<Person>(entityId); entity.Name = Guid.NewGuid().ToString(); session.Flush(); }); }); }); await Task.WhenAll(tasks); } [Fact] async Task concurrent_session_factories_with_reads_and_writes() { DisableLogging(); const int sessionFactoryCount = 5; const int iterations = 1000; // Create factories on the same thread so we don't run into // concurrency issues with NHibernate. var sessionFactories = Enumerable.Range(0, sessionFactoryCount).Select(i => { return CreateSessionFactory(); }); var tasks = sessionFactories.Select(sessionFactory => { return Task.Run(() => { for (int i = 0; i < iterations; i++) { object entityId = null; UsingSession(sessionFactory, session => { var entity = new Person("Foo", 1); entityId = session.Save(entity); session.Flush(); session.Clear(); entity = session.Load<Person>(entityId); entity.Name = Guid.NewGuid().ToString(); session.Flush(); }); } }); }); await Task.WhenAll(tasks); } } }
Use Name and title interchangeably.
using Newtonsoft.Json; namespace TMDbLib.Objects.General { public class TranslationData { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("overview")] public string Overview { get; set; } [JsonProperty("homepage")] public string HomePage { get; set; } [JsonProperty("tagline")] public string Tagline { get; set; } [JsonProperty("runtime")] public int Runtime { get; set; } } }
using Newtonsoft.Json; namespace TMDbLib.Objects.General { public class TranslationData { [JsonProperty("name")] public string Name { get; set; } // Private hack to ensure two properties (name, title) are deserialized into Name. // Tv Shows and Movies will use different names for their translation data. [JsonProperty("title")] private string Title { set => Name = value; } [JsonProperty("overview")] public string Overview { get; set; } [JsonProperty("homepage")] public string HomePage { get; set; } [JsonProperty("tagline")] public string Tagline { get; set; } [JsonProperty("runtime")] public int Runtime { get; set; } } }
Revert "Remove uneeded player collection methods"
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// The collection of network players that are known about. /// </summary> public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer> { /// <summary> /// The networked players. /// </summary> IEnumerable<INetworkPlayer> Players { get; } /// <summary> /// Returns the <see cref="INetworkPlayer"/> with the id. /// Or null if the player doesn't exist. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns> INetworkPlayer this[int id] { get; } /// <summary> /// Indicates if it contains the <see cref="id"/> key value. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>True if the collection contains the ID.</returns> bool ContainsId(int id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Booma.Proxy { /// <summary> /// The collection of network players that are known about. /// </summary> public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer> { /// <summary> /// The local player. /// </summary> INetworkPlayer Local { get; } /// <summary> /// The networked players. /// </summary> IEnumerable<INetworkPlayer> Players { get; } /// <summary> /// The networked player's excluding the <see cref="Local"/> player. /// </summary> IEnumerable<INetworkPlayer> ExcludingLocal { get; } /// <summary> /// Returns the <see cref="INetworkPlayer"/> with the id. /// Or null if the player doesn't exist. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns> INetworkPlayer this[int id] { get; } /// <summary> /// Indicates if it contains the <see cref="id"/> key value. /// </summary> /// <param name="id">The id to check for.</param> /// <returns>True if the collection contains the ID.</returns> bool ContainsId(int id); } }
Store selected implementation in cookie
using System; using System.Collections.Generic; using System.Linq; using System.Web; using DataAccessExamples.Core.Services; using DataAccessExamples.Core.ViewModels; using Nancy.TinyIoc; namespace DataAccessExamples.Web { using Nancy; public class Bootstrapper : DefaultNancyBootstrapper { // The bootstrapper enables you to reconfigure the composition of the framework, // by overriding the various methods and properties. // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context) { base.ConfigureRequestContainer(container, context); container.Register(ResolveImplementation<IDepartmentService>(container, context)); } private T ResolveImplementation<T>(TinyIoCContainer container, NancyContext context) where T : class { var implementations = container.ResolveAll<T>(); var implementationName = (string) context.Request.Query["Impl"]; if (!String.IsNullOrWhiteSpace(implementationName)) { return implementations.Distinct().FirstOrDefault(i => i.GetType().Name.StartsWith(implementationName)); } return implementations.FirstOrDefault(); } } }
using System; using System.Linq; using DataAccessExamples.Core.Services; using Nancy.Bootstrapper; using Nancy.Responses; using Nancy.TinyIoc; namespace DataAccessExamples.Web { using Nancy; public class Bootstrapper : DefaultNancyBootstrapper { protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context) { base.ConfigureRequestContainer(container, context); container.Register(ResolveImplementation<IDepartmentService>(container, context)); } protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); pipelines.BeforeRequest += context => { var implementationName = (string) context.Request.Query["Impl"]; if (!String.IsNullOrWhiteSpace(implementationName)) { var response = new RedirectResponse(context.Request.Path); response.AddCookie("Impl", implementationName); return response; } return null; }; } private T ResolveImplementation<T>(TinyIoCContainer container, NancyContext context) where T : class { var implementations = container.ResolveAll<T>(); if (context.Request.Cookies.ContainsKey("Impl")) { return implementations.FirstOrDefault(i => i.GetType().Name.StartsWith(context.Request.Cookies["Impl"])); } return implementations.FirstOrDefault(); } } }
Hide cursor and quit with escape.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { void Start () { } void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { void Start () { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } void Update () { if (Input.GetKey(KeyCode.Escape)) { Application.Quit(); } } }
Implement interface in concrete class
namespace Our.Umbraco.Nexu.Core.Services { /// <summary> /// Represents nexu entity relation service. /// </summary> public class NexuEntityRelationService { } }
namespace Our.Umbraco.Nexu.Core.Services { using Our.Umbraco.Nexu.Common.Interfaces.Services; /// <summary> /// Represents nexu entity relation service. /// </summary> public class NexuEntityRelationService : IEntityRelationService { } }
Remove disused data collection partition registers.
using Lbookshelf.Models; using Lbookshelf.Utils; using Lbookshelf.ViewModels; using Ldata; using Ldata.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Lbookshelf { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private static JsonDataStore _dataStore; public static IDataStore DataStore { get { if (_dataStore == null) { _dataStore = new JsonDataStore("db"); //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.Books); //_dataStore.RegisterPartitionSelector<string>(obj => DataCollectionNames.RecentKeywords); _dataStore.RegisterPartitionSelector<SortedObservableGroup<string, Book>>(DataCollectionNames.Booklists, obj => obj.Key); //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.RecentlyAdded); //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.RecentlyOpened); //_dataStore.RegisterPartitionSelector<Book>(obj => DataCollectionNames.Pinned); } return _dataStore; } } private static BrowseBooksViewModel _browseBooksViewModel; public static BrowseBooksViewModel BrowseBooksViewModel { get { if (_browseBooksViewModel == null) { _browseBooksViewModel = new BrowseBooksViewModel(); } return _browseBooksViewModel; } } private static HomeViewModel _homeViewModel; public static HomeViewModel HomeViewModel { get { if (_homeViewModel == null) { _homeViewModel = new HomeViewModel(); } return _homeViewModel; } } } }
using Lbookshelf.Models; using Lbookshelf.Utils; using Lbookshelf.ViewModels; using Ldata; using Ldata.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Lbookshelf { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private static JsonDataStore _dataStore; public static IDataStore DataStore { get { if (_dataStore == null) { _dataStore = new JsonDataStore("db"); _dataStore.RegisterPartitionSelector<SortedObservableGroup<string, Book>>(DataCollectionNames.Booklists, obj => obj.Key); } return _dataStore; } } private static BrowseBooksViewModel _browseBooksViewModel; public static BrowseBooksViewModel BrowseBooksViewModel { get { if (_browseBooksViewModel == null) { _browseBooksViewModel = new BrowseBooksViewModel(); } return _browseBooksViewModel; } } private static HomeViewModel _homeViewModel; public static HomeViewModel HomeViewModel { get { if (_homeViewModel == null) { _homeViewModel = new HomeViewModel(); } return _homeViewModel; } } } }
Tweak format of evaluation email per BC request
@model BatteryCommander.Web.Models.Evaluation <h1>@Model.Ratee</h1> <table border="1"> <tbody> <tr> <td>Soldier</td> <td>@Model.Ratee</td> </tr> <tr> <td>Rater</td> <td>@Model.Rater</td> </tr> <tr> <td>SR Rater</td> <td>@Model.SeniorRater</td> </tr> <tr> <td>Last Message</td> <td>@Model.LastEvent.Message</td> </tr> <tr> <td>Author</td> <td>@Model.LastEvent.Author</td> </tr> <tr> <td>Timestamp</td> <td>@Model.LastEvent.TimestampHumanized</td> </tr> <tr> <td>Link</td> <td><a href="https://bc.redleg.app/Evaluations/Details/@Model.Id">Evaluation</a></td> </tr> </tbody> </table> <hr /> <a href="https://bc.redleg.app/Evaluations">Evaluation Tracker</a>
@model BatteryCommander.Web.Models.Evaluation <h1>@Model.Ratee</h1> <table border="1"> <tbody> <tr> <td>Soldier</td> <td>@Model.Ratee</td> </tr> <tr> <td>Rater</td> <td>@Model.Rater</td> </tr> <tr> <td>SR Rater</td> <td>@Model.SeniorRater</td> </tr> <tr> <td>Last Message</td> <td>@Model.LastEvent.Message by @Model.LastEvent.Author @Model.LastUpdatedHumanized</td> </tr> <tr> <td>Link</td> <td><a href="https://bc.redleg.app/Evaluations/Details/@Model.Id">Evaluation</a></td> </tr> @if(!String.IsNullOrWhiteSpace(Model.EvaluationLink)) { <tr> <td>EES</td> <td><a href="@Model.EvaluationLink">@Model.EvaluationId</a></td> </tr> } </tbody> </table> <hr /> <a href="https://bc.redleg.app/Evaluations">Evaluation Tracker</a>
Implement embedify function on frontend.
using BibleBot.Lib; using DSharpPlus.Entities; namespace BibleBot.Frontend { public class Utils { public DiscordEmbed Embed2Embed(InternalEmbed embed) { var builder = new DiscordEmbedBuilder(); var footerText = builder.WithTitle(embed.Title); builder.WithDescription(embed.Description); builder.WithColor(new DiscordColor((int) embed.Colour)); builder.WithFooter(embed.Footer.Text, "https://i.imgur.com/hr4RXpy.png"); if (embed.Author != null) { builder.WithAuthor(embed.Author.Name, null, null); } return builder.Build(); } } }
using BibleBot.Lib; using DSharpPlus.Entities; namespace BibleBot.Frontend { public class Utils { public enum Colours { NORMAL_COLOR = 6709986, ERROR_COLOR = 16723502 } public DiscordEmbed Embed2Embed(InternalEmbed embed) { var builder = new DiscordEmbedBuilder(); builder.WithTitle(embed.Title); builder.WithDescription(embed.Description); builder.WithColor(new DiscordColor((int) embed.Colour)); builder.WithFooter(embed.Footer.Text, "https://i.imgur.com/hr4RXpy.png"); if (embed.Author != null) { builder.WithAuthor(embed.Author.Name, null, null); } return builder.Build(); } public DiscordEmbed Embedify(string title, string description, bool isError) { return Embedify(null, title, description, isError, null); } public DiscordEmbed Embedify(string author, string title, string description, bool isError, string copyright) { // TODO: Do not use hard-coded version tags. string footerText = "BibleBot v9.1-beta by Kerygma Digital"; var builder = new DiscordEmbedBuilder(); builder.WithTitle(title); builder.WithDescription(description); builder.WithColor(isError ? (int) Colours.ERROR_COLOR : (int) Colours.NORMAL_COLOR); builder.WithFooter(footerText, "https://i.imgur.com/hr4RXpy.png"); if (author != null) { builder.WithAuthor(author, null, null); } return builder.Build(); } } }
Use Amount as coin identifier.
using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class CoinInfoTabViewModel : WasabiDocumentTabViewModel { public CoinInfoTabViewModel(CoinViewModel coin) : base(string.Empty) { Coin = coin; Title = $"Details of {coin.OutputIndex}:{coin.TransactionId[0..7]}"; } public CoinViewModel Coin { get; } } }
using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class CoinInfoTabViewModel : WasabiDocumentTabViewModel { public CoinInfoTabViewModel(CoinViewModel coin) : base(string.Empty) { Coin = coin; Title = $"Coin ({coin.Amount.ToString(false, true)}) Details"; } public CoinViewModel Coin { get; } } }
Fix autogeneration of Framework version Version has to be Major.Minor.* instead of Major.Minor.*.*
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("RegTesting.Tests.Framework")] [assembly: AssemblyDescription("A test framework for tests with selenium.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HOTELDE AG")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("2012-2015 HOTELDE AG, Apache License, Version 2.0")] [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("a7e6a771-5f9d-425a-a401-3a5f4c71b270")] // Version information for an assembly consists of the following four values: // // Major Version <- upper this for breaking api changes // Minor Version <- upper this for new functionality // Build Number <- this should match to the referenced selenium version // Revision // [assembly: AssemblyVersion("1.0.*.*")] [assembly: AssemblyFileVersion("1.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("RegTesting.Tests.Framework")] [assembly: AssemblyDescription("A test framework for tests with selenium.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HOTELDE AG")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("2012-2015 HOTELDE AG, Apache License, Version 2.0")] [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("a7e6a771-5f9d-425a-a401-3a5f4c71b270")] // Version information for an assembly consists of the following four values: // // Major Version <- upper this for breaking api changes // Minor Version <- upper this for new functionality // Build Number <- auto generated while build // Revision <- auto generated while build // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.*")]
Allow testing of all chat-related classes dynamically
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; namespace osu.Game.Tests.Visual { [Description("Testing chat api and overlay")] public class TestCaseChatDisplay : OsuTestCase { public TestCaseChatDisplay() { Add(new ChatOverlay { State = Visibility.Visible }); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.ComponentModel; using osu.Framework.Graphics.Containers; using osu.Game.Overlays; using osu.Game.Overlays.Chat; using osu.Game.Overlays.Chat.Tabs; namespace osu.Game.Tests.Visual { [Description("Testing chat api and overlay")] public class TestCaseChatDisplay : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ChatOverlay), typeof(ChatLine), typeof(DrawableChannel), typeof(ChannelSelectorTabItem), typeof(ChannelTabControl), typeof(ChannelTabItem), typeof(PrivateChannelTabItem), typeof(TabCloseButton) }; public TestCaseChatDisplay() { Add(new ChatOverlay { State = Visibility.Visible }); } } }
Update pinned score container header to use localised title
// 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.Game.Overlays.Profile.Sections.Ranks; using osu.Game.Online.API.Requests; using osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.Profile.Sections { public class RanksSection : ProfileSection { public override LocalisableString Title => UsersStrings.ShowExtraTopRanksTitle; public override string Identifier => @"top_ranks"; public RanksSection() { Children = new[] { // todo: update to use UsersStrings.ShowExtraTopRanksPinnedTitle once that exists. new PaginatedScoreContainer(ScoreType.Pinned, User, "Pinned Scores"), new PaginatedScoreContainer(ScoreType.Best, User, UsersStrings.ShowExtraTopRanksBestTitle), new PaginatedScoreContainer(ScoreType.Firsts, User, UsersStrings.ShowExtraTopRanksFirstTitle) }; } } }
// 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.Game.Overlays.Profile.Sections.Ranks; using osu.Game.Online.API.Requests; using osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.Profile.Sections { public class RanksSection : ProfileSection { public override LocalisableString Title => UsersStrings.ShowExtraTopRanksTitle; public override string Identifier => @"top_ranks"; public RanksSection() { Children = new[] { new PaginatedScoreContainer(ScoreType.Pinned, User, UsersStrings.ShowExtraTopRanksPinnedTitle), new PaginatedScoreContainer(ScoreType.Best, User, UsersStrings.ShowExtraTopRanksBestTitle), new PaginatedScoreContainer(ScoreType.Firsts, User, UsersStrings.ShowExtraTopRanksFirstTitle) }; } } }
Replace GetHover implementation with generated classes.
using System.Threading.Tasks; namespace DanTup.DartAnalysis { class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>> { public string method = "analysis.getHover"; public AnalysisGetHoverRequest(string file, int offset) { this.@params = new AnalysisGetHoverParams(file, offset); } } class AnalysisGetHoverParams { public string file; public int offset; public AnalysisGetHoverParams(string file, int offset) { this.file = file; this.offset = offset; } } class AnalysisGetHoverResponse { public AnalysisHoverItem[] hovers = null; } public class AnalysisHoverItem { public int offset; public int length; public string containingLibraryPath; public string containingLibraryName; public string dartdoc; public string elementKind; public string elementDescription; public string propagatedType; public string staticType; public string parameter; } public static class AnalysisGetHoverImplementation { public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset) { var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset)).ConfigureAwait(continueOnCapturedContext: false); return response.result.hovers; } } }
using System.Threading.Tasks; using DanTup.DartAnalysis.Json; namespace DanTup.DartAnalysis { public static class AnalysisGetHoverImplementation { public static async Task<HoverInformation[]> GetHover(this DartAnalysisService service, string file, int offset) { var request = new AnalysisGetHoverRequest { File = file, Offset = offset }; var response = await service.Service .Send(new AnalysisGetHover(request)) .ConfigureAwait(continueOnCapturedContext: false); return response.result.Hovers; } } }
Add System Programming Lab2 Automaton Builder - Added Start and Finish
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab2.Automaton { public class AutomatonBuilder : IIOAutomatonBuilder { private FiniteStateAutomaton automaton = new FiniteStateAutomaton(); public void AddState(int identifier) { StateDescription state = new StateDescription(identifier.ToString()); automaton.AddNewState(state); } public void AddTransition(int from, int to, char? label) { StateDescription head = automaton.FindByName(from.ToString()); StateDescription tale = automaton.FindByName(to.ToString()); if (head == null || tale == null) { throw new ArgumentException(); } SymbolBase symbol = null; if (label.HasValue) { symbol = new CharSybmol(label.Value); } else { symbol = new EpsilonSymbol(); } head.AddNewTransition(symbol, tale); } public void SetStartState(int identifier) { throw new NotImplementedException(); } public void SetFinhState(int identifier) { throw new NotImplementedException(); } public IAutomaton GetAutomaton() { return automaton; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab2.Automaton { public class AutomatonBuilder : IIOAutomatonBuilder { private FiniteStateAutomaton automaton = new FiniteStateAutomaton(); public void AddState(int identifier) { StateDescription state = new StateDescription(identifier.ToString()); automaton.AddNewState(state); } public void AddTransition(int from, int to, char? label) { StateDescription head = automaton.FindByName(from.ToString()); StateDescription tale = automaton.FindByName(to.ToString()); if (head == null || tale == null) { throw new ArgumentException(); } SymbolBase symbol = null; if (label.HasValue) { symbol = new CharSybmol(label.Value); } else { symbol = new EpsilonSymbol(); } head.AddNewTransition(symbol, tale); } public void SetStartState(int identifier) { StateDescription start = automaton.FindByName(identifier.ToString()); if (start == null) { throw new ArgumentException(); } start.IsStart = true; } public void SetFinhState(int identifier) { StateDescription finish = automaton.FindByName(identifier.ToString()); if (finish == null) { throw new ArgumentException(); } finish.IsFinish = true; } public IAutomaton GetAutomaton() { return automaton; } } }
Remove redundant code from Admin controller
using System; using AlphaDev.Core; using AlphaDev.Web.Controllers; using AlphaDev.Web.Models; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using NSubstitute; using Optional; using Xunit; namespace AlphaDev.Web.Tests.Unit.Controllers { public class AdminControllerTests { private AdminController GetAdminController() { var blogService = Substitute.For<IBlogService>(); blogService.GetLatest().Returns(((BlogBase) new Blog(default, null, null, default)).Some()); return GetAdminController(blogService); } private AdminController GetAdminController(IBlogService blogService) { return new AdminController(); } [Fact] public void IndexShouldReturnIndexView() { var controller = GetAdminController(); controller.Index().Should().BeOfType<ViewResult>(); } } }
using System; using AlphaDev.Core; using AlphaDev.Web.Controllers; using AlphaDev.Web.Models; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using NSubstitute; using Optional; using Xunit; namespace AlphaDev.Web.Tests.Unit.Controllers { public class AdminControllerTests { private AdminController GetAdminController() { return new AdminController(); } [Fact] public void IndexShouldReturnIndexViewResult() { var controller = GetAdminController(); controller.Index().Should().BeOfType<ViewResult>().Which.ViewName.Should().BeEquivalentTo("Index"); } } }
Make the assembly's internals visible to the reference assembly
 using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Watsonia.Data.Tests")]
 using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Watsonia.Data.Tests")] [assembly: InternalsVisibleTo("Watsonia.Data.Reference")]
Add input binder to allow for comma-separated list inputs for API routes
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } }
using System; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } }
Add toString override to error class
namespace ExifLibrary { /// <summary> /// Represents error severity. /// </summary> public enum Severity { Info, Warning, Error, } /// <summary> /// Represents errors or warnings generated while reading/writing image files. /// </summary> public class ImageError { /// <summary> /// Gets the severity of the error. /// </summary> public Severity Severity { get;} /// <summary> /// Gets the error message. /// </summary> public string Message { get; } /// <summary> /// Initializes a new instance of the <see cref="ImageError"/> class. /// </summary> /// <param name="severity"></param> /// <param name="message"></param> public ImageError(Severity severity, string message) { Severity = severity; Message = message; } } }
namespace ExifLibrary { /// <summary> /// Represents error severity. /// </summary> public enum Severity { Info, Warning, Error, } /// <summary> /// Represents errors or warnings generated while reading/writing image files. /// </summary> public class ImageError { /// <summary> /// Gets the severity of the error. /// </summary> public Severity Severity { get;} /// <summary> /// Gets the error message. /// </summary> public string Message { get; } /// <summary> /// Initializes a new instance of the <see cref="ImageError"/> class. /// </summary> /// <param name="severity"></param> /// <param name="message"></param> public ImageError(Severity severity, string message) { Severity = severity; Message = message; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns></returns> public override string ToString() { return Message; } } }
Increase nuget package version to 2.0.0-beta03
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-beta02")]
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-beta03")]
Fix exception when box info is empty
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.UI; public class BoxInfo : MonoBehaviour { public Text LeftText; public Text RightText; readonly StringBuilder names = new StringBuilder(); readonly StringBuilder values = new StringBuilder(); public void Clear() { names.Length = 0; names.Capacity = 0; values.Length = 0; values.Capacity = 0; LeftText.text = string.Empty; RightText.text = string.Empty; gameObject.SetActive(false); } public void Append(string name, object value) { names.AppendLine(name); values.AppendLine(value.ToString()); } public void Append() { Append(string.Empty, string.Empty); } public void AppendFormat(string name, string format, params object[] args) { Append(name, string.Format(format, args)); } public void UpdateText() { //remove last line return character names.Length -= 2; values.Length -= 2; LeftText.text = names.ToString(); RightText.text = values.ToString(); gameObject.SetActive(LeftText.text.Length > 0); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.UI; public class BoxInfo : MonoBehaviour { public Text LeftText; public Text RightText; readonly StringBuilder names = new StringBuilder(); readonly StringBuilder values = new StringBuilder(); public void Clear() { names.Length = 0; names.Capacity = 0; values.Length = 0; values.Capacity = 0; LeftText.text = string.Empty; RightText.text = string.Empty; gameObject.SetActive(false); } public void Append(string name, object value) { names.AppendLine(name); values.AppendLine(value.ToString()); } public void Append() { Append(string.Empty, string.Empty); } public void AppendFormat(string name, string format, params object[] args) { Append(name, string.Format(format, args)); } public void UpdateText() { //remove last line return character if (names.Length >= 2) { names.Length -= 2; values.Length -= 2; } LeftText.text = names.ToString(); RightText.text = values.ToString(); gameObject.SetActive(LeftText.text.Length > 0); } }
Remove Windows long path workaround.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.Text.RegularExpressions; namespace osu.Framework.Platform.Windows { public class WindowsStorage : DesktopStorage { public WindowsStorage(string baseName, DesktopGameHost host) : base(baseName, host) { // allows traversal of long directory/filenames beyond the standard limitations (see https://stackoverflow.com/a/5188559) BasePath = Regex.Replace(BasePath, @"^([a-zA-Z]):\\", @"\\?\$1:\"); } public override void OpenInNativeExplorer() => Process.Start("explorer.exe", GetFullPath(string.Empty)); protected override string LocateBasePath() => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; namespace osu.Framework.Platform.Windows { public class WindowsStorage : DesktopStorage { public WindowsStorage(string baseName, DesktopGameHost host) : base(baseName, host) { } public override void OpenInNativeExplorer() => Process.Start("explorer.exe", GetFullPath(string.Empty)); protected override string LocateBasePath() => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } }
Rephrase null-safe Dispose helper to use pattern matching syntax.
namespace Fixie { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using static Internal.Maybe; public static class ReflectionExtensions { public static bool IsVoid(this MethodInfo method) { return method.ReturnType == typeof(void); } public static bool IsStatic(this Type type) { return type.IsAbstract && type.IsSealed; } public static bool Has<TAttribute>(this MemberInfo member) where TAttribute : Attribute { return member.GetCustomAttributes<TAttribute>(true).Any(); } public static bool Has<TAttribute>(this MemberInfo member, [NotNullWhen(true)] out TAttribute? matchingAttribute) where TAttribute : Attribute { return Try(() => member.GetCustomAttribute<TAttribute>(true), out matchingAttribute); } public static void Dispose(this object? o) { (o as IDisposable)?.Dispose(); } } }
namespace Fixie { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using static Internal.Maybe; public static class ReflectionExtensions { public static bool IsVoid(this MethodInfo method) { return method.ReturnType == typeof(void); } public static bool IsStatic(this Type type) { return type.IsAbstract && type.IsSealed; } public static bool Has<TAttribute>(this MemberInfo member) where TAttribute : Attribute { return member.GetCustomAttributes<TAttribute>(true).Any(); } public static bool Has<TAttribute>(this MemberInfo member, [NotNullWhen(true)] out TAttribute? matchingAttribute) where TAttribute : Attribute { return Try(() => member.GetCustomAttribute<TAttribute>(true), out matchingAttribute); } public static void Dispose(this object? o) { if (o is IDisposable disposable) disposable.Dispose(); } } }
Tidy up some formatting of code file
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MvcMiniProfiler; using Raven.Client.Connection; using Raven.Client.Connection.Profiling; using Raven.Client.Document; namespace MvcMiniProfiler.RavenDb { public class Profiler { private static Dictionary<string, IDisposable> _Requests = new Dictionary<string, IDisposable>(); public static void AttachTo(DocumentStore store) { store.SessionCreatedInternal += TrackSession; store.JsonRequestFactory.ConfigureRequest += BeginRequest; store.JsonRequestFactory.LogRequest += EndREquest; } private static void TrackSession(InMemoryDocumentSessionOperations obj) { MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Created Session").Dispose(); } private static void BeginRequest(object sender, WebRequestEventArgs e) { _Requests.Add(e.Request.RequestUri.PathAndQuery, MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Query - " + e.Request.RequestUri.PathAndQuery)); } private static void EndREquest(object sender, RequestResultArgs e) { IDisposable request; if (_Requests.TryGetValue(e.Url, out request)) request.Dispose(); } } }
using System; using System.Collections.Generic; using Raven.Client.Connection; using Raven.Client.Connection.Profiling; using Raven.Client.Document; namespace MvcMiniProfiler.RavenDb { public class Profiler { private static Dictionary<string, IDisposable> _Requests = new Dictionary<string, IDisposable>(); public static void AttachTo(DocumentStore store) { store.SessionCreatedInternal += TrackSession; store.JsonRequestFactory.ConfigureRequest += BeginRequest; store.JsonRequestFactory.LogRequest += EndRequest; } private static void TrackSession(InMemoryDocumentSessionOperations obj) { MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Created Session").Dispose(); } private static void BeginRequest(object sender, WebRequestEventArgs e) { _Requests.Add(e.Request.RequestUri.PathAndQuery, MvcMiniProfiler.MiniProfiler.Current.Step("RavenDb: Query - " + e.Request.RequestUri.PathAndQuery)); } private static void EndRequest(object sender, RequestResultArgs e) { IDisposable request; if (_Requests.TryGetValue(e.Url, out request)) request.Dispose(); } } }
Test code for SQL queries
using System; namespace NHibernate.DomainModel { /// <summary> /// Summary description for SubComponent. /// </summary> public class SubComponent { private string _subName; private string _subName1; public SubComponent() { } public string SubName { get { return _subName; } set { _subName = value; } } public string SubName1 { get { return _subName1; } set { _subName1 = value; } } } }
Make this enum a byte for small serialization
namespace ZocMonLib { public enum MonitorReductionType { Custom = 0, DefaultAverage = 1, DefaultAccumulate = 2 } }
namespace ZocMonLib { public enum MonitorReductionType : byte { Custom = 0, DefaultAverage = 1, DefaultAccumulate = 2 } }
Add a reusable hash-code class.
using System.Collections; using System.Collections.Generic; using System.Linq; namespace DasMulli.Win32.ServiceUtils { /// <summary> /// Simplifies the work of hashing. /// Taken from <see cref="https://rehansaeed.com/gethashcode-made-easy/"/>, and modified with Reshaper /// </summary> public struct HashCode { private readonly int value; private HashCode(int value) { this.value = value; } public static implicit operator int(HashCode hashCode) { return hashCode.value; } public static HashCode Of<T>(T item) { return new HashCode(GetHashCode(item)); } public HashCode And<T>(T item) { return new HashCode(CombineHashCodes(this.value, GetHashCode(item))); } public HashCode AndEach<T>(IEnumerable<T> items) { int hashCode = items.Select(GetHashCode).Aggregate(CombineHashCodes); return new HashCode(CombineHashCodes(this.value, hashCode)); } private static int CombineHashCodes(int h1, int h2) { unchecked { // Code copied from System.Tuple so it must be the best way to combine hash codes or at least a good one. return ((h1 << 5) + h1) ^ h2; } } private static int GetHashCode<T>(T item) { return item == null ? 0 : item.GetHashCode(); } } }
Split string per given pattern
// http://careercup.com/question?id=5702976138117120 // Split string per pattern // using System; using System.Collections.Generic; using System.Linq; static class Program { static IEnumerable<String> Split(this String s, IEnumerable<int> pattern) { int prev = 0; foreach (int index in pattern) { yield return s.Substring(prev, index - prev + 1); prev = index + 1; } yield return s.Substring(prev, s.Length - prev); } static void Main() { String s = "Programmingproblemforidiots"; Console.WriteLine(String.Join(", ", s.Split(new List<int> {10, 17, 20}))); } }
Add "no normalization performed" test for Storage client.
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.IO; using System.Text; using Xunit; namespace Google.Cloud.Storage.V1.IntegrationTests { /// <summary> /// Tests that ensure the client does *not* perform any normalization. /// The bucket <see cref="s_bucket"/> contains two files, which are both named "Café" /// but using different normalization. The client should be able to retrieve both. /// </summary> public class NormalizationTest { private const string s_bucket = "storage-library-test-bucket"; [Theory] // Normalization Form C: a single character for e-acute. // URL should end with Cafe%CC%81 [InlineData("Caf\u00e9", "Normalization Form C")] // Normalization Form D: an ASCII e followed by U+0301 combining character // URL should end with Caf%C3%A9 [InlineData("Cafe\u0301", "Normalization Form D")] public void FetchObjectAndCheckContent(string name, string expectedContent) { var client = StorageClient.Create(); var obj = client.GetObject(s_bucket, name); Assert.Equal(name, obj.Name); var stream = new MemoryStream(); client.DownloadObject(s_bucket, name, stream); string text = Encoding.UTF8.GetString(stream.ToArray()); Assert.Equal(expectedContent, text); } } }
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> /// 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(); } } }
Add first draft of AppBuilderExtension tests.
using System; using Microsoft.AspNetCore.Builder; using Moq; using Xunit; namespace Marvin.Cache.Headers.Test.Extensions { public class AppBuilderExtensionsFacts { [Fact(Skip = "The Verify throws an exception because UseMiddleware is an extension function as well and can't be mocked, need to find ")] public void Correctly_register_HttpCacheHeadersMiddleware() { var appBuilderMock = new Mock<IApplicationBuilder>(); appBuilderMock.Object.UseHttpCacheHeaders(); appBuilderMock.Verify(x => x.UseMiddleware<HttpCacheHeadersMiddleware>(), "Application builder isn't registering the middleware."); } [Fact] public void When_no_ApplicationBuilder_expect_ArgumentNullException() { IApplicationBuilder appBuilder = null; Assert.Throws<ArgumentNullException>(() => appBuilder.UseHttpCacheHeaders()); } } }
Add path element class for selection access
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace Pather.CSharp.PathElements { public class SelectionAccess : IPathElement { public SelectionAccess() { } public object Apply(object target) { var enumerable = target as IEnumerable; var result = new Selection(enumerable); return result; } } }
Add baseline test coverage for blocking exit flow
// 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.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Extensions; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Framework.Tests.Platform { [TestFixture] public class GameExitTest { private TestTestGame game; private ManualExitHeadlessGameHost host; private const int timeout = 5000; [Test] public void TestExitBlocking() { var gameCreated = new ManualResetEventSlim(); var task = Task.Factory.StartNew(() => { using (host = new ManualExitHeadlessGameHost()) { game = new TestTestGame(); gameCreated.Set(); host.Run(game); } }, TaskCreationOptions.LongRunning); gameCreated.Wait(timeout); Assert.IsTrue(game.BecameAlive.Wait(timeout)); // block game from exiting. game.BlockExit.Value = true; // `RequestExit()` should return true. Assert.That(host.RequestExit(), Is.True); // exit should be blocked. Assert.That(() => host.ExecutionState, Is.EqualTo(ExecutionState.Running).After(timeout)); Assert.That(task.IsCompleted, Is.False); // unblock game from exiting. game.BlockExit.Value = false; // `RequestExit()` should not be blocked and return false. Assert.That(host.RequestExit(), Is.False); // finally, the game should exit. Assert.That(() => host.ExecutionState, Is.EqualTo(ExecutionState.Stopped).After(timeout)); task.WaitSafely(); } private class ManualExitHeadlessGameHost : TestRunHeadlessGameHost { public bool RequestExit() => OnExitRequested(); } private class TestTestGame : TestGame { public readonly ManualResetEventSlim BecameAlive = new ManualResetEventSlim(); protected override void LoadComplete() { BecameAlive.Set(); } } } }
Add failing tests for GH-854
using System.Linq; using Xunit; using Marten.Testing.Linq; namespace Marten.Testing.Bugs { public class Bug_854_multiple_or_expressions_softdelete_tenancy_filters_appended_incorrectly: IntegratedFixture { [Fact] public void query_where_with_multiple_or_expressions_against_single_tenant() { StoreOptions(_ => { _.Schema.For<Target>().MultiTenanted(); }); Target[] reds = Target.GenerateRandomData(50).ToArray(); theStore.BulkInsert("Bug_854", reds); var expected = reds.Where(x => x.String == "Red" || x.String == "Orange").Select(x => x.Id).OrderBy(x => x).ToArray(); using (var query = theStore.QuerySession("Bug_854")) { var actual = query.Query<Target>().Where(x => x.String == "Red" || x.String == "Orange") .OrderBy(x => x.Id).Select(x => x.Id).ToArray(); actual.ShouldHaveTheSameElementsAs(expected); } } [Fact] public void query_where_with_multiple_or_expresions_against_soft_Deletes() { StoreOptions(_ => _.Schema.For<SoftDeletedItem>().SoftDeleted()); var item1 = new SoftDeletedItem { Number = 1, Name = "Jim Bob" }; var item2 = new SoftDeletedItem { Number = 2, Name = "Joe Bill" }; var item3 = new SoftDeletedItem { Number = 1, Name = "Jim Beam" }; int expected = 3; using (var session = theStore.OpenSession()) { session.Store(item1, item2, item3); session.SaveChanges(); } using (var session = theStore.QuerySession()) { var query = session.Query<SoftDeletedItem>() .Where(x => x.Number == 1 || x.Number == 2); var actual = query.ToList().Count; Assert.Equal(expected, actual); } } } }
Remove unused project tree factory.
using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio.ProjectSystem.Designers; using Microsoft.VisualStudio.ProjectSystem.Utilities; using Microsoft.VisualStudio.ProjectSystem.Utilities.Designers; namespace NuProj.ProjectSystem { [Export(typeof(IProjectTreeModifier))] [PartMetadata(ProjectCapabilities.Requires, NuProjCapabilities.NuProj)] internal sealed class NuProjProjectTreeModifier : IProjectTreeModifier { [Import] public Lazy<IProjectTreeFactory> TreeFactory { get; set; } public IProjectTree ApplyModifications(IProjectTree tree, IProjectTreeProvider projectTreeProvider) { if (tree.Capabilities.Contains(ProjectTreeCapabilities.ProjectRoot)) tree = tree.SetIcon(Resources.NuProj); return tree; } } }
using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio.ProjectSystem.Designers; using Microsoft.VisualStudio.ProjectSystem.Utilities; using Microsoft.VisualStudio.ProjectSystem.Utilities.Designers; namespace NuProj.ProjectSystem { [Export(typeof(IProjectTreeModifier))] [PartMetadata(ProjectCapabilities.Requires, NuProjCapabilities.NuProj)] internal sealed class NuProjProjectTreeModifier : IProjectTreeModifier { public IProjectTree ApplyModifications(IProjectTree tree, IProjectTreeProvider projectTreeProvider) { if (tree.Capabilities.Contains(ProjectTreeCapabilities.ProjectRoot)) tree = tree.SetIcon(Resources.NuProj); return tree; } } }
Copy list with random pointer
// https://leetcode.com/problems/copy-list-with-random-pointer/ // // A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. // // Return a deep copy of the list. // Finally nailed it. // https://leetcode.com/submissions/detail/53588998/ // // Submission Details // 11 / 11 test cases passed. // Status: Accepted // Runtime: 112 ms // // Submitted: 0 minutes ago public class Solution { public RandomListNode CopyRandomList(RandomListNode head, Dictionary<RandomListNode, RandomListNode> hash = null) { if (head == null) { return null; } if (hash == null) { hash = new Dictionary<RandomListNode, RandomListNode>(); } if (hash.ContainsKey(head)) { return hash[head]; } hash[head] = new RandomListNode(head.label); hash[head].next = CopyRandomList(head.next, hash); hash[head].random = CopyRandomList(head.random, hash); return hash[head]; } }
Disable test parallelization in PowerShellEditorServices.Test project
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Xunit; // Disable test parallelization to avoid port reuse issues [assembly: CollectionBehavior(DisableTestParallelization = true)]
Add extension method check for success HTTP Status code
namespace System { internal static class SystemExtensions { internal static bool IsSuccessStatusCode(this int @this) { return @this >= 200 && @this <= 299; } } }
Add delegates and VTables for ITaskBarList2.
using System; using System.Runtime.InteropServices; using static Avalonia.Win32.Interop.UnmanagedMethods; namespace Avalonia.Win32 { delegate void MarkFullscreenWindow(IntPtr This, IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fullscreen); delegate HRESULT HrInit(IntPtr This); struct ITaskBarList2VTable { public IntPtr IUnknown1; public IntPtr IUnknown2; public IntPtr IUnknown3; public IntPtr HrInit; public IntPtr AddTab; public IntPtr DeleteTab; public IntPtr ActivateTab; public IntPtr SetActiveAlt; public IntPtr MarkFullscreenWindow; } }
Add extension overload of Render that takes care of the BitmapWrapper.
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace Pinta.ImageManipulation { public static class BitmapExtensions { public static void Render (this BaseEffect effect, Bitmap source) { var wrapper = new BitmapWrapper (source); effect.Render (wrapper); } } }
Add Groping class for Employee
using System.Collections.Generic; using System.Xml.Serialization; namespace parallel_extension_demo { [XmlRoot("groop")] public class Groups { [XmlArray("employees"), XmlArrayItem("employee")] public List<Employee> Colection { get; set; } [XmlAttribute("employeeCount")] public long Count { get; set; } public Groups() { } public Groups(List<Employee> list) { Colection = list; //.AddRange(list); Count = Colection.Count; } } }
Add fund test account method
using System; using System.IO; using System.Net; namespace stellar_dotnet_sdk { public static class AccountUtil { public static void FundTestAccount(string Public_Key) { UriBuilder baseUri = new UriBuilder("https://horizon-testnet.stellar.org/friendbot"); string queryToAppend = "addr=" + Public_Key; baseUri.Query = queryToAppend; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUri.ToString()); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); sr.ReadToEnd(); } } }
Add unit test for OptionExtensions
using Sprache; using Xunit; namespace Sprache.Tests { public class OptionTests { private Parser<IOption<char>> ParserOptionalSelect = Parse.Char('a').Optional().Select(o => o.Select(c => char.ToUpperInvariant(c))); private Parser<IOption<string>> ParserOptionalSelectMany = from o1 in Parse.Char('a').Optional() from o2 in Parse.Char('b').Optional() select o1.SelectMany(c1 => o2.Select(c2 => $"{c2}{c1}")); private Parser<IOption<string>> ParserOptionalLinq = from o1 in Parse.Char('a').Optional() from o2 in Parse.Char('b').Optional() select (from c1 in o1 from c2 in o2 select $"{c2}{c1}"); private void AssertSome<T>(IOption<T> option, T expected) => Assert.True(option.IsDefined && option.Get().Equals(expected)); [Fact] public void TestSelect() => AssertParser.SucceedsWith(ParserOptionalSelect, "a", o => AssertSome(o, 'A')); [Fact] public void TestSelectManySome() => AssertParser.SucceedsWith(ParserOptionalSelectMany, "ab", o => AssertSome(o, "ba")); [Fact] public void TestSelectManyNone() => AssertParser.SucceedsWith(ParserOptionalSelectMany, "b", o => Assert.True(o.IsEmpty)); [Fact] public void TestSelectManyLinq() => AssertParser.SucceedsWith(ParserOptionalLinq, "ab", o => AssertSome(o, "ba")); } }
Add AppendSpace extension method for StringBuilder
using System.Text; namespace Atata { /// <summary> /// Provides a set of extension methods for <see cref="StringBuilder"/>. /// </summary> public static class StringBuilderExtensions { /// <summary> /// Appends the space character. /// </summary> /// <param name="builder">The builder.</param> /// <returns>A reference to the same <see cref="StringBuilder"/> instance after the append operation has completed.</returns> public static StringBuilder AppendSpace(this StringBuilder builder) { builder.CheckNotNull(nameof(builder)); return builder.Append(' '); } } }
Add test scene for Triangles
// 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.Game.Graphics.Backgrounds; using osu.Framework.Graphics; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; namespace osu.Game.Tests.Visual.Background { public class TestSceneTrianglesBackground : OsuTestScene { private readonly Triangles triangles; public TestSceneTrianglesBackground() { Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black }, triangles = new Triangles { RelativeSizeAxes = Axes.Both, ColourLight = Color4.White, ColourDark = Color4.Gray } }; } protected override void LoadComplete() { base.LoadComplete(); AddSliderStep("Triangle scale", 0f, 10f, 1f, s => triangles.TriangleScale = s); } } }
Add test coverage for distance/rectangular grid exclusivity
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets.Osu.Edit; using osu.Game.Screens.Edit.Compose.Components; using osu.Game.Tests.Visual; using osuTK.Input; namespace osu.Game.Rulesets.Osu.Tests.Editor { public class TestSceneOsuEditorGrids : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); [Test] public void TestGridExclusivity() { AddStep("enable distance snap grid", () => InputManager.Key(Key.T)); AddStep("select second object", () => EditorBeatmap.SelectedHitObjects.Add(EditorBeatmap.HitObjects.ElementAt(1))); AddUntilStep("distance snap grid visible", () => this.ChildrenOfType<OsuDistanceSnapGrid>().Any()); AddStep("enable rectangular grid", () => InputManager.Key(Key.Y)); AddUntilStep("distance snap grid hidden", () => !this.ChildrenOfType<OsuDistanceSnapGrid>().Any()); AddUntilStep("rectangular grid visible", () => this.ChildrenOfType<RectangularPositionSnapGrid>().Any()); AddStep("enable distance snap grid", () => InputManager.Key(Key.T)); AddUntilStep("distance snap grid visible", () => this.ChildrenOfType<OsuDistanceSnapGrid>().Any()); AddUntilStep("rectangular grid hidden", () => !this.ChildrenOfType<RectangularPositionSnapGrid>().Any()); } } }
Add a worktree repository test
using GitTools.Testing; using LibGit2Sharp; using NUnit.Framework; using System.IO; using GitVersionCore.Tests.Helpers; namespace GitVersionCore.Tests.IntegrationTests { [TestFixture] public class WorktreeScenarios : TestBase { [Test] [Category("NoMono")] [Description("LibGit2Sharp fails here when running under Mono")] public void UseWorktreeRepositoryForVersion() { using var fixture = new EmptyRepositoryFixture(); var repoDir = new DirectoryInfo(fixture.RepositoryPath); var worktreePath = Path.Combine(repoDir.Parent.FullName, $"{repoDir.Name}-v1"); fixture.Repository.MakeATaggedCommit("v1.0.0"); var branchV1 = fixture.Repository.CreateBranch("support/1.0"); fixture.Repository.MakeATaggedCommit("v2.0.0"); fixture.AssertFullSemver("2.0.0"); fixture.Repository.Worktrees.Add(branchV1.CanonicalName, "1.0", worktreePath, false); using var worktreeFixture = new LocalRepositoryFixture(new Repository(worktreePath)); worktreeFixture.AssertFullSemver("1.0.0"); } } }
Fix autosave and refresh on shared projects
using JetBrains.Annotations; using JetBrains.Application.changes; using JetBrains.Application.FileSystemTracker; using JetBrains.Application.Threading; using JetBrains.DocumentManagers; using JetBrains.DocumentModel; using JetBrains.Lifetimes; using JetBrains.ProjectModel; using JetBrains.ReSharper.Host.Features.Documents; using JetBrains.ReSharper.Plugins.Unity.ProjectModel; using JetBrains.Rider.Model; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity.Rider { [SolutionComponent] public class RiderUnityDocumentOperationsImpl : RiderDocumentOperationsImpl { [NotNull] private readonly ILogger myLogger; public RiderUnityDocumentOperationsImpl(Lifetime lifetime, [NotNull] SolutionModel solutionModel, [NotNull] SettingsModel settingsModel, [NotNull] ISolution solution, [NotNull] IShellLocks locks, [NotNull] ChangeManager changeManager, [NotNull] DocumentToProjectFileMappingStorage documentToProjectFileMappingStorage, [NotNull] IFileSystemTracker fileSystemTracker, [NotNull] ILogger logger) : base(lifetime, solutionModel, settingsModel, solution, locks, changeManager, documentToProjectFileMappingStorage, fileSystemTracker, logger) { myLogger = logger; } public override void SaveDocumentAfterModification(IDocument document, bool forceSaveOpenDocuments) { Locks.Dispatcher.AssertAccess(); if (forceSaveOpenDocuments) { var projectFile = DocumentToProjectFileMappingStorage.TryGetProjectFile(document); var isUnitySharedProjectFile = projectFile != null && projectFile.IsShared() && projectFile.GetProject().IsUnityProject(); if (isUnitySharedProjectFile) { myLogger.Info($"Trying to save document {document.Moniker}. Force = true"); myLogger.Verbose("File is shared and contained in Unity project. Skip saving."); return; } } base.SaveDocumentAfterModification(document, forceSaveOpenDocuments); } } }
Add beatmap parsing as sample benchmark.
// 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.IO; using BenchmarkDotNet.Attributes; using osu.Framework.IO.Stores; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Formats; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.Resources; namespace osu.Game.Benchmarks { public class BenchmarkBeatmapParsing : BenchmarkTest { private readonly MemoryStream beatmapStream = new MemoryStream(); public override void SetUp() { using (var resources = new DllResourceStore(OsuResources.ResourceAssembly)) using (var archive = resources.GetStream("Beatmaps/241526 Soleily - Renatus.osz")) using (var reader = new ZipArchiveReader(archive)) reader.GetStream("Soleily - Renatus (Gamu) [Insane].osu").CopyTo(beatmapStream); } [Benchmark] public Beatmap BenchmarkBundledBeatmap() { beatmapStream.Seek(0, SeekOrigin.Begin); var reader = new LineBufferedReader(beatmapStream); // no disposal var decoder = Decoder.GetDecoder<Beatmap>(reader); return decoder.Decode(reader); } } }
Set list to readonly after fetch.
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ProjectTracker.Library { [Serializable()] public class ResourceList : ReadOnlyListBase<ResourceList, ResourceInfo> { #region Factory Methods public static ResourceList GetResourceList() { return DataPortal.Fetch<ResourceList>(new Criteria()); } private ResourceList() { /* require use of factory methods */ } #endregion #region Data Access [Serializable()] private class Criteria { /* no criteria - retrieve all resources */ } private void DataPortal_Fetch(Criteria criteria) { this.RaiseListChangedEvents = false; using (SqlConnection cn = new SqlConnection(Database.PTrackerConnection)) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "getResources"; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; while (dr.Read()) { ResourceInfo info = new ResourceInfo(dr); this.Add(info); } IsReadOnly = false; } } } this.RaiseListChangedEvents = true; } #endregion } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ProjectTracker.Library { [Serializable()] public class ResourceList : ReadOnlyListBase<ResourceList, ResourceInfo> { #region Factory Methods public static ResourceList GetResourceList() { return DataPortal.Fetch<ResourceList>(new Criteria()); } private ResourceList() { /* require use of factory methods */ } #endregion #region Data Access [Serializable()] private class Criteria { /* no criteria - retrieve all resources */ } private void DataPortal_Fetch(Criteria criteria) { this.RaiseListChangedEvents = false; using (SqlConnection cn = new SqlConnection(Database.PTrackerConnection)) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "getResources"; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; while (dr.Read()) { ResourceInfo info = new ResourceInfo(dr); this.Add(info); } IsReadOnly = true; } } } this.RaiseListChangedEvents = true; } #endregion } }
Add default provider for RequestRuntime
using System; using System.Collections.Generic; using System.Linq; namespace Glimpse.Web { public class DefaultRequestRuntimeProvider : IRequestRuntimeProvider { private readonly ITypeService _typeService; public DefaultRequestRuntimeProvider(ITypeService typeService) { _typeService = typeService; } public IEnumerable<IRequestRuntime> Runtimes { get { return _typeService.Resolve<IRequestRuntime>().ToArray(); } } } }
Test Fixture for Template class.
using System; using NHibernate.Dialect; using NHibernate.SqlCommand; using NUnit.Framework; namespace NHibernate.Test.SqlCommandTest { [TestFixture] public class TemplateFixture { public TemplateFixture() { } /// <summary> /// Tests that a column enclosed by <c>`</c> is enclosed by the Dialect.OpenQuote /// and Dialect.CloseQuote after the Template Renders the Where String. /// </summary> [Test] public void ReplaceWithDialectQuote() { Dialect.Dialect dialect = new Dialect.MsSql2000Dialect(); string whereFragment = "column_name = 'string value' and `backtick` = 1"; string expectedFragment = "$PlaceHolder.column_name = 'string value' and $PlaceHolder.[backtick] = 1"; Assert.AreEqual( expectedFragment, Template.RenderWhereStringTemplate(whereFragment, dialect) ); } } }
Add test scene for NewsHeader
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Overlays.News; using osu.Framework.Graphics; using osu.Game.Overlays; using osu.Framework.Allocation; namespace osu.Game.Tests.Visual.Online { public class TestSceneNewsHeader : OsuTestScene { [Cached] private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple); private TestHeader header; [SetUp] public void Setup() { Child = header = new TestHeader { Anchor = Anchor.Centre, Origin = Anchor.Centre }; } [Test] public void TestControl() { AddAssert("Front page selected", () => header.Current.Value == "frontpage"); AddAssert("1 tab total", () => header.TabCount == 1); AddStep("Set article 1", () => header.SetArticle("1")); AddAssert("Article 1 selected", () => header.Current.Value == "1"); AddAssert("2 tabs total", () => header.TabCount == 2); AddStep("Set article 2", () => header.SetArticle("2")); AddAssert("Article 2 selected", () => header.Current.Value == "2"); AddAssert("2 tabs total", () => header.TabCount == 2); AddStep("Set front page", () => header.SetFrontPage()); AddAssert("Front page selected", () => header.Current.Value == "frontpage"); AddAssert("1 tab total", () => header.TabCount == 1); } private class TestHeader : NewsHeader { public int TabCount => TabControl.Items.Count; } } }
Add Server Web Options Setup
using System; using Microsoft.Framework.OptionsModel; namespace Glimpse.Server { public class GlimpseServerWebOptionsSetup : ConfigureOptions<GlimpseServerWebOptions> { public GlimpseServerWebOptionsSetup() : base(ConfigureGlimpseServerWebOptions) { Order = -1000; } public static void ConfigureGlimpseServerWebOptions(GlimpseServerWebOptions options) { // TODO: Setup different settings here } } }
Add first API stub endpoint
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]")] public class SoldiersController : Controller { private readonly Database db; public SoldiersController(Database db) { this.db = db; } // GET: api/soldiers [HttpGet] public async Task<IEnumerable<dynamic>> Get(SoldierSearchService.Query query) { return (await SoldierSearchService.Filter(db, query)) .Select(s => new { s.Id, s.LastName, s.FirstName }) .ToList(); } // GET api/soldiers/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/soldiers [HttpPost] public void Post([FromBody]string value) { // TODO } // PUT api/soldiers/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { // TODO } } }
Add unit tests for the SqliteAnchorStateBuilder class
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using Xunit; namespace Openchain.Sqlite.Tests { public class SqliteAnchorStateBuilderTests { [Fact] public void Name_Success() { Assert.Equal("SQLite", new SqliteAnchorStateBuilder().Name); } [Fact] public async Task Build_Success() { Dictionary<string, string> parameters = new Dictionary<string, string>() { ["path"] = ":memory:" }; SqliteAnchorStateBuilder builder = new SqliteAnchorStateBuilder(); await builder.Initialize(parameters); SqliteAnchorState ledger = builder.Build(null); Assert.NotNull(ledger); } [Fact] public async Task InitializeTables_CallTwice() { Dictionary<string, string> parameters = new Dictionary<string, string>() { ["path"] = ":memory:" }; SqliteAnchorStateBuilder builder = new SqliteAnchorStateBuilder(); await builder.Initialize(parameters); SqliteAnchorState ledger = builder.Build(null); await SqliteAnchorStateBuilder.InitializeTables(ledger.Connection); await SqliteAnchorStateBuilder.InitializeTables(ledger.Connection); Assert.Equal(ConnectionState.Open, ledger.Connection.State); } } }
Test to verify inline projections with lots of events. Closes GH-1723
using System; using System.Threading.Tasks; using Marten.Testing.Events.Aggregation; using Marten.Testing.Harness; using Shouldly; using Xunit; using Xunit.Abstractions; namespace Marten.Testing.Events.Bugs { public class Bug_1723_inline_projections_get_cut_off : AggregationContext { private readonly ITestOutputHelper _output; public Bug_1723_inline_projections_get_cut_off(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture) { _output = output; } [Fact] public async Task big_streams() { var stream1 = Guid.NewGuid(); var stream2 = Guid.NewGuid(); UsingDefinition<AllSync>(); _output.WriteLine(_projection.SourceCode()); await InlineProject(x => { x.Streams[stream1].IsNew = true; x.Streams[stream1].Add(new CreateEvent(1, 2, 3, 4)); for (int i = 0; i < 20; i++) { x.Streams[stream1].A(); x.Streams[stream1].B(); x.Streams[stream1].B(); x.Streams[stream1].C(); x.Streams[stream1].C(); x.Streams[stream1].C(); } x.Streams[stream2].IsNew = true; x.Streams[stream2].Add(new CreateEvent(3, 3, 3, 3)); for (int i = 0; i < 100; i++) { x.Streams[stream2].A(); x.Streams[stream2].B(); x.Streams[stream2].C(); } }); using var query = theStore.QuerySession(); var aggregate1 = await query.LoadAsync<MyAggregate>(stream1); aggregate1.ACount.ShouldBe(21); aggregate1.BCount.ShouldBe(42); aggregate1.CCount.ShouldBe(63); var aggregate2 = await query.LoadAsync<MyAggregate>(stream2); aggregate2.ACount.ShouldBe(103); aggregate2.BCount.ShouldBe(103); } } }
Add headless test ensuring correct cancelling download behaviour
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Overlays.Notifications; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Online { [HeadlessTest] public class TestSceneBeatmapManager : OsuTestScene { private BeatmapManager beatmaps; private ProgressNotification recentNotification; private static readonly BeatmapSetInfo test_model = new BeatmapSetInfo { OnlineBeatmapSetID = 1 }; [BackgroundDependencyLoader] private void load(BeatmapManager beatmaps) { this.beatmaps = beatmaps; beatmaps.PostNotification = n => recentNotification = n as ProgressNotification; } [TestCase(true)] [TestCase(false)] public void TestCancelDownloadFromRequest(bool closeFromRequest) { AddStep("download beatmap", () => beatmaps.Download(test_model)); if (closeFromRequest) AddStep("cancel download from request", () => beatmaps.GetExistingDownload(test_model).Cancel()); else AddStep("cancel download from notification", () => recentNotification.Close()); AddUntilStep("is removed from download list", () => beatmaps.GetExistingDownload(test_model) == null); AddAssert("is notification cancelled", () => recentNotification.State == ProgressNotificationState.Cancelled); } } }
Add CilLocalVariableCollection index consistency tests.
using AsmResolver.DotNet.Code.Cil; using Xunit; namespace AsmResolver.DotNet.Tests.Code.Cil { public class CilLocalVariableCollectionTest { private readonly CilLocalVariableCollection _collection = new CilLocalVariableCollection(); private readonly ModuleDefinition _module = new ModuleDefinition("Test.dll"); private void AssertCollectionIndicesAreConsistent(CilLocalVariableCollection collection) { for (int i = 0; i < collection.Count; i++) Assert.Equal(i, collection[i].Index); } [Fact] public void NoIndex() { var variable = new CilLocalVariable(_module.CorLibTypeFactory.Object); Assert.Equal(-1, variable.Index); } [Fact] public void AddToEmptyListShouldSetIndexToZero() { _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); AssertCollectionIndicesAreConsistent(_collection); } [Fact] public void AddToEndOfListShouldSetIndexToCount() { _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); AssertCollectionIndicesAreConsistent(_collection); } [Fact] public void InsertShouldUpdateIndices() { _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Insert(1, new CilLocalVariable(_module.CorLibTypeFactory.String)); AssertCollectionIndicesAreConsistent(_collection); } [Fact] public void RemoveShouldUpdateIndices() { _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); _collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object)); var variable = _collection[1]; _collection.RemoveAt(1); AssertCollectionIndicesAreConsistent(_collection); Assert.Equal(-1, variable.Index); } [Fact] public void ClearingVariablesShouldUpdateAllIndices() { var variables = new[] { new CilLocalVariable(_module.CorLibTypeFactory.Object), new CilLocalVariable(_module.CorLibTypeFactory.Object), new CilLocalVariable(_module.CorLibTypeFactory.Object), new CilLocalVariable(_module.CorLibTypeFactory.Object) }; foreach (var variable in variables) _collection.Add(variable); _collection.Clear(); foreach (var variable in variables) Assert.Equal(-1, variable.Index); } } }
Add thread safe event trigger
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Recipe.ThreadAndConcurrent { public static class EventRaiseExtentions { public static void Raise<TEventArgs>(this TEventArgs e, object sender, ref EventHandler<TEventArgs> eventDelegate) { EventHandler<TEventArgs> temp = Volatile.Read(ref eventDelegate); if (temp != null) { temp(sender, e); } } } }
Add factory for the PathElement class for array like access
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Pather.CSharp.PathElements { public class EnumerableAccessFactory : IPathElementFactory { public IPathElement Create(string pathElement) { var matches = Regex.Matches(pathElement, @"^(\w+)\[(\d+)\]$"); Match match = matches[0]; //0 is the whole match string property = match.Captures[1].Value; int index = int.Parse(match.Captures[2].Value); //the regex guarantees that the second group is an integer, so no further check is needed return new EnumerableAccess(property, index); } public bool IsApplicable(string pathElement) { return Regex.IsMatch(pathElement, @"^\w+\[\d+\]$"); } } }
Add test scene for "Freeze Frame" mod
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModFreezeFrame : OsuModTestScene { [Test] public void TestFreezeFrame() { CreateModTest(new ModTestData { Mod = new OsuModFreezeFrame(), PassCondition = () => true, Autoplay = false, }); } } }
Add fixed implementation for RequestProfilers provider
using System.Collections.Generic; using System.Linq; namespace Glimpse.Agent.Web { public class FixedRequestProfilerProvider : IRequestProfilerProvider { public FixedRequestProfilerProvider() : this(Enumerable.Empty<IRequestProfiler>()) { } public FixedRequestProfilerProvider(IEnumerable<IRequestProfiler> controllerTypes) { Profilers = new List<IRequestProfiler>(controllerTypes); } public IList<IRequestProfiler> Profilers { get; } IEnumerable<IRequestProfiler> IRequestProfilerProvider.Profilers => Profilers; } }
Add settings for backward compatibility
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using sys = System; namespace Google.Cloud.Container.V1 { // This is a partial class introduced for backward compatibility with earlier versions. public partial class ClusterManagerSettings { /// <summary> /// In previous releases, this property returned a filter used by default for "Idempotent" RPC methods. /// It is now unused, and may not represent the current default behavior. /// </summary> [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")] public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable); /// <summary> /// In previous releases, this property returned a filter used by default for "NonIdempotent" RPC methods. /// It is now unused, and may not represent the current default behavior. /// </summary> [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")] public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(); /// <summary> /// In previous releases, this method returned the backoff used by default for "Idempotent" RPC methods. /// It is now unused, and may not represent the current default behavior. /// </summary> [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")] public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(1000), maxDelay: sys::TimeSpan.FromMilliseconds(32000), delayMultiplier: 1.3 ); /// <summary> /// In previous releases, this method returned the backoff used by default for "NonIdempotent" RPC methods. /// It is now unused, and may not represent the current default behavior. /// </summary> [Obsolete("This member is no longer called by other code in this library. Please use the individual CallSettings properties.")] public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(60000), maxDelay: sys::TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.0 ); } }
Add tests for Id struct serialization and deserialization
using System; using Newtonsoft.Json; using Xunit; namespace ReactiveDomain.Messaging.Tests { public sealed class when_serializing_ids { private readonly CorrelationId _corrId; private readonly SourceId _sourceId; private readonly SourceId _nullSourceId; public when_serializing_ids() { _corrId = CorrelationId.NewId(); _sourceId = new SourceId(Guid.NewGuid()); _nullSourceId = SourceId.NullSourceId(); } [Fact] public void can_serialize_and_recover_ids() { var idTester = new IdTester(_corrId, _sourceId); var jsonString = JsonConvert.SerializeObject(idTester, Json.JsonSettings); var idTesterOut = JsonConvert.DeserializeObject<IdTester>(jsonString, Json.JsonSettings); Assert.IsType<IdTester>(idTesterOut); Assert.Equal(_corrId, idTester.CorrId); Assert.Equal(_sourceId, idTester.SrcId); } [Fact] public void can_serialize_and_recover_nullsourceid() { var idTester = new IdTester(_corrId, _nullSourceId); var jsonString = JsonConvert.SerializeObject(idTester, Json.JsonSettings); var idTesterOut = JsonConvert.DeserializeObject<IdTester>(jsonString, Json.JsonSettings); Assert.IsType<IdTester>(idTesterOut); Assert.Equal(_corrId, idTester.CorrId); Assert.Equal(_nullSourceId, idTester.SrcId); } } public class IdTester { public readonly CorrelationId CorrId; public readonly SourceId SrcId; public IdTester( CorrelationId correlationId, SourceId sourceId) { CorrId = correlationId; SrcId = sourceId; } } }
Add sample code to the unit test project for now.
using LonoNet.Client; using LonoNet.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; namespace LonoNetTest { /// <summary> /// Early stage. At this point, this is more of sample code to get you started. Will work on actual unit tests soon. /// </summary> [TestClass] public class UnitTest1 { public readonly string _clientId = "CLIENT KEY"; public readonly string _clientSecret = "CLIENT SECRET"; public readonly string _authToken = "AUTH TOKEN"; public readonly string _deviceId = "DEVICE ID"; public readonly string _authCode = "AUTH CODE"; [TestMethod] public void TestMethod1() { LonoNetClient client = new LonoNetClient(_clientId, _clientSecret, _authToken, _deviceId); var login = client.GetAccessToken(_authCode, "http://localhost"); ZoneState zs = client.GetActiveZone(); ZoneInfo zi = client.GetAllZones(); DeviceInfo di = client.GetDeviceInfo(); client.SetZoneOn(1); Thread.Sleep(10); client.SetZoneOff(1); } [TestMethod] public void TestMethod2() { LonoNetClient client = new LonoNetClient(_clientId, _clientSecret, _deviceId); string url = client.BuildAuthorizeUrl(LonoNet.Authenticators.OAuth2AuthorizationFlow.Code, "http://localhost", "write"); // Launch url // set _authCode to value returned in url var login = client.GetAccessToken(_authCode, "http://localhost"); ZoneState zs = client.GetActiveZone(); ZoneInfo zi = client.GetAllZones(); DeviceInfo di = client.GetDeviceInfo(); client.SetZoneOn(1); Thread.Sleep(10); client.SetZoneOff(1); } } }
Add view for "Initiative Create Closed" error page.
@{ ViewData["Title"] = "Access Denied"; } <br> <br> <br> <div class="container"> <h2 class="text-danger">Creating Initiative projects is unavailable.</h2> <p> You do not have appropriate permissions to create Initiative projects. Please create a Draft project. </p> </div>
Create data source for local storage
using Microsoft.Live; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Storage; namespace ClumsyWordsUniversal.Data { public class LocalDataSource : DataSource { public LocalDataSource() { } private static readonly StorageFolder localFolder = ApplicationData.Current.LocalFolder; private readonly string _fileName = "definitions.json"; /// <summary> /// Initializes the data source trying to load data /// </summary> /// <returns></returns> public override async Task InitAsync() { await this.LoadDataAsync(); } /// <summary> /// Loads data from local storage and populates the data source /// </summary> /// <returns></returns> public override async Task LoadDataAsync() { bool exists = true; StorageFile file = null; try { file = await LocalDataSource.localFolder.GetFileAsync(this._fileName); } catch (FileNotFoundException) { exists = false; } if (!exists) { file = await LocalDataSource.localFolder.CreateFileAsync(this._fileName); return; } var result = await FileIO.ReadTextAsync(file); this.groupsMap = await JsonConvert.DeserializeObjectAsync<Dictionary<string, DefinitionsDataGroup>>(result); if (this.groupsMap == null) this.groupsMap = new Dictionary<string, DefinitionsDataGroup>(); } /// <summary> /// Saves data to local storage /// </summary> /// <returns></returns> public override async Task SaveDataAsync() { var file = await LocalDataSource.localFolder.CreateFileAsync(this._fileName, CreationCollisionOption.ReplaceExisting); string jsonData = await JsonConvert.SerializeObjectAsync(this.groupsMap, Formatting.None); await FileIO.WriteTextAsync(file, jsonData); } /// <summary> /// Saves data to local storage /// </summary> /// <param name="filename">The name of the file to write in</param> /// <param name="data">The data object to be serialized and written in the file</param> /// <returns></returns> public override async Task SaveDataAsync(string filename, object data) { var file = await LocalDataSource.localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); string jsonData = await JsonConvert.SerializeObjectAsync(data, Formatting.None); await FileIO.WriteTextAsync(file, jsonData); } } }
Add failing test covering RomanisableString usage in SpriteText
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; namespace osu.Framework.Tests.Visual.Sprites { public class TestSceneRomanisableSpriteText : FrameworkTestScene { private FillFlowContainer flow; public TestSceneRomanisableSpriteText() { Children = new Drawable[] { new BasicScrollContainer { RelativeSizeAxes = Axes.Both, Children = new[] { flow = new FillFlowContainer { Anchor = Anchor.TopLeft, AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, } } } }; flow.Add(new SpriteText { Text = new RomanisableString("music", "ongaku") }); flow.Add(new SpriteText { Text = new RomanisableString("music", "") }); flow.Add(new SpriteText { Text = new RomanisableString("", "ongaku") }); } [Resolved] private FrameworkConfigManager config { get; set; } [Test] public void TestToggleRomanisedState() { AddStep("prefer romanised", () => config.Set(FrameworkSetting.ShowUnicode, false)); AddAssert("check strings correct", () => flow.OfType<SpriteText>().Select(st => st.Current.Value).SequenceEqual(new[] { "music", "music", "ongaku" })); AddStep("prefer unicode", () => config.Set(FrameworkSetting.ShowUnicode, true)); AddAssert("check strings correct", () => flow.OfType<SpriteText>().Select(st => st.Current.Value).SequenceEqual(new[] { "ongaku", "music", "ongaku" })); } } }
Add delete auto index creation
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; namespace LiteDB { public partial class LiteCollection<T> { /// <summary> /// Remove all document based on a Query object. Returns removed document counts /// </summary> public int Delete(Query query) { if(query == null) throw new ArgumentNullException("query"); return _engine.DeleteDocuments(_name, query); } /// <summary> /// Remove all document based on a LINQ query. Returns removed document counts /// </summary> public int Delete(Expression<Func<T, bool>> predicate) { return this.Delete(_visitor.Visit(predicate)); } /// <summary> /// Remove an document in collection using Document Id - returns false if not found document /// </summary> public bool Delete(BsonValue id) { if (id == null || id.IsNull) throw new ArgumentNullException("id"); return this.Delete(Query.EQ("_id", id)) > 0; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; namespace LiteDB { public partial class LiteCollection<T> { /// <summary> /// Remove all document based on a Query object. Returns removed document counts /// </summary> public int Delete(Query query) { if(query == null) throw new ArgumentNullException("query"); // keep trying execute query to auto-create indexes when not found while (true) { try { return _engine.DeleteDocuments(_name, query); } catch (IndexNotFoundException ex) { // if query returns this exception, let's auto create using mapper (or using default options) var options = _mapper.GetIndexFromMapper<T>(ex.Field) ?? new IndexOptions(); _engine.EnsureIndex(ex.Collection, ex.Field, options); } } } /// <summary> /// Remove all document based on a LINQ query. Returns removed document counts /// </summary> public int Delete(Expression<Func<T, bool>> predicate) { return this.Delete(_visitor.Visit(predicate)); } /// <summary> /// Remove an document in collection using Document Id - returns false if not found document /// </summary> public bool Delete(BsonValue id) { if (id == null || id.IsNull) throw new ArgumentNullException("id"); return this.Delete(Query.EQ("_id", id)) > 0; } } }
Remove reference to settings icon
using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; } //--------------------------------------------------------------------------- }
Add failing test coverage of gameplay sample pausing (during seek)
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Audio; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Rulesets.UI; using osu.Game.Screens.Play; using osu.Game.Skinning; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneGameplaySamplePlayback : PlayerTestScene { [Test] public void TestAllSamplesStopDuringSeek() { DrawableSlider slider = null; DrawableSample[] samples = null; ISamplePlaybackDisabler gameplayClock = null; AddStep("get variables", () => { gameplayClock = Player.ChildrenOfType<FrameStabilityContainer>().First().GameplayClock; slider = Player.ChildrenOfType<DrawableSlider>().OrderBy(s => s.HitObject.StartTime).First(); samples = slider.ChildrenOfType<DrawableSample>().ToArray(); }); AddUntilStep("wait for slider sliding then seek", () => { if (!slider.Tracking.Value) return false; if (!samples.Any(s => s.Playing)) return false; Player.ChildrenOfType<GameplayClockContainer>().First().Seek(40000); return true; }); AddAssert("sample playback disabled", () => gameplayClock.SamplePlaybackDisabled.Value); // because we are in frame stable context, it's quite likely that not all samples are "played" at this point. // the important thing is that at least one started, and that sample has since stopped. AddAssert("no samples are playing", () => Player.ChildrenOfType<PausableSkinnableSound>().All(s => !s.IsPlaying)); AddAssert("sample playback still disabled", () => gameplayClock.SamplePlaybackDisabled.Value); AddUntilStep("seek finished, sample playback enabled", () => !gameplayClock.SamplePlaybackDisabled.Value); AddUntilStep("any sample is playing", () => Player.ChildrenOfType<PausableSkinnableSound>().Any(s => s.IsPlaying)); } protected override bool Autoplay => true; protected override Ruleset CreatePlayerRuleset() => new OsuRuleset(); } }
Add assembly info to OneSignal.Core
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Com.OneSignal.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("OneSignal")] [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 ("3.10.6")] // 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("")]
Add stub endpoint for getting vehicle info
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]"), Authorize] public class VehiclesController : Controller { private readonly Database db; public VehiclesController(Database db) { this.db = db; } [HttpGet] public async Task<IEnumerable<dynamic>> Get() { // GET: api/vehicles return await db .Vehicles .Select(_ => new { _.Id, _.UnitId, _.Bumper, _.Registration, _.Nomenclature, _.Notes, _.Serial, _.Status, _.Type, _.HasFuelCard, _.HasJBCP, _.HasTowBar }) .ToListAsync(); } } }
Add ${aspnet-request-contenttype} (ASP.NET Core only)
#if NETSTANDARD_1plus using NLog.LayoutRenderers; using System.Text; using Microsoft.AspNetCore.Routing; using NLog.Web.Internal; namespace NLog.Web.LayoutRenderers { /// <summary> /// ASP.NET content type. /// </summary> /// <example> /// <code lang="NLog Layout Renderer"> /// ${aspnet-request-contenttype} /// </code> /// </example> [LayoutRenderer("aspnet-request-contenttype")] public class AspNetRequestContentTypeLayoutRenderer : AspNetLayoutRendererBase { /// <summary> /// Renders the specified ASP.NET Application variable and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent) { var request = HttpContextAccessor?.HttpContext?.TryGetRequest(); var contentType = request?.ContentType; if (!string.IsNullOrEmpty(contentType)) builder.Append(contentType); } } } #endif
Add realtime multiplayer test scene abstract class
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.RealtimeMultiplayer; using osu.Game.Screens.Multi.Lounge.Components; using osu.Game.Screens.Multi.RealtimeMultiplayer; namespace osu.Game.Tests.Visual.RealtimeMultiplayer { public class RealtimeMultiplayerTestScene : MultiplayerTestScene { [Cached(typeof(StatefulMultiplayerClient))] public TestRealtimeMultiplayerClient Client { get; } [Cached(typeof(RealtimeRoomManager))] public TestRealtimeRoomManager RoomManager { get; } [Cached] public Bindable<FilterCriteria> Filter { get; } protected override Container<Drawable> Content => content; private readonly TestRealtimeRoomContainer content; private readonly bool joinRoom; public RealtimeMultiplayerTestScene(bool joinRoom = true) { this.joinRoom = joinRoom; base.Content.Add(content = new TestRealtimeRoomContainer { RelativeSizeAxes = Axes.Both }); Client = content.Client; RoomManager = content.RoomManager; Filter = content.Filter; } [SetUp] public new void Setup() => Schedule(() => { RoomManager.Schedule(() => RoomManager.PartRoom()); if (joinRoom) { Room.RoomID.Value = 1; RoomManager.Schedule(() => RoomManager.JoinRoom(Room, null, null)); } }); } }
Use value formatters to describe asserted call
namespace FakeItEasy.Expressions.ArgumentConstraints { using System; using System.Diagnostics.CodeAnalysis; using FakeItEasy.Core; internal class EqualityArgumentConstraint : IArgumentConstraint { public EqualityArgumentConstraint(object expectedValue) { this.ExpectedValue = expectedValue; } public object ExpectedValue { get; } public string ConstraintDescription => this.ToString(); public bool IsValid(object argument) { return object.Equals(this.ExpectedValue, argument); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Any type of exception may be encountered.")] public override string ToString() { if (this.ExpectedValue == null) { return "<NULL>"; } var stringValue = this.ExpectedValue as string; if (stringValue != null) { return $@"""{stringValue}"""; } try { return this.ExpectedValue.ToString(); } catch (Exception) { FakeManager manager = Fake.TryGetFakeManager(this.ExpectedValue); return manager != null ? "Faked " + manager.FakeObjectType : this.ExpectedValue.GetType().ToString(); } } public void WriteDescription(IOutputWriter writer) { writer.Write(this.ConstraintDescription); } } }
namespace FakeItEasy.Expressions.ArgumentConstraints { using System; using System.Diagnostics.CodeAnalysis; using FakeItEasy.Core; internal class EqualityArgumentConstraint : IArgumentConstraint { public EqualityArgumentConstraint(object expectedValue) { this.ExpectedValue = expectedValue; } public object ExpectedValue { get; } public string ConstraintDescription => this.ToString(); public bool IsValid(object argument) { return object.Equals(this.ExpectedValue, argument); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Any type of exception may be encountered.")] public override string ToString() { try { var writer = ServiceLocator.Current.Resolve<StringBuilderOutputWriter>(); writer.WriteArgumentValue(this.ExpectedValue); return writer.Builder.ToString(); } catch (Exception) { FakeManager manager = Fake.TryGetFakeManager(this.ExpectedValue); return manager != null ? "Faked " + manager.FakeObjectType : this.ExpectedValue.GetType().ToString(); } } public void WriteDescription(IOutputWriter writer) { writer.Write(this.ConstraintDescription); } } }
Add test scene for mania composer
// 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.Containers; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.Edit; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Screens.Edit; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Mania.Tests { public class TestSceneManiaHitObjectComposer : EditorClockTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(ManiaBlueprintContainer) }; [Cached(typeof(EditorBeatmap))] [Cached(typeof(IBeatSnapProvider))] private readonly EditorBeatmap editorBeatmap; protected override Container<Drawable> Content { get; } private ManiaHitObjectComposer composer; public TestSceneManiaHitObjectComposer() { base.Content.Add(new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { editorBeatmap = new EditorBeatmap(new ManiaBeatmap(new StageDefinition { Columns = 4 })) { BeatmapInfo = { Ruleset = new ManiaRuleset().RulesetInfo } }, Content = new Container { RelativeSizeAxes = Axes.Both, } }, }); for (int i = 0; i < 10; i++) { editorBeatmap.Add(new Note { StartTime = 100 * i }); } } [SetUp] public void Setup() => Schedule(() => { Children = new Drawable[] { composer = new ManiaHitObjectComposer(new ManiaRuleset()) }; BeatDivisor.Value = 8; }); } }
Add test scene for labelled dropdowns
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneLabelledDropdown : OsuTestScene { [Test] public void TestLabelledDropdown() => AddStep(@"create dropdown", () => Child = new LabelledDropdown<string> { Label = @"Countdown speed", Items = new[] { @"Half", @"Normal", @"Double" }, Description = @"This is a description" }); [Test] public void TestLabelledEnumDropdown() => AddStep(@"create dropdown", () => Child = new LabelledEnumDropdown<BeatmapSetOnlineStatus> { Label = @"Beatmap status", Description = @"This is a description" }); } }
Test for headers in GAPIC client libraries
// Copyright 2019 Google LLC // // 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 // // https://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 Grpc.Core; using System; using System.Linq; using Xunit; using static Google.Cloud.Language.V1.AnnotateTextRequest.Types; namespace Google.Cloud.Language.V1.Tests { public class ApiClientHeaderTest { [Fact] public void ClientProvidesHeader() { var invoker = new FakeCallInvoker(); var client = new LanguageServiceClientBuilder { CallInvoker = invoker }.Build(); client.AnnotateText(Document.FromPlainText("Some text"), new Features { ClassifyText = true }); var metadata = invoker.Metadata; var entry = metadata.FirstOrDefault(pair => pair.Key == "x-goog-api-client"); Assert.NotNull(entry); var keys = entry.Value.Split(' ') .Select(value => value.Split('/')[0]) .OrderBy(key => key) .ToList(); string[] expectedKeys = { "gapic", "gax", "gccl", "gl-dotnet", "grpc" }; Assert.Equal(expectedKeys, keys); } private class FakeCallInvoker : CallInvoker { public Metadata Metadata { get; private set; } public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options) => throw new NotImplementedException(); public override AsyncDuplexStreamingCall<TRequest, TResponse> AsyncDuplexStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options) => throw new NotImplementedException(); public override AsyncServerStreamingCall<TResponse> AsyncServerStreamingCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request) => throw new NotImplementedException(); public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request) => throw new NotImplementedException(); public override TResponse BlockingUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request) { Metadata = options.Headers; return (TResponse) Activator.CreateInstance(typeof(TResponse)); } } } }
Add renderscript for the Preset playerextension.
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using Mpdn.RenderScript.Config; using Mpdn.PlayerExtensions.GitHub; using YAXLib; namespace Mpdn.RenderScript { namespace Mpdn.ScriptChain { public abstract class PresetRenderScript : IRenderScriptUi { protected abstract RenderScriptPreset Preset { get; } protected virtual IRenderScriptUi Script { get { return Preset.Script; } } public virtual IRenderScript CreateRenderScript() { return Script.CreateRenderScript(); } public virtual void Destroy() { Script.Destroy(); } public virtual void Initialize() { } public virtual bool ShowConfigDialog(IWin32Window owner) { return Script.ShowConfigDialog(owner); } public virtual ScriptDescriptor Descriptor { get { var descriptor = Script.Descriptor; descriptor.Guid = Preset.Guid; return descriptor; } } } public class ActivePresetRenderScript : PresetRenderScript { private Guid m_Guid = new Guid("B1F3B882-3E8F-4A8C-B225-30C9ABD67DB1"); protected override RenderScriptPreset Preset { get { return PresetExtension.ActivePreset ?? new RenderScriptPreset() { Script = new ScriptChainScript() }; } } public override void Initialize() { base.Initialize(); PresetExtension.ScriptGuid = m_Guid; } public override ScriptDescriptor Descriptor { get { var descriptor = base.Descriptor; descriptor.Name = "Preset"; descriptor.Guid = m_Guid; descriptor.Description = "Active Preset"; return descriptor; } } } } }
Test replicating the asp webapi failure scenario
using System.IO; using System.Threading.Tasks; using NuGet.Versioning; using NuKeeper.Configuration; using NuKeeper.Inspection.RepositoryInspection; using NuKeeper.NuGet.Process; using NUnit.Framework; namespace NuKeeper.Integration.Tests.NuGet.Process { [TestFixture] public class DotNetUpdatePackageCommandTests { private readonly string _testWebApiProject = @"<Project ToolsVersion=""15.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <ItemGroup><PackageReference Include=""Microsoft.AspNet.WebApi.Client""><Version>5.2.3</Version></PackageReference></ItemGroup> <PropertyGroup> <VisualStudioVersion Condition=""'$(VisualStudioVersion)' == ''"">10.0</VisualStudioVersion> <VSToolsPath Condition=""'$(VSToolsPath)' == ''"">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath> <TargetFrameworkVersion>v4.7</TargetFrameworkVersion> </PropertyGroup> <Import Project=""$(MSBuildBinPath)\Microsoft.CSharp.targets"" /> <Import Project=""$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets"" Condition=""'$(VSToolsPath)' != ''"" /> </Project>"; [Test] [Ignore("Known failure, issue #239")] public async Task ShouldNotThrowOnWebProjectMixedStyleUpdates() { const string testFolder = nameof(ShouldNotThrowOnWebProjectMixedStyleUpdates); const string testProject = "TestWebApiProject.csproj"; const string packageSource = "https://api.nuget.org/v3/index.json"; var workDirectory = Path.Combine(TestContext.CurrentContext.WorkDirectory, testFolder); Directory.CreateDirectory(workDirectory); File.WriteAllText(Path.Combine(workDirectory, testProject), _testWebApiProject); var command = new DotNetUpdatePackageCommand( new UserSettings {NuGetSources = new[] {packageSource}}); await command.Invoke(new NuGetVersion("5.2.4"), packageSource, new PackageInProject("Microsoft.AspNet.WebApi.Client", "5.2.3", new PackagePath(workDirectory, testProject, PackageReferenceType.ProjectFile))); } } }