doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
5c059dfe-e3a3-40e6-9083-720f1972ba1b
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Media.Imaging; namespace TestAppUWP.Core { // ReSharper disable once InconsistentNaming public static class UIElementExtension { public static async Task<IBuffer> RenderTargetBitmapBuffer(this UIElement uiElement) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uiElement); return await renderTargetBitmap.GetPixelsAsync(); } } } ``` Add save UIElement to stream snippet
```c# using System; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Graphics.Display; using Windows.Graphics.Imaging; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Media.Imaging; namespace TestAppUWP.Core { // ReSharper disable once InconsistentNaming public static class UIElementExtension { public static async Task<IBuffer> RenderTargetBitmapBuffer(this UIElement uiElement) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uiElement); return await renderTargetBitmap.GetPixelsAsync(); } public static async Task SaveUiElementToStream(this UIElement uiElement, IRandomAccessStream stream) { DisplayInformation displayInformation = DisplayInformation.GetForCurrentView(); var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uiElement); IBuffer buffer = await renderTargetBitmap.GetPixelsAsync(); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.LogicalDpi, displayInformation.LogicalDpi, buffer.ToArray()); await encoder.FlushAsync(); } } } ```
4d322b44-9f49-4eac-97bd-55673bedef85
{ "language": "C#" }
```c# using System; using System.IO; namespace AppHarbor { public class ConsoleProgressBar { private const char ProgressBarCharacter = '\u2592'; public static void Render(double percentage, ConsoleColor color, string message) { ConsoleColor originalColor = Console.ForegroundColor; Console.CursorLeft = 0; try { Console.CursorVisible = false; Console.ForegroundColor = color; int width = Console.WindowWidth - 1; int newWidth = (int)((width * percentage) / 100d); string progressBar = string.Empty .PadRight(newWidth, ProgressBarCharacter) .PadRight(width - newWidth, ' '); Console.Write(progressBar); message = message ?? string.Empty; Console.CursorTop++; OverwriteConsoleMessage(message); Console.CursorTop--; } finally { Console.ForegroundColor = originalColor; Console.CursorVisible = true; } } private static void OverwriteConsoleMessage(string message) { Console.CursorLeft = 0; int maxCharacterWidth = Console.WindowWidth - 1; if (message.Length > maxCharacterWidth) { message = message.Substring(0, maxCharacterWidth - 3) + "..."; } message = message + new string(' ', maxCharacterWidth - message.Length); Console.Write(message); } } } ``` Use writeline instead of CursorTop++
```c# using System; using System.IO; namespace AppHarbor { public class ConsoleProgressBar { private const char ProgressBarCharacter = '\u2592'; public static void Render(double percentage, ConsoleColor color, string message) { ConsoleColor originalColor = Console.ForegroundColor; Console.CursorLeft = 0; try { Console.CursorVisible = false; Console.ForegroundColor = color; int width = Console.WindowWidth - 1; int newWidth = (int)((width * percentage) / 100d); string progressBar = string.Empty .PadRight(newWidth, ProgressBarCharacter) .PadRight(width - newWidth, ' '); Console.Write(progressBar); message = message ?? string.Empty; Console.WriteLine(); OverwriteConsoleMessage(message); Console.CursorTop--; } finally { Console.ForegroundColor = originalColor; Console.CursorVisible = true; } } private static void OverwriteConsoleMessage(string message) { Console.CursorLeft = 0; int maxCharacterWidth = Console.WindowWidth - 1; if (message.Length > maxCharacterWidth) { message = message.Substring(0, maxCharacterWidth - 3) + "..."; } message = message + new string(' ', maxCharacterWidth - message.Length); Console.Write(message); } } } ```
3f3a0ca4-faa0-43d8-87b9-aac144935b90
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Reflection; using System.Text; using WalletWasabi.Models; namespace WalletWasabi.Gui.ViewModels.Validation { public delegate void ValidateMethod(IErrorList errors); public static class Validator { //public static IEnumerable<(string propertyName, ErrorDescriptors errors)> ValidateAllProperties(Dictionary<string, ValidateMethod> validationMethodCache) //{ // if(validationMethodCache is null || validationMethodCache.Count == 0) // { // throw new Exception("Cant call ValidateAllProperties on ViewModels with no ValidateAttributes"); // } // var result = new List<(string propertyName, ErrorDescriptors errors)>(); // foreach (var propertyName in validationMethodCache.Keys) // { // var invokeRes = (ErrorDescriptors)validationMethodCache[propertyName].Invoke(); // result.Add((propertyName, invokeRes)); // } // return result; //} //public static ErrorDescriptors ValidateProperty(ViewModelBase viewModelBase, string propertyName, // Dictionary<string, MethodInfo> validationMethodCache) //{ // if (validationMethodCache is null) // { // return ErrorDescriptors.Empty; // } // ErrorDescriptors result = null; // if(validationMethodCache.ContainsKey(propertyName)) // { // var invokeRes = (ErrorDescriptors)validationMethodCache[propertyName].Invoke(viewModelBase, null); // if (result is null) // { // result = new ErrorDescriptors(); // } // result.AddRange(invokeRes); // } // return result ?? ErrorDescriptors.Empty; //} } } ``` Remove validator methods, no longer needed.
```c# using System; using System.Collections.Generic; using System.Reflection; using System.Text; using WalletWasabi.Models; namespace WalletWasabi.Gui.ViewModels.Validation { public delegate void ValidateMethod(IErrorList errors); } ```
5fb90a66-c4f3-4686-98d5-1817fdf13954
{ "language": "C#" }
```c# // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal static class CompilationOptionsConversion { internal static LanguageVersion? GetLanguageVersion(string projectLanguageVersion) { switch (projectLanguageVersion.ToLowerInvariant()) { case "iso-1": return LanguageVersion.CSharp1; case "iso-2": return LanguageVersion.CSharp2; case "experimental": return LanguageVersion.Experimental; default: if (!string.IsNullOrEmpty(projectLanguageVersion)) { int version; if (int.TryParse(projectLanguageVersion, out version)) { return (LanguageVersion)version; } } // use default; return null; } } } } ``` Allow null string in langversion conversion (changeset 1252651)
```c# // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal static class CompilationOptionsConversion { internal static LanguageVersion? GetLanguageVersion(string projectLanguageVersion) { switch ((projectLanguageVersion ?? string.Empty).ToLowerInvariant()) { case "iso-1": return LanguageVersion.CSharp1; case "iso-2": return LanguageVersion.CSharp2; case "experimental": return LanguageVersion.Experimental; default: if (!string.IsNullOrEmpty(projectLanguageVersion)) { int version; if (int.TryParse(projectLanguageVersion, out version)) { return (LanguageVersion)version; } } // use default; return null; } } } } ```
d95b4555-7ba5-47c6-8390-7b04723d6bf8
{ "language": "C#" }
```c# namespace net.opgenorth.yegvote.droid.Service { using System; using System.IO; using Android.Content; using Environment = Android.OS.Environment; /// <summary> /// This class will figure out where to store files. /// </summary> /// <remarks>Different versions of Android have different diretories for storage.</remarks> internal class ElectionServiceDownloadDirectory { private readonly Context _context; public ElectionServiceDownloadDirectory(Context context) { _context = context; } public void EnsureExternalStorageIsUsable() { if (Environment.MediaMountedReadOnly.Equals(Environment.ExternalStorageState)) { throw new ApplicationException(String.Format("External storage {0} is mounted read-only.", _context.GetExternalFilesDir(null))); } if (!Environment.MediaMounted.Equals(Environment.ExternalStorageState)) { throw new ApplicationException("External storage is not mounted."); } } public bool ResultsAreDownloaded { get { // TODO [TO201310041632] Maybe check to see how old the file is, > 30 minutes should return false? return File.Exists(GetResultsXmlFile()); } } public string GetResultsXmlFile() { var dir = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads).AbsolutePath; return Path.Combine(dir, "election_results.xml"); } } } ``` Create the download directory if it doesn't exist.
```c# using Android.Runtime; namespace net.opgenorth.yegvote.droid.Service { using System; using System.IO; using Android.Content; using Environment = Android.OS.Environment; /// <summary> /// This class will figure out where to store files. /// </summary> /// <remarks>Different versions of Android have different diretories for storage.</remarks> internal class ElectionServiceDownloadDirectory { private readonly Context _context; public ElectionServiceDownloadDirectory(Context context) { _context = context; } public void EnsureExternalStorageIsUsable() { if (Environment.MediaMountedReadOnly.Equals(Environment.ExternalStorageState)) { throw new ApplicationException(String.Format("External storage {0} is mounted read-only.", _context.GetExternalFilesDir(null))); } if (!Environment.MediaMounted.Equals(Environment.ExternalStorageState)) { throw new ApplicationException("External storage is not mounted."); } } public bool ResultsAreDownloaded { get { // TODO [TO201310041632] Maybe check to see how old the file is, > 30 minutes should return false? return File.Exists(GetResultsXmlFileName()); } } public string GetResultsXmlFileName() { var dir = _context.ExternalCacheDir.AbsolutePath; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } return Path.Combine(dir, "election_results.xml"); } } } ```
ad7977c8-c062-44a0-98e2-d4632b69bc1a
{ "language": "C#" }
```c# using DavidLievrouw.Utils.ForTesting.DotNet; using DavidLievrouw.Voter.Api.Users.Models; using DavidLievrouw.Voter.Security; using FakeItEasy; using NUnit.Framework; namespace DavidLievrouw.Voter.Api.Users.Handlers { [TestFixture] public class LogoutHandlerTests { LogoutHandler _sut; [SetUp] public void SetUp() { _sut = new LogoutHandler(); } [Test] public void ConstructorTests() { Assert.That(_sut.NoDependenciesAreOptional()); } [Test] public void DelegatesControlToAuthenticatedUserApplyer() { var securityContext = A.Fake<ISecurityContext>(); var command = new LogoutRequest { SecurityContext = securityContext }; _sut.Handle(command).Wait(); A.CallTo(() => securityContext.SetAuthenticatedUser(null)) .MustHaveHappened(); } } }``` Refactor the tests in the LogoutHandler slightly.
```c# using DavidLievrouw.Utils.ForTesting.DotNet; using DavidLievrouw.Voter.Api.Users.Models; using DavidLievrouw.Voter.Security; using FakeItEasy; using NUnit.Framework; namespace DavidLievrouw.Voter.Api.Users.Handlers { [TestFixture] public class LogoutHandlerTests { LogoutHandler _sut; [SetUp] public void SetUp() { _sut = new LogoutHandler(); } [TestFixture] public class Construction : LogoutHandlerTests { [Test] public void ConstructorTests() { Assert.That(_sut.NoDependenciesAreOptional()); } } [TestFixture] public class Handle : LogoutHandlerTests { [Test] public void DelegatesControlToAuthenticatedUserApplyer() { var securityContext = A.Fake<ISecurityContext>(); var command = new LogoutRequest { SecurityContext = securityContext }; _sut.Handle(command).Wait(); A.CallTo(() => securityContext.SetAuthenticatedUser(null)) .MustHaveHappened(); } } } }```
54de89d5-2fed-4181-a288-df699529738f
{ "language": "C#" }
```c# using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Algorithms { public static class Sha256Tests { public static readonly string HashOfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; [Fact] public static void HashEmpty() { var a = new Sha256(); var expected = HashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan<byte>.Empty); Assert.Equal(a.DefaultHashSize, actual.Length); Assert.Equal(expected, actual); } [Fact] public static void HashEmptyWithSpan() { var a = new Sha256(); var expected = HashOfEmpty.DecodeHex(); var actual = new byte[expected.Length]; a.Hash(ReadOnlySpan<byte>.Empty, actual); Assert.Equal(expected, actual); } } } ``` Add tests for Sha256 class
```c# using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Algorithms { public static class Sha256Tests { public static readonly string HashOfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; [Fact] public static void Properties() { var a = new Sha256(); Assert.Equal(32, a.MinHashSize); Assert.True(a.DefaultHashSize >= a.MinHashSize); Assert.True(a.MaxHashSize >= a.DefaultHashSize); Assert.Equal(32, a.MaxHashSize); } [Fact] public static void HashEmpty() { var a = new Sha256(); var expected = HashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan<byte>.Empty); Assert.Equal(a.DefaultHashSize, actual.Length); Assert.Equal(expected, actual); } [Fact] public static void HashEmptyWithSize() { var a = new Sha256(); var expected = HashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan<byte>.Empty, a.MaxHashSize); Assert.Equal(a.MaxHashSize, actual.Length); Assert.Equal(expected, actual); } [Fact] public static void HashEmptyWithSpan() { var a = new Sha256(); var expected = HashOfEmpty.DecodeHex(); var actual = new byte[expected.Length]; a.Hash(ReadOnlySpan<byte>.Empty, actual); Assert.Equal(expected, actual); } } } ```
81cfef91-4dd3-4481-a5ae-dcfc90149c57
{ "language": "C#" }
```c# namespace Nancy.Hosting.Self { /// <summary> /// Configuration for automatic url reservation creation /// </summary> public class UrlReservations { public UrlReservations() { this.CreateAutomatically = false; this.User = "Everyone"; } /// <summary> /// Gets or sets a value indicating whether url reservations /// are automatically created when necessary. /// Defaults to false. /// </summary> public bool CreateAutomatically { get; set; } /// <summary> /// Gets or sets a value for the user to use to create the url reservations for. /// Defaults to the "Everyone" group. /// </summary> public string User { get; set; } } }``` Fix for 'everyone' account in other languages
```c# namespace Nancy.Hosting.Self { using System; using System.Security.Principal; /// <summary> /// Configuration for automatic url reservation creation /// </summary> public class UrlReservations { private const string EveryoneAccountName = "Everyone"; private static readonly IdentityReference EveryoneReference = new SecurityIdentifier(WellKnownSidType.WorldSid, null); public UrlReservations() { this.CreateAutomatically = false; this.User = GetEveryoneAccountName(); } /// <summary> /// Gets or sets a value indicating whether url reservations /// are automatically created when necessary. /// Defaults to false. /// </summary> public bool CreateAutomatically { get; set; } /// <summary> /// Gets or sets a value for the user to use to create the url reservations for. /// Defaults to the "Everyone" group. /// </summary> public string User { get; set; } private static string GetEveryoneAccountName() { try { var account = EveryoneReference.Translate(typeof(NTAccount)) as NTAccount; if (account != null) { return account.Value; } return EveryoneAccountName; } catch (Exception) { return EveryoneAccountName; } } } }```
bad81cd4-49ea-46be-8673-f2dfbeeab028
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; namespace PalmDB.Serialization { internal class UIntPalmValue : IPalmValue<uint> { public int Length { get; } public UIntPalmValue(int length) { Guard.NotNegative(length, nameof(length)); this.Length = length; } public async Task<uint> ReadValueAsync(AsyncBinaryReader reader) { Guard.NotNull(reader, nameof(reader)); var data = await reader.ReadAsync(this.Length); Array.Reverse(data); Array.Resize(ref data, 4); return BitConverter.ToUInt32(data, 0); } public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value) { Guard.NotNull(writer, nameof(writer)); var data = BitConverter.GetBytes(value); Array.Reverse(data); Array.Resize(ref data, this.Length); await writer.WriteAsync(data); } } }``` Add code documentation to the UIntPalmValue
```c# using System; using System.Threading.Tasks; namespace PalmDB.Serialization { /// <summary> /// Represents a <see cref="uint"/> value inside a palm database. /// </summary> internal class UIntPalmValue : IPalmValue<uint> { /// <summary> /// Gets the length of this uint block. /// </summary> public int Length { get; } /// <summary> /// Initializes a new instance of the <see cref="UIntPalmValue"/> class. /// </summary> /// <param name="length">The length of the uint block.</param> public UIntPalmValue(int length) { Guard.NotNegative(length, nameof(length)); this.Length = length; } /// <summary> /// Reads the <see cref="uint"/> using the specified <paramref name="reader"/>. /// </summary> /// <param name="reader">The reader.</param> public async Task<uint> ReadValueAsync(AsyncBinaryReader reader) { Guard.NotNull(reader, nameof(reader)); var data = await reader.ReadAsync(this.Length); Array.Reverse(data); Array.Resize(ref data, 4); return BitConverter.ToUInt32(data, 0); } /// <summary> /// Writes the specified <paramref name="value"/> using the specified <paramref name="writer"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value.</param> public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value) { Guard.NotNull(writer, nameof(writer)); var data = BitConverter.GetBytes(value); Array.Reverse(data); Array.Resize(ref data, this.Length); await writer.WriteAsync(data); } } }```
e66eee28-5c1c-4fd2-aa9d-23c20fd5a0b5
{ "language": "C#" }
```c# // 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Screens.Edit.Screens.Compose; using OpenTK; namespace osu.Game.Tests.Visual { public class TestCaseBeatDivisorControl : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(BindableBeatDivisor) }; [BackgroundDependencyLoader] private void load() { Child = new BeatDivisorControl(new BindableBeatDivisor()) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Y = -200, Size = new Vector2(100, 110) }; } } } ``` Adjust testcase sizing to match editor
```c# // 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Screens.Edit.Screens.Compose; using OpenTK; namespace osu.Game.Tests.Visual { public class TestCaseBeatDivisorControl : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(BindableBeatDivisor) }; [BackgroundDependencyLoader] private void load() { Child = new BeatDivisorControl(new BindableBeatDivisor()) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(90, 90) }; } } } ```
e9125b3c-7cd3-4f31-8a99-aa9fe864e3fa
{ "language": "C#" }
```c# using System; using System.Globalization; using System.Windows; using System.Windows.Data; using NullGuard; namespace GitHub.VisualStudio.Converters { /// <summary> /// Convert a count to visibility based on the following rule: /// * If count == 0, return Visibility.Visible /// * If count > 0, return Visibility.Collapsed /// </summary> public class CountToVisibilityConverter : IValueConverter { public object Convert([AllowNull] object value, [AllowNull] Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture) { return ((int)value == 0) ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack([AllowNull] object value, [AllowNull] Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture) { return null; } } } ``` Use AllowNull for appropriate parameters
```c# using System; using System.Globalization; using System.Windows; using System.Windows.Data; using NullGuard; namespace GitHub.VisualStudio.Converters { /// <summary> /// Convert a count to visibility based on the following rule: /// * If count == 0, return Visibility.Visible /// * If count > 0, return Visibility.Collapsed /// </summary> public class CountToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture) { return ((int)value == 0) ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture) { return null; } } } ```
7eecc5eb-814a-4c19-ae31-f69d0ff6f40b
{ "language": "C#" }
```c# // 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 System.Linq; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Scoring; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { [Description("Player instantiated with a replay.")] public class TestCaseReplay : TestCasePlayer { protected override Player CreatePlayer(Ruleset ruleset) { // We create a dummy RulesetContainer just to get the replay - we don't want to use mods here // to simulate setting a replay rather than having the replay already set for us Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Concat(new[] { ruleset.GetAutoplayMod() }); var dummyRulesetContainer = ruleset.CreateRulesetContainerWith(Beatmap.Value); // Reset the mods Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Where(m => !(m is ModAutoplay)); return new ReplayPlayer(new Score { Replay = dummyRulesetContainer.ReplayScore.Replay }); } } } ``` Create ReplayPlayer using Score from the dummy RulesetContainer
```c# // 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 System.Linq; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Play; namespace osu.Game.Tests.Visual { [Description("Player instantiated with a replay.")] public class TestCaseReplay : TestCasePlayer { protected override Player CreatePlayer(Ruleset ruleset) { // We create a dummy RulesetContainer just to get the replay - we don't want to use mods here // to simulate setting a replay rather than having the replay already set for us Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Concat(new[] { ruleset.GetAutoplayMod() }); var dummyRulesetContainer = ruleset.CreateRulesetContainerWith(Beatmap.Value); // Reset the mods Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Where(m => !(m is ModAutoplay)); return new ReplayPlayer(dummyRulesetContainer.ReplayScore); } } } ```
a4ad9044-9c0a-4835-ac43-e73d0dfdfbd7
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace AxosoftAPI.NET.Models { public class WorkLog : BaseModel { [JsonProperty("project")] public Project Project { get; set; } [JsonProperty("release")] public Release Release { get; set; } [JsonProperty("user")] public User User { get; set; } [JsonProperty("work_done")] public DurationUnit WorkDone { get; set; } [JsonProperty("item")] public Item Item { get; set; } [JsonProperty("work_log_type")] public WorkLogType WorklogType { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("date_time")] public DateTime? DateTime { get; set; } } } ``` Add Custom Work Log field
```c# using System; using Newtonsoft.Json; using System.Collections.Generic; namespace AxosoftAPI.NET.Models { public class WorkLog : BaseModel { [JsonProperty("project")] public Project Project { get; set; } [JsonProperty("release")] public Release Release { get; set; } [JsonProperty("user")] public User User { get; set; } [JsonProperty("work_done")] public DurationUnit WorkDone { get; set; } [JsonProperty("item")] public Item Item { get; set; } [JsonProperty("work_log_type")] public WorkLogType WorklogType { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("date_time")] public DateTime? DateTime { get; set; } [JsonProperty("custom_fields")] public IDictionary<string, object> CustomFields { get; set; } } } ```
e87a3afc-e3ea-45f0-92ef-344a4c9a49e3
{ "language": "C#" }
```c# using System; namespace DevelopmentInProgress.DipState { public class LogEntry { public LogEntry(string message) { Message = message; Time = DateTime.Now; } public DateTime Time { get; private set; } public string Message { get; private set; } public override string ToString() { return String.Format("{0} {1}", Time.ToString("yy-mm-dd hhmmss"), Message); } } } ``` Change time format for log entry
```c# using System; namespace DevelopmentInProgress.DipState { public class LogEntry { public LogEntry(string message) { Message = message; Time = DateTime.Now; } public DateTime Time { get; private set; } public string Message { get; private set; } public override string ToString() { return String.Format("{0} {1}", Time.ToString("yyyy-MM-dd HH:mm:ss"), Message); } } } ```
a2bd93a3-4de4-4caf-97eb-f65e08182068
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SGEnviro.Utilities { public class NumberParseException : Exception { public NumberParseException(string message) { } } public class Parsing { public static void ParseFloatOrThrowException(string value, out float destination, string message) { if (!float.TryParse(value, out destination)) { throw new Exception(message); } } } } ``` Use invariant culture when parsing floats.
```c# using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace SGEnviro.Utilities { public class NumberParseException : Exception { public NumberParseException(string message) { } } public class Parsing { public static void ParseFloatOrThrowException(string value, out float destination, string message) { if (!float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination)) { throw new Exception(message); } } } } ```
d2e223cd-28d7-447a-b65c-eceb83d9206b
{ "language": "C#" }
```c# using System; using System.Linq; using Pixie; using Pixie.Markup; using Pixie.Options; using Pixie.Terminal; namespace ParseOptions { public static class Program { private static readonly FlagOption syntaxOnlyFlag = new FlagOption( OptionForm.Short("fsyntax-only"), OptionForm.Short("fno-syntax-only"), false); private static OptionSet parsedOptions; public static void Main(string[] args) { // First, acquire a terminal log. You should acquire // a log once and then re-use it in your application. var log = TerminalLog.Acquire(); var allOptions = new Option[] { syntaxOnlyFlag }; var parser = new GnuOptionSetParser( allOptions, syntaxOnlyFlag, syntaxOnlyFlag.PositiveForms[0]); parsedOptions = parser.Parse(args, log); foreach (var item in allOptions) { log.Log( new LogEntry( Severity.Info, new BulletedList( allOptions .Select<Option, MarkupNode>(TypesetParsedOption) .ToArray<MarkupNode>(), true))); } } private static MarkupNode TypesetParsedOption(Option opt) { return new Sequence( new DecorationSpan(new Text(opt.Forms[0].ToString()), TextDecoration.Bold), new Text(": "), new Text(parsedOptions.GetValue<object>(opt).ToString())); } } } ``` Make option parsing output prettier
```c# using System; using System.Linq; using Pixie; using Pixie.Markup; using Pixie.Options; using Pixie.Terminal; using Pixie.Transforms; namespace ParseOptions { public static class Program { private static readonly FlagOption syntaxOnlyFlag = new FlagOption( OptionForm.Short("fsyntax-only"), OptionForm.Short("fno-syntax-only"), false); private static OptionSet parsedOptions; public static void Main(string[] args) { // First, acquire a terminal log. You should acquire // a log once and then re-use it in your application. ILog log = TerminalLog.Acquire(); log = new TransformLog( log, new Func<LogEntry, LogEntry>[] { MakeDiagnostic }); var allOptions = new Option[] { syntaxOnlyFlag }; var parser = new GnuOptionSetParser( allOptions, syntaxOnlyFlag, syntaxOnlyFlag.PositiveForms[0]); parsedOptions = parser.Parse(args, log); foreach (var item in allOptions) { log.Log( new LogEntry( Severity.Info, new BulletedList( allOptions .Select<Option, MarkupNode>(TypesetParsedOption) .ToArray<MarkupNode>(), true))); } } private static MarkupNode TypesetParsedOption(Option opt) { return new Sequence( new DecorationSpan(new Text(opt.Forms[0].ToString()), TextDecoration.Bold), new Text(": "), new Text(parsedOptions.GetValue<object>(opt).ToString())); } private static LogEntry MakeDiagnostic(LogEntry entry) { return DiagnosticExtractor.Transform(entry, new Text("program")); } } } ```
37c4d04e-c1b4-41a2-aec0-153588ea91f6
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace Group.Net.Groups { public class PermutationGroup<T> where T : IComparable<T> { protected readonly IList<IList<int>> Generators; public int GeneratorCount { get { return Generators.Count; } } public PermutationGroup(IList<IList<int>> generators) { Generators = generators; } public Points<T> Apply(int index, Points<T> points) { var permutedPoints = new Points<T>(points); for (var i = 0; i < Generators[index].Count - 1; ++i) permutedPoints[Generators[index][i + 1]] = points[Generators[index][i]]; permutedPoints[Generators[index][0]] = points[Generators[index][Generators[index].Count - 1]]; return permutedPoints; } } } ``` Fix for attempting to permute singleton Points objects.
```c# using System; using System.Collections.Generic; namespace Group.Net.Groups { public class PermutationGroup<T> where T : IComparable<T> { protected readonly IList<IList<int>> Generators; public int GeneratorCount { get { return Generators.Count; } } public PermutationGroup(IList<IList<int>> generators) { Generators = generators; } public Points<T> Apply(int index, Points<T> points) { var permutedPoints = new Points<T>(points); if (permutedPoints.Count == 1) return permutedPoints; for (var i = 0; i < Generators[index].Count - 1; ++i) permutedPoints[Generators[index][i + 1]] = points[Generators[index][i]]; permutedPoints[Generators[index][0]] = points[Generators[index][Generators[index].Count - 1]]; return permutedPoints; } } } ```
2c474bb2-0195-4336-b2a7-c901918d94ed
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Globalization; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Core { /// <summary> /// Extensions for <see cref="IApplicationBuilder"/> /// </summary> static class ApplicationBuilderExtensions { /// <summary> /// Return a <see cref="ConflictObjectResult"/> for <see cref="DbUpdateException"/>s /// </summary> /// <param name="applicationBuilder">The <see cref="IApplicationBuilder"/> to configure</param> public static void UseDbConflictHandling(this IApplicationBuilder applicationBuilder) => applicationBuilder.Use(async (context, next) => { if (applicationBuilder == null) throw new ArgumentNullException(nameof(applicationBuilder)); try { await next().ConfigureAwait(false); } catch (DbUpdateException e) { await new ConflictObjectResult(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "A database conflict has occurred: {0}", (e.InnerException ?? e).Message) }).ExecuteResultAsync(new ActionContext { HttpContext = context }).ConfigureAwait(false); } }); } } ``` Check parameter before actually using it
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Globalization; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Host.Core { /// <summary> /// Extensions for <see cref="IApplicationBuilder"/> /// </summary> static class ApplicationBuilderExtensions { /// <summary> /// Return a <see cref="ConflictObjectResult"/> for <see cref="DbUpdateException"/>s /// </summary> /// <param name="applicationBuilder">The <see cref="IApplicationBuilder"/> to configure</param> public static void UseDbConflictHandling(this IApplicationBuilder applicationBuilder) { if (applicationBuilder == null) throw new ArgumentNullException(nameof(applicationBuilder)); applicationBuilder.Use(async (context, next) => { try { await next().ConfigureAwait(false); } catch (DbUpdateException e) { await new ConflictObjectResult(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "A database conflict has occurred: {0}", (e.InnerException ?? e).Message) }).ExecuteResultAsync(new ActionContext { HttpContext = context }).ConfigureAwait(false); } }); } } } ```
dea0f1dd-7cb2-4592-9c7a-c346d8bb9447
{ "language": "C#" }
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; using Microsoft.Practices.Unity; namespace EOLib { public static class UnityExtensions { public static void RegisterInstance<T>(this IUnityContainer container) { container.RegisterType<T>(new ContainerControlledLifetimeManager()); } public static void RegisterInstance<T, U>(this IUnityContainer container) where U : T { container.RegisterType<T, U>(new ContainerControlledLifetimeManager()); } public static void RegisterVaried<T, U>(this IUnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); container.RegisterType<T, U>(typeof(U).Name); } public static void RegisterInstanceVaried<T, U>(this IUnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager()); } private static void RegisterEnumerableIfNeeded<T, U>(IUnityContainer container) where U : T { if (!container.IsRegistered(typeof(IEnumerable<T>))) { container.RegisterType<IEnumerable<T>>( new ContainerControlledLifetimeManager(), new InjectionFactory(c => c.ResolveAll<T>())); } } } } ``` Return IUnityContainer from unity extension methods
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System.Collections.Generic; using Microsoft.Practices.Unity; namespace EOLib { public static class UnityExtensions { public static IUnityContainer RegisterInstance<T>(this IUnityContainer container) { return container.RegisterType<T>(new ContainerControlledLifetimeManager()); } public static IUnityContainer RegisterInstance<T, U>(this IUnityContainer container) where U : T { return container.RegisterType<T, U>(new ContainerControlledLifetimeManager()); } public static IUnityContainer RegisterVaried<T, U>(this IUnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); return container.RegisterType<T, U>(typeof(U).Name); } public static IUnityContainer RegisterInstanceVaried<T, U>(this IUnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); return container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager()); } private static void RegisterEnumerableIfNeeded<T, U>(IUnityContainer container) where U : T { if (!container.IsRegistered(typeof(IEnumerable<T>))) { container.RegisterType<IEnumerable<T>>( new ContainerControlledLifetimeManager(), new InjectionFactory(c => c.ResolveAll<T>())); } } } } ```
1c4bc62d-6e82-41fc-8c5b-1821fa0615c7
{ "language": "C#" }
```c# using System.Windows.Input; namespace RegEditor { public static class ComandsContextMenu { public static readonly RoutedUICommand CreateKey = new RoutedUICommand( "Create Key", "CreateKey", typeof(MainWindow)); public static readonly RoutedUICommand UpdateKey = new RoutedUICommand( "Update Key", "UpdateKey", typeof(MainWindow)); public static readonly RoutedUICommand DeleteKey = new RoutedUICommand( "Delete Key", "DeleteKey", typeof(MainWindow)); } } ``` Add puncts key value in context menu
```c# using System.Windows.Input; namespace RegEditor { public static class ComandsContextMenu { public static readonly RoutedUICommand CreateKey = new RoutedUICommand( "Create Key", "CreateKey", typeof(MainWindow)); public static readonly RoutedUICommand UpdateKey = new RoutedUICommand( "Update Key", "UpdateKey", typeof(MainWindow)); public static readonly RoutedUICommand DeleteKey = new RoutedUICommand( "Delete Key", "DeleteKey", typeof(MainWindow)); public static readonly RoutedUICommand DeleteKeyValue = new RoutedUICommand( "Delete Key Value", "DeleteKeyValue", typeof(MainWindow)); public static readonly RoutedUICommand CreateKeyValue = new RoutedUICommand( "Delete Key Value", "DeleteKeyValue", typeof(MainWindow)); public static readonly RoutedUICommand UpdateKeyValue = new RoutedUICommand( "Update Key Value", "UpdateKeyValue", typeof(MainWindow)); } } ```
e7a932cf-4a79-4b97-9145-c435929f8c25
{ "language": "C#" }
```c# using System; using System.Reactive.Disposables; using System.Reactive.Linq; using ReactiveUI; using Splat; using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel { public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction, UiConfig uiConfig) : base("") { Transaction = transaction; UiConfig = uiConfig; Title = $"Transaction ({transaction.TransactionId[0..10]}) Details"; } public TransactionDetailsViewModel Transaction { get; } public UiConfig UiConfig { get; } public override void OnOpen(CompositeDisposable disposables) { UiConfig.WhenAnyValue(x => x.LurkingWifeMode) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId))) .DisposeWith(disposables); base.OnOpen(disposables); } } } ``` Add param name to better readability
```c# using System; using System.Reactive.Disposables; using System.Reactive.Linq; using ReactiveUI; using Splat; using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel { public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction, UiConfig uiConfig) : base(title: "") { Transaction = transaction; UiConfig = uiConfig; Title = $"Transaction ({transaction.TransactionId[0..10]}) Details"; } public TransactionDetailsViewModel Transaction { get; } public UiConfig UiConfig { get; } public override void OnOpen(CompositeDisposable disposables) { UiConfig.WhenAnyValue(x => x.LurkingWifeMode) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId))) .DisposeWith(disposables); base.OnOpen(disposables); } } } ```
96151b7e-b293-4825-b0a3-7e241f6748f1
{ "language": "C#" }
```c# namespace SqlStreamStore { using System; using System.Collections.Concurrent; using System.Threading.Tasks; using SqlStreamStore.MySql; using Xunit; using Xunit.Abstractions; public class MySqlStreamStoreFixturePool : IAsyncLifetime { private readonly ConcurrentQueue<MySqlStreamStoreFixture> _fixturePool = new ConcurrentQueue<MySqlStreamStoreFixture>(); public async Task<MySqlStreamStoreFixture> Get(ITestOutputHelper outputHelper) { if (!_fixturePool.TryDequeue(out var fixture)) { var dbUniqueName = (DateTime.UtcNow - DateTime.UnixEpoch).TotalMilliseconds; var databaseName = $"sss-v3-{dbUniqueName}"; var dockerInstance = new MySqlDockerDatabaseManager(outputHelper, databaseName); await dockerInstance.CreateDatabase(); fixture = new MySqlStreamStoreFixture( dockerInstance, databaseName, onDispose:() => _fixturePool.Enqueue(fixture)); outputHelper.WriteLine($"Using new fixture with db {databaseName}"); } else { outputHelper.WriteLine($"Using pooled fixture with db {fixture.DatabaseName}"); } await fixture.Prepare(); return fixture; } public Task InitializeAsync() { return Task.CompletedTask; } public Task DisposeAsync() { return Task.CompletedTask; } } }``` Add todo - this will give wrong test output.
```c# namespace SqlStreamStore { using System; using System.Collections.Concurrent; using System.Threading.Tasks; using SqlStreamStore.MySql; using Xunit; using Xunit.Abstractions; public class MySqlStreamStoreFixturePool : IAsyncLifetime { private readonly ConcurrentQueue<MySqlStreamStoreFixture> _fixturePool = new ConcurrentQueue<MySqlStreamStoreFixture>(); public async Task<MySqlStreamStoreFixture> Get(ITestOutputHelper outputHelper) { if (!_fixturePool.TryDequeue(out var fixture)) { var dbUniqueName = (DateTime.UtcNow - DateTime.UnixEpoch).TotalMilliseconds; var databaseName = $"sss-v3-{dbUniqueName}"; var dockerInstance = new MySqlDockerDatabaseManager(outputHelper, databaseName); // TODO output helper here will be interleaved await dockerInstance.CreateDatabase(); fixture = new MySqlStreamStoreFixture( dockerInstance, databaseName, onDispose:() => _fixturePool.Enqueue(fixture)); outputHelper.WriteLine($"Using new fixture with db {databaseName}"); } else { outputHelper.WriteLine($"Using pooled fixture with db {fixture.DatabaseName}"); } await fixture.Prepare(); return fixture; } public Task InitializeAsync() { return Task.CompletedTask; } public Task DisposeAsync() { return Task.CompletedTask; } } }```
1a20f915-fd41-4fce-bbd6-50b6846f569e
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Mania.Edit.Blueprints { public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint { public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject; [Resolved] private IScrollingInfo scrollingInfo { get; set; } protected ManiaSelectionBlueprint(DrawableHitObject drawableObject) : base(drawableObject) { RelativeSizeAxes = Axes.None; } protected override void Update() { base.Update(); Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero)); } public override void Show() { DrawableObject.AlwaysAlive = true; base.Show(); } public override void Hide() { DrawableObject.AlwaysAlive = false; base.Hide(); } } } ``` Fix mania editor null reference
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Mania.Edit.Blueprints { public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint { public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject; [Resolved] private IScrollingInfo scrollingInfo { get; set; } // Overriding the base because this method is called right after `Column` is changed and `DrawableObject` is not yet loaded and Parent is not set. public override Vector2 GetInstantDelta(Vector2 screenSpacePosition) => Parent.ToLocalSpace(screenSpacePosition) - Position; protected ManiaSelectionBlueprint(DrawableHitObject drawableObject) : base(drawableObject) { RelativeSizeAxes = Axes.None; } protected override void Update() { base.Update(); Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero)); } public override void Show() { DrawableObject.AlwaysAlive = true; base.Show(); } public override void Hide() { DrawableObject.AlwaysAlive = false; base.Hide(); } } } ```
95ae83e0-5129-4e62-bc3c-e9aad280d57f
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Tournament.Components; using osu.Framework.Graphics.Shapes; using osuTK.Graphics; namespace osu.Game.Tournament.Screens.Showcase { public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo { [BackgroundDependencyLoader] private void load() { AddRangeInternal(new Drawable[] { new TournamentLogo(), new TourneyVideo("showcase") { Loop = true, RelativeSizeAxes = Axes.Both, }, new Box { // chroma key area for stable gameplay Name = "chroma", Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Height = 695, Width = 1366, Colour = new Color4(0, 255, 0, 255), } }); } } } ``` Use SongBar height instead of hard-coded dimensions
```c# // 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; using osu.Game.Tournament.Components; using osu.Framework.Graphics.Shapes; using osuTK.Graphics; namespace osu.Game.Tournament.Screens.Showcase { public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo { [BackgroundDependencyLoader] private void load() { AddRangeInternal(new Drawable[] { new TournamentLogo(), new TourneyVideo("showcase") { Loop = true, RelativeSizeAxes = Axes.Both, }, new Container { Padding = new MarginPadding { Bottom = SongBar.HEIGHT }, RelativeSizeAxes = Axes.Both, Child = new Box { // chroma key area for stable gameplay Name = "chroma", Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.Both, Colour = new Color4(0, 255, 0, 255), } } }); } } } ```
19ce2f05-77f4-4df5-ac13-98a3c46d1a16
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Alexa.NET.Management.AccountLinking; using Refit; namespace Alexa.NET.Management.Internals { [Headers("Authorization: Bearer")] public interface IClientAccountLinkingApi { [Get("/skills/{skilIid}/accountLinkingClient")] Task<AccountLinkInformation> Get(string skillId); [Put("/skills/{skillId}/accountLinkingClient")] Task Update(string skillId, [Body]AccountLinkUpdate information); } } ``` Fix issue with mismatched parameter on AccountLinking Api
```c# using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Alexa.NET.Management.AccountLinking; using Refit; namespace Alexa.NET.Management.Internals { [Headers("Authorization: Bearer")] public interface IClientAccountLinkingApi { [Get("/skills/{skillId}/accountLinkingClient")] Task<AccountLinkInformation> Get(string skillId); [Put("/skills/{skillId}/accountLinkingClient")] Task Update(string skillId, [Body]AccountLinkUpdate information); } } ```
a609ef4a-e90f-4a6c-aaba-9304f2cb3e02
{ "language": "C#" }
```c# using System; using ClosedXML.Excel; namespace ClosedXML_Examples.Misc { public class WorkbookProperties : IXLExample { #region Variables // Public // Private #endregion #region Properties // Public // Private // Override #endregion #region Events // Public // Private // Override #endregion #region Methods // Public public void Create(String filePath) { var wb = new XLWorkbook(); var ws = wb.Worksheets.Add("Workbook Properties"); wb.Properties.Author = "theAuthor"; wb.Properties.Title = "theTitle"; wb.Properties.Subject = "theSubject"; wb.Properties.Category = "theCategory"; wb.Properties.Keywords = "theKeywords"; wb.Properties.Comments = "theComments"; wb.Properties.Status = "theStatus"; wb.Properties.LastModifiedBy = "theLastModifiedBy"; wb.Properties.Company = "theCompany"; wb.Properties.Manager = "theManager"; // Creating/Using custom properties wb.CustomProperties.Add("theText", "XXX"); wb.CustomProperties.Add("theDate", new DateTime(2011, 1, 1)); wb.CustomProperties.Add("theNumber", 123.456); wb.CustomProperties.Add("theBoolean", true); wb.SaveAs(filePath); } // Private // Override #endregion } } ``` Fix time zone issue in tests
```c# using System; using ClosedXML.Excel; namespace ClosedXML_Examples.Misc { public class WorkbookProperties : IXLExample { #region Variables // Public // Private #endregion #region Properties // Public // Private // Override #endregion #region Events // Public // Private // Override #endregion #region Methods // Public public void Create(String filePath) { var wb = new XLWorkbook(); var ws = wb.Worksheets.Add("Workbook Properties"); wb.Properties.Author = "theAuthor"; wb.Properties.Title = "theTitle"; wb.Properties.Subject = "theSubject"; wb.Properties.Category = "theCategory"; wb.Properties.Keywords = "theKeywords"; wb.Properties.Comments = "theComments"; wb.Properties.Status = "theStatus"; wb.Properties.LastModifiedBy = "theLastModifiedBy"; wb.Properties.Company = "theCompany"; wb.Properties.Manager = "theManager"; // Creating/Using custom properties wb.CustomProperties.Add("theText", "XXX"); wb.CustomProperties.Add("theDate", new DateTime(2011, 1, 1, 17, 0, 0, DateTimeKind.Utc)); // Use UTC to make sure test can be run in any time zone wb.CustomProperties.Add("theNumber", 123.456); wb.CustomProperties.Add("theBoolean", true); wb.SaveAs(filePath); } // Private // Override #endregion } } ```
2c0edacb-9047-46fd-ac2f-afef97d2f529
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: AssemblyInformationalVersion("1.2.0")] ``` Update version to at least above published version on nuget.org
```c# using System.Reflection; [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0")] ```
d4d79a02-d1e9-4bb2-85ae-713872d4899c
{ "language": "C#" }
```c# using System; using MessageBird.Utilities; using Newtonsoft.Json; namespace MessageBird.Json.Converters { class RFC3339DateTimeConverter : JsonConverter { private const string Format = "yyyy-MM-dd'T'HH:mm:ssK"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is DateTime) { var dateTime = (DateTime)value; writer.WriteValue(dateTime.ToString(Format)); } else { throw new JsonSerializationException("Expected value of type 'DateTime'."); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; if (reader.TokenType == JsonToken.Null) { return null; } if (reader.TokenType == JsonToken.Date) { return reader.Value; } throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); } public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; return t == typeof(DateTime); } } } ``` Raise exception when the kind of a DateTime is unspecified
```c# using System; using MessageBird.Utilities; using Newtonsoft.Json; namespace MessageBird.Json.Converters { class RFC3339DateTimeConverter : JsonConverter { private const string Format = "yyyy-MM-dd'T'HH:mm:ssK"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is DateTime) { var dateTime = (DateTime)value; if (dateTime.Kind == DateTimeKind.Unspecified) { throw new JsonSerializationException("Cannot convert date time with an unspecified kind"); } string convertedDateTime = dateTime.ToString(Format); writer.WriteValue(convertedDateTime); } else { throw new JsonSerializationException("Expected value of type 'DateTime'."); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; if (reader.TokenType == JsonToken.Null) { return null; } if (reader.TokenType == JsonToken.Date) { return reader.Value; } throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType)); } public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullable(objectType)) ? Nullable.GetUnderlyingType(objectType) : objectType; return t == typeof(DateTime); } } } ```
06895c01-f44f-4f25-a304-3ac73082f288
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Engine.cgimin.texture; using System.IO; namespace Mugo { public static class TextureLoader { private static readonly Dictionary<String, TextureHolder> textures = new Dictionary<string, TextureHolder>(); public static TextureHolder Load(String path) { TextureHolder texture; if(!textures.TryGetValue(path, out texture)) { var normalTexturePath = Path.ChangeExtension(path, "normals" + Path.GetExtension(path)); var normalMapId = 0; if (File.Exists(normalTexturePath)) { normalMapId = TextureManager.LoadTexture(normalTexturePath); } texture = new TextureHolder(TextureManager.LoadTexture(path), normalMapId); } return texture; } } public class TextureHolder { public TextureHolder(int textureId, int normalMapId) { TextureId = textureId; NormalMapId = normalMapId; } public int TextureId { get; private set; } public int NormalMapId { get; private set; } } } ``` Save loaded textures in map.
```c# using System; using System.Collections.Generic; using Engine.cgimin.texture; using System.IO; namespace Mugo { public static class TextureLoader { private static readonly Dictionary<String, TextureHolder> textures = new Dictionary<string, TextureHolder>(); public static TextureHolder Load(String path) { TextureHolder texture; if(!textures.TryGetValue(path, out texture)) { var normalTexturePath = Path.ChangeExtension(path, "normals" + Path.GetExtension(path)); var normalMapId = 0; if (File.Exists(normalTexturePath)) { normalMapId = TextureManager.LoadTexture(normalTexturePath); } texture = new TextureHolder(TextureManager.LoadTexture(path), normalMapId); textures[path] = texture; } return texture; } } public class TextureHolder { public TextureHolder(int textureId, int normalMapId) { TextureId = textureId; NormalMapId = normalMapId; } public int TextureId { get; private set; } public int NormalMapId { get; private set; } } } ```
2ac41041-acd8-434a-9f48-5d49b211cc2e
{ "language": "C#" }
```c# namespace DynamixelServo.Driver { public enum ComplianceSlope { S2 = 2, S4 = 4, S8 = 8, S16 = 16, S32 = 32, Default = 32, S64 = 64, S128 = 128 } } ``` Add description to default Compliance slope
```c# namespace DynamixelServo.Driver { public enum ComplianceSlope { S2 = 2, S4 = 4, S8 = 8, S16 = 16, S32 = 32, /// <summary> /// Same as S32 /// </summary> Default = 32, S64 = 64, S128 = 128 } } ```
e1431020-b970-4593-a3ed-379a7ea7c302
{ "language": "C#" }
```c# using System; using Recurly; using Recurly.Resources; namespace RecurlyTestRig { class Program { static void Main(string[] args) { var client = new Recurly.Client("subdomain-client-lib-test", "382c053318a04154905c4d27a48f74a6"); var site = client.GetSite("subdomain-client-lib-test"); Console.WriteLine(site.Id); var account = client.GetAccount("subdomain-client-lib-test", "code-benjamin-du-monde"); Console.WriteLine(account.CreatedAt); var createAccount = new AccountCreate() { Code = "abcsdaskdljsda", Username = "myuser", Address = new Address() { City = "New Orleans", Street1 = "1 Canal St.", Region = "LA", Country = "US", PostalCode = "70115" } }; var createdAccount = client.CreateAccount("subdomain-client-lib-test", createAccount); Console.WriteLine(createdAccount.CreatedAt); try { var nonexistentAccount = client.GetAccount("subdomain-client-lib-test", "idontexist"); } catch (Recurly.ApiError err) { Console.WriteLine(err); } } } } ``` Use env vars for test client
```c# using System; using Recurly; using Recurly.Resources; namespace RecurlyTestRig { class Program { static void Main(string[] args) { try { var subdomain = Environment.GetEnvironmentVariable("RECURLY_SUBDOMAIN"); var apiKey = Environment.GetEnvironmentVariable("RECURLY_API_KEY"); var client = new Recurly.Client(subdomain, apiKey); var site = client.GetSite(subdomain); Console.WriteLine(site.Id); var account = client.GetAccount(subdomain, "code-benjamin-du-monde"); Console.WriteLine(account.CreatedAt); var createAccount = new CreateAccount() { Code = "abcsdaskdljsda", Username = "myuser", Address = new Address() { City = "New Orleans", Street1 = "1 Canal St.", Region = "LA", Country = "US", PostalCode = "70115" } }; var createdAccount = client.CreateAccount(subdomain, createAccount); Console.WriteLine(createdAccount.CreatedAt); try { var nonexistentAccount = client.GetAccount(subdomain, "idontexist"); } catch (Recurly.ApiError err) { Console.WriteLine(err); } } catch (Recurly.ApiError err) { Console.WriteLine(err); } } } } ```
0bf09146-3c90-4801-9a96-0a69354810be
{ "language": "C#" }
```c# using System.Collections.Generic; using MongoDB.Driver; namespace RapidCore.Mongo.Testing { /// <summary> /// Base class for functional tests that need access to /// a Mongo database. /// /// It provides simple helpers that we use ourselves. /// </summary> public abstract class MongoConnectedTestBase { private MongoClient lowLevelClient; private IMongoDatabase db; private bool isConnected = false; protected string GetDbName() { return GetType().Name; } protected void Connect(string connectionString = "mongodb://localhost:27017") { lowLevelClient = new MongoClient(connectionString); lowLevelClient.DropDatabase(GetDbName()); db = lowLevelClient.GetDatabase(GetDbName()); } protected MongoClient GetClient() { if (!isConnected) { Connect(); isConnected = true; } return lowLevelClient; } protected IMongoDatabase GetDb() { return GetClient().GetDatabase(GetDbName()); } protected void EnsureEmptyCollection(string collectionName) { GetDb().DropCollection(collectionName); } protected void Insert<TDocument>(string collectionName, TDocument doc) { GetDb().GetCollection<TDocument>(collectionName).InsertOne(doc); } protected IList<TDocument> GetAll<TDocument>(string collectionName) { return GetDb().GetCollection<TDocument>(collectionName).Find(filter => true).ToList(); } } }``` Define a property for the connection string
```c# using System.Collections.Generic; using MongoDB.Driver; namespace RapidCore.Mongo.Testing { /// <summary> /// Base class for functional tests that need access to /// a Mongo database. /// /// It provides simple helpers that we use ourselves. /// </summary> public abstract class MongoConnectedTestBase { private MongoClient lowLevelClient; private IMongoDatabase db; private bool isConnected = false; protected string ConnectionString { get; set; } = "mongodb://localhost:27017"; protected string GetDbName() { return GetType().Name; } protected void Connect() { if (!isConnected) { lowLevelClient = new MongoClient(ConnectionString); lowLevelClient.DropDatabase(GetDbName()); db = lowLevelClient.GetDatabase(GetDbName()); isConnected = true; } } protected MongoClient GetClient() { Connect(); return lowLevelClient; } protected IMongoDatabase GetDb() { return GetClient().GetDatabase(GetDbName()); } protected void EnsureEmptyCollection(string collectionName) { GetDb().DropCollection(collectionName); } protected void Insert<TDocument>(string collectionName, TDocument doc) { GetDb().GetCollection<TDocument>(collectionName).InsertOne(doc); } protected IList<TDocument> GetAll<TDocument>(string collectionName) { return GetDb().GetCollection<TDocument>(collectionName).Find(filter => true).ToList(); } } }```
616ce14e-1404-4fe9-bea9-ab69e4a5caff
{ "language": "C#" }
```c# using GitHub.Api; using GitHub.Models; using GitHub.Services; using Microsoft.TeamFoundation.Controls; using System.ComponentModel.Composition; namespace GitHub.VisualStudio.TeamExplorer.Connect { [TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 10)] [PartCreationPolicy(CreationPolicy.NonShared)] public class GitHubConnectSection1 : GitHubConnectSection { public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91"; [ImportingConstructor] public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager) : base(apiFactory, holder, manager, 1) { } } } ``` Fix ordering of connection sections
```c# using GitHub.Api; using GitHub.Models; using GitHub.Services; using Microsoft.TeamFoundation.Controls; using System.ComponentModel.Composition; namespace GitHub.VisualStudio.TeamExplorer.Connect { [TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 11)] [PartCreationPolicy(CreationPolicy.NonShared)] public class GitHubConnectSection1 : GitHubConnectSection { public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91"; [ImportingConstructor] public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager) : base(apiFactory, holder, manager, 1) { } } } ```
6b12236d-310a-47a7-8162-6a4edf55265d
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.ServiceBus; namespace Microsoft.Azure.WebJobs.Script.Description { public class EventHubBindingMetadata : BindingMetadata { [AllowNameResolution] public string Path { get; set; } public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder) { if (configBuilder == null) { throw new ArgumentNullException("configBuilder"); } EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration; string connectionString = null; if (!string.IsNullOrEmpty(Connection)) { connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection); } if (this.IsTrigger) { string eventProcessorHostName = Guid.NewGuid().ToString(); string storageConnectionString = configBuilder.Config.StorageConnectionString; var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost( eventProcessorHostName, this.Path, Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName, connectionString, storageConnectionString); eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost); } else { var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString( connectionString, this.Path); eventHubConfig.AddEventHubClient(this.Path, client); } } } } ``` Support EventHub Consumer Groups in Script
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.ServiceBus; namespace Microsoft.Azure.WebJobs.Script.Description { public class EventHubBindingMetadata : BindingMetadata { [AllowNameResolution] public string Path { get; set; } // Optional Consumer group public string ConsumerGroup { get; set; } public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder) { if (configBuilder == null) { throw new ArgumentNullException("configBuilder"); } EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration; string connectionString = null; if (!string.IsNullOrEmpty(Connection)) { connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection); } if (this.IsTrigger) { string eventProcessorHostName = Guid.NewGuid().ToString(); string storageConnectionString = configBuilder.Config.StorageConnectionString; string consumerGroup = this.ConsumerGroup; if (consumerGroup == null) { consumerGroup = Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName; } var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost( eventProcessorHostName, this.Path, consumerGroup, connectionString, storageConnectionString); eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost); } else { var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString( connectionString, this.Path); eventHubConfig.AddEventHubClient(this.Path, client); } } } } ```
40d092f3-2a98-4971-93f7-31946062dea9
{ "language": "C#" }
```c# using System; using System.Windows; using DereTore.Applications.StarlightDirector.Extensions; namespace DereTore.Applications.StarlightDirector.UI.Controls.Pages { public partial class SummaryPage : IDirectorPage { public SummaryPage() { InitializeComponent(); Table = new ObservableDictionary<string, string>(); DataContext = this; } public ObservableDictionary<string, string> Table { get; } private void SummaryPage_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { var visible = (bool)e.NewValue; if (!visible) { return; } var t = Table; t.Clear(); var mainWindow = this.GetMainWindow(); var editor = mainWindow.Editor; Func<string, string> res = key => Application.Current.FindResource<string>(key); t[res(App.ResourceKeys.SummaryMusicFile)] = editor.Project.HasMusic ? editor.Project.MusicFileName : "(none)"; t[res(App.ResourceKeys.SummaryTotalNotes)] = editor.ScoreNotes.Count.ToString(); t[res(App.ResourceKeys.SummaryTotalBars)] = editor.ScoreBars.Count.ToString(); } } } ``` Fix crash after discarding autosave file
```c# using System; using System.Windows; using DereTore.Applications.StarlightDirector.Extensions; namespace DereTore.Applications.StarlightDirector.UI.Controls.Pages { public partial class SummaryPage : IDirectorPage { public SummaryPage() { InitializeComponent(); Table = new ObservableDictionary<string, string>(); DataContext = this; } public ObservableDictionary<string, string> Table { get; } private void SummaryPage_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { var visible = (bool)e.NewValue; if (!visible) { return; } var t = Table; t.Clear(); var mainWindow = this.GetMainWindow(); var editor = mainWindow.Editor; Func<string, string> res = key => Application.Current.FindResource<string>(key); t[res(App.ResourceKeys.SummaryMusicFile)] = editor.Project?.HasMusic ?? false ? editor.Project.MusicFileName : "(none)"; t[res(App.ResourceKeys.SummaryTotalNotes)] = editor.ScoreNotes.Count.ToString(); t[res(App.ResourceKeys.SummaryTotalBars)] = editor.ScoreBars.Count.ToString(); } } } ```
9bdd2d01-42ba-40b2-b79b-459651c0e7a2
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.DynamicProxy2")] [assembly: AssemblyDescription("")] ``` 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.
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.DynamicProxy2")] ```
5dde77a2-8cc2-4c8e-8283-992e05f73e1f
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Arkivverket.Arkade.Core.Resources; using Arkivverket.Arkade.Core.Testing; using Arkivverket.Arkade.Core.Util; using Serilog; namespace Arkivverket.Arkade.Core.Base.Noark5 { public abstract class Noark5BaseTest : IArkadeTest { private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType); protected readonly Stopwatch Stopwatch = new Stopwatch(); public abstract TestId GetId(); public abstract string GetName(); public abstract TestType GetTestType(); public string GetDescription() { var description = Noark5TestDescriptions.ResourceManager.GetObject(GetName()) as string; if (description == null) { Log.Debug($"Missing description of Noark5Test: {GetType().FullName}"); } return description; } public TestRun GetTestRun() { Stopwatch.Start(); List<TestResult> testResults = GetTestResults(); Stopwatch.Stop(); return new TestRun(this) { Results = testResults, TestDuration = Stopwatch.ElapsedMilliseconds }; } protected abstract List<TestResult> GetTestResults(); public int CompareTo(object obj) { var arkadeTest = (IArkadeTest) obj; return GetId().CompareTo(arkadeTest.GetId()); } } } ``` Use TestID for N5 test description lookup
```c# using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Arkivverket.Arkade.Core.Resources; using Arkivverket.Arkade.Core.Testing; using Arkivverket.Arkade.Core.Util; using Serilog; namespace Arkivverket.Arkade.Core.Base.Noark5 { public abstract class Noark5BaseTest : IArkadeTest { private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType); protected readonly Stopwatch Stopwatch = new Stopwatch(); public abstract TestId GetId(); public abstract string GetName(); public abstract TestType GetTestType(); public string GetDescription() { var description = Noark5TestDescriptions.ResourceManager.GetObject(GetId().ToString()) as string; if (description == null) { Log.Debug($"Missing description of Noark 5 test: {GetId()}"); } return description; } public TestRun GetTestRun() { Stopwatch.Start(); List<TestResult> testResults = GetTestResults(); Stopwatch.Stop(); return new TestRun(this) { Results = testResults, TestDuration = Stopwatch.ElapsedMilliseconds }; } protected abstract List<TestResult> GetTestResults(); public int CompareTo(object obj) { var arkadeTest = (IArkadeTest) obj; return GetId().CompareTo(arkadeTest.GetId()); } } } ```
94dfd06f-fb44-4d2d-8661-0f3563cededd
{ "language": "C#" }
```c# // Program.cs // <copyright file="Program.cs"> This code is protected under the MIT License. </copyright> using System; using System.Collections.Generic; using CardsLibrary; namespace ConsoleTesting { /// <summary> /// The main program (for testing at the moment). /// </summary> public class Program { /// <summary> /// The main entry point for the program. /// </summary> /// <param name="args"> Any arguments/commands that the program is run/compiled with. </param> public static void Main(string[] args) { List<Card> deck = CardFactory.PopulateDeck(true); List<CardGames.Whist.ConsolePlayer> players = new List<CardGames.Whist.ConsolePlayer>(); Card[][] tempPlayers = CardFactory.Deal(ref deck, 2, 7); players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[0])); players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[1])); CardGames.Whist.WhistInfo gameInfo = new CardGames.Whist.WhistInfo(new List<Card>(), Suit.Clubs, Suit.Null); players[0].MakeMove(gameInfo); Console.WriteLine(); Console.WriteLine(); players[1].MakeMove(gameInfo); } } } ``` Update to remove WhistInfo constructor call
```c# // Program.cs // <copyright file="Program.cs"> This code is protected under the MIT License. </copyright> using System; using System.Collections.Generic; using CardsLibrary; namespace ConsoleTesting { /// <summary> /// The main program (for testing at the moment). /// </summary> public class Program { /// <summary> /// The main entry point for the program. /// </summary> /// <param name="args"> Any arguments/commands that the program is run/compiled with. </param> public static void Main(string[] args) { List<Card> deck = CardFactory.PopulateDeck(true); List<CardGames.Whist.ConsolePlayer> players = new List<CardGames.Whist.ConsolePlayer>(); Card[][] tempPlayers = CardFactory.Deal(ref deck, 2, 7); players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[0])); players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[1])); CardGames.Whist.WhistInfo gameInfo = new CardGames.Whist.WhistInfo(); gameInfo.CardsInPlay = new List<Card>(); gameInfo.Trumps = Suit.Clubs; gameInfo.FirstSuitLaid = Suit.Null; players[0].MakeMove(gameInfo); Console.WriteLine(); Console.WriteLine(); players[1].MakeMove(gameInfo); } } } ```
9fa033b5-b40c-4da6-8d14-3bf912c64528
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using PlayerRank.Scoring; namespace PlayerRank { public class League { private readonly List<Game> m_Games = new List<Game>(); public IEnumerable<PlayerScore> GetLeaderBoard(IScoringStrategy scoringStrategy) { IList<PlayerScore> leaderBoard = new List<PlayerScore>(); m_Games.Aggregate(leaderBoard, scoringStrategy.UpdateScores); return leaderBoard; } public void RecordGame(Game game) { m_Games.Add(game); } } }``` Call reset before calculating leaderboard
```c# using System.Collections.Generic; using System.Linq; using PlayerRank.Scoring; namespace PlayerRank { public class League { private readonly List<Game> m_Games = new List<Game>(); public IEnumerable<PlayerScore> GetLeaderBoard(IScoringStrategy scoringStrategy) { scoringStrategy.Reset(); IList<PlayerScore> leaderBoard = new List<PlayerScore>(); m_Games.Aggregate(leaderBoard, scoringStrategy.UpdateScores); return leaderBoard; } public void RecordGame(Game game) { m_Games.Add(game); } } }```
50e74231-673e-4efb-9617-54bb56e7fd91
{ "language": "C#" }
```c# namespace NBench.VisualStudio.TestAdapter { using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using System; using System.Collections.Generic; public class NBenchTestDiscoverer : ITestDiscoverer { public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) { if (sources == null) { throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated."); } throw new NotImplementedException(); } } }``` Make the tests pertaining to an empty sources collection pass.
```c# namespace NBench.VisualStudio.TestAdapter { using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using System; using System.Collections.Generic; using System.Linq; public class NBenchTestDiscoverer : ITestDiscoverer { public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) { if (sources == null) { throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated."); } else if (!sources.Any()) { throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources"); } throw new NotImplementedException(); } } }```
c3c1fa75-729d-46b1-bd6b-d5bf7b183c8f
{ "language": "C#" }
```c# namespace NBench.VisualStudio.TestAdapter { using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using System; using System.Collections.Generic; using System.Linq; public class NBenchTestDiscoverer : ITestDiscoverer { public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) { if (sources == null) { throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated."); } else if (!sources.Any()) { throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources"); } else if (discoveryContext == null) { throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null."); } else if (logger == null) { throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null."); } throw new NotImplementedException(); } } }``` Make the tests pertaining to the test case discovery sink being null pass.
```c# namespace NBench.VisualStudio.TestAdapter { using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; using System; using System.Collections.Generic; using System.Linq; public class NBenchTestDiscoverer : ITestDiscoverer { public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) { if (sources == null) { throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated."); } else if (!sources.Any()) { throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources"); } else if (discoveryContext == null) { throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null."); } else if (logger == null) { throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null."); } else if (discoverySink == null) { throw new ArgumentNullException( "discoverySink", "The test case discovery sink you have passed in is null. The test case discovery sink must not be null."); } throw new NotImplementedException(); } } }```
d05b5370-fd5b-4a8d-b7ba-6c1cc8a5e063
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Reflection.Emit.Tests { public class PropertyBuilderTest9 { public static IEnumerable<object[]> Names_TestData() { yield return new object[] { "TestName" }; yield return new object[] { "class" }; yield return new object[] { new string('a', short.MaxValue) }; } [Theory] [MemberData(nameof(Names_TestData))] public void Name(string name) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public); PropertyBuilder property = type.DefineProperty(name, PropertyAttributes.None, typeof(int), null); Assert.Equal(name, property.Name); } [Fact] public void Name_InvalidString() { // TODO: move into Names_TestData when #7166 is fixed Name("1A\0\t\v\r\n\n\uDC81\uDC91"); } } } ``` Add some more tests for PropertyBuilder.Name
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Reflection.Emit.Tests { public class PropertyBuilderTest9 { public static IEnumerable<object[]> Names_TestData() { yield return new object[] { "TestName" }; yield return new object[] { "\uD800\uDC00" }; yield return new object[] { "привет" }; yield return new object[] { "class" }; yield return new object[] { new string('a', short.MaxValue) }; } [Theory] [MemberData(nameof(Names_TestData))] public void Name(string name) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public); PropertyBuilder property = type.DefineProperty(name, PropertyAttributes.None, typeof(int), null); Assert.Equal(name, property.Name); } [Fact] public void Name_InvalidString() { // TODO: move into Names_TestData when #7166 is fixed Name("\uDC00"); Name("\uD800"); Name("1A\0\t\v\r\n\n\uDC81\uDC91"); } } } ```
125666f8-7829-47eb-aeb6-7489622f1b43
{ "language": "C#" }
```c# // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. using System; using PInvoke; using Xunit; using static PInvoke.DwmApi; public class DwmApiFacts { [Fact] public void Flush() { DwmFlush().ThrowOnFailure(); } [Fact] public void GetColorizationColor() { uint colorization; bool opaqueBlend; DwmGetColorizationColor(out colorization, out opaqueBlend).ThrowOnFailure(); Assert.NotEqual(colorization, 0u); } } ``` Fix test failure on CI
```c# // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. using System; using PInvoke; using Xunit; using static PInvoke.DwmApi; public class DwmApiFacts { [Fact] public void Flush() { HResult hr = DwmFlush(); // Accept success, or "Desktop composition is disabled". if (hr.AsUInt32 != 0x80263001) { hr.ThrowOnFailure(); } } [Fact] public void GetColorizationColor() { uint colorization; bool opaqueBlend; DwmGetColorizationColor(out colorization, out opaqueBlend).ThrowOnFailure(); } } ```
9b67bf30-3ff6-420f-8b86-822a578f9c2b
{ "language": "C#" }
```c# @model CRP.Controllers.ViewModels.ReportViewModel @{ ViewBag.Title = "ViewReport"; } <div class="boundary"> <p> @Html.ActionLink("Back to Item", "Details", "ItemManagement", null, null, "Reports", new { id = Model.ItemId }, null) | @Html.ActionLink("Generate Excel Report", "CreateExcelReport", "Excel", new { id = Model.ItemReportId, itemId = Model.ItemId }, null) </p> <hr/> <h2>@Model.ReportName</h2> <table id="table" class="table table-bordered"> <thead> <tr> @foreach (var ch in Model.ColumnNames) { <td>@ch</td> } </tr> </thead> <tbody> @foreach (var row in Model.RowValues) { <tr> @foreach (var cell in row) { <td>@cell</td> } </tr> } </tbody> </table> </div> @section AdditionalScripts { <script type="text/javascript"> $(function() { $("#table").dataTable({ responsive: true }); }); </script> } ``` Make generate Excel action a button
```c# @model CRP.Controllers.ViewModels.ReportViewModel @{ ViewBag.Title = "ViewReport"; } <div class="boundary"> <p> @Html.ActionLink("Generate Excel Report", "CreateExcelReport", "Excel", new { id = Model.ItemReportId, itemId = Model.ItemId }, new { @class = "btn" }) </p> <p>@Html.ActionLink("Back to Item", "Details", "ItemManagement", null, null, "Reports", new { id = Model.ItemId }, null)</p> <hr/> <h2>@Model.ReportName</h2> <table id="table" class="table table-bordered"> <thead> <tr> @foreach (var ch in Model.ColumnNames) { <td>@ch</td> } </tr> </thead> <tbody> @foreach (var row in Model.RowValues) { <tr> @foreach (var cell in row) { <td>@cell</td> } </tr> } </tbody> </table> </div> @section AdditionalScripts { <script type="text/javascript"> $(function() { $("#table").dataTable({ responsive: true }); }); </script> } ```
52aac3b3-f260-4b62-b03d-2c62fcf9df1f
{ "language": "C#" }
```c# using MbCache.Logic; namespace MbCache.Configuration { /// <summary> /// Creates the proxy. /// The implementation of this interface needs a default ctor /// </summary> public interface IProxyFactory { /// <summary> /// Called once after this object is instansiated. /// </summary> void Initialize(CacheAdapter cache); /// <summary> /// Creates the proxy. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="configurationForType">The method data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> T CreateProxy<T>(ConfigurationForType configurationForType, params object[] parameters) where T : class; /// <summary> /// Creates the proxy with a specified target. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uncachedComponent"></param> /// <param name="configurationForType"></param> /// <returns></returns> T CreateProxyWithTarget<T>(T uncachedComponent, ConfigurationForType configurationForType) where T : class; } }``` Remove no longer valid comment
```c# using MbCache.Logic; namespace MbCache.Configuration { /// <summary> /// Creates the proxy. /// </summary> public interface IProxyFactory { /// <summary> /// Called once after this object is instansiated. /// </summary> void Initialize(CacheAdapter cache); /// <summary> /// Creates the proxy. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="configurationForType">The method data.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> T CreateProxy<T>(ConfigurationForType configurationForType, params object[] parameters) where T : class; /// <summary> /// Creates the proxy with a specified target. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="uncachedComponent"></param> /// <param name="configurationForType"></param> /// <returns></returns> T CreateProxyWithTarget<T>(T uncachedComponent, ConfigurationForType configurationForType) where T : class; } }```
714f7016-4edf-485a-83f7-03d3d48f25d4
{ "language": "C#" }
```c# using System.Reflection; 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("libgit2sharp.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("libgit2sharp.Tests")] [assembly: AssemblyCopyright("Copyright © 2010")] [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("808554a4-f9fd-4035-8ab9-325793c7da51")] // 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")] ``` Disable test parallelization to avoid test failures
```c# using System.Reflection; using System.Runtime.InteropServices; using Xunit; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("libgit2sharp.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("libgit2sharp.Tests")] [assembly: AssemblyCopyright("Copyright © 2010")] [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("808554a4-f9fd-4035-8ab9-325793c7da51")] // 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")] [assembly: CollectionBehavior(DisableTestParallelization = true)] ```
59ebb1bb-7431-48a5-a99e-f8a0afbb9333
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="https://martincostello.com/"> // Martin Costello (c) 2016 // </copyright> // <summary> // Program.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace MartinCostello.Api { using System; using System.IO; using System.Threading; using Microsoft.AspNetCore.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> public static void Main(string[] args) { // TODO Also use command-line arguments var builder = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>(); using (CancellationTokenSource tokenSource = new CancellationTokenSource()) { Console.CancelKeyPress += (_, e) => { tokenSource.Cancel(); e.Cancel = true; }; using (var host = builder.Build()) { host.Run(tokenSource.Token); } } } } } ``` Handle application errors more gracefully
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="Program.cs" company="https://martincostello.com/"> // Martin Costello (c) 2016 // </copyright> // <summary> // Program.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace MartinCostello.Api { using System; using System.IO; using System.Threading; using Microsoft.AspNetCore.Hosting; /// <summary> /// A class representing the entry-point to the application. This class cannot be inherited. /// </summary> public static class Program { /// <summary> /// The main entry-point to the application. /// </summary> /// <param name="args">The arguments to the application.</param> /// <returns> /// The exit code from the application. /// </returns> public static int Main(string[] args) { try { // TODO Also use command-line arguments var builder = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>(); using (CancellationTokenSource tokenSource = new CancellationTokenSource()) { Console.CancelKeyPress += (_, e) => { tokenSource.Cancel(); e.Cancel = true; }; using (var host = builder.Build()) { host.Run(tokenSource.Token); } return 0; } } catch (Exception ex) { Console.Error.WriteLine($"Unhandled exception: {ex}"); return -1; } } } } ```
ca1225ad-89bd-4b7b-a3d0-23b16be117eb
{ "language": "C#" }
```c# using System; namespace Sakuno.ING.Game.Models { public sealed class PlayerShipSlot : Slot { public PlayerShip Owner { get; } public int Index { get; } public override SlotItem? Item => _slotItem; private PlayerSlotItem? _slotItem; public PlayerSlotItem? PlayerSlotItem { get => _slotItem; internal set => Set(ref _slotItem, value); } public PlayerShipSlot(PlayerShip owner, int index) { Owner = owner; Index = index; } } } ``` Add slot property changed notification
```c# using System; namespace Sakuno.ING.Game.Models { public sealed class PlayerShipSlot : Slot { public PlayerShip Owner { get; } public int Index { get; } public override SlotItem? Item => _slotItem; private PlayerSlotItem? _slotItem; public PlayerSlotItem? PlayerSlotItem { get => _slotItem; internal set { Set(ref _slotItem, value); NotifyPropertyChanged(nameof(Item)); } } public PlayerShipSlot(PlayerShip owner, int index) { Owner = owner; Index = index; } } } ```
8b38f474-4f74-4f76-8c25-147fe0f3918c
{ "language": "C#" }
```c# namespace DanTup.DartVS.ProjectSystem { using Microsoft.VisualStudio.Project; public class DartProjectConfig : ProjectConfig { internal DartProjectConfig(DartProjectNode project, string configuration, string platform) : base(project, configuration, platform) { } public new DartProjectNode ProjectManager { get { return (DartProjectNode)base.ProjectManager; } } public override void Invalidate() { base.Invalidate(); } } } ``` Disable run/debug commands for Dart projects
```c# namespace DanTup.DartVS.ProjectSystem { using Microsoft.VisualStudio; using Microsoft.VisualStudio.Project; public class DartProjectConfig : ProjectConfig { internal DartProjectConfig(DartProjectNode project, string configuration, string platform) : base(project, configuration, platform) { } public new DartProjectNode ProjectManager { get { return (DartProjectNode)base.ProjectManager; } } public override void Invalidate() { base.Invalidate(); } public override int QueryDebugLaunch(uint flags, out int fCanLaunch) { fCanLaunch = 0; return VSConstants.S_OK; } } } ```
eab51355-f4ea-4a81-9585-692cf0274ad4
{ "language": "C#" }
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace borkedLabs.CrestScribe { public class ScribeQueryWorker { private BlockingCollection<SsoCharacter> _queryQueue; private CancellationToken _cancelToken; public Thread Thread { get; private set; } public ScribeQueryWorker(BlockingCollection<SsoCharacter> queryQueue, CancellationToken cancelToken) { _queryQueue = queryQueue; _cancelToken = cancelToken; Thread = new Thread(_worker); Thread.Name = "scribe query worker"; Thread.IsBackground = true; } public void Start() { Thread.Start(); } private void _worker() { while (!_cancelToken.IsCancellationRequested) { var character = _queryQueue.Take(_cancelToken); if(character != null) { try { var t = Task.Run(character.Poll,_cancelToken); t.Wait(_cancelToken); } catch (MySql.Data.MySqlClient.MySqlException ex) { switch (ex.Number) { case 0: //no connect case (int)MySql.Data.MySqlClient.MySqlErrorCode.UnableToConnectToHost: //catch these silently, the main service thread will do magic to cancel out everything break; default: throw ex; break; } } catch(System.OperationCanceledException) { break; } } } } } } ``` Move the blockingcollection take to inside the try catch
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace borkedLabs.CrestScribe { public class ScribeQueryWorker { private BlockingCollection<SsoCharacter> _queryQueue; private CancellationToken _cancelToken; public Thread Thread { get; private set; } public ScribeQueryWorker(BlockingCollection<SsoCharacter> queryQueue, CancellationToken cancelToken) { _queryQueue = queryQueue; _cancelToken = cancelToken; Thread = new Thread(_worker); Thread.Name = "scribe query worker"; Thread.IsBackground = true; } public void Start() { Thread.Start(); } private void _worker() { while (!_cancelToken.IsCancellationRequested) { try { var character = _queryQueue.Take(_cancelToken); if(character != null) { var t = Task.Run(character.Poll,_cancelToken); t.Wait(_cancelToken); } } catch (MySql.Data.MySqlClient.MySqlException ex) { switch (ex.Number) { case 0: //no connect case (int)MySql.Data.MySqlClient.MySqlErrorCode.UnableToConnectToHost: //catch these silently, the main service thread will do magic to cancel out everything break; default: throw ex; } } catch (System.OperationCanceledException) { break; } } } } } ```
e5cc09eb-460b-4b40-bce4-e6056b3efb26
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Okra.TodoSample.Data { [Export(typeof(ITodoRepository))] public class TodoRepository : ITodoRepository { private IList<TodoItem> todoItems; public TodoRepository() { this.todoItems = new List<TodoItem> { new TodoItem() { Id = "1", Title = "First item"}, new TodoItem() { Id = "2", Title = "Second item"}, new TodoItem() { Id = "3", Title = "Third item"} }; } public TodoItem GetTodoItemById(string id) { return todoItems.Where(item => item.Id == id).FirstOrDefault(); } public IList<TodoItem> GetTodoItems() { return todoItems; } public void AddTodoItem(TodoItem todoItem) { this.todoItems.Add(todoItem); } public void RemoveTodoItem(TodoItem todoItem) { this.todoItems.Remove(todoItem); } } } ``` Fix AddTodoItem to autoincrement the item id
```c# using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Okra.TodoSample.Data { [Export(typeof(ITodoRepository))] public class TodoRepository : ITodoRepository { private IList<TodoItem> todoItems; private int nextId = 4; public TodoRepository() { this.todoItems = new List<TodoItem> { new TodoItem() { Id = "1", Title = "First item"}, new TodoItem() { Id = "2", Title = "Second item"}, new TodoItem() { Id = "3", Title = "Third item"} }; } public TodoItem GetTodoItemById(string id) { return todoItems.Where(item => item.Id == id).FirstOrDefault(); } public IList<TodoItem> GetTodoItems() { return todoItems; } public void AddTodoItem(TodoItem todoItem) { todoItem.Id = (nextId++).ToString(); this.todoItems.Add(todoItem); } public void RemoveTodoItem(TodoItem todoItem) { this.todoItems.Remove(todoItem); } } } ```
f759d912-a160-4db6-8625-bca19cf2b123
{ "language": "C#" }
```c# using System; using System.Linq; namespace Modix.Data.Utilities { public static class Extensions { public static string Truncate(this string value, int maxLength, int maxLines, string suffix = "…") { if (string.IsNullOrEmpty(value)) return value; if (value.Length <= maxLength) { return value; } var lines = value.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return lines.Length > maxLines ? string.Join("\n", lines.Take(maxLines)) : $"{value.Substring(0, maxLength).Trim()}{suffix}"; } public static bool OrdinalContains(this string value, string search) { return value.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0; } } } ``` Fix "Value cannot be null." error
```c# using System; using System.Linq; namespace Modix.Data.Utilities { public static class Extensions { public static string Truncate(this string value, int maxLength, int maxLines, string suffix = "…") { if (string.IsNullOrEmpty(value)) return value; if (value.Length <= maxLength) { return value; } var lines = value.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return lines.Length > maxLines ? string.Join("\n", lines.Take(maxLines)) : $"{value.Substring(0, maxLength).Trim()}{suffix}"; } public static bool OrdinalContains(this string value, string search) { if (value is null || search is null) return false; return value.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0; } } } ```
21f73824-8d4d-40b6-a823-1ff9cce734bc
{ "language": "C#" }
```c# using System.IO; using System.Linq; using ICSharpCode.SharpZipLib.Tar; namespace AppHarbor { public static class CompressionExtensions { public static void ToTar(this DirectoryInfo sourceDirectory, Stream output) { var archive = TarArchive.CreateOutputTarArchive(output); archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/'); var entries = from x in sourceDirectory.GetFiles("*", SearchOption.AllDirectories) select TarEntry.CreateEntryFromFile(x.FullName); foreach (var entry in entries) { archive.WriteEntry(entry, true); } archive.Close(); } } } ``` Refactor to use own method for getting files recursively
```c# using System.Collections.Generic; using System.IO; using System.Linq; using ICSharpCode.SharpZipLib.Tar; namespace AppHarbor { public static class CompressionExtensions { public static void ToTar(this DirectoryInfo sourceDirectory, Stream output) { var archive = TarArchive.CreateOutputTarArchive(output); archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/'); var entries = GetFiles(sourceDirectory).Select(x => TarEntry.CreateEntryFromFile(x.FullName)); foreach (var entry in entries) { archive.WriteEntry(entry, true); } archive.Close(); } private static FileInfo[] GetFiles(DirectoryInfo directory) { var files = directory.GetFiles("*", SearchOption.TopDirectoryOnly); foreach (var nestedDirectory in directory.GetDirectories()) { files.Concat(GetFiles(nestedDirectory)); } return files; } } } ```
3e635667-a57e-4a25-8211-0dbeb4b3cea3
{ "language": "C#" }
```c# // 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.Graphics; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Multiplayer.Match; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene { [SetUp] public new void Setup() => Schedule(() => { SelectedRoom.Value = new Room(); Child = new MultiplayerMatchFooter { Anchor = Anchor.Centre, Origin = Anchor.Centre, Height = 50 }; }); } } ``` Fix match footer test scene not working in visual testing
```c# // 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.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Multiplayer.Match; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene { [SetUp] public new void Setup() => Schedule(() => { SelectedRoom.Value = new Room(); Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = 50, Child = new MultiplayerMatchFooter() }; }); } } ```
3655d72c-bbe4-47d9-8f05-58b90f6ac7c7
{ "language": "C#" }
```c# // 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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { [Benchmark(Baseline = true)] public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy(); [Benchmark] public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy(); private class BindableOld<T> : Bindable<T> { public BindableOld(T defaultValue = default) : base(defaultValue) { } protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value); } } } ``` Add basic bindable instantiation benchmark
```c# // 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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { [MemoryDiagnoser] public class BenchmarkBindableInstantiation { [Benchmark] public Bindable<int> Instantiate() => new Bindable<int>(); [Benchmark] public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy(); [Benchmark(Baseline = true)] public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy(); private class BindableOld<T> : Bindable<T> { public BindableOld(T defaultValue = default) : base(defaultValue) { } protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value); } } } ```
cc94b057-3633-46bf-85d7-081076f44b08
{ "language": "C#" }
```c# using Bit.Core.Contracts; using Bit.Core.Models; using System.Data.SqlClient; using System.Threading.Tasks; namespace Bit.Data.Implementations { public class SqlServerJsonLogStore : ILogStore { public virtual AppEnvironment ActiveAppEnvironment { get; set; } public virtual IContentFormatter Formatter { get; set; } public void SaveLog(LogEntry logEntry) { using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring"))) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)"; command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry)); connection.Open(); command.ExecuteNonQuery(); } } } public virtual async Task SaveLogAsync(LogEntry logEntry) { using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring"))) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)"; command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry)); await connection.OpenAsync(); await command.ExecuteNonQueryAsync(); } } } } } ``` Use configureAwait(false) for sql server json log store
```c# using Bit.Core.Contracts; using Bit.Core.Models; using System.Data.SqlClient; using System.Threading.Tasks; namespace Bit.Data.Implementations { public class SqlServerJsonLogStore : ILogStore { public virtual AppEnvironment ActiveAppEnvironment { get; set; } public virtual IContentFormatter Formatter { get; set; } public void SaveLog(LogEntry logEntry) { using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring"))) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)"; command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry)); connection.Open(); command.ExecuteNonQuery(); } } } public virtual async Task SaveLogAsync(LogEntry logEntry) { using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring"))) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)"; command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry)); await connection.OpenAsync().ConfigureAwait(false); await command.ExecuteNonQueryAsync().ConfigureAwait(false); } } } } } ```
de79ffcc-8a3d-410f-aa1e-4d0a1fc36fcd
{ "language": "C#" }
```c# using System.IO; using System.Text; using Mapsui.Extensions; using Mapsui.Styles; using SkiaSharp; using Svg.Skia; namespace Mapsui.Rendering.Skia { public static class BitmapHelper { public static BitmapInfo LoadBitmap(object bitmapData) { // todo: Our BitmapRegistry stores not only bitmaps. Perhaps we should store a class in it // which has all information. So we should have a SymbolImageRegistry in which we store a // SymbolImage. Which holds the type, data and other parameters. if (bitmapData is string str) { if (str.ToLower().Contains("<svg")) { var svg = new SKSvg(); svg.FromSvg(str); return new BitmapInfo { Svg = svg }; } } if (bitmapData is Stream stream) { if (stream.IsSvg()) { var svg = new SKSvg(); svg.Load(stream); return new BitmapInfo {Svg = svg}; } var image = SKImage.FromEncodedData(SKData.CreateCopy(stream.ToBytes())); return new BitmapInfo {Bitmap = image}; } if (bitmapData is Sprite sprite) { return new BitmapInfo {Sprite = sprite}; } return null; } } }``` Revert "Changed name for bitmap data from bitmapStream to bitmapData, because bitmapStream is misleading."
```c# using System.IO; using System.Text; using Mapsui.Extensions; using Mapsui.Styles; using SkiaSharp; using Svg.Skia; namespace Mapsui.Rendering.Skia { public static class BitmapHelper { public static BitmapInfo LoadBitmap(object bitmapStream) { // todo: Our BitmapRegistry stores not only bitmaps. Perhaps we should store a class in it // which has all information. So we should have a SymbolImageRegistry in which we store a // SymbolImage. Which holds the type, data and other parameters. if (bitmapStream is string str) { if (str.ToLower().Contains("<svg")) { var svg = new SKSvg(); svg.FromSvg(str); return new BitmapInfo { Svg = svg }; } } if (bitmapStream is Stream stream) { if (stream.IsSvg()) { var svg = new SKSvg(); svg.Load(stream); return new BitmapInfo {Svg = svg}; } var image = SKImage.FromEncodedData(SKData.CreateCopy(stream.ToBytes())); return new BitmapInfo {Bitmap = image}; } if (bitmapStream is Sprite sprite) { return new BitmapInfo {Sprite = sprite}; } return null; } } }```
3daf869b-4f73-4e2c-bc18-8f0114097ee2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using NewPackageAction = NuGet.Client.Resolution.PackageAction; namespace NuGet.Client.Installation { public class UninstallActionHandler : IActionHandler { public Task Execute(NewPackageAction action, IExecutionLogger logger, CancellationToken cancelToken) { return Task.Run(() => { // Get the project manager var projectManager = action.Target.GetRequiredFeature<IProjectManager>(); // Get the package out of the project manager var package = projectManager.LocalRepository.FindPackage( action.PackageIdentity.Id, CoreConverters.SafeToSemVer(action.PackageIdentity.Version)); Debug.Assert(package != null); // Add the package to the project projectManager.Logger = new ShimLogger(logger); projectManager.Execute(new PackageOperation( package, NuGet.PackageAction.Uninstall)); // Run uninstall.ps1 if present ActionHandlerHelpers.ExecutePowerShellScriptIfPresent( "uninstall.ps1", action.Target, package, projectManager.PackageManager.PathResolver.GetInstallPath(package), logger); }); } public Task Rollback(NewPackageAction action, IExecutionLogger logger) { // Just run the install action to undo a uninstall return new InstallActionHandler().Execute(action, logger, CancellationToken.None); } } } ``` Fix uninstall for project k projects
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using NewPackageAction = NuGet.Client.Resolution.PackageAction; namespace NuGet.Client.Installation { public class UninstallActionHandler : IActionHandler { public Task Execute(NewPackageAction action, IExecutionLogger logger, CancellationToken cancelToken) { var nugetAware = action.Target.TryGetFeature<NuGetAwareProject>(); if (nugetAware != null) { return nugetAware.UninstallPackage( action.PackageIdentity, logger, cancelToken); } return Task.Run(() => { // Get the project manager var projectManager = action.Target.GetRequiredFeature<IProjectManager>(); // Get the package out of the project manager var package = projectManager.LocalRepository.FindPackage( action.PackageIdentity.Id, CoreConverters.SafeToSemVer(action.PackageIdentity.Version)); Debug.Assert(package != null); // Add the package to the project projectManager.Logger = new ShimLogger(logger); projectManager.Execute(new PackageOperation( package, NuGet.PackageAction.Uninstall)); // Run uninstall.ps1 if present ActionHandlerHelpers.ExecutePowerShellScriptIfPresent( "uninstall.ps1", action.Target, package, projectManager.PackageManager.PathResolver.GetInstallPath(package), logger); }); } public Task Rollback(NewPackageAction action, IExecutionLogger logger) { // Just run the install action to undo a uninstall return new InstallActionHandler().Execute(action, logger, CancellationToken.None); } } } ```
744c6a44-48a1-49b1-8ffe-1defe588baf1
{ "language": "C#" }
```c# using System; using System.ComponentModel.DataAnnotations; namespace SpaceBlog.Models { public class Article { public Article() { Date = DateTime.Now; } [Key] public int Id { get; set; } [Required] [MaxLength(50)] public string Title { get; set; } [Required] public string Content { get; set; } public DateTime Date { get; set; } //public virtual IEnumerable<Comment> Comments { get; set; } //public Category Category { get; set; } //public virtual IEnumerable<Tag> Tags { get; set; } public ApplicationUser Author { get; set; } } }``` Create Error message in Title
```c# using System; using System.ComponentModel.DataAnnotations; namespace SpaceBlog.Models { public class Article { public Article() { Date = DateTime.Now; } [Key] public int Id { get; set; } [Required] [MaxLength(50, ErrorMessage = "The Title must be text with maximum 50 characters.")] public string Title { get; set; } [Required] public string Content { get; set; } public DateTime Date { get; set; } //public virtual IEnumerable<Comment> Comments { get; set; } //public Category Category { get; set; } //public virtual IEnumerable<Tag> Tags { get; set; } public ApplicationUser Author { get; set; } } }```
9f2075de-1c44-42aa-b1f5-b21640909ffd
{ "language": "C#" }
```c#  @{ ViewBag.Title = "Resume"; } <div class="col-sm-8 col-sm-offset-2"> <div class="col-xs-12 col-sm-6 col-sm-offset-3 list-group" id="aboutButtonGroup"> <button type="button" class="list-group-item storyList" id="2015"><p class="text-center">2015</p></button> <button type="button" class="list-group-item storyList" id="2014"><p class="text-center">2014</p></button> <button type="button" class="list-group-item storyList" id="2013"><p class="text-center">2013</p></button> <button type="button" class="list-group-item storyList" id="2012"><p class="text-center">2012</p></button> <button type="button" class="list-group-item storyList" id="2011"><p class="text-center">2011</p></button> </div> </div> <div class="col-xs-12 col-sm-10 col-sm-offset-1 text-center"> <p class="white">To view the PDF version of my resume click <a href="#" id="pdfLink">here</a>.</p> </div> <div></div>``` Change to jobs on resume page
```c#  @{ ViewBag.Title = "Resume"; } <div class="col-sm-8 col-sm-offset-2"> <div class="col-xs-12 col-sm-6 col-sm-offset-3 list-group" id="aboutButtonGroup"> <button type="button" class="list-group-item storyList" id="2015"><p class="text-center">Information Technology Intern</p></button> <button type="button" class="list-group-item storyList" id="2014"><p class="text-center">Web Developer Intern</p></button> <button type="button" class="list-group-item storyList" id="2013"><p class="text-center">Unit Deployment Manager</p></button> <button type="button" class="list-group-item storyList" id="2012"><p class="text-center">Hydraulic Systems Journeyman</p></button> </div> </div> <div class="col-xs-12 col-sm-10 col-sm-offset-1 text-center"> <p class="white">To view the PDF version of my resume click <a href="#" id="pdfLink">here</a>.</p> </div> <div></div>```
5cbbb869-c5b0-4c15-a8cb-526b1dd30b23
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Framework.Platform; using osu.Framework.Screens.Testing; namespace osu.Framework.VisualTests { internal class VisualTestGame : Game { [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { new TestBrowser(), new CursorContainer(), }; } protected override void LoadComplete() { base.LoadComplete(); Host.Window.CursorState = CursorState.Hidden; } } } ``` Move mouse state setting to SetHost.
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Framework.Platform; using osu.Framework.Screens.Testing; namespace osu.Framework.VisualTests { internal class VisualTestGame : Game { [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { new TestBrowser(), new CursorContainer(), }; } public override void SetHost(GameHost host) { base.SetHost(host); host.Window.CursorState = CursorState.Hidden; } } } ```
04002849-d1b9-4f73-bdc0-d2f9e8bf9bdd
{ "language": "C#" }
```c# using AvalonStudio.Extensibility; using AvalonStudio.Shell; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WalletWasabi.Blockchain.TransactionBuilding; using WalletWasabi.Gui.Helpers; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class BuildTabViewModel : SendControlViewModel { public override string DoButtonText => "Build Transaction"; public override string DoingButtonText => "Building Transaction..."; public BuildTabViewModel(WalletViewModel walletViewModel) : base(walletViewModel, "Build Transaction") { } protected override Task DoAfterBuildTransaction(BuildTransactionResult result) { try { var txviewer = IoC.Get<IShell>().Documents?.OfType<TransactionViewerViewModel>()?.FirstOrDefault(x => x.Wallet.Id == Wallet.Id); if (txviewer is null) { txviewer = new TransactionViewerViewModel(Wallet); IoC.Get<IShell>().AddDocument(txviewer); } IoC.Get<IShell>().Select(txviewer); txviewer.Update(result); ResetUi(); NotificationHelpers.Success("Transaction is successfully built!", ""); } catch (Exception ex) { return Task.FromException(ex); } return Task.CompletedTask; } } } ``` Fix the wording at tx build
```c# using AvalonStudio.Extensibility; using AvalonStudio.Shell; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WalletWasabi.Blockchain.TransactionBuilding; using WalletWasabi.Gui.Helpers; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class BuildTabViewModel : SendControlViewModel { public override string DoButtonText => "Build Transaction"; public override string DoingButtonText => "Building Transaction..."; public BuildTabViewModel(WalletViewModel walletViewModel) : base(walletViewModel, "Build Transaction") { } protected override Task DoAfterBuildTransaction(BuildTransactionResult result) { try { var txviewer = IoC.Get<IShell>().Documents?.OfType<TransactionViewerViewModel>()?.FirstOrDefault(x => x.Wallet.Id == Wallet.Id); if (txviewer is null) { txviewer = new TransactionViewerViewModel(Wallet); IoC.Get<IShell>().AddDocument(txviewer); } IoC.Get<IShell>().Select(txviewer); txviewer.Update(result); ResetUi(); NotificationHelpers.Success("Transaction was built!"); } catch (Exception ex) { return Task.FromException(ex); } return Task.CompletedTask; } } } ```
9a027578-bea0-4655-88f6-8d7d6f1d2f80
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Orchard.UI.Resources; namespace Orchard.Packaging { public class ResourceManifest : IResourceManifestProvider { public void BuildManifests(ResourceManifestBuilder builder) { builder.Add().DefineStyle("PackagingAdmin").SetUrl("admin.css"); } } } ``` Fix resource manifest for gallery -- should enable with the Gallery feature
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Orchard.Environment.Extensions; using Orchard.UI.Resources; namespace Orchard.Packaging { [OrchardFeature("Gallery")] public class ResourceManifest : IResourceManifestProvider { public void BuildManifests(ResourceManifestBuilder builder) { builder.Add().DefineStyle("PackagingAdmin").SetUrl("admin.css"); } } } ```
bfd51232-85ae-4785-b8d4-4691217f6bb5
{ "language": "C#" }
```c# namespace Stripe.Terminal { using System; using Newtonsoft.Json; public class ReaderListOptions : ListOptions { /// <summary> /// A location ID to filter the response list to only readers at the specific location. /// </summary> [JsonProperty("location")] public string Location { get; set; } /// <summary> /// A status filter to filter readers to only offline or online readers. Possible values /// are <c>offline</c> and <c>online</c>. /// </summary> [JsonProperty("status")] public string Status { get; set; } } } ``` Add `DeviceType` filter when listing Terminal `Reader`s
```c# namespace Stripe.Terminal { using System; using Newtonsoft.Json; public class ReaderListOptions : ListOptions { /// <summary> /// Filters readers by device type. /// </summary> [JsonProperty("device_type")] public string DeviceType { get; set; } /// <summary> /// A location ID to filter the response list to only readers at the specific location. /// </summary> [JsonProperty("location")] public string Location { get; set; } /// <summary> /// A status filter to filter readers to only offline or online readers. Possible values /// are <c>offline</c> and <c>online</c>. /// </summary> [JsonProperty("status")] public string Status { get; set; } } } ```
4f196e43-7e64-4c0e-aecd-8955c63d13de
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace _4OpEenRijScreensaver { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_KeyDown(object sender, KeyEventArgs e) { App.Current.Shutdown(); } private void Window_MouseDown(object sender, MouseButtonEventArgs e) { App.Current.Shutdown(); } Point _mousePos; private void Window_MouseMove(object sender, MouseEventArgs e) { if (_mousePos != default(Point) && _mousePos != e.GetPosition(MainWindowWindow)) App.Current.Shutdown(); _mousePos = e.GetPosition(MainWindowWindow); } } } ``` Disable exit on mousemove/keypress in DEBUG
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace _4OpEenRijScreensaver { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_KeyDown(object sender, KeyEventArgs e) { #if !DEBUG App.Current.Shutdown(); #endif } private void Window_MouseDown(object sender, MouseButtonEventArgs e) { App.Current.Shutdown(); } Point _mousePos; private void Window_MouseMove(object sender, MouseEventArgs e) { #if !DEBUG if (_mousePos != default(Point) && _mousePos != e.GetPosition(MainWindowWindow)) App.Current.Shutdown(); _mousePos = e.GetPosition(MainWindowWindow); #endif } } } ```
7753b793-95b4-42d5-9fe8-eb8ebd38d156
{ "language": "C#" }
```c# using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; namespace Msiler.AssemblyParser { public class OpCodeInfo { public string Name { get; set; } public string Description { get; set; } } public static class Helpers { private static Dictionary<string, OpCodeInfo> ReadOpCodeInfoResource() { var reader = new StringReader(Resources.Instructions); var serializer = new XmlSerializer(typeof(List<OpCodeInfo>)); var list = (List<OpCodeInfo>)serializer.Deserialize(reader); return list.ToDictionary(i => i.Name, i => i); } private static readonly Dictionary<string, OpCodeInfo> OpCodesInfoCache = ReadOpCodeInfoResource(); public static OpCodeInfo GetInstructionInformation(string s) { if (OpCodesInfoCache.ContainsKey(s)) { return OpCodesInfoCache[s]; } return null; } public static string ReplaceNewLineCharacters(this string str) { return str.Replace("\n", @"\n").Replace("\r", @"\r"); } } } ``` Fix instruction help when "Upcase OpCode" option is enabled
```c# using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; namespace Msiler.AssemblyParser { public class OpCodeInfo { public string Name { get; set; } public string Description { get; set; } } public static class Helpers { private static Dictionary<string, OpCodeInfo> ReadOpCodeInfoResource() { var reader = new StringReader(Resources.Instructions); var serializer = new XmlSerializer(typeof(List<OpCodeInfo>)); var list = (List<OpCodeInfo>)serializer.Deserialize(reader); return list.ToDictionary(i => i.Name, i => i); } private static readonly Dictionary<string, OpCodeInfo> OpCodesInfoCache = ReadOpCodeInfoResource(); public static OpCodeInfo GetInstructionInformation(string s) { var instruction = s.ToLower(); if (OpCodesInfoCache.ContainsKey(instruction)) { return OpCodesInfoCache[instruction]; } return null; } public static string ReplaceNewLineCharacters(this string str) { return str.Replace("\n", @"\n").Replace("\r", @"\r"); } } } ```
7507ec91-dd18-4a88-bd5a-b9195a7d915b
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Burr.Tests { public class Readme { public Readme() { // create an anonymous client var client = new GitHubClient(); // create a client with basic auth client = new GitHubClient { Username = "tclem", Password = "pwd" }; // create a client with an oauth token client = new GitHubClient { Token = "oauthtoken" }; //// Authorizations API //var authorizations = client.Authorizations.All(); //var authorization = client.Authorizations.Get(1); //var authorization = client.Authorizations.Delete(1); //var a = client.Authorizations.Update(1, scopes: new[] { "user", "repo" }, "notes", "http://notes_url"); //var token = client.Authorizations.Create(new[] { "user", "repo" }, "notes", "http://notes_url"); //var gists = client.Gists.All(); //var gists = client.Gists.All("user"); //var gists = client.Gists.Public(); //var gists = client.Gists.Starred(); //var gist = client.Gists.Get(1); //client.Gists.Create(); } public async Task UserApi() { var client = new GitHubClient(); var user = await client.GetUserAsync("octocat"); } } } ``` Clarify api a bit in readme.cs
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Burr.Tests { public class Readme { public Readme() { // create an anonymous client var client = new GitHubClient(); // create a client with basic auth client = new GitHubClient { Username = "tclem", Password = "pwd" }; // create a client with an oauth token client = new GitHubClient { Token = "oauthtoken" }; //// Authorizations API //var authorizations = client.Authorizations.All(); //var authorization = client.Authorizations.Get(1); //var authorization = client.Authorizations.Delete(1); //var a = client.Authorizations.Update(1, scopes: new[] { "user", "repo" }, "notes", "http://notes_url"); //var token = client.Authorizations.Create(new[] { "user", "repo" }, "notes", "http://notes_url"); //var gists = client.Gists.All(); //var gists = client.Gists.All("user"); //var gists = client.Gists.Public(); //var gists = client.Gists.Starred(); //var gist = client.Gists.Get(1); //client.Gists.Create(); } public async Task UserApi() { var client = new GitHubClient{ Username = "octocat", Password = "pwd" }; // Get the authenticated user var authUser = await client.GetUserAsync(); // Get a user by username var user = await client.GetUserAsync("tclem"); } } } ```
9964bd7c-6624-4037-9021-e03c53b376b0
{ "language": "C#" }
```c# using System; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer.Initializers { public class RandomAlpha : IParticleInitializer { private readonly int alphaMin = 255; private readonly int alphaMax = 255; private readonly Random random; public RandomAlpha(IKeyValueCollection keyValue) { random = new Random(); if (keyValue.ContainsKey("m_nAlphaMin")) { alphaMin = (int)keyValue.GetIntegerProperty("m_nAlphaMin"); } if (keyValue.ContainsKey("m_nAlphaMax")) { alphaMax = (int)keyValue.GetIntegerProperty("m_nAlphaMax"); } } public Particle Initialize(Particle particle, ParticleSystemRenderState particleSystemRenderState) { var alpha = random.Next(alphaMin, alphaMax) / 255f; particle.ConstantAlpha = alpha; particle.Alpha = alpha; return particle; } } } ``` Fix alpha min/max order if wrong
```c# using System; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer.Initializers { public class RandomAlpha : IParticleInitializer { private readonly int alphaMin = 255; private readonly int alphaMax = 255; private readonly Random random; public RandomAlpha(IKeyValueCollection keyValue) { random = new Random(); if (keyValue.ContainsKey("m_nAlphaMin")) { alphaMin = (int)keyValue.GetIntegerProperty("m_nAlphaMin"); } if (keyValue.ContainsKey("m_nAlphaMax")) { alphaMax = (int)keyValue.GetIntegerProperty("m_nAlphaMax"); } if (alphaMin > alphaMax) { var temp = alphaMin; alphaMin = alphaMax; alphaMax = temp; } } public Particle Initialize(Particle particle, ParticleSystemRenderState particleSystemRenderState) { var alpha = random.Next(alphaMin, alphaMax) / 255f; particle.ConstantAlpha = alpha; particle.Alpha = alpha; return particle; } } } ```
5c862e65-e92c-41af-a4d9-d57389e89bb3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Web.Areas.Admin.Controllers { class ElmahResult : ActionResult { private string _resouceType; public ElmahResult(string resouceType) { _resouceType = resouceType; } public override void ExecuteResult(ControllerContext context) { var factory = new Elmah.ErrorLogPageFactory(); if (!string.IsNullOrEmpty(_resouceType)) { var pathInfo = "." + _resouceType; HttpContext.Current.RewritePath(HttpContext.Current.Request.Path, pathInfo, HttpContext.Current.Request.QueryString.ToString()); } var handler = factory.GetHandler(HttpContext.Current, null, null, null); handler.ProcessRequest(HttpContext.Current); } } public class ElmahController : Controller { public ActionResult Index(string type) { return new ElmahResult(type); } public ActionResult Detail(string type) { return new ElmahResult(type); } } } ``` Fix css styles in Elmah subpages
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Web.Areas.Admin.Controllers { class ElmahResult : ActionResult { private string _resouceType; public ElmahResult(string resouceType) { _resouceType = resouceType; } public override void ExecuteResult(ControllerContext context) { var factory = new Elmah.ErrorLogPageFactory(); if (!string.IsNullOrEmpty(_resouceType)) { var pathInfo = "." + _resouceType; HttpContext.Current.RewritePath(_resouceType != "stylesheet" ? HttpContext.Current.Request.Path.Replace(String.Format("/{0}", _resouceType), string.Empty) : HttpContext.Current.Request.Path, pathInfo, HttpContext.Current.Request.QueryString.ToString()); } var handler = factory.GetHandler(HttpContext.Current, null, null, null); handler.ProcessRequest(HttpContext.Current); } } public class ElmahController : Controller { public ActionResult Index(string type) { return new ElmahResult(type); } public ActionResult Detail(string type) { return new ElmahResult(type); } } } ```
43c15c7c-e66e-4b0f-b988-46f85d180218
{ "language": "C#" }
```c# // Copyright 2017 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NUnitLite; using System.Reflection; namespace NodaTime.Test { class Program { public static int Main(string[] args) { return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args); } } } ``` Update copyright in the test executable
```c# // <copyright file="Program.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2017 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using NUnitLite; using System.Reflection; namespace NodaTime.Test { class Program { public static int Main(string[] args) { return new AutoRun(typeof(Program).GetTypeInfo().Assembly).Execute(args); } } } ```
b058219b-ab67-43ed-ac08-16128a83a84b
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Windows; using System.Windows.Threading; namespace Homie.Common { public class ExceptionUtils { public enum ExitCodes { Ok = 0, UnhandledException = 91, UnobservedTaskException = 92, DispatcherUnhandledException = 93 } public static Exception UnwrapExceptionObject(object pException) { var lException = (Exception)pException; if (lException is TargetInvocationException && lException.InnerException is AggregateException) { return lException.InnerException; } return lException; } public static void ShowException(Exception pException) { var exception = UnwrapExceptionObject(pException); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() => { MessageBox.Show(String.Format("Unexpected error: {0}", exception.Message), Application.Current.MainWindow.GetType().Assembly.GetName().Name, MessageBoxButton.OK, MessageBoxImage.Error); })); } } } ``` Check if calling thread is already GUI thread when showing the global exception handler dialog.
```c# using System; using System.Reflection; using System.Windows; using System.Windows.Threading; namespace Homie.Common { public class ExceptionUtils { public enum ExitCodes { Ok = 0, UnhandledException = 91, UnobservedTaskException = 92, DispatcherUnhandledException = 93 } public static Exception UnwrapExceptionObject(object pException) { var lException = (Exception)pException; if (lException is TargetInvocationException && lException.InnerException is AggregateException) { return lException.InnerException; } return lException; } public static void ShowException(Exception pException) { var exception = UnwrapExceptionObject(pException); if (!Application.Current.Dispatcher.CheckAccess()) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() => { ShowExceptionMessageDialog(exception.Message); })); } else { ShowExceptionMessageDialog(exception.Message); } } private static void ShowExceptionMessageDialog(string errorMessage) { MessageBox.Show ( $"Unexpected error: {errorMessage}", Application.Current.MainWindow.GetType().Assembly.GetName().Name, MessageBoxButton.OK, MessageBoxImage.Error ); } } } ```
e541f509-4850-48e9-b910-4561f4b31811
{ "language": "C#" }
```c# using System; namespace DiscogsClient.Internal { public class TokenAuthenticationInformation { public string Token { get; set; } private string _secretToken; public TokenAuthenticationInformation(string token) { this.Token = token; _secretToken = $"Discogs token={_secretToken}"; } public string GetDiscogsSecretToken() { return _secretToken; } } } ``` Fix problem with token authentication
```c# using System; namespace DiscogsClient.Internal { public class TokenAuthenticationInformation { public string Token { get; set; } private string _secretToken; public TokenAuthenticationInformation(string token) { this.Token = token; _secretToken = $"Discogs token={token}"; } public string GetDiscogsSecretToken() { return _secretToken; } } } ```
22074d52-97ef-41a3-a84e-6fd93336d969
{ "language": "C#" }
```c# using System; using EvilDICOM.Core.Enums; namespace EvilDICOM.Core.IO.Data { public class DataRestriction { public static string EnforceLengthRestriction(uint lengthLimit, string data) { if (data.Length > lengthLimit) { Console.Write( "Not DICOM compliant. Attempted data input of {0} characters. Data size is limited to {1} characters. Read anyway.", data.Length, lengthLimit); return data; } return data; } public static byte[] EnforceEvenLength(byte[] data, VR vr) { switch (vr) { case VR.UniqueIdentifier: case VR.OtherByteString: case VR.Unknown: return DataPadder.PadNull(data); case VR.AgeString: case VR.ApplicationEntity: case VR.CodeString: case VR.Date: case VR.DateTime: case VR.DecimalString: case VR.IntegerString: case VR.LongString: case VR.LongText: case VR.PersonName: case VR.ShortString: case VR.ShortText: case VR.Time: case VR.UnlimitedText: return DataPadder.PadSpace(data); default: return data; } } } }``` Write to Logger instead of Console
```c# using System; using EvilDICOM.Core.Enums; using EvilDICOM.Core.Logging; namespace EvilDICOM.Core.IO.Data { public class DataRestriction { public static string EnforceLengthRestriction(uint lengthLimit, string data) { if (data.Length > lengthLimit) { EvilLogger.Instance.Log( "Not DICOM compliant. Attempted data input of {0} characters. Data size is limited to {1} characters. Read anyway.", data.Length, lengthLimit); return data; } return data; } public static byte[] EnforceEvenLength(byte[] data, VR vr) { switch (vr) { case VR.UniqueIdentifier: case VR.OtherByteString: case VR.Unknown: return DataPadder.PadNull(data); case VR.AgeString: case VR.ApplicationEntity: case VR.CodeString: case VR.Date: case VR.DateTime: case VR.DecimalString: case VR.IntegerString: case VR.LongString: case VR.LongText: case VR.PersonName: case VR.ShortString: case VR.ShortText: case VR.Time: case VR.UnlimitedText: return DataPadder.PadSpace(data); default: return data; } } } }```
8d05bfa1-56a6-4008-a23d-406d2bb8e7cb
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NHibernate.Test.TestDialects { public class PostgreSQL82TestDialect : TestDialect { public PostgreSQL82TestDialect(Dialect.Dialect dialect) : base(dialect) { } public override bool SupportsSelectForUpdateOnOuterJoin { get { return false; } } public override bool SupportsNullCharactersInUtfStrings { get { return false; } } } } ``` Disable DTC tests since Npgsql support for it seems to be broken.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NHibernate.Test.TestDialects { public class PostgreSQL82TestDialect : TestDialect { public PostgreSQL82TestDialect(Dialect.Dialect dialect) : base(dialect) { } public override bool SupportsSelectForUpdateOnOuterJoin { get { return false; } } public override bool SupportsNullCharactersInUtfStrings { get { return false; } } /// <summary> /// Npgsql's DTC code seems to be somewhat broken as of 2.0.11. /// </summary> public override bool SupportsDistributedTransactions { get { return false; } } } } ```
42aa1607-1304-4e64-92a4-e0995a966d59
{ "language": "C#" }
```c# using System; using System.Web.UI.WebControls; namespace R7.HelpDesk { public partial class Comments { protected Panel pnlInsertComment; protected Label lblAttachFile1; protected FileUpload TicketFileUpload; protected Label lblAttachFile2; protected FileUpload fuAttachment; protected Panel pnlTableHeader; protected Panel pnlExistingComments; protected Panel pnlEditComment; protected CheckBox chkCommentVisible; protected CheckBox chkCommentVisibleEdit; protected HyperLink lnkDelete; protected Image Image5; protected HyperLink lnkUpdate; protected Image Image4; protected Panel pnlDisplayFile; protected Panel pnlAttachFile; protected Image imgDelete; protected HyperLink lnkUpdateRequestor; protected Image ImgEmailUser; protected Button btnInsertCommentAndEmail; protected TextBox txtComment; protected Label lblError; protected GridView gvComments; protected Label lblDetailID; protected TextBox txtDescription; protected Label lblDisplayUser; protected Label lblInsertDate; protected LinkButton lnkFileAttachment; //protected HyperLink lnkFileAttachment; protected Label lblErrorEditComment; } } ``` Fix wrong type for linkbuttons
```c# using System; using System.Web.UI.WebControls; namespace R7.HelpDesk { public partial class Comments { protected Panel pnlInsertComment; protected Label lblAttachFile1; protected FileUpload TicketFileUpload; protected Label lblAttachFile2; protected FileUpload fuAttachment; protected Panel pnlTableHeader; protected Panel pnlExistingComments; protected Panel pnlEditComment; protected CheckBox chkCommentVisible; protected CheckBox chkCommentVisibleEdit; protected LinkButton lnkDelete; protected Image Image5; protected LinkButton lnkUpdate; protected Image Image4; protected Panel pnlDisplayFile; protected Panel pnlAttachFile; protected Image imgDelete; protected LinkButton lnkUpdateRequestor; protected Image ImgEmailUser; protected Button btnInsertCommentAndEmail; protected TextBox txtComment; protected Label lblError; protected GridView gvComments; protected Label lblDetailID; protected TextBox txtDescription; protected Label lblDisplayUser; protected Label lblInsertDate; protected LinkButton lnkFileAttachment; //protected HyperLink lnkFileAttachment; protected Label lblErrorEditComment; } } ```
a45ce3d8-ce01-4457-b78c-8d76f2de1925
{ "language": "C#" }
```c# /* * Created by SharpDevelop. * User: Lars Magnus * Date: 12.06.2014 * Time: 20:52 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using Nancy.Hosting.Self; namespace webstats { class Program { public static void Main(string[] args) { // Start web server Console.WriteLine("Press enter to terminate server"); HostConfiguration hc = new HostConfiguration(); hc.UrlReservations.CreateAutomatically = true; using (var host = new NancyHost(hc, new Uri("http://localhost:4444"))) { host.Start(); Console.ReadLine(); } Console.WriteLine("Server terminated"); } } }``` Make server able to run as deamon on mono
```c# /* * Created by SharpDevelop. * User: Lars Magnus * Date: 12.06.2014 * Time: 20:52 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Linq; using System.Threading; using Nancy.Hosting.Self; namespace webstats { class Program { public static void Main(string[] args) { // Start web server Console.WriteLine("Press enter to terminate server"); HostConfiguration hc = new HostConfiguration(); hc.UrlReservations.CreateAutomatically = true; var host = new NancyHost(hc, new Uri("http://localhost:8888")); host.Start(); //Under mono if you deamonize a process a Console.ReadLine with cause an EOF //so we need to block another way if (args.Any(s => s.Equals("-d", StringComparison.CurrentCultureIgnoreCase))) { Thread.Sleep(Timeout.Infinite); } else { Console.ReadKey(); } host.Stop(); Console.WriteLine("Server terminated"); } } }```
f43c0504-2ad5-4480-99ff-17e9c9afaea0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; namespace PCLAppConfig.FileSystemStream { public class UWPAppConfigPathExtractor : IAppConfigPathExtractor { public string Path { get { string rootPath = Package.Current.InstalledLocation.Path; string exeConfig = System.IO.Path.Combine(rootPath, Package.Current.DisplayName + ".exe.config"); if (!File.Exists(exeConfig)) { return System.IO.Path.Combine(rootPath, "App.config"); } else { return exeConfig; } } } } } ``` Correct searching config base on exe file name.
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; namespace PCLAppConfig.FileSystemStream { public class UWPAppConfigPathExtractor : IAppConfigPathExtractor { public string Path { get { string rootPath = Package.Current.InstalledLocation.Path; string packageConfig = System.IO.Path.Combine(rootPath, Package.Current.DisplayName + ".exe.config"); string exeConfig = System.IO.Path.Combine(rootPath, System.AppDomain.CurrentDomain.FriendlyName + ".exe.config"); if (File.Exists(packageConfig)) { return packageConfig; } else if (File.Exists(exeConfig)) { return exeConfig; } else { return System.IO.Path.Combine(rootPath, "App.config"); } } } } } ```
6cdff649-4b77-42df-b445-778cc7daba41
{ "language": "C#" }
```c# using Content.Shared.GameObjects.Components.Movement; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Physics; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.Physics; using Robust.Client.Player; using Robust.Shared.GameObjects.Components; using Robust.Shared.IoC; using Robust.Shared.Physics; #nullable enable namespace Content.Client.GameObjects.EntitySystems { [UsedImplicitly] public class MoverSystem : SharedMoverSystem { [Dependency] private readonly IPlayerManager _playerManager = default!; public override void Initialize() { base.Initialize(); UpdatesBefore.Add(typeof(PhysicsSystem)); } public override void FrameUpdate(float frameTime) { var playerEnt = _playerManager.LocalPlayer?.ControlledEntity; if (playerEnt == null || !playerEnt.TryGetComponent(out IMoverComponent mover)) { return; } var physics = playerEnt.GetComponent<PhysicsComponent>(); playerEnt.TryGetComponent(out CollidableComponent? collidable); UpdateKinematics(playerEnt.Transform, mover, physics, collidable); } public override void Update(float frameTime) { FrameUpdate(frameTime); } protected override void SetController(SharedPhysicsComponent physics) { ((PhysicsComponent)physics).SetController<MoverController>(); } } } ``` Reset predict flag on mover updat.e
```c# using Content.Shared.GameObjects.Components.Movement; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Physics; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.Physics; using Robust.Client.Player; using Robust.Shared.GameObjects.Components; using Robust.Shared.IoC; using Robust.Shared.Physics; #nullable enable namespace Content.Client.GameObjects.EntitySystems { [UsedImplicitly] public class MoverSystem : SharedMoverSystem { [Dependency] private readonly IPlayerManager _playerManager = default!; public override void Initialize() { base.Initialize(); UpdatesBefore.Add(typeof(PhysicsSystem)); } public override void FrameUpdate(float frameTime) { var playerEnt = _playerManager.LocalPlayer?.ControlledEntity; if (playerEnt == null || !playerEnt.TryGetComponent(out IMoverComponent mover)) { return; } var physics = playerEnt.GetComponent<PhysicsComponent>(); playerEnt.TryGetComponent(out CollidableComponent? collidable); physics.Predict = true; UpdateKinematics(playerEnt.Transform, mover, physics, collidable); } public override void Update(float frameTime) { FrameUpdate(frameTime); } protected override void SetController(SharedPhysicsComponent physics) { ((PhysicsComponent)physics).SetController<MoverController>(); } } } ```
999ae6cb-748e-4f1c-a786-8bc083305be8
{ "language": "C#" }
```c# using System.Collections; using PatchKit.Api; using UnityEngine; namespace PatchKit.Unity.UI { public abstract class UIApiComponent : MonoBehaviour { private Coroutine _loadCoroutine; private bool _isDirty; private ApiConnection _apiConnection; public bool LoadOnAwake = true; protected ApiConnection ApiConnection { get { return _apiConnection; } } [ContextMenu("Reload")] public void SetDirty() { _isDirty = true; } protected abstract IEnumerator LoadCoroutine(); private void Load() { try { if (_loadCoroutine != null) { StopCoroutine(_loadCoroutine); } _loadCoroutine = StartCoroutine(LoadCoroutine()); } finally { _isDirty = false; } } protected virtual void Awake() { _apiConnection = new ApiConnection(Settings.GetApiConnectionSettings()); if (LoadOnAwake) { Load(); } } protected virtual void Update() { if (_isDirty) { Load(); } } } }``` Change load event of UI component to from Awake to Start
```c# using System.Collections; using PatchKit.Api; using UnityEngine; namespace PatchKit.Unity.UI { public abstract class UIApiComponent : MonoBehaviour { private Coroutine _loadCoroutine; private bool _isDirty; private ApiConnection _apiConnection; public bool LoadOnStart = true; protected ApiConnection ApiConnection { get { return _apiConnection; } } [ContextMenu("Reload")] public void SetDirty() { _isDirty = true; } protected abstract IEnumerator LoadCoroutine(); private void Load() { try { if (_loadCoroutine != null) { StopCoroutine(_loadCoroutine); } _loadCoroutine = StartCoroutine(LoadCoroutine()); } finally { _isDirty = false; } } protected virtual void Awake() { _apiConnection = new ApiConnection(Settings.GetApiConnectionSettings()); } protected virtual void Start() { if (LoadOnStart) { Load(); } } protected virtual void Update() { if (_isDirty) { Load(); } } } }```
66832dab-5509-45d7-ad5a-ddee19b686a3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Examine; namespace Umbraco.Examine { /// <summary> /// Utility to rebuild all indexes ensuring minimal data queries /// </summary> public class IndexRebuilder { private readonly IEnumerable<IIndexPopulator> _populators; public IExamineManager ExamineManager { get; } public IndexRebuilder(IExamineManager examineManager, IEnumerable<IIndexPopulator> populators) { _populators = populators; ExamineManager = examineManager; } public bool CanRebuild(IIndex index) { return _populators.Any(x => x.IsRegistered(index)); } public void RebuildIndex(string indexName) { if (!ExamineManager.TryGetIndex(indexName, out var index)) throw new InvalidOperationException($"No index found with name {indexName}"); index.CreateIndex(); // clear the index foreach (var populator in _populators) { populator.Populate(index); } } public void RebuildIndexes(bool onlyEmptyIndexes) { var indexes = (onlyEmptyIndexes ? ExamineManager.Indexes.Where(x => !x.IndexExists()) : ExamineManager.Indexes).ToArray(); if (indexes.Length == 0) return; foreach (var index in indexes) { index.CreateIndex(); // clear the index } //run the populators in parallel against all indexes Parallel.ForEach(_populators, populator => populator.Populate(indexes)); } } } ``` Remove the usage of Parallel to run the populators
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Examine; namespace Umbraco.Examine { /// <summary> /// Utility to rebuild all indexes ensuring minimal data queries /// </summary> public class IndexRebuilder { private readonly IEnumerable<IIndexPopulator> _populators; public IExamineManager ExamineManager { get; } public IndexRebuilder(IExamineManager examineManager, IEnumerable<IIndexPopulator> populators) { _populators = populators; ExamineManager = examineManager; } public bool CanRebuild(IIndex index) { return _populators.Any(x => x.IsRegistered(index)); } public void RebuildIndex(string indexName) { if (!ExamineManager.TryGetIndex(indexName, out var index)) throw new InvalidOperationException($"No index found with name {indexName}"); index.CreateIndex(); // clear the index foreach (var populator in _populators) { populator.Populate(index); } } public void RebuildIndexes(bool onlyEmptyIndexes) { var indexes = (onlyEmptyIndexes ? ExamineManager.Indexes.Where(x => !x.IndexExists()) : ExamineManager.Indexes).ToArray(); if (indexes.Length == 0) return; foreach (var index in indexes) { index.CreateIndex(); // clear the index } // run each populator over the indexes foreach(var populator in _populators) { populator.Populate(indexes); } } } } ```
aefcc133-1518-4ba6-adce-76c16836e2a6
{ "language": "C#" }
```c# // Copyright 2014-2019 Vladimir Alyamkin. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class VaRest : ModuleRules { public VaRest(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PrivateIncludePaths.AddRange( new string[] { "VaRest/Private", // ... add other private include paths required here ... }); PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "HTTP", "Json", "Projects" // Required by IPluginManager etc (used to get plugin information) // ... add other public dependencies that you statically link with here ... }); } } } ``` Enable pre-compile for all targets
```c# // Copyright 2014-2019 Vladimir Alyamkin. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class VaRest : ModuleRules { public VaRest(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PrecompileForTargets = PrecompileTargetsType.Any; PrivateIncludePaths.AddRange( new string[] { "VaRest/Private", // ... add other private include paths required here ... }); PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "HTTP", "Json", "Projects" // Required by IPluginManager etc (used to get plugin information) // ... add other public dependencies that you statically link with here ... }); } } } ```
03fad1e2-d59b-46d4-9709-a9f7dfca4ba3
{ "language": "C#" }
```c# namespace WalletWasabi.Backend.Models.Responses { public class VersionsResponse { public string ClientVersion { get; set; } public string BackendMajorVersion { get; set; } } } ``` Add back typo with JsonProperty and explain in comment why it's necessary.
```c# using Newtonsoft.Json; namespace WalletWasabi.Backend.Models.Responses { public class VersionsResponse { public string ClientVersion { get; set; } // KEEP THE TYPO IN IT! Otherwise the response would not be backwards compatible. [JsonProperty(PropertyName = "BackenMajordVersion")] public string BackendMajorVersion { get; set; } } } ```
6d1d70ce-1de4-42cb-a355-359c81472c09
{ "language": "C#" }
```c# #region Copyright and license // // <copyright file="NotNullTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // </license> #endregion namespace Delizious.Filtering { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class NotNullTests { [TestMethod] public void Fail__When_Value_Is_Null() { Assert.IsFalse(Match.NotNull<GenericParameterHelper>().Matches(null)); } [TestMethod] public void Succeed__When_Value_Is_An_Instance() { Assert.IsTrue(Match.NotNull<GenericParameterHelper>().Matches(new GenericParameterHelper())); } } } ``` Improve naming of tests to clearly indicate the feature to be tested
```c# #region Copyright and license // // <copyright file="NotNullTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // </license> #endregion namespace Delizious.Filtering { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class NotNullTests { [TestMethod] public void Match_Fails_When_Value_To_Match_Is_Null() { Assert.IsFalse(Match.NotNull<GenericParameterHelper>().Matches(null)); } [TestMethod] public void Match_Succeeds_When_Value_To_Match_Is_An_Instance() { Assert.IsTrue(Match.NotNull<GenericParameterHelper>().Matches(new GenericParameterHelper())); } } } ```
b4202ca8-8fc8-46b3-a657-fd7fe693ee43
{ "language": "C#" }
```c# using System; public struct Foo : ICloneable { public int CloneCounter { get; private set; } public object Clone() { CloneCounter++; return this; } } public static class Program { public static ICloneable BoxAndCast<T>(T Value) { return (ICloneable)Value; } public static void Main(string[] Args) { var foo = default(Foo); Console.WriteLine(((Foo)foo.Clone()).CloneCounter); Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter); Console.WriteLine(foo.CloneCounter); object i = 42; Console.WriteLine((int)i); } } ``` Extend the box/unbox test again
```c# using System; public struct Foo : ICloneable { public int CloneCounter { get; private set; } public object Clone() { CloneCounter++; return this; } } public static class Program { public static ICloneable BoxAndCast<T>(T Value) { return (ICloneable)Value; } public static T Unbox<T>(object Value) { return (T)Value; } public static void Main(string[] Args) { var foo = default(Foo); Console.WriteLine(((Foo)foo.Clone()).CloneCounter); Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter); Console.WriteLine(foo.CloneCounter); object i = 42; Console.WriteLine((int)i); Console.WriteLine(Unbox<int>(i)); } } ```
cd622cff-5dd6-4598-a81c-4f6774a2f62e
{ "language": "C#" }
```c# #region Usings using System.Collections.Generic; using System.Text.RegularExpressions; #endregion namespace Buildron.Infrastructure.BuildsProvider.TeamCity { /// <summary> /// Build queue parser. /// </summary> public static class BuildQueueParser { #region Fields private static Regex s_getBuildConfigurationIdsRegex = new Regex("name=\"ref(bt\\d+)\"", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); #endregion #region Methods /// <summary> /// Parses the build configurations identifiers from queue html (http://TeamCityServer/queue.html). /// </summary> /// <returns> /// The build configurations identifiers from queue html. /// </returns> /// <param name='html'> /// Html. /// </param> public static IList<string> ParseBuildConfigurationsIdsFromQueueHtml (string html) { var ids = new List<string> (); var matches = s_getBuildConfigurationIdsRegex.Matches (html); foreach (Match m in matches) { ids.Add(m.Groups[1].Value); } return ids; } #endregion } }``` Fix how to find TeamCity queued builds.
```c# #region Usings using System.Collections.Generic; using System.Text.RegularExpressions; #endregion namespace Buildron.Infrastructure.BuildsProvider.TeamCity { /// <summary> /// Build queue parser. /// </summary> public static class BuildQueueParser { #region Fields private static Regex s_getBuildConfigurationIdsRegex = new Regex("viewType\\.html\\?buildTypeId=(.+)\"", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); #endregion #region Methods /// <summary> /// Parses the build configurations identifiers from queue html (http://TeamCityServer/queue.html). /// </summary> /// <returns> /// The build configurations identifiers from queue html. /// </returns> /// <param name='html'> /// Html. /// </param> public static IList<string> ParseBuildConfigurationsIdsFromQueueHtml (string html) { var ids = new List<string> (); var matches = s_getBuildConfigurationIdsRegex.Matches (html); foreach (Match m in matches) { ids.Add(m.Groups[1].Value); } return ids; } #endregion } }```
27587715-d3cc-4f0f-a9c0-3b0aa73f42fd
{ "language": "C#" }
```c# using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Order; namespace NHasher.Benchmarks { [ClrJob, CoreJob] [MemoryDiagnoser] public class Benchmarks { private const int N = 10000; private readonly byte[] _data; private readonly MurmurHash3X64L128 _murmurHash3X64L128 = new MurmurHash3X64L128(); private readonly XXHash32 _xxHash32 = new XXHash32(); private readonly XXHash64 _xxHash64 = new XXHash64(); public Benchmarks() { _data = new byte[N]; new Random(42).NextBytes(_data); } [Benchmark] public byte[] MurmurHash3X64L128() { return _murmurHash3X64L128.ComputeHash(_data); } [Benchmark] public byte[] XXHash32() { return _xxHash32.ComputeHash(_data); } [Benchmark] public byte[] XXHash64() { return _xxHash64.ComputeHash(_data); } } } ``` Add missing file with benchmarks
```c# using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; namespace NHasher.Benchmarks { [ClrJob, CoreJob] [MemoryDiagnoser] public class Benchmarks { private byte[] _data; private readonly MurmurHash3X64L128 _murmurHash3X64L128 = new MurmurHash3X64L128(); private readonly XXHash32 _xxHash32 = new XXHash32(); private readonly XXHash64 _xxHash64 = new XXHash64(); [Params(4, 11, 25, 100, 1000, 10000)] public int PayloadLength { get; set; } [Setup] public void SetupData() { _data = new byte[PayloadLength]; new Random(42).NextBytes(_data); } [Benchmark] public byte[] MurmurHash3X64L128() => _murmurHash3X64L128.ComputeHash(_data); [Benchmark] public byte[] XXHash32() => _xxHash32.ComputeHash(_data); [Benchmark] public byte[] XXHash64() => _xxHash64.ComputeHash(_data); } } ```
bddca62f-220e-4b52-a2a7-498cdde5d722
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; // Nuget: Title [assembly: AssemblyTitle( "D2L Security For Web API" )] // Nuget: Description [assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )] // Nuget: Author [assembly: AssemblyCompany( "Desire2Learn" )] // Nuget: Owners [assembly: AssemblyProduct( "Brightspace" )] // Nuget: Version [assembly: AssemblyInformationalVersion( "5.2.0.0" )] [assembly: AssemblyVersion( "5.2.0.0" )] [assembly: AssemblyFileVersion( "5.2.0.0" )] [assembly: AssemblyCopyright( "Copyright © Desire2Learn" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )] ``` Make assembly title match assembly name
```c# using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle( "D2L.Security.WebApi" )] [assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )] [assembly: AssemblyCompany( "Desire2Learn" )] [assembly: AssemblyProduct( "Brightspace" )] [assembly: AssemblyInformationalVersion( "5.2.0.0" )] [assembly: AssemblyVersion( "5.2.0.0" )] [assembly: AssemblyFileVersion( "5.2.0.0" )] [assembly: AssemblyCopyright( "Copyright © Desire2Learn" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )] [assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )] ```
02a76ced-43df-4e01-8c28-aed0cf8612fc
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Text; using System.Xml; using Xunit; public class XmlWriterTests { [Fact] public static void WriteWithEncoding() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.ConformanceLevel = ConformanceLevel.Fragment; settings.CloseOutput = false; settings.Encoding = Encoding.GetEncoding("Windows-1252"); MemoryStream strm = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(strm, settings)) { writer.WriteElementString("orderID", "1-456-ab\u0661"); writer.WriteElementString("orderID", "2-36-00a\uD800\uDC00\uD801\uDC01"); writer.Flush(); } strm.Seek(0, SeekOrigin.Begin); byte[] bytes = new byte[strm.Length]; int bytesCount = strm.Read(bytes, 0, (int)strm.Length); string s = settings.Encoding.GetString(bytes, 0, bytesCount); Assert.Equal("<orderID>1-456-ab&#x661;</orderID><orderID>2-36-00a&#x10000;&#x10401;</orderID>", s); } }``` Disable flaky XML encoding test
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Text; using System.Xml; using Xunit; public class XmlWriterTests { [Fact] [ActiveIssue(1263)] public static void WriteWithEncoding() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.ConformanceLevel = ConformanceLevel.Fragment; settings.CloseOutput = false; settings.Encoding = Encoding.GetEncoding("Windows-1252"); MemoryStream strm = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(strm, settings)) { writer.WriteElementString("orderID", "1-456-ab\u0661"); writer.WriteElementString("orderID", "2-36-00a\uD800\uDC00\uD801\uDC01"); writer.Flush(); } strm.Seek(0, SeekOrigin.Begin); byte[] bytes = new byte[strm.Length]; int bytesCount = strm.Read(bytes, 0, (int)strm.Length); string s = settings.Encoding.GetString(bytes, 0, bytesCount); Assert.Equal("<orderID>1-456-ab&#x661;</orderID><orderID>2-36-00a&#x10000;&#x10401;</orderID>", s); } }```
8783825f-d0be-4242-8e39-24af243c1588
{ "language": "C#" }
```c# namespace MiX.Integrate.Shared.Entities.Assets { /// <summary>Instance of a custom asset detail data point/summary> public class AdditionalDetailItem { public AdditionalDetailItem(int id, string label, string value) { Id = id; Label = label; Value = value; } /// <summary>Identifiedr of the custom detail</summary> public int Id { get; set; } /// <summary>Name of the custom detail</summary> public string Label { get; set; } /// <summary>Value of the custom detail</summary> public string Value { get; set; } } } ``` Use long instead of int for field Id
```c# namespace MiX.Integrate.Shared.Entities.Assets { /// <summary>Instance of a custom asset detail data point/summary> public class AdditionalDetailItem { public AdditionalDetailItem(long id, string label, string value) { Id = id; Label = label; Value = value; } /// <summary>Identifier of the custom detail</summary> public long Id { get; set; } /// <summary>Name of the custom detail</summary> public string Label { get; set; } /// <summary>Value of the custom detail</summary> public string Value { get; set; } } } ```
b363f62d-9e39-4e7f-841b-6f03fd9be55b
{ "language": "C#" }
```c# using LiveSplit.UI; using LiveSplit.UI.Components; using System; using System.Windows.Forms; using System.Xml; namespace LiveSplit.View { public partial class ComponentSettingsDialog : Form { public XmlNode ComponentSettings { get; set; } public IComponent Component { get; set; } public ComponentSettingsDialog(IComponent component) { InitializeComponent(); Component = component; AddComponent(component); } private void btnOK_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void btnCancel_Click(object sender, EventArgs e) { Component.SetSettings(ComponentSettings); DialogResult = DialogResult.Cancel; Close(); } protected void AddComponent(IComponent component) { var settingsControl = Component.GetSettingsControl(LayoutMode.Vertical); AddControl(component.ComponentName, settingsControl); ComponentSettings = component.GetSettings(new XmlDocument()); } protected void AddControl(string name, Control control) { panel.Controls.Add(control); Name = name + " Settings"; } } } ``` Fix auto splitter settings scroll bar not always appearing
```c# using LiveSplit.UI; using LiveSplit.UI.Components; using System; using System.Drawing; using System.Windows.Forms; using System.Xml; namespace LiveSplit.View { public partial class ComponentSettingsDialog : Form { public XmlNode ComponentSettings { get; set; } public IComponent Component { get; set; } public ComponentSettingsDialog(IComponent component) { InitializeComponent(); Component = component; AddComponent(component); } private void btnOK_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void btnCancel_Click(object sender, EventArgs e) { Component.SetSettings(ComponentSettings); DialogResult = DialogResult.Cancel; Close(); } protected void AddComponent(IComponent component) { var settingsControl = Component.GetSettingsControl(LayoutMode.Vertical); AddControl(component.ComponentName, settingsControl); ComponentSettings = component.GetSettings(new XmlDocument()); } protected void AddControl(string name, Control control) { control.Location = new Point(0, 0); panel.Controls.Add(control); Name = name + " Settings"; } } } ```
e80f2a37-b178-4d89-b433-f83220b8f632
{ "language": "C#" }
```c# using System; using FluentAssertions; using OpenMagic.Extensions; using OpenMagic.Specifications.Helpers; using TechTalk.SpecFlow; namespace OpenMagic.Specifications.Steps.Extensions.UriExtensions { [Binding] public class IsReposondingSteps { private readonly GivenData _given; private readonly ActualData _actual; public IsReposondingSteps(GivenData given, ActualData actual) { _given = given; _actual = actual; } [Given(@"URI is responding")] public void GivenUriIsResponding() { _given.Uri = new Uri("http://www.google.com"); } [Given(@"URI is not responding")] public void GivenUriIsNotResponding() { _given.Uri = new Uri("http://" + Guid.NewGuid()); } [When(@"I call IsResponding\(<uri>\)")] public void WhenICallIsResponding() { _actual.GetResult(() => _given.Uri.IsResponding()); } } } ``` Fix URI Is Not Responding test
```c# using System; using FluentAssertions; using OpenMagic.Extensions; using OpenMagic.Specifications.Helpers; using TechTalk.SpecFlow; namespace OpenMagic.Specifications.Steps.Extensions.UriExtensions { [Binding] public class IsReposondingSteps { private readonly GivenData _given; private readonly ActualData _actual; public IsReposondingSteps(GivenData given, ActualData actual) { _given = given; _actual = actual; } [Given(@"URI is responding")] public void GivenUriIsResponding() { _given.Uri = new Uri("http://www.google.com"); } [Given(@"URI is not responding")] public void GivenUriIsNotResponding() { _given.Uri = new Uri("http://domainthat.doesnotexist"); } [When(@"I call IsResponding\(<uri>\)")] public void WhenICallIsResponding() { _actual.GetResult(() => _given.Uri.IsResponding()); } } } ```
f4669ffc-603f-42ec-9018-36e90c23b450
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Users; namespace osu.Game.Overlays.Profile.Sections.Historical { public class PaginatedMostPlayedBeatmapContainer : PaginatedContainer<APIUserMostPlayedBeatmap> { public PaginatedMostPlayedBeatmapContainer(Bindable<User> user) : base(user, "No records. :(") { ItemsPerPage = 5; } [BackgroundDependencyLoader] private void load() { ItemsContainer.Direction = FillDirection.Vertical; } protected override APIRequest<List<APIUserMostPlayedBeatmap>> CreateRequest() => new GetUserMostPlayedBeatmapsRequest(User.Value.Id, VisiblePages++, ItemsPerPage); protected override Drawable CreateDrawableItem(APIUserMostPlayedBeatmap model) => new DrawableMostPlayedBeatmap(model.GetBeatmapInfo(Rulesets), model.PlayCount); } } ``` Add missing header to MostPlayedBeatmapsContainer
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Users; namespace osu.Game.Overlays.Profile.Sections.Historical { public class PaginatedMostPlayedBeatmapContainer : PaginatedContainer<APIUserMostPlayedBeatmap> { public PaginatedMostPlayedBeatmapContainer(Bindable<User> user) : base(user, "No records. :(", "Most Played Beatmaps") { ItemsPerPage = 5; } [BackgroundDependencyLoader] private void load() { ItemsContainer.Direction = FillDirection.Vertical; } protected override APIRequest<List<APIUserMostPlayedBeatmap>> CreateRequest() => new GetUserMostPlayedBeatmapsRequest(User.Value.Id, VisiblePages++, ItemsPerPage); protected override Drawable CreateDrawableItem(APIUserMostPlayedBeatmap model) => new DrawableMostPlayedBeatmap(model.GetBeatmapInfo(Rulesets), model.PlayCount); } } ```
750d66b6-1143-4dc2-9faa-fb60f603f2a0
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class SwitchStatementStructureProvider : AbstractSyntaxNodeStructureProvider<SwitchStatementSyntax> { protected override void CollectBlockSpans( SwitchStatementSyntax node, ArrayBuilder<BlockSpan> spans, CancellationToken cancellationToken) { spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(node.CloseParenToken.Span.End, node.CloseBraceToken.Span.End), hintSpan: node.Span, type: BlockTypes.Statement)); } } }``` Update BlockType of switch statement.
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class SwitchStatementStructureProvider : AbstractSyntaxNodeStructureProvider<SwitchStatementSyntax> { protected override void CollectBlockSpans( SwitchStatementSyntax node, ArrayBuilder<BlockSpan> spans, CancellationToken cancellationToken) { spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(node.CloseParenToken.Span.End, node.CloseBraceToken.Span.End), hintSpan: node.Span, type: BlockTypes.Conditional)); } } }```
0938d449-a0ae-401e-9ebc-c9938d991075
{ "language": "C#" }
```c# // 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.Rulesets.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Catch.Judgements { public class CatchBananaJudgement : CatchJudgement { public override bool AffectsCombo => false; protected override int NumericResultFor(HitResult result) { switch (result) { default: return 0; case HitResult.Perfect: return 1100; } } protected override double HealthIncreaseFor(HitResult result) { switch (result) { default: return 0; case HitResult.Perfect: return 0.01; } } public override bool ShouldExplodeFor(JudgementResult result) => true; } } ``` Increase HP gain of bananas
```c# // 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.Rulesets.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Catch.Judgements { public class CatchBananaJudgement : CatchJudgement { public override bool AffectsCombo => false; protected override int NumericResultFor(HitResult result) { switch (result) { default: return 0; case HitResult.Perfect: return 1100; } } protected override double HealthIncreaseFor(HitResult result) { switch (result) { default: return 0; case HitResult.Perfect: return DEFAULT_MAX_HEALTH_INCREASE * 0.75; } } public override bool ShouldExplodeFor(JudgementResult result) => true; } } ```
b8b9d6a6-731d-42a6-9f21-6089e74cd923
{ "language": "C#" }
```c# using Foundation; using System; using UIKit; using MyTrips.ViewModel; using Humanizer; namespace MyTrips.iOS { public partial class TripsTableViewController : UITableViewController { const string TRIP_CELL_IDENTIFIER = "TRIP_CELL_IDENTIFIER"; PastTripsViewModel ViewModel { get; set; } public TripsTableViewController (IntPtr handle) : base (handle) { } public override async void ViewDidLoad() { base.ViewDidLoad(); // TODO: Grab data for UITableView. ViewModel = new PastTripsViewModel(); await ViewModel.ExecuteLoadPastTripsCommandAsync(); } #region UITableViewSource public override nint RowsInSection(UITableView tableView, nint section) { return ViewModel.Trips.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { // No need to check for null; storyboards always return a dequeable cell. var cell = tableView.DequeueReusableCell(TRIP_CELL_IDENTIFIER) as TripTableViewCell; if (cell == null) { cell = new TripTableViewCell(new NSString(TRIP_CELL_IDENTIFIER)); } var trip = ViewModel.Trips[indexPath.Row]; cell.LocationName = trip.TripId; cell.TimeAgo = trip.TimeAgo; cell.Distance = $"{trip.TotalDistance} miles"; return cell; } #endregion } }``` Fix trip cell distance label.
```c# using Foundation; using System; using UIKit; using MyTrips.ViewModel; using Humanizer; namespace MyTrips.iOS { public partial class TripsTableViewController : UITableViewController { const string TRIP_CELL_IDENTIFIER = "TRIP_CELL_IDENTIFIER"; PastTripsViewModel ViewModel { get; set; } public TripsTableViewController (IntPtr handle) : base (handle) { } public override async void ViewDidLoad() { base.ViewDidLoad(); // TODO: Grab data for UITableView. ViewModel = new PastTripsViewModel(); await ViewModel.ExecuteLoadPastTripsCommandAsync(); } #region UITableViewSource public override nint RowsInSection(UITableView tableView, nint section) { return ViewModel.Trips.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { // No need to check for null; storyboards always return a dequeable cell. var cell = tableView.DequeueReusableCell(TRIP_CELL_IDENTIFIER) as TripTableViewCell; if (cell == null) { cell = new TripTableViewCell(new NSString(TRIP_CELL_IDENTIFIER)); } var trip = ViewModel.Trips[indexPath.Row]; cell.LocationName = trip.TripId; cell.TimeAgo = trip.TimeAgo; cell.Distance = trip.TotalDistance; return cell; } #endregion } }```
dc4b43d1-853e-4ed4-a5ff-0435adacc1d0
{ "language": "C#" }
```c# using System; using System.Globalization; using System.Windows.Data; namespace KodiRemote.Wp81.Converters { public class ShorterStringConverter : IValueConverter { public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string str = value.ToString(); int max; if (!int.TryParse(parameter.ToString(), out max)) return str; if (str.Length <= max) return str; return str.Substring(0, max - 3) + "..."; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }``` Fix issue in a converter
```c# using System; using System.Globalization; using System.Windows.Data; namespace KodiRemote.Wp81.Converters { public class ShorterStringConverter : IValueConverter { public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || parameter == null) return string.Empty; int max; if (!int.TryParse(parameter.ToString(), out max)) return value; string str = value.ToString(); if (str.Length <= max) return str; return str.Substring(0, max - 3) + "..."; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }```
0562f3d7-b22e-412c-bb5c-66fc0ff632b6
{ "language": "C#" }
```c# using System.Reflection; 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("Urho3DNet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Urho3D")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("58DA6FEF-5C52-4CB9-9E0E-C9621ABFAB76")] // 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")] ``` Clean up engine bindings assembly info.
```c# using System.Reflection; [assembly: AssemblyTitle("Urho3DNet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Urho3D")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
5884e202-4f04-4f69-95f6-e59abc21d2ff
{ "language": "C#" }
```c# using System; namespace AllReady.Providers { public interface IConvertDateTimeOffset { DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0); DateTimeOffset ConvertDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0); } public class DateTimeOffsetConverter : IConvertDateTimeOffset { public DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0) { return ConvertDateTimeOffsetTo(FindSystemTimeZoneBy(timeZoneId), dateTimeOffset, hour, minute, second); } public DateTimeOffset ConvertDateTimeOffsetTo(TimeZoneInfo timeZoneInfo, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0) { return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, hour, minute, second, timeZoneInfo.GetUtcOffset(dateTimeOffset)); //both of these implemenations lose the ability to specificy the hour, minute and second unless the given dateTimeOffset value being passed into this method //already has those values set //1. //return TimeZoneInfo.ConvertTime(dateTimeOffset, timeZoneInfo); //2. //var timeSpan = timeZoneInfo.GetUtcOffset(dateTimeOffset); //return dateTimeOffset.ToOffset(timeSpan); } private static TimeZoneInfo FindSystemTimeZoneBy(string timeZoneId) { return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); } } }``` Remove unused method on DateTimeOffsetConvertrer and consolidated code
```c# using System; namespace AllReady.Providers { public interface IConvertDateTimeOffset { DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0); } public class DateTimeOffsetConverter : IConvertDateTimeOffset { public DateTimeOffset ConvertDateTimeOffsetTo(string timeZoneId, DateTimeOffset dateTimeOffset, int hour = 0, int minute = 0, int second = 0) { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, hour, minute, second, timeZoneInfo.GetUtcOffset(dateTimeOffset)); } } }```
0f17d07d-4577-407f-a52f-578827c22a6b
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using Newtonsoft.Json; namespace osu.Game.Users { public class User { [JsonProperty(@"id")] public long Id = 1; [JsonProperty(@"username")] public string Username; public Country Country; public Team Team; [JsonProperty(@"colour")] public string Colour; } } ``` Add a placeholder cover URL for users.
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using Newtonsoft.Json; namespace osu.Game.Users { public class User { [JsonProperty(@"id")] public long Id = 1; [JsonProperty(@"username")] public string Username; public Country Country; public Team Team; [JsonProperty(@"colour")] public string Colour; public string CoverUrl = @"https://assets.ppy.sh/user-profile-covers/2/08cad88747c235a64fca5f1b770e100f120827ded1ffe3b66bfcd19c940afa65.jpeg"; } } ```
4e69c492-c89a-4d37-894e-0c179c644e92
{ "language": "C#" }
```c# using System; using System.Linq; namespace AppHarbor.Commands { public class CreateCommand : ICommand { private readonly IAppHarborClient _appHarborClient; private readonly IApplicationConfiguration _applicationConfiguration; public CreateCommand(IAppHarborClient appHarborClient, IApplicationConfiguration applicationConfiguration) { _appHarborClient = appHarborClient; _applicationConfiguration = applicationConfiguration; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("An application name must be provided to create an application"); } var result = _appHarborClient.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()); Console.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", result.ID); _applicationConfiguration.SetupApplication(result.ID, _appHarborClient.GetUser()); } } } ``` Write an additional line after creating application
```c# using System; using System.Linq; namespace AppHarbor.Commands { public class CreateCommand : ICommand { private readonly IAppHarborClient _appHarborClient; private readonly IApplicationConfiguration _applicationConfiguration; public CreateCommand(IAppHarborClient appHarborClient, IApplicationConfiguration applicationConfiguration) { _appHarborClient = appHarborClient; _applicationConfiguration = applicationConfiguration; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("An application name must be provided to create an application"); } var result = _appHarborClient.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()); Console.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", result.ID); Console.WriteLine(""); _applicationConfiguration.SetupApplication(result.ID, _appHarborClient.GetUser()); } } } ```