doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
2eab8789-8f14-433d-af6e-c49b8c476008
{ "language": "C#" }
```c# using System.ComponentModel; namespace Msiler.DialogPages { public class ExtensionDisplayOptions : MsilerDialogPage { [Category("Display")] [DisplayName("Listing font name")] [Description("")] public string FontName { get; set; } = "Consolas"; [Category("Display")] [DisplayName("Listing font size")] [Description("")] public int FontSize { get; set; } = 12; [Category("Display")] [DisplayName("Show line numbers")] [Description("")] public bool LineNumbers { get; set; } = true; [Category("Display")] [DisplayName("VS Color theme")] [Description("Visual Studio color theme, Msiler highlighting will be adjusted based on this value")] public MsilerColorTheme ColorTheme { get; set; } = MsilerColorTheme.Auto; } } ``` Disable line numbers by default
```c# using System.ComponentModel; namespace Msiler.DialogPages { public class ExtensionDisplayOptions : MsilerDialogPage { [Category("Display")] [DisplayName("Listing font name")] [Description("")] public string FontName { get; set; } = "Consolas"; [Category("Display")] [DisplayName("Listing font size")] [Description("")] public int FontSize { get; set; } = 12; [Category("Display")] [DisplayName("Show line numbers")] [Description("")] public bool LineNumbers { get; set; } = false; [Category("Display")] [DisplayName("VS Color theme")] [Description("Visual Studio color theme, Msiler highlighting will be adjusted based on this value")] public MsilerColorTheme ColorTheme { get; set; } = MsilerColorTheme.Auto; } } ```
26e2ce34-c1a0-4c6b-b6e6-5c9342eb599b
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpcMock; namespace OpcMockTests { [TestClass] public class ProtocolComparerTests { private const int EQUALITY = 0; [TestMethod] public void Protocols_With_The_Same_Name_Are_Equal() { ProtocolComparer pc = new ProtocolComparer(); OpcMockProtocol omp1 = new OpcMockProtocol("omp1"); OpcMockProtocol compare1 = new OpcMockProtocol("omp1"); Assert.AreEqual(EQUALITY, pc.Compare(omp1, compare1)); } } } ``` Test names changed to Should notation
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpcMock; namespace OpcMockTests { [TestClass] public class ProtocolComparerTests { private const int EQUALITY = 0; [TestMethod] public void ProtocolsWithTheSameNameShould_Be_Equal() { ProtocolComparer pc = new ProtocolComparer(); OpcMockProtocol omp1 = new OpcMockProtocol("omp1"); OpcMockProtocol compare1 = new OpcMockProtocol("omp1"); Assert.AreEqual(EQUALITY, pc.Compare(omp1, compare1)); } } } ```
daadd0fc-1fc7-455f-bb11-90dfb1b7b7f0
{ "language": "C#" }
```c# using System; namespace Glimpse { public interface IMessageBus { IObservable<T> Listen<T>(); IObservable<T> ListenIncludeLatest<T>(); void SendMessage(object message); } }``` Update types on Message Bus definition
```c# using System; namespace Glimpse { public interface IMessageBus { IObservable<T> Listen<T>() where T : IMessage; IObservable<T> ListenIncludeLatest<T>() where T : IMessage; void SendMessage(IMessage message); } }```
7ec08f7d-4e26-46e5-86ea-a0996e375cff
{ "language": "C#" }
```c# using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; using HashidsNet; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HashingService : IHashingService { public string HashValue(long id) { var hashIds = new Hashids("SFA: digital apprenticeship service",10, "46789BCDFGHJKLMNPRSTVWXY"); return hashIds.EncodeLong(id); } } } ``` Change so that the minimum hash length is 6 characters and not 10
```c# using SFA.DAS.EmployerApprenticeshipsService.Domain.Interfaces; using HashidsNet; namespace SFA.DAS.EmployerApprenticeshipsService.Infrastructure.Services { public class HashingService : IHashingService { public string HashValue(long id) { var hashIds = new Hashids("SFA: digital apprenticeship service",6, "46789BCDFGHJKLMNPRSTVWXY"); return hashIds.EncodeLong(id); } } } ```
c1083f1d-ebad-47d2-9065-5f732f6985ad
{ "language": "C#" }
```c# using TAP; using System; using System.Net; public class TAPCfgTest { private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start("Device name"); Console.WriteLine("Got device name: {0}", dev.DeviceName); dev.MTU = 1280; dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16); dev.SetAddress(IPAddress.Parse("fc00::1"), 64); dev.Enabled = true; while (true) { EthernetFrame frame = dev.Read(); if (frame == null) break; if (frame.EtherType == EtherType.IPv6) { IPv6Packet packet = new IPv6Packet(frame.Payload); if (packet.NextHeader == ProtocolType.ICMPv6) { ICMPv6Type type = (ICMPv6Type) packet.Payload[0]; Console.WriteLine("Got ICMPv6 packet type {0}", type); Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload)); } } Console.WriteLine("Read Ethernet frame of type {0}", frame.EtherType); Console.WriteLine("Source address: {0}", BitConverter.ToString(frame.SourceAddress)); Console.WriteLine("Destination address: {0}", BitConverter.ToString(frame.DestinationAddress)); } } } ``` Print source and destination addresses on ICMPv6 packets
```c# using TAP; using System; using System.Net; public class TAPCfgTest { private static void Main(string[] args) { EthernetDevice dev = new EthernetDevice(); dev.Start("Device name"); Console.WriteLine("Got device name: {0}", dev.DeviceName); dev.MTU = 1280; dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16); dev.SetAddress(IPAddress.Parse("fc00::1"), 64); dev.Enabled = true; while (true) { EthernetFrame frame = dev.Read(); if (frame == null) break; if (frame.EtherType == EtherType.IPv6) { IPv6Packet packet = new IPv6Packet(frame.Payload); if (packet.NextHeader == ProtocolType.ICMPv6) { ICMPv6Type type = (ICMPv6Type) packet.Payload[0]; Console.WriteLine("Got ICMPv6 packet type {0}", type); Console.WriteLine("Src: {0}", packet.Source); Console.WriteLine("Dst: {0}", packet.Destination); Console.WriteLine("Data: {0}", BitConverter.ToString(packet.Payload)); } } Console.WriteLine("Read Ethernet frame of type {0}", frame.EtherType); Console.WriteLine("Source address: {0}", BitConverter.ToString(frame.SourceAddress)); Console.WriteLine("Destination address: {0}", BitConverter.ToString(frame.DestinationAddress)); } } } ```
acdca92d-04ae-43e3-9a4c-45d5e5d178b1
{ "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. namespace osu.Game.Utils { public static class FormatUtils { /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// Omits all decimal places when <paramref name="accuracy"/> equals 1d. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this double accuracy) => accuracy == 1 ? "100%" : $"{accuracy:0.00%}"; /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// Omits all decimal places when <paramref name="accuracy"/> equals 100m. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this decimal accuracy) => accuracy == 100 ? "100%" : $"{accuracy:0.00}%"; } } ``` Add alwaysShowDecimals param to FormatAccuracy
```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. namespace osu.Game.Utils { public static class FormatUtils { /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 1d</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this double accuracy, bool alwaysShowDecimals = false) => accuracy == 1 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00%}"; /// <summary> /// Turns the provided accuracy into a percentage with 2 decimal places. /// </summary> /// <param name="accuracy">The accuracy to be formatted</param> /// <param name="alwaysShowDecimals">Whether to show decimal places if <paramref name="accuracy"/> equals 100m</param> /// <returns>formatted accuracy in percentage</returns> public static string FormatAccuracy(this decimal accuracy, bool alwaysShowDecimals = false) => accuracy == 100 && !alwaysShowDecimals ? "100%" : $"{accuracy:0.00}%"; } } ```
e225b50b-8b5a-48b6-a5b8-96be299de69d
{ "language": "C#" }
```c# ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Restore-NuGet-Packages") .Does(() => { NuGetRestore("SimpSim.NET.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration)); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./SimpSim.NET.Tests/SimpSim.NET.Tests.csproj"); DotNetCoreTest("./SimpSim.NET.Presentation.Tests/SimpSim.NET.Presentation.Tests.csproj"); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target); ``` Use DotNetCoreBuild in Cake script.
```c# ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Build") .Does(() => { DotNetCoreBuild("SimpSim.NET.sln", new DotNetCoreBuildSettings{Configuration = configuration}); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { DotNetCoreTest(); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target); ```
cab8e382-961d-483c-aec3-db09d98dc6ee
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private EntityManager entityManager; private SystemManager systemManager; public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager(); systemManager.context = this; } public Entity CreateEntity() { return entityManager.CreateEntity(); } public void AddSystem(System system, int priority = 0) { systemManager.SetSystem(system, priority); } public void Update(float deltaTime) { foreach (var systems in systemManager.SystemsByPriority()) { entityManager.ProcessQueues(); foreach (var system in systems) { system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime); } } systemManager.ProcessQueues(); } } } ``` Add method for querying active entities
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private EntityManager entityManager; private SystemManager systemManager; public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager(); systemManager.context = this; } public Entity CreateEntity() { return entityManager.CreateEntity(); } public void AddSystem(System system, int priority = 0) { systemManager.SetSystem(system, priority); } // TODO: Is this needed and is this right place for this method? public IEnumerable<Entity> QueryActiveEntities(Aspect aspect) { return entityManager.GetEntitiesForAspect(aspect); } public void Update(float deltaTime) { foreach (var systems in systemManager.SystemsByPriority()) { entityManager.ProcessQueues(); foreach (var system in systems) { system.processAll(entityManager.GetEntitiesForAspect(system.Aspect), deltaTime); } } systemManager.ProcessQueues(); } } } ```
be43b3d3-1b88-43e3-8f02-ca006fb7e03c
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Starboard"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("starboard-remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("starboard-remote")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Change remote app version to v0.1
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Starboard"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // AssemblyInfo.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("starboard-remote")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ascend")] [assembly: AssemblyProduct("starboard-remote")] [assembly: AssemblyCopyright("Copyright © Ascend 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] ```
545d8492-a799-4c62-9537-23eebba6bc94
{ "language": "C#" }
```c# // Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // 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. using System; namespace MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new SphereGame()) program.Run(); } } } ``` Fix compilation error in sample
```c# // Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // 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. using System; namespace MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new MiniCubeGame()) program.Run(); } } } ```
5f436228-61f9-4ed5-8e6d-b879a20d67d0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens; namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers { public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver { private readonly IEnumerable<Type> _functionTypeSamples; private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap; public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples) { _functionTypeSamples = functionTypeSamples; _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap); } public Type Resolve(FunctionCall functionCall) { Type result; return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result) ? null : result; } private IDictionary<string, Type> InitializeFunctionNameToTypeMap() { var result = new Dictionary<string, Type>(); foreach (var functionTypeSample in _functionTypeSamples) { // TODO: Scan sample's assembly for function types // TODO: Fill result with type names without "Function" suffix } return result; } } } ``` Implement scanning assemblies for function types
```c# using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Manisero.DSLExecutor.Domain.FunctionsDomain; using Manisero.DSLExecutor.Extensions; using Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens; namespace Manisero.DSLExecutor.Parser.SampleDSL.ExpressionGeneration.FunctionExpressionGeneration.FunctionTypeResolvers { public class TypeSamplesAndSuffixConventionBasedFunctionTypeResolver : IFunctionTypeResolver { private readonly IEnumerable<Type> _functionTypeSamples; private readonly Lazy<IDictionary<string, Type>> _functionNameToTypeMap; public TypeSamplesAndSuffixConventionBasedFunctionTypeResolver(IEnumerable<Type> functionTypeSamples) { _functionTypeSamples = functionTypeSamples; _functionNameToTypeMap = new Lazy<IDictionary<string, Type>>(InitializeFunctionNameToTypeMap); } public Type Resolve(FunctionCall functionCall) { Type result; return !_functionNameToTypeMap.Value.TryGetValue(functionCall.FunctionName, out result) ? null : result; } private IDictionary<string, Type> InitializeFunctionNameToTypeMap() { var result = new Dictionary<string, Type>(); var assembliesToScan = _functionTypeSamples.Select(x => x.Assembly).Distinct(); var typesToScan = assembliesToScan.SelectMany(x => x.GetTypes()); foreach (var type in typesToScan) { var functionDefinitionImplementation = type.GetGenericInterfaceDefinitionImplementation(typeof(IFunction<>)); if (functionDefinitionImplementation == null) { continue; } // TODO: Fill result with type names without "Function" suffix } return result; } } } ```
1245958e-3fe7-44c4-8b8e-d97c28935b6e
{ "language": "C#" }
```c# using Microsoft.MixedReality.Toolkit.Physics; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// The default implementation of IMixedRealityRaycastProvider. /// </summary> public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider { public DefaultRaycastProvider( IMixedRealityServiceRegistrar registrar, IMixedRealityInputSystem inputSystem, MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile) { } /// <inheritdoc /> public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } /// <inheritdoc /> public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } } } ``` Add missing copyright header text.
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Physics; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// The default implementation of IMixedRealityRaycastProvider. /// </summary> public class DefaultRaycastProvider : BaseDataProvider, IMixedRealityRaycastProvider { public DefaultRaycastProvider( IMixedRealityServiceRegistrar registrar, IMixedRealityInputSystem inputSystem, MixedRealityInputSystemProfile profile) : base(registrar, inputSystem, null, DefaultPriority, profile) { } /// <inheritdoc /> public bool Raycast(RayStep step, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSimplePhysicsStep(step, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } /// <inheritdoc /> public bool SphereCast(RayStep step, float radius, LayerMask[] prioritizedLayerMasks, out MixedRealityRaycastHit hitInfo) { var result = MixedRealityRaycaster.RaycastSpherePhysicsStep(step, radius, step.Length, prioritizedLayerMasks, out RaycastHit physicsHit); hitInfo = new MixedRealityRaycastHit(physicsHit); return result; } } } ```
fab9e27f-3aad-45c8-a5b2-86df467c8471
{ "language": "C#" }
```c# using System; using UIKit; namespace MyTrips.iOS { public partial class TripSummaryViewController : UIViewController { public ViewModel.CurrentTripViewModel ViewModel { get; set; } public TripSummaryViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}"; lblDuration.Text = ViewModel.ElapsedTime; lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}"; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await DismissViewControllerAsync(true); await ViewModel.SaveRecordingTripAsync(); } } }``` Save trip before dismissing summary.
```c# using System; using UIKit; namespace MyTrips.iOS { public partial class TripSummaryViewController : UIViewController { public ViewModel.CurrentTripViewModel ViewModel { get; set; } public TripSummaryViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { lblDateTime.Text = $"{DateTime.Now.ToString("M")} {DateTime.Now.ToString("t")}"; lblDistance.Text = $"{ViewModel.Distance} {ViewModel.DistanceUnits.ToLower()}"; lblDuration.Text = ViewModel.ElapsedTime; lblFuelConsumed.Text = $"{ViewModel.FuelConsumption} {ViewModel.FuelConsumptionUnits.ToLower()}"; lblDistance.Alpha = 0; lblDuration.Alpha = 0; lblTopSpeed.Alpha = 0; lblFuelConsumed.Alpha = 0; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); lblDistance.FadeIn(0.4, 0.1f); lblDuration.FadeIn(0.4, 0.2f); lblTopSpeed.FadeIn(0.4, 0.3f); lblFuelConsumed.FadeIn(0.4, 0.4f); } async partial void BtnClose_TouchUpInside(UIButton sender) { await ViewModel.SaveRecordingTripAsync(); await DismissViewControllerAsync(true); } } }```
82622067-5a1d-485b-90dd-ede2704f1256
{ "language": "C#" }
```c# using Nito.AsyncEx; using WalletWasabi.Crypto; namespace WalletWasabi.Io { public class MutexIoManager : IoManager { public MutexIoManager(string filePath) : base(filePath) { var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(1, 7); // https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8 // On a server that is running Terminal Services, a named system mutex can have two levels of visibility. // If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. // If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. // In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. // If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". // Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, // and both are visible to all processes in the terminal server session. // That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes. Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}"); } public AsyncMutex Mutex { get; } } } ``` Fix off by one bug
```c# using Nito.AsyncEx; using WalletWasabi.Crypto; namespace WalletWasabi.Io { public class MutexIoManager : IoManager { public MutexIoManager(string filePath) : base(filePath) { var shortHash = HashHelpers.GenerateSha256Hash(FilePath).Substring(0, 7); // https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8 // On a server that is running Terminal Services, a named system mutex can have two levels of visibility. // If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. // If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. // In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. // If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". // Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, // and both are visible to all processes in the terminal server session. // That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes. Mutex = new AsyncMutex($"{FileNameWithoutExtension}-{shortHash}"); } public AsyncMutex Mutex { get; } } } ```
14026cad-3c8b-400c-90ee-60feb473b7ac
{ "language": "C#" }
```c# using FluentAssertions; using MergableMigrations.EF6; using MergableMigrations.Specification.Implementation; using System; using System.Linq; using Xunit; namespace Mathematicians.UnitTests { public class SqlGeneratorTests { [Fact] public void CanGenerateSql() { var migrations = new Migrations(); var migrationHistory = new MigrationHistory(); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(3); sql[0].Should().Be("CREATE DATABASE [Mathematicians]"); sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]"); sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]"); } } } ``` Test for migrations up to date.
```c# using FluentAssertions; using MergableMigrations.EF6; using MergableMigrations.Specification; using MergableMigrations.Specification.Implementation; using System; using System.Linq; using Xunit; namespace Mathematicians.UnitTests { public class SqlGeneratorTests { [Fact] public void CanGenerateSql() { var migrations = new Migrations(); var migrationHistory = new MigrationHistory(); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(3); sql[0].Should().Be("CREATE DATABASE [Mathematicians]"); sql[1].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Mathematician]"); sql[2].Should().Be("CREATE TABLE [Mathematicians].[dbo].[Contribution]"); } [Fact] public void GeneratesNoSqlWhenUpToDate() { var migrations = new Migrations(); var migrationHistory = GivenCompleteMigrationHistory(migrations); var sqlGenerator = new SqlGenerator(migrations, migrationHistory); var sql = sqlGenerator.Generate(); sql.Length.Should().Be(0); } private MigrationHistory GivenCompleteMigrationHistory(Migrations migrations) { var model = new ModelSpecification(); migrations.AddMigrations(model); return model.MigrationHistory; } } } ```
71558cba-3717-4fa2-a082-01ba6c6650c0
{ "language": "C#" }
```c# using System; using System.Threading; namespace Criteo.Profiling.Tracing.Utils { /// <summary> /// Thread-safe random long generator. /// /// See "Correct way to use Random in multithread application" /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application /// </summary> internal static class RandomUtils { private static int seed = Environment.TickCount; private static readonly ThreadLocal<Random> rand = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed))); public static long NextLong() { return (long)((rand.Value.NextDouble() * 2.0 - 1.0) * long.MaxValue); } } } ``` Change random to avoid identical seed
```c# using System; using System.Threading; namespace Criteo.Profiling.Tracing.Utils { /// <summary> /// Thread-safe random long generator. /// /// See "Correct way to use Random in multithread application" /// http://stackoverflow.com/questions/19270507/correct-way-to-use-random-in-multithread-application /// </summary> internal static class RandomUtils { private static int _seed = Guid.NewGuid().GetHashCode(); private static readonly ThreadLocal<Random> LocalRandom = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref _seed))); public static long NextLong() { var buffer = new byte[8]; LocalRandom.Value.NextBytes(buffer); return BitConverter.ToInt64(buffer, 0); } } } ```
c6c9baa7-def1-4e10-8971-cb58ca6fbf47
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace NuPack { public class PackageAuthoring { private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" }, StringComparer.OrdinalIgnoreCase); public static void Main(string[] args) { // Review: Need to use a command-line parsing library instead of parsing it this way. string executable = Path.GetFileName(Environment.GetCommandLineArgs().First()); string Usage = String.Format(CultureInfo.InvariantCulture, "Usage: {0} <manifest-file>", executable); if (!args.Any()) { Console.Error.WriteLine(Usage); return; } try { // Parse the arguments. The last argument is the content to be added to the package var manifestFile = args.First(); PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile); builder.Created = DateTime.Now; builder.Modified = DateTime.Now; var outputFile = String.Join(".", builder.Id, builder.Version, "nupack"); // Remove the output file or the package spec might try to include it (which is default behavior) builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path))); using (Stream stream = File.Create(outputFile)) { builder.Save(stream); } Console.WriteLine("{0} created successfully", outputFile); } catch (Exception exception) { Console.Error.WriteLine(exception.Message); } } } } ``` Allow output directory to be specified as a second parameter.
```c# using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace NuPack { public class PackageAuthoring { private static readonly HashSet<string> _exclude = new HashSet<string>(new[] { ".nupack", ".nuspec" }, StringComparer.OrdinalIgnoreCase); public static void Main(string[] args) { // Review: Need to use a command-line parsing library instead of parsing it this way. string executable = Path.GetFileName(Environment.GetCommandLineArgs().First()); string Usage = String.Format(CultureInfo.InvariantCulture, "Usage: {0} <manifest-file>", executable); if (!args.Any()) { Console.Error.WriteLine(Usage); return; } try { var manifestFile = args.First(); string outputDirectory = args.Length > 1 ? args[1] : Directory.GetCurrentDirectory(); PackageBuilder builder = PackageBuilder.ReadFrom(manifestFile); builder.Created = DateTime.Now; builder.Modified = DateTime.Now; var outputFile = String.Join(".", builder.Id, builder.Version, "nupack"); // Remove the output file or the package spec might try to include it (which is default behavior) builder.Files.RemoveAll(file => _exclude.Contains(Path.GetExtension(file.Path))); string outputPath = Path.Combine(outputDirectory, outputFile); using (Stream stream = File.Create(outputPath)) { builder.Save(stream); } Console.WriteLine("{0} created successfully", outputPath); } catch (Exception exception) { Console.Error.WriteLine(exception.Message); } } } } ```
3450ff10-a7e3-443a-98e2-701bffd81619
{ "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 System.Collections.Generic; using System.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Allocation { /// <summary> /// A queue which batches object disposal on threadpool threads. /// </summary> internal static class AsyncDisposalQueue { private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal"); private static readonly Queue<IDisposable> disposal_queue = new Queue<IDisposable>(); private static Task runTask; public static void Enqueue(IDisposable disposable) { lock (disposal_queue) disposal_queue.Enqueue(disposable); if (runTask?.Status < TaskStatus.Running) return; runTask = Task.Run(() => { IDisposable[] itemsToDispose; lock (disposal_queue) { itemsToDispose = disposal_queue.ToArray(); disposal_queue.Clear(); } foreach (var item in itemsToDispose) { last_disposal.Value = item.ToString(); item.Dispose(); } }); } } } ``` Make the queue into a list
```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 System.Collections.Generic; using System.Threading.Tasks; using osu.Framework.Statistics; namespace osu.Framework.Allocation { /// <summary> /// A queue which batches object disposal on threadpool threads. /// </summary> internal static class AsyncDisposalQueue { private static readonly GlobalStatistic<string> last_disposal = GlobalStatistics.Get<string>("Drawable", "Last disposal"); private static readonly List<IDisposable> disposal_queue = new List<IDisposable>(); private static Task runTask; public static void Enqueue(IDisposable disposable) { lock (disposal_queue) disposal_queue.Add(disposable); if (runTask?.Status < TaskStatus.Running) return; runTask = Task.Run(() => { IDisposable[] itemsToDispose; lock (disposal_queue) { itemsToDispose = disposal_queue.ToArray(); disposal_queue.Clear(); } foreach (var item in itemsToDispose) { last_disposal.Value = item.ToString(); item.Dispose(); } }); } } } ```
14ca073f-f776-43fc-88d9-ed3ce38b3a27
{ "language": "C#" }
```c# using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } } } ``` Make performance counter tests more stable
```c# using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 1000000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 1000000, "Because memory usage can change between the two values"); } } } ```
6387b424-0717-4b8e-b570-11012a943823
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; namespace mvcWebApp.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { string domain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); // NICE-TO-HAVE Sort images by height. string imagesDir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Images"); string[] files = Directory.EnumerateFiles(imagesDir).Select(p => domain + "/Images/" + Path.GetFileName(p)).ToArray(); ViewBag.ImageVirtualPaths = files; return View(); } } } ``` Make domain a property for reuse.
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; namespace mvcWebApp.Controllers { public class HomeController : Controller { public string domain { get { string domain = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port); return domain; } } // // GET: /Home/ public ActionResult Index() { // NICE-TO-HAVE Sort images by height. string imagesDir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Images"); string[] files = Directory.EnumerateFiles(imagesDir).Select(p => this.domain + "/Images/" + Path.GetFileName(p)).ToArray(); ViewBag.ImageVirtualPaths = files; return View(); } } } ```
8677da11-e201-4716-b3c5-b7213e46e2bc
{ "language": "C#" }
```c# using System.Collections.Generic; using Nest.Domain; using Newtonsoft.Json; using System.Linq.Expressions; using System; using System.Linq; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("name")] public string State { get; set;} [JsonProperty("primary")] public bool Primary { get; set;} [JsonProperty("node")] public string Node { get; set;} [JsonProperty("relocating_node")] public string RelocatingNode { get; set;} [JsonProperty("shard")] public int Shard { get; set;} [JsonProperty("index")] public string Index { get; set;} } }``` Fix wrong property mapping in SearchShard
```c# using Nest.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("state")] public string State { get; set; } [JsonProperty("primary")] public bool Primary { get; set; } [JsonProperty("node")] public string Node { get; set; } [JsonProperty("relocating_node")] public string RelocatingNode { get; set; } [JsonProperty("shard")] public int Shard { get; set; } [JsonProperty("index")] public string Index { get; set; } } }```
612e099a-2e2c-4fcd-a733-2643e7284733
{ "language": "C#" }
```c# using System.Collections.Generic; using Glimpse.Core.Extensibility; using Nancy.Bootstrapper; namespace Glimpse.Nancy { public class GlimpseRegistrations : IApplicationRegistrations { public GlimpseRegistrations() { AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly); } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>(); var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>(); return new[] { new CollectionTypeRegistration(typeof(ITab), tabs), new CollectionTypeRegistration(typeof(IInspector), inspectors) }; } } public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } public IEnumerable<TypeRegistration> TypeRegistrations { get { return null; } } } }``` Remove usage of obsolete IApplicationRegistration
```c# using System.Collections.Generic; using Glimpse.Core.Extensibility; using Nancy.Bootstrapper; namespace Glimpse.Nancy { public class GlimpseRegistrations : IRegistrations { public GlimpseRegistrations() { AppDomainAssemblyTypeScanner.AddAssembliesToScan(typeof(Glimpse.Core.Tab.Timeline).Assembly); } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get { var tabs = AppDomainAssemblyTypeScanner.TypesOf<ITab>(); var inspectors = AppDomainAssemblyTypeScanner.TypesOf<IInspector>(); return new[] { new CollectionTypeRegistration(typeof(ITab), tabs), new CollectionTypeRegistration(typeof(IInspector), inspectors) }; } } public IEnumerable<InstanceRegistration> InstanceRegistrations { get { return null; } } public IEnumerable<TypeRegistration> TypeRegistrations { get { return null; } } } }```
7b70e51c-5951-4185-9e2a-1bdd9bc9f34c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => _.ThruDate > DateTime.Today).Where(_ => DateTime.Today.AddDays(30) < _.ThruDate).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => _.ThruDate > DateTime.Today.AddDays(30)).Where(_ => DateTime.Today.AddDays(60) <= _.ThruDate).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => _.ThruDate > DateTime.Today.AddDays(60)).Where(_ => DateTime.Today.AddDays(90) <= _.ThruDate).Count(); } }``` Fix logic on 30/60/90 day buckets
```c# using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace BatteryCommander.Web.Models { public class EvaluationListViewModel { public IEnumerable<Evaluation> Evaluations { get; set; } = Enumerable.Empty<Evaluation>(); [Display(Name = "Delinquent > 60 Days")] public int Delinquent => Evaluations.Where(_ => _.IsDelinquent).Count(); public int Due => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => _.ThruDate < DateTime.Today).Count(); [Display(Name = "Next 30")] public int Next30 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 0 <= _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 30).Count(); [Display(Name = "Next 60")] public int Next60 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 30 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 60).Count(); [Display(Name = "Next 90")] public int Next90 => Evaluations.Where(_ => !_.IsDelinquent).Where(_ => 60 < _.Delinquency.TotalDays && _.Delinquency.TotalDays <= 90).Count(); } }```
a3cfad8a-7bce-4112-9a71-b40312aa654c
{ "language": "C#" }
```c# using System; using System.Linq; using FluentAssertions; using NSaga; using Xunit; namespace Tests { public class NamespaceTests { [Fact] public void NSaga_Contains_Only_One_Namespace() { //Arrange var assembly = typeof(ISagaMediator).Assembly; // Act var namespaces = assembly.GetTypes() .Where(t => t.IsPublic) .Select(t => t.Namespace) .Distinct() .ToList(); // Assert var names = String.Join(", ", namespaces); namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'"); } [Fact] public void PetaPoco_Stays_Internal() { //Arrange var petapocoTypes = typeof(SqlSagaRepository).Assembly .GetTypes() .Where(t => !String.IsNullOrEmpty(t.Namespace)) .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase)) .Where(t => t.IsPublic) .ToList(); petapocoTypes.Should().BeEmpty(); } } } ``` Test to check tinyioc is internal
```c# using System; using System.Linq; using FluentAssertions; using NSaga; using Xunit; namespace Tests { public class NamespaceTests { [Fact] public void NSaga_Contains_Only_One_Namespace() { //Arrange var assembly = typeof(ISagaMediator).Assembly; // Act var namespaces = assembly.GetTypes() .Where(t => t.IsPublic) .Select(t => t.Namespace) .Distinct() .ToList(); // Assert var names = String.Join(", ", namespaces); namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'"); } [Fact] public void PetaPoco_Stays_Internal() { //Arrange var petapocoTypes = typeof(SqlSagaRepository).Assembly .GetTypes() .Where(t => !String.IsNullOrEmpty(t.Namespace)) .Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase)) .Where(t => t.IsPublic) .ToList(); petapocoTypes.Should().BeEmpty(); } [Fact] public void TinyIoc_Stays_Internal() { typeof(TinyIoCContainer).IsPublic.Should().BeFalse(); } } } ```
d85939eb-7120-4486-a948-0666078d78b4
{ "language": "C#" }
```c# @{ var version = ""; var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString(); if(Yio.Data.Constants.VersionConstant.Patch == 0) { version = Yio.Data.Constants.VersionConstant.Release.ToString(); } else { version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." + Yio.Data.Constants.VersionConstant.Patch.ToString(); } } <div class="panel" id="about-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>About</h1> <p> <strong>Curl your paw round your dick, and get clicking!</strong> </p> <p> Filled with furry (and more) porn, stripped from many sources &mdash; tumblr, e621, 4chan, 8chan, etc. &mdash; Yiff.co is the never-ending full-width stream of NSFW images. Built by <a href="https://zyr.io">Zyrio</a>. </p> <p> Running on version <strong>@version '@(versionName)'</strong> </p> </div> </div>``` Add license and disclaimer to About panel
```c# @{ var version = ""; var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString(); if(Yio.Data.Constants.VersionConstant.Patch == 0) { version = Yio.Data.Constants.VersionConstant.Release.ToString(); } else { version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." + Yio.Data.Constants.VersionConstant.Patch.ToString(); } } <div class="panel" id="about-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1>About</h1> <p> <strong>Curl your paw round your dick, and get clicking!</strong> </p> <p> Filled with furry (and more) porn, stripped from many sources &mdash; tumblr, e621, 4chan, 8chan, etc. &mdash; Yiff.co is the never-ending full-width stream of NSFW images. </p> <p> Built by <a href="https://zyr.io">Zyrio</a>. Licensed under the MIT license, with code available on <a href="https://git.zyr.io/zyrio/yio">Zyrio Git</a>. All copyrights belong to their respectful owner, and Yiff.co does not claim ownership over any of them, nor does Yiff.co generate any money. </p> <p> Running on version <strong>@version '@(versionName)'</strong> </p> </div> </div>```
1d182982-32d3-4d57-bb2b-cfde9bd5e01b
{ "language": "C#" }
```c# // ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Profile { [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")] [Alias("Enable-AzureDataCollection")] public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet { protected override void ProcessRecord() { SetDataCollectionProfile(true); } protected void SetDataCollectionProfile(bool enable) { var profile = GetDataCollectionProfile(); profile.EnableAzureDataCollection = enable; SaveDataCollectionProfile(); } } } ``` Fix data collection cmdlets to not require login
```c# // ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using System.Security.Permissions; namespace Microsoft.Azure.Commands.Profile { [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection")] [Alias("Enable-AzureDataCollection")] public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet { protected override void BeginProcessing() { // do not call begin processing there is no context needed for this cmdlet } protected override void ProcessRecord() { SetDataCollectionProfile(true); } protected void SetDataCollectionProfile(bool enable) { var profile = GetDataCollectionProfile(); profile.EnableAzureDataCollection = enable; SaveDataCollectionProfile(); } } } ```
a12def5d-1132-4ffc-8d87-92a7a2ea2390
{ "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 System.Linq; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSingleTap : InputBlockingMod { public override string Name => @"Single Tap"; public override string Acronym => @"ST"; public override string Description => @"You must only use one key!"; public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray(); protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action; } } ``` Change "single tap" mod acronym to not conflict with "strict tracking"
```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 System.Linq; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSingleTap : InputBlockingMod { public override string Name => @"Single Tap"; public override string Acronym => @"SG"; public override string Description => @"You must only use one key!"; public override Type[] IncompatibleMods => base.IncompatibleMods.Concat(new[] { typeof(OsuModAlternate) }).ToArray(); protected override bool CheckValidNewAction(OsuAction action) => LastAcceptedAction == null || LastAcceptedAction == action; } } ```
7f9b094c-65ec-40d9-b682-1373827ec903
{ "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.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Ladder.Components; namespace osu.Game.Tournament.Tests { public class TestCaseMapPool : LadderTestCase { [BackgroundDependencyLoader] private void load() { var round = Ladder.Groupings.First(g => g.Name == "Finals"); Add(new MapPoolScreen(round)); } } public class MapPoolScreen : CompositeDrawable { public MapPoolScreen(TournamentGrouping round) { FillFlowContainer maps; InternalChildren = new Drawable[] { maps = new FillFlowContainer { Direction = FillDirection.Full, RelativeSizeAxes = Axes.Both, }, }; foreach (var b in round.Beatmaps) maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo)); } } } ``` Make map pool layout more correct
```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.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Screens; using osu.Game.Tournament.Components; using osu.Game.Tournament.Screens.Ladder.Components; using OpenTK; namespace osu.Game.Tournament.Tests { public class TestCaseMapPool : LadderTestCase { [BackgroundDependencyLoader] private void load() { var round = Ladder.Groupings.First(g => g.Name == "Finals"); Add(new MapPoolScreen(round)); } } public class MapPoolScreen : OsuScreen { public MapPoolScreen(TournamentGrouping round) { FillFlowContainer maps; InternalChildren = new Drawable[] { maps = new FillFlowContainer { Spacing = new Vector2(20), Padding = new MarginPadding(50), Direction = FillDirection.Full, RelativeSizeAxes = Axes.Both, }, }; foreach (var b in round.Beatmaps) maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }); } } } ```
fe3a404c-967b-4ed9-b937-03b883a8d713
{ "language": "C#" }
```c# using System; using System.Dynamic; namespace BobTheBuilder { public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class { private readonly IDynamicBuilder<T> wrappedBuilder; private readonly IArgumentStore argumentStore; internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore) { if (wrappedBuilder == null) { throw new ArgumentNullException("wrappedBuilder"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.wrappedBuilder = wrappedBuilder; this.argumentStore = argumentStore; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { return wrappedBuilder.TryInvokeMember(binder, args, out result); } public T Build() { return wrappedBuilder.Build(); } } }``` Add support for named argument parsing.
```c# using System; using System.Dynamic; using System.Linq; namespace BobTheBuilder { public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class { private readonly IDynamicBuilder<T> wrappedBuilder; private readonly IArgumentStore argumentStore; internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore) { if (wrappedBuilder == null) { throw new ArgumentNullException("wrappedBuilder"); } if (argumentStore == null) { throw new ArgumentNullException("argumentStore"); } this.wrappedBuilder = wrappedBuilder; this.argumentStore = argumentStore; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder.Name == "With") { ParseNamedArgumentValues(binder.CallInfo, args); } return wrappedBuilder.TryInvokeMember(binder, args, out result); } private void ParseNamedArgumentValues(CallInfo callInfo, object[] args) { var argumentName = callInfo.ArgumentNames.First(); argumentName = argumentName.First().ToString().ToUpper() + argumentName.Substring(1); argumentStore.SetMemberNameAndValue(argumentName, args.First()); } public T Build() { return wrappedBuilder.Build(); } } }```
dccb304a-779e-4ffb-b346-dbcc5566833c
{ "language": "C#" }
```c# // Copyright 2014 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. #if !PCL using System.Diagnostics; using JetBrains.Annotations; using NodaTime.Utility; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="Stopwatch"/>. /// </summary> public static class StopwatchExtensions { /// <summary> /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>. /// </summary> /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param> /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns> public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch) { Preconditions.CheckNotNull(stopwatch, nameof(stopwatch)); return stopwatch.Elapsed.ToDuration(); } } } #endif``` Enable stopwatch extension methods for .NET Core
```c# // Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Diagnostics; using JetBrains.Annotations; using NodaTime.Utility; namespace NodaTime.Extensions { /// <summary> /// Extension methods for <see cref="Stopwatch"/>. /// </summary> public static class StopwatchExtensions { /// <summary> /// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>. /// </summary> /// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param> /// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns> public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch) { Preconditions.CheckNotNull(stopwatch, nameof(stopwatch)); return stopwatch.Elapsed.ToDuration(); } } } ```
bebbd6ee-715f-4a90-b1f9-261874858ba1
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RedCard.API.Contexts; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace RedCard.API.Controllers { [Route("api/[controller]")] public class StatsController : Controller { public StatsController(ApplicationDbContext dbContext) { _dbContext = dbContext; } readonly ApplicationDbContext _dbContext; [HttpGet] public IActionResult RedCardCountForCountry() { var redCardCount = _dbContext.Players .GroupBy(player => player.Country) .Select(grouping => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) }) .ToArray(); return new ObjectResult(new { redCardCountForCountry = redCardCount }); } } } ``` Add group by yellow cards count
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RedCard.API.Contexts; using RedCard.API.Models; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace RedCard.API.Controllers { [Route("api/[controller]")] public class StatsController : Controller { public StatsController(ApplicationDbContext dbContext) { _dbContext = dbContext; } readonly ApplicationDbContext _dbContext; [Route("redcards")] [HttpGet] public IActionResult RedCardCountForCountry() { Func<IGrouping<string, Player>, object> getRedCardsForCountry = (grouping) => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) }; var redCardCount = _CardsForCountry(getRedCardsForCountry); return new ObjectResult(new { redCardCountForCountry = redCardCount }); } [Route("yellowcards")] [HttpGet] public IActionResult YellowCardCountForCountry() { Func<IGrouping<string, Player>, object> getYellowCardsForCountry = (grouping) => new { country = grouping.Key, yellowCardCount = grouping.Sum(player => player.YellowCards) }; var yellowCardCount = _CardsForCountry(getYellowCardsForCountry); return new ObjectResult(new { yellowCardCountForCountry = yellowCardCount }); } IEnumerable<object> _CardsForCountry(Func<IGrouping<string, Player>, object> getInfo) { return _dbContext.Players .GroupBy(player => player.Country) .Select(getInfo) .ToArray(); } } } ```
88a17b4b-9f0c-4e65-b813-99711d855b07
{ "language": "C#" }
```c# using System; using System.Collections; using UnityEngine; namespace LunaClient.Utilities { public class CoroutineUtil { public static void StartDelayedRoutine(string routineName, Action action, float delayInSec) { Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec)); } private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec) { yield return new WaitForSeconds(delayInSec); try { action(); } catch (Exception e) { LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}"); } } } } ``` Allow coroutines of 0 sec delay
```c# using System; using System.Collections; using UnityEngine; namespace LunaClient.Utilities { public class CoroutineUtil { public static void StartDelayedRoutine(string routineName, Action action, float delayInSec) { Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec)); } private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec) { if (delayInSec > 0) yield return new WaitForSeconds(delayInSec); try { action(); } catch (Exception e) { LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}"); } } } } ```
9d96abb8-0028-4953-9711-4d2888aa5b51
{ "language": "C#" }
```c# namespace uSync { /// <summary> /// we only have this class, so there is a dll in the root /// uSync package. /// /// With a root dll, the package can be stopped from installing /// on .netframework sites. /// </summary> public static class uSync { // private static string Welcome = "uSync all the things"; } } ``` Add blank package migration (to get into the list)
```c# using System; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Packaging; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Migrations; using Umbraco.Cms.Infrastructure.Packaging; namespace uSync { /// <summary> /// we only have this class, so there is a dll in the root /// uSync package. /// /// With a root dll, the package can be stopped from installing /// on .netframework sites. /// </summary> public static class uSync { public static string PackageName = "uSync"; // private static string Welcome = "uSync all the things"; } /// <summary> /// A package migration plan, allows us to put uSync in the list /// of installed packages. we don't actually need a migration /// for uSync (doesn't add anything to the db). but by doing /// this people can see that it is insalled. /// </summary> public class uSyncMigrationPlan : PackageMigrationPlan { public uSyncMigrationPlan() : base(uSync.PackageName) { } protected override void DefinePlan() { To<SetupuSync>(new Guid("65735030-E8F2-4F34-B28A-2201AF9792BE")); } } public class SetupuSync : PackageMigrationBase { public SetupuSync( IPackagingService packagingService, IMediaService mediaService, MediaFileManager mediaFileManager, MediaUrlGeneratorCollection mediaUrlGenerators, IShortStringHelper shortStringHelper, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, IMigrationContext context) : base(packagingService, mediaService, mediaFileManager, mediaUrlGenerators, shortStringHelper, contentTypeBaseServiceProvider, context) { } protected override void Migrate() { // we don't actually need to do anything, but this means we end up // on the list of installed packages. } } } ```
b56a1bb1-6c0e-4271-a19b-c769fdb5364d
{ "language": "C#" }
```c# using System; using System.Net.Http.Headers; using System.Threading.Tasks; using Infrastructure.Model; using Microsoft.AspNetCore.Mvc; namespace Web.Controllers { public class HomeController : Controller { [HttpGet] public async Task<string> Index() { var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); var response = await client.GetAsync("api/home"); if (response.IsSuccessStatusCode) { using(var stream = await response.Content.ReadAsStreamAsync()) { var model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream); return $"{model.Name}, {model.StringValue}, {model.Id}"; } } return "Failed"; } } }``` Add check for content type when parsing in client. Fallback to Json if Protobuf is not available
```c# using System; using System.Net.Http.Headers; using System.Threading.Tasks; using Infrastructure.Model; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace Web.Controllers { public class HomeController : Controller { [HttpGet] public async Task<string> Index() { var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync("api/home"); if (response.IsSuccessStatusCode) { using(var stream = await response.Content.ReadAsStreamAsync()) { ProtobufModelDto model = null; if (response.Content.Headers.ContentType.MediaType == "application/x-protobuf") { model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream); return $"{model.Name}, {model.StringValue}, {model.Id}"; } var content = await response.Content.ReadAsStringAsync(); model = JsonConvert.DeserializeObject<ProtobufModelDto>(content); return $"{model.Name}, {model.StringValue}, {model.Id}"; } } return "Failed"; } } }```
2f0bee5a-f4be-4f93-8315-02ffc88f8d61
{ "language": "C#" }
```c# using System; using System.IO; using System.Runtime.CompilerServices; using ExpressionToCodeLib; using Xunit; //requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core namespace ExpressionToCodeTest { public class ExceptionsSerialization { [MethodImpl(MethodImplOptions.NoInlining)] static void IntentionallyFailingMethod() => PAssert.That(() => false); [Fact] public void PAssertExceptionIsSerializable() => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod); static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod) { var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, original); var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray())); Assert.Equal(original.ToString(), deserialized.ToString()); } } } ``` Disable warnings about obsoletion since the point is testing the obsolete stuff still works
```c# using System; using System.IO; using System.Runtime.CompilerServices; using ExpressionToCodeLib; using Xunit; //requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core namespace ExpressionToCodeTest { public class ExceptionsSerialization { [MethodImpl(MethodImplOptions.NoInlining)] static void IntentionallyFailingMethod() => PAssert.That(() => false); [Fact] public void PAssertExceptionIsSerializable() => AssertMethodFailsWithSerializableException(IntentionallyFailingMethod); #pragma warning disable SYSLIB0011 // BinaryFormatter is Obsolete static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod) { var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod); var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, original); var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray())); Assert.Equal(original.ToString(), deserialized.ToString()); } #pragma warning restore SYSLIB0011 } } ```
6fde7adb-ddc0-4ddf-84a3-b18533a039a5
{ "language": "C#" }
```c# //////////////////////////////////////////////////////////////// // // (c) 2009, 2010 Careminster Limited and Melanie Thielker // // All rights reserved // using System; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using Nini.Config; using log4net; using Careminster; using OpenMetaverse; namespace Careminster { public interface IAttachmentsService { string Get(string id); void Store(string id, string data); } } ``` Remove some usings that stopped compilation
```c# //////////////////////////////////////////////////////////////// // // (c) 2009, 2010 Careminster Limited and Melanie Thielker // // All rights reserved // using System; using Nini.Config; namespace OpenSim.Services.Interfaces { public interface IAttachmentsService { string Get(string id); void Store(string id, string data); } } ```
238a589c-fae1-4785-a463-5e79ff84aada
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FizzWare.NBuilder; using IntermediatorBotSample.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Schema; using Newtonsoft.Json; namespace IntermediatorBotSample.Controllers.Api { [Route("api/[controller]")] public class ConversationsController : Controller { [HttpGet] public IEnumerable<Conversation> Get() { return Builder<Conversation>.CreateListOfSize(2) .All() .With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew().Build()) .With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew().Build()) .With(o => o.UserInformation = Builder<UserInformation>.CreateNew().Build()) .Build() .ToList(); } } }``` Add intermediate comments to help explain what to do
```c# using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FizzWare.NBuilder; using IntermediatorBotSample.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Schema; using Newtonsoft.Json; namespace IntermediatorBotSample.Controllers.Api { [Route("api/[controller]")] public class ConversationsController : Controller { [HttpGet] public IEnumerable<Conversation> Get(int convId, int top) { var channels = new[] { "facebook", "skype", "skype for business", "directline" }; var random = new RandomGenerator(); return Builder<Conversation>.CreateListOfSize(5) .All() .With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew() .With(ci => ci.MessagesCount = random.Next(2, 30)) .With(ci => ci.SentimentScore = random.Next(0.0d, 1.0d)) .Build()) .With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew() .With(cr => cr.ChannelId = channels[random.Next(0, channels.Count())]) .Build()) .With(o => o.UserInformation = Builder<UserInformation>.CreateNew() .Build()) .Build() .ToList(); } //TODO: Retrieve ALL the conversation //TOOD: Forward conersation //TODO: DELETE Conversation = immediate kill by conversationId } }```
8585d2cc-1e19-4698-901b-6102095b79b7
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ datablock AudioProfile(MinigunProjectileImpactSound) { filename = "share/sounds/rotc/impact1.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(MinigunProjectileFlybySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(MinigunProjectileMissedEnemySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioClose3D; preload = true; }; ``` Use different sounds for minigun's missed enemy effect.
```c# //------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ datablock AudioProfile(MinigunProjectileImpactSound) { filename = "share/sounds/rotc/impact1.wav"; description = AudioDefault3D; preload = true; }; datablock AudioProfile(MinigunProjectileFlybySound) { filename = "share/sounds/rotc/flyby1.wav"; description = AudioCloseLooping3D; preload = true; }; datablock AudioProfile(MinigunProjectileMissedEnemySound) { filename = "share/sounds/rotc/ricochet1-1.wav"; alternate[0] = "share/sounds/rotc/ricochet1-1.wav"; alternate[1] = "share/sounds/rotc/ricochet1-2.wav"; alternate[2] = "share/sounds/rotc/ricochet1-3.wav"; alternate[3] = "share/sounds/rotc/ricochet1-4.wav"; alternate[4] = "share/sounds/rotc/ricochet1-5.wav"; alternate[5] = "share/sounds/rotc/ricochet1-6.wav"; description = AudioClose3D; preload = true; }; ```
ac6f7b49-f05d-4b75-830a-ae7111d5c080
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EchoServer { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { Console.WriteLine("Starting server"); CancellationToken cancellationToken = new CancellationTokenSource().Token; TcpListener listener = new TcpListener(IPAddress.IPv6Loopback, 8080); listener.Start(); TcpClient client = await listener.AcceptTcpClientAsync(); client.ReceiveTimeout = 30; NetworkStream stream = client.GetStream(); StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; StreamReader reader = new StreamReader(stream, Encoding.ASCII); while (true) { string line = await reader.ReadLineAsync(); Console.WriteLine($"Received {line}"); await writer.WriteLineAsync(line); if (cancellationToken.IsCancellationRequested) break; } listener.Stop(); } } } ``` Move client handling into a separate method.
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EchoServer { class Program { static void Main(string[] args) { Task main = MainAsync(args); main.Wait(); } static async Task MainAsync(string[] args) { Console.WriteLine("Starting server"); TcpListener server = new TcpListener(IPAddress.IPv6Loopback, 8080); Console.WriteLine("Starting listener"); server.Start(); while (true) { TcpClient client = await server.AcceptTcpClientAsync(); Task.Factory.StartNew(() => HandleConnection(client)); } server.Stop(); } static async Task HandleConnection(TcpClient client) { Console.WriteLine($"New connection from {client.Client.RemoteEndPoint}"); client.ReceiveTimeout = 30; client.SendTimeout = 30; NetworkStream stream = client.GetStream(); StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; StreamReader reader = new StreamReader(stream, Encoding.ASCII); string line = await reader.ReadLineAsync(); Console.WriteLine($"Received {line}"); await writer.WriteLineAsync(line); } } } ```
f8407ee1-78a6-47b0-b6b5-a1dddc067fe1
{ "language": "C#" }
```c# using System.Linq; using CppSharp.AST; using CppSharp.Generators; namespace CppSharp.Passes { public class FieldToPropertyPass : TranslationUnitPass { public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); return base.VisitClassDecl(@class); } public override bool VisitFieldDecl(Field field) { if (!VisitDeclaration(field)) return false; var @class = field.Namespace as Class; if (@class == null) return false; if (ASTUtils.CheckIgnoreField(field)) return false; // Check if we already have a synthetized property. var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field); if (existingProp != null) return false; field.GenerationKind = GenerationKind.Internal; var prop = new Property { Name = field.Name, Namespace = field.Namespace, QualifiedType = field.QualifiedType, Access = field.Access, Field = field }; // do not rename value-class fields because they would be // generated as fields later on even though they are wrapped by properties; // that is, in turn, because it's cleaner to write // the struct marshalling logic just for properties if (!prop.IsInRefTypeAndBackedByValueClassField()) field.Name = Generator.GeneratedIdentifier(field.Name); @class.Properties.Add(prop); Diagnostics.Debug("Property created from field: {0}::{1}", @class.Name, field.Name); return false; } } } ``` Clean up the diagnostic in FieldToProperty pass.
```c# using System.Linq; using CppSharp.AST; using CppSharp.Generators; namespace CppSharp.Passes { public class FieldToPropertyPass : TranslationUnitPass { public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); return base.VisitClassDecl(@class); } public override bool VisitFieldDecl(Field field) { if (!VisitDeclaration(field)) return false; var @class = field.Namespace as Class; if (@class == null) return false; if (ASTUtils.CheckIgnoreField(field)) return false; // Check if we already have a synthetized property. var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field); if (existingProp != null) return false; field.GenerationKind = GenerationKind.Internal; var prop = new Property { Name = field.Name, Namespace = field.Namespace, QualifiedType = field.QualifiedType, Access = field.Access, Field = field }; // do not rename value-class fields because they would be // generated as fields later on even though they are wrapped by properties; // that is, in turn, because it's cleaner to write // the struct marshalling logic just for properties if (!prop.IsInRefTypeAndBackedByValueClassField()) field.Name = Generator.GeneratedIdentifier(field.Name); @class.Properties.Add(prop); Diagnostics.Debug($"Property created from field: {field.QualifiedName}"); return false; } } } ```
fff2c78b-83f5-4ae3-b417-d6dc971cd3d8
{ "language": "C#" }
```c#  using System; using NUnit.Framework; namespace HttpMock.Unit.Tests { [TestFixture] public class HttpFactoryTests { [Test] public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed() { var serverFactory = new HttpServerFactory(); var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting())); IHttpServer server1, server2 = null; server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); try { server1.Start(); server1.Dispose(); server1 = null; server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); Assert.DoesNotThrow(server2.Start); } finally { if (server1 != null) { server1.Dispose(); } if (server2 != null) { server2.Dispose(); } } } } } ``` Mark evil test as ignore, again
```c#  using System; using NUnit.Framework; namespace HttpMock.Unit.Tests { [TestFixture] public class HttpFactoryTests { [Test] [Ignore ("Makes the test suite flaky (???)")] public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed() { var serverFactory = new HttpServerFactory(); var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting())); IHttpServer server1, server2 = null; server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); try { server1.Start(); server1.Dispose(); server1 = null; server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri); Assert.DoesNotThrow(server2.Start); } finally { if (server1 != null) { server1.Dispose(); } if (server2 != null) { server2.Dispose(); } } } } } ```
9b91238f-814d-4096-ae47-7fa5a61b415e
{ "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 osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = current.TravelDistance + current.JumpDistance; return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } } ``` Make sure distance is clamped to sane values
```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 osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance); return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } } ```
ecbd5714-3891-4323-943a-59052f7edd61
{ "language": "C#" }
```c# using Qart.Core.DataStore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Qart.Testing { public class TestSystem { public IDataStore DataStorage { get; private set; } public TestSystem(IDataStore dataStorage) { DataStorage = dataStorage; } public TestCase GetTestCase(string id) { return new TestCase(id, this); } public IEnumerable<TestCase> GetTestCases() { return DataStorage.GetAllGroups().Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this)); } } } ``` Fix for GetTestCases not returning current folder
```c# using Qart.Core.DataStore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Qart.Testing { public class TestSystem { public IDataStore DataStorage { get; private set; } public TestSystem(IDataStore dataStorage) { DataStorage = dataStorage; } public TestCase GetTestCase(string id) { return new TestCase(id, this); } public IEnumerable<TestCase> GetTestCases() { return DataStorage.GetAllGroups().Concat(new[]{"."}).Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this)); } } } ```
c6910d75-2281-47eb-8c6d-c72eb5df435e
{ "language": "C#" }
```c# using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:JoyOI.OnlineJudge.Models.VirtualJudgeUser"/> is in use. /// </summary> /// <value><c>true</c> if is in use; otherwise, <c>false</c>.</value> public bool IsInUse { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } } ``` Refactor virtual judge user table schema
```c# using System; using System.ComponentModel.DataAnnotations; namespace JoyOI.OnlineJudge.Models { public class VirtualJudgeUser { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value>The identifier.</value> public Guid Id { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value>The username.</value> [MaxLength(32)] public string Username { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value>The password.</value> [MaxLength(64)] public string Password { get; set; } /// <summary> /// Gets or sets the locker id. /// </summary> /// <value>The locker id.</value> public Guid? LockerId { get; set; } /// <summary> /// Gets or sets the source. /// </summary> /// <value>The source of this user.</value> public ProblemSource Source { get; set; } } } ```
b372641b-17bc-4588-98da-a7325770da8f
{ "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 osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(TextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } } ``` Use LargeTextureStore for online retrievals
```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 osu.Framework.Allocation; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Beatmaps.Drawables { public class BeatmapSetCover : Sprite { private readonly BeatmapSetInfo set; private readonly BeatmapSetCoverType type; public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover) { if (set == null) throw new ArgumentNullException(nameof(set)); this.set = set; this.type = type; } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { string resource = null; switch (type) { case BeatmapSetCoverType.Cover: resource = set.OnlineInfo.Covers.Cover; break; case BeatmapSetCoverType.Card: resource = set.OnlineInfo.Covers.Card; break; case BeatmapSetCoverType.List: resource = set.OnlineInfo.Covers.List; break; } if (resource != null) Texture = textures.Get(resource); } } public enum BeatmapSetCoverType { Cover, Card, List, } } ```
c376c11e-775b-4e05-8a9d-b4d8ea3eb820
{ "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; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder() { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Connection, PacketAction.Player) }; } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }``` Use registered types for Out of Band handlers in packet handling type finder
```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 System.Linq; namespace EOLib.Net.Handlers { public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder { private readonly List<FamilyActionPair> _inBandPackets; private readonly List<FamilyActionPair> _outOfBandPackets; public PacketHandlingTypeFinder(IEnumerable<IPacketHandler> outOfBandHandlers) { _inBandPackets = new List<FamilyActionPair> { new FamilyActionPair(PacketFamily.Init, PacketAction.Init), new FamilyActionPair(PacketFamily.Account, PacketAction.Reply), new FamilyActionPair(PacketFamily.Character, PacketAction.Reply), new FamilyActionPair(PacketFamily.Login, PacketAction.Reply) }; _outOfBandPackets = outOfBandHandlers.Select(x => new FamilyActionPair(x.Family, x.Action)).ToList(); } public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action) { var fap = new FamilyActionPair(family, action); if (_inBandPackets.Contains(fap)) return PacketHandlingType.InBand; if (_outOfBandPackets.Contains(fap)) return PacketHandlingType.OutOfBand; return PacketHandlingType.NotHandled; } } }```
68253c5a-5a97-4f1b-ba8a-3b5c23f4ee94
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get { return Forwards.Count + Backwards.Count - order; } } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { int start = Forwards.Count - order; return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { int start = Backwards.Count - order; return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain, int order) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); this.order = order; } internal void Append(string word) { Forwards.Add(word); } internal void Prepend(string word) { Backwards.Add(word); } } }``` Fix latest chain properties, simplify WordCount property and make it deduce the order from the passed initial chain.
```c# using System; using System.Collections.Generic; namespace Chainey { internal class SentenceConstruct { internal int WordCount { get; private set; } internal string Sentence { get { var sen = new List<string>(Backwards); sen.RemoveRange(0, order); sen.Reverse(); sen.AddRange(Forwards); return string.Join(" ", sen); } } internal string LatestForwardChain { get { var chain = new string[order]; int start = Forwards.Count - order; Forwards.CopyTo(start, chain, 0, order); return string.Join(" ", Forwards, start, order); } } internal string LatestBackwardChain { get { var chain = new string[order]; int start = Backwards.Count - order; Backwards.CopyTo(start, chain, 0, order); return string.Join(" ", Backwards, start, order); } } List<string> Forwards; List<string> Backwards; readonly int order; internal SentenceConstruct(string initialChain) { string[] split = initialChain.Split(' '); Forwards = new List<string>(split); Backwards = new List<string>(split); Backwards.Reverse(); WordCount = split.Length; order = split.Length; } internal void Append(string word) { Forwards.Add(word); WordCount++; } internal void Prepend(string word) { Backwards.Add(word); WordCount++; } } }```
79d2c188-e31a-4a3f-867d-88486ce0dc6b
{ "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("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Update Nuget version of package to 1.1.0.10-rc
```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("KeyPay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("KeyPay")] [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("93365e33-3b92-4ea6-ab42-ffecbc504138")] // 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: AssemblyInformationalVersion("1.1.0.10-rc2")] [assembly: AssemblyFileVersion("1.0.0.0")] ```
8602c422-7fdf-4ad5-b513-9af631f51696
{ "language": "C#" }
```c# using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly ExceptionExpectancyAtAttributeLevel _attribute; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { _attribute = attribute; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_attribute.UserMessage}\""))); // TODO: no need for full attribute, msg only var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }``` Refactor - UserMessage instead of attribute
```c# using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Migrator.Model; namespace NUnit.Migrator.CodeActions { internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator { private readonly string _userMessage; public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator, ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); _userMessage = attribute.UserMessage; } public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType) { var body = base.Create(method, assertedType); if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation)) return body; var userMessageArgument = SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.ParseToken($"\"{_userMessage}\""))); var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument); return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList); } private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation) { invocation = null; if (block.Statements.Count == 0) return false; invocation = (block.Statements.First() as ExpressionStatementSyntax)? .Expression as InvocationExpressionSyntax; return invocation != null; } } }```
277882de-4756-4292-996d-11807f4830c2
{ "language": "C#" }
```c#  using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } class InvokeCacheKey { public object Target{get;set;} public object Func{get;set;} } } ``` Remove caching of invoked expressions as it is hard to do and adds little benefit
```c#  using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; namespace MFlow.Core.Internal { /// <summary> /// An expression builder /// </summary> class ExpressionBuilder<T> : IExpressionBuilder<T> { static IDictionary<object, object> _expressions= new Dictionary<object, object>(); static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>(); /// <summary> /// Compiles the expression /// </summary> public Func<T, C> Compile<C>(Expression<Func<T, C>> expression) { if(_expressions.ContainsKey(expression)) return (Func<T, C>)_expressions[expression]; var compiled = expression.Compile(); _expressions.Add(expression, compiled); return compiled; } /// <summary> /// Invokes the expression /// </summary> public C Invoke<C>(Func<T, C> compiled, T target) { return compiled.Invoke(target); } } } ```
21a56cc8-83bc-4bf9-92d6-65c86bec5fd0
{ "language": "C#" }
```c# using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Schema = schema; Name = name; } } } ``` Add missing ctor field initializations
```c# using SSMScripter.Integration; using System; using System.Data; namespace SSMScripter.Scripter.Smo { public class SmoObjectMetadata { public SmoObjectType Type { get; protected set; } public string Schema { get; protected set; } public string Name { get; protected set; } public string ParentSchema { get; protected set; } public string ParentName { get; protected set; } public bool? AnsiNullsStatus { get; set; } public bool? QuotedIdentifierStatus { get; set; } public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName) { Type = type; Schema = schema; Name = name; ParentSchema = parentSchema; ParentName = parentName; } } } ```
631afc0c-7043-4387-afed-9f7daf967389
{ "language": "C#" }
```c# @model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Comment</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } ``` Change div class and change the position of button back
```c# @model SpaceBlog.Models.CommentViewModel @{ ViewBag.Title = "Edit"; ViewBag.Message = "Comment"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="container"> <h2>@ViewBag.Title</h2> <h4>@ViewBag.Message</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.ArticleId) @Html.HiddenFor(m => m.AuthorId) <div class="form-group"> @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10" style="margin-top: 10px"> <input type="submit" value="Save" class="btn btn-success" /> @Html.ActionLink("Back", "Index", new { @id = ""}, new { @class = "btn btn-primary" }) </div> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }```
6a09dc31-8ff9-4d13-a9a2-928e21852551
{ "language": "C#" }
```c# using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); Assert.Collection(result, issue => Assert.Equal("DP1", ((dynamic)issue).ProjectShortName)); } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }``` Change assertion to support multiple issues in test
```c# using System.Threading.Tasks; using Xunit; using YouTrackSharp.Issues; using YouTrackSharp.Tests.Infrastructure; namespace YouTrackSharp.Tests.Integration.Issues { public partial class IssuesServiceTests { public class GetIssuesInProject { [Fact] public async Task Valid_Connection_Returns_Issues() { // Arrange var connection = Connections.Demo1Token; var service = new IssuesService(connection); // Act var result = await service.GetIssuesInProject("DP1", filter: "assignee:me"); // Assert Assert.NotNull(result); foreach (dynamic issue in result) { Assert.Equal("DP1", issue.ProjectShortName); } } [Fact] public async Task Invalid_Connection_Throws_UnauthorizedConnectionException() { // Arrange var service = new IssuesService(Connections.UnauthorizedConnection); // Act & Assert await Assert.ThrowsAsync<UnauthorizedConnectionException>( async () => await service.GetIssuesInProject("DP1")); } } } }```
45f78b34-2965-45d5-82a3-a7dd2e44cbd2
{ "language": "C#" }
```c#  using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } } }``` Update aspnet middleware extension message to allow shouldRun to be passed in
```c#  using Glimpse.Web; using Microsoft.AspNet.Builder; using System; namespace Glimpse.Host.Web.AspNet { public static class GlimpseExtension { /// <summary> /// Adds a middleware that allows GLimpse to be registered into the system. /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices).Invoke); } public static IApplicationBuilder UseGlimpse(this IApplicationBuilder app, Func<IHttpContext, bool> shouldRun) { return app.Use(next => new GlimpseMiddleware(next, app.ApplicationServices, shouldRun).Invoke); } } }```
8640e184-58bf-4020-8990-bac131264f41
{ "language": "C#" }
```c# using System; using System.Threading; using MbCacheTest.TestData; using NUnit.Framework; using SharpTestsEx; namespace MbCacheTest.Logic.Concurrency { public class SimultaneousCachePutTest : TestCase { public SimultaneousCachePutTest(Type proxyType) : base(proxyType) { } [Test] public void ShouldNotMakeTheSameCallMoreThanOnce() { CacheBuilder.For<ObjectWithCallCounter>() .CacheMethod(c => c.Increment()) .PerInstance() .As<IObjectWithCallCounter>(); var factory = CacheBuilder.BuildFactory(); 10.Times(() => { var instance = factory.Create<IObjectWithCallCounter>(); var task1 = new Thread(() => instance.Increment()); var task2 = new Thread(() => instance.Increment()); var task3 = new Thread(() => instance.Increment()); task1.Start(); task2.Start(); task3.Start(); task1.Join(); task2.Join(); task3.Join(); instance.Count.Should().Be(1); }); } } }``` Make sure test fails more often if locks are removed
```c# using System; using System.Threading; using MbCacheTest.TestData; using NUnit.Framework; using SharpTestsEx; namespace MbCacheTest.Logic.Concurrency { public class SimultaneousCachePutTest : TestCase { public SimultaneousCachePutTest(Type proxyType) : base(proxyType) { } [Test] public void ShouldNotMakeTheSameCallMoreThanOnce() { CacheBuilder.For<ObjectWithCallCounter>() .CacheMethod(c => c.Increment()) .PerInstance() .As<IObjectWithCallCounter>(); var factory = CacheBuilder.BuildFactory(); 1000.Times(() => { var instance = factory.Create<IObjectWithCallCounter>(); var task1 = new Thread(() => instance.Increment()); var task2 = new Thread(() => instance.Increment()); var task3 = new Thread(() => instance.Increment()); task1.Start(); task2.Start(); task3.Start(); task1.Join(); task2.Join(); task3.Join(); instance.Count.Should().Be(1); }); } } }```
07b49c9f-a37e-4934-a52a-83781546a6d4
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MigrateMSTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MigrateMSTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Make internals in MSTest2 visible for JustMock dll in lite version
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("MigrateMSTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MigrateMSTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("12629109-a1aa-4abb-852a-087dd15205f3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if LITE_EDITION [assembly: InternalsVisibleTo("Telerik.JustMock")] #endif```
09ba0fee-3afe-4b99-a4bd-1649c1ecc435
{ "language": "C#" }
```c# namespace Fixie.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using Fixie.Execution; public static class TestExtensions { const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; public static MethodInfo GetInstanceMethod(this Type type, string methodName) { return type.GetMethod(methodName, InstanceMethods); } public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type) { return type.GetMethods(InstanceMethods); } public static IEnumerable<string> Lines(this RedirectedConsole console) { return console.Output.Lines(); } public static IEnumerable<string> Lines(this string multiline) { var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); while (lines.Count > 0 && lines[lines.Count-1] == "") lines.RemoveAt(lines.Count-1); return lines; } public static string CleanStackTraceLineNumbers(this string stackTrace) { //Avoid brittle assertion introduced by stack trace line numbers. return Regex.Replace(stackTrace, @":line \d+", ":line #"); } public static string CleanDuration(this string output) { //Avoid brittle assertion introduced by test duration. var decimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator; return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds"); } } }``` Rephrase culture-neutral number format helper so that it can successfully compile against both the full .NET Framework and .NET Core.
```c# namespace Fixie.Tests { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Fixie.Execution; public static class TestExtensions { const BindingFlags InstanceMethods = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; public static MethodInfo GetInstanceMethod(this Type type, string methodName) { return type.GetMethod(methodName, InstanceMethods); } public static IReadOnlyList<MethodInfo> GetInstanceMethods(this Type type) { return type.GetMethods(InstanceMethods); } public static IEnumerable<string> Lines(this RedirectedConsole console) { return console.Output.Lines(); } public static IEnumerable<string> Lines(this string multiline) { var lines = multiline.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); while (lines.Count > 0 && lines[lines.Count-1] == "") lines.RemoveAt(lines.Count-1); return lines; } public static string CleanStackTraceLineNumbers(this string stackTrace) { //Avoid brittle assertion introduced by stack trace line numbers. return Regex.Replace(stackTrace, @":line \d+", ":line #"); } public static string CleanDuration(this string output) { //Avoid brittle assertion introduced by test duration. var decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; return Regex.Replace(output, @"took [\d" + Regex.Escape(decimalSeparator) + @"]+ seconds", @"took 1.23 seconds"); } } }```
5bab320e-602d-49db-8a5d-79c14a80b300
{ "language": "C#" }
```c# using MultiMiner.Engine.Configuration; using System; using System.IO; namespace MultiMiner.Win { public class ApplicationConfiguration { public ApplicationConfiguration() { this.StartupMiningDelay = 45; } public bool LaunchOnWindowsLogin { get; set; } public bool StartMiningOnStartup { get; set; } public int StartupMiningDelay { get; set; } public bool RestartCrashedMiners { get; set; } private static string AppDataPath() { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } private static string DeviceConfigurationsFileName() { return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml"); } public void SaveApplicationConfiguration() { ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName()); } public void LoadApplicationConfiguration() { ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName()); this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin; this.StartMiningOnStartup = tmp.StartMiningOnStartup; this.StartupMiningDelay = tmp.StartupMiningDelay; this.RestartCrashedMiners = tmp.RestartCrashedMiners; } } } ``` Implement the option to start the app when logging into Windows
```c# using Microsoft.Win32; using MultiMiner.Engine.Configuration; using System; using System.IO; using System.Windows.Forms; namespace MultiMiner.Win { public class ApplicationConfiguration { public ApplicationConfiguration() { this.StartupMiningDelay = 45; } public bool LaunchOnWindowsLogin { get; set; } public bool StartMiningOnStartup { get; set; } public int StartupMiningDelay { get; set; } public bool RestartCrashedMiners { get; set; } private static string AppDataPath() { string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(rootPath, "MultiMiner"); } private static string DeviceConfigurationsFileName() { return Path.Combine(AppDataPath(), "ApplicationConfiguration.xml"); } public void SaveApplicationConfiguration() { ConfigurationReaderWriter.WriteConfiguration(this, DeviceConfigurationsFileName()); ApplyLaunchOnWindowsStartup(); } private void ApplyLaunchOnWindowsStartup() { RegistryKey registrykey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); if (LaunchOnWindowsLogin) registrykey.SetValue("MultiMiner", Application.ExecutablePath); else registrykey.DeleteValue("MultiMiner", false); } public void LoadApplicationConfiguration() { ApplicationConfiguration tmp = ConfigurationReaderWriter.ReadConfiguration<ApplicationConfiguration>(DeviceConfigurationsFileName()); this.LaunchOnWindowsLogin = tmp.LaunchOnWindowsLogin; this.StartMiningOnStartup = tmp.StartMiningOnStartup; this.StartupMiningDelay = tmp.StartupMiningDelay; this.RestartCrashedMiners = tmp.RestartCrashedMiners; } } } ```
7e5c8e8d-885e-4cb0-a60b-5b16453064bd
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Battlezeppelins.Models { public class GameTable { public const int TABLE_ROWS = 10; public const int TABLE_COLS = 10; public Game.Role role { get; private set; } public List<OpenPoint> openPoints { get; private set; } public List<Zeppelin> zeppelins { get; private set; } public GameTable(Game.Role role) { this.role = role; this.openPoints = new List<OpenPoint>(); this.zeppelins = new List<Zeppelin>(); } public void removeZeppelins() { zeppelins = null; } public bool AddZeppelin(Zeppelin newZeppelin) { foreach (Zeppelin zeppelin in this.zeppelins) { // No multiple zeppelins of the same type if (zeppelin.type == newZeppelin.type) return false; // No colliding zeppelins if (zeppelin.collides(newZeppelin)) return false; } if (newZeppelin.x < 0 || newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 || newZeppelin.y < 0 || newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1) { return false; } this.zeppelins.Add(newZeppelin); return true; } } } ``` Add non-args constructor for serialization.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Battlezeppelins.Models { public class GameTable { public const int TABLE_ROWS = 10; public const int TABLE_COLS = 10; public Game.Role role { get; private set; } public List<OpenPoint> openPoints { get; private set; } public List<Zeppelin> zeppelins { get; private set; } public GameTable() { } public GameTable(Game.Role role) { this.role = role; this.openPoints = new List<OpenPoint>(); this.zeppelins = new List<Zeppelin>(); } public void removeZeppelins() { zeppelins = null; } public bool AddZeppelin(Zeppelin newZeppelin) { foreach (Zeppelin zeppelin in this.zeppelins) { // No multiple zeppelins of the same type if (zeppelin.type == newZeppelin.type) return false; // No colliding zeppelins if (zeppelin.collides(newZeppelin)) return false; } if (newZeppelin.x < 0 || newZeppelin.x + newZeppelin.getWidth()-1 > TABLE_COLS - 1 || newZeppelin.y < 0 || newZeppelin.y + newZeppelin.getHeight()-1 > TABLE_ROWS - 1) { return false; } this.zeppelins.Add(newZeppelin); return true; } } } ```
e282f6e5-4adf-4346-9cf8-583a882e6f94
{ "language": "C#" }
```c# namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer { using JustBehave; using NBench.VisualStudio.TestAdapter; using NBench.VisualStudio.TestAdapter.Helpers; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoNSubstitute; using Xunit; public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer> { private INBenchFunctionalityWrapper functionalitywrapper; protected override NBenchTestDiscoverer CreateSystemUnderTest() { return new NBenchTestDiscoverer(this.functionalitywrapper); } protected override void CustomizeAutoFixture(IFixture fixture) { fixture.Customize(new AutoNSubstituteCustomization()); } protected override void Given() { this.functionalitywrapper = null; } protected override void When() { } [Fact] public void TheNBenchTestDiscovererIsNotNull() { Assert.NotNull(this.SystemUnderTest); } } }``` Create a non-null functionality wrapper in the required test.
```c# namespace NBench.VisualStudio.TestAdapter.Tests.Unit.NBenchTestDiscoverer.NBenchTestDiscoverer { using JustBehave; using NBench.VisualStudio.TestAdapter; using NBench.VisualStudio.TestAdapter.Helpers; using Ploeh.AutoFixture; using Ploeh.AutoFixture.AutoNSubstitute; using Xunit; public class WhenTheNBenchFunctionalityWrapperIsNotNull : XBehaviourTest<NBenchTestDiscoverer> { private INBenchFunctionalityWrapper functionalitywrapper; protected override NBenchTestDiscoverer CreateSystemUnderTest() { return new NBenchTestDiscoverer(this.functionalitywrapper); } protected override void CustomizeAutoFixture(IFixture fixture) { fixture.Customize(new AutoNSubstituteCustomization()); } protected override void Given() { this.functionalitywrapper = this.Fixture.Create<INBenchFunctionalityWrapper>(); } protected override void When() { } [Fact] public void TheNBenchTestDiscovererIsNotNull() { Assert.NotNull(this.SystemUnderTest); } } }```
7e61bce9-45b8-41b6-8303-18deb4bf64da
{ "language": "C#" }
```c# using System; using System.Diagnostics; using System.Reflection; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } public static string DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } } }``` Add several methods for Windows: IsAdmin
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Security.Principal; namespace FonctionsUtiles.Fred.Csharp { public class FunctionsWindows { public static bool IsInWinPath(string substring) { bool result = false; string winPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); if (winPath != null) result = winPath.Contains(substring); return result; } public static string DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); return $@"V{fvi.FileMajorPart}.{fvi.FileMinorPart}.{fvi.FileBuildPart}.{fvi.FilePrivatePart}"; } public static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } public static bool IsAdmin() { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } public static IEnumerable<Process> GetAllProcesses() { Process[] processlist = Process.GetProcesses(); return processlist.ToList(); } public static bool IsProcessRunningById(Process process) { try { Process.GetProcessById(process.Id); } catch (InvalidOperationException) { return false; } catch (ArgumentException) { return false; } return true; } public static bool IsProcessRunningByName(string processName) { try { Process.GetProcessesByName(processName); } catch (InvalidOperationException) { return false; } catch (ArgumentException) { return false; } return true; } public static Process GetProcessByName(string processName) { Process result = new Process(); foreach (Process process in GetAllProcesses()) { if (process.ProcessName == processName) { result = process; break; } } return result; } } }```
a3f9e2ed-b1e2-4766-86e4-b12984666585
{ "language": "C#" }
```c# using System.Globalization; using System.Reflection; using FluentAssertions; using Microsoft.Office.Interop.Outlook; using Moq; using NUnit.Framework; using OutlookMatters.Core.Settings; namespace Test.OutlookMatters.Core.Settings { [TestFixture] public class EnumMatchToBooleanConverterTest { [Test] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)] [TestCase(null, MattermostVersion.ApiVersionThree, false)] [TestCase(MattermostVersion.ApiVersionOne, null, false)] public void Convert_ConvertsToExpectedResult(object parameter, object value, bool expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } } } ``` Add additional tests for EnumMatchToBooleanConverter
```c# using System.Globalization; using System.Reflection; using FluentAssertions; using Microsoft.Office.Interop.Outlook; using Moq; using NUnit.Framework; using OutlookMatters.Core.Settings; namespace Test.OutlookMatters.Core.Settings { [TestFixture] public class EnumMatchToBooleanConverterTest { [Test] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionOne, true)] [TestCase(MattermostVersion.ApiVersionOne, MattermostVersion.ApiVersionThree, false)] [TestCase(null, MattermostVersion.ApiVersionThree, false)] [TestCase(MattermostVersion.ApiVersionOne, null, false)] public void Convert_ConvertsToExpectedResult(object parameter, object value, bool expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.Convert(value, typeof (bool), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } [Test] [TestCase(true, "ApiVersionOne", MattermostVersion.ApiVersionOne)] [TestCase(false, "ApiVersionOne", null)] [TestCase(true, null, null)] [TestCase(null, "ApiVersionOne", null)] public void ConvertBack_ConvertsToExpectedResult(object value, object parameter, object expectedResult) { var classUnderTest = new EnumMatchToBooleanConverter(); var result = classUnderTest.ConvertBack(value, typeof(MattermostVersion), parameter, It.IsAny<CultureInfo>()); Assert.That(result, Is.EqualTo(expectedResult)); } } } ```
63fa2b42-a216-4983-ae5d-72793d87c4ba
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ChutesAndLadders.GamePlay; using ChutesAndLadders.Entities; using System.Diagnostics; namespace Chute { class Program { static void Main(string[] args) { var board = new GameBoard(); #region Demo 1 // board.Demo1a_GreedyAlgorithm(); #endregion #region Demo 2 // board.Demo2a_RulesEngine(); // board.Demo2b_ImprovedLinear(); #endregion #region Demo 3 // Only do demo 3b unless there is time left over // board.Demo3a_GeneticAnalysis(); // board.Demo3b_GeneticEvolution(); // board.Demo3c_GeneticSuperiority(); #endregion #region Demo 4 // board.Demo4a_ShortestPath(); #endregion #region Supplemental Demos // board.SupplementalDemo_SingleGame(); // board.SupplementalDemo_Player1Advantage(); board.GameActionOutput_SmallSample(); #endregion } } } ``` Reset Chutes & Ladders demos to run demo 1 by default
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ChutesAndLadders.GamePlay; using ChutesAndLadders.Entities; using System.Diagnostics; namespace Chute { class Program { static void Main(string[] args) { var board = new GameBoard(); #region Demo 1 board.Demo1a_GreedyAlgorithm(); #endregion #region Demo 2 // board.Demo2a_RulesEngine(); // board.Demo2b_ImprovedLinear(); #endregion #region Demo 3 // Only do demo 3b unless there is time left over // board.Demo3a_GeneticAnalysis(); // board.Demo3b_GeneticEvolution(); // board.Demo3c_GeneticSuperiority(); #endregion #region Demo 4 // board.Demo4a_ShortestPath(); #endregion #region Supplemental Demos // board.SupplementalDemo_SingleGame(); // board.SupplementalDemo_Player1Advantage(); // board.GameActionOutput_SmallSample(); #endregion } } } ```
6d9d32db-b1ad-471b-bcc0-85e2aef2615a
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Bogus; using Dexiom.EPPlusExporter; using OfficeOpenXml; namespace Dexiom.EPPlusExporterTests.Helpers { public static class TestHelper { public static void OpenDocument(ExcelPackage excelPackage) { Console.WriteLine("Opening document"); Directory.CreateDirectory("temp"); var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx"); excelPackage.SaveAs(fileInfo); Process.Start(fileInfo.FullName); } public static ExcelPackage FakeAnExistingDocument() { Console.WriteLine("FakeAnExistingDocument"); var retVal = new ExcelPackage(); var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet"); worksheet.Cells[1, 1].Value = "I am a normal sheet"; worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!"; return retVal; } } } ``` Remove output on some tests
```c# using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Bogus; using Dexiom.EPPlusExporter; using OfficeOpenXml; namespace Dexiom.EPPlusExporterTests.Helpers { public static class TestHelper { public static void OpenDocument(ExcelPackage excelPackage) { Console.WriteLine("Opening document"); Directory.CreateDirectory("temp"); var fileInfo = new FileInfo($"temp\\Test_{Guid.NewGuid():N}.xlsx"); excelPackage.SaveAs(fileInfo); Process.Start(fileInfo.FullName); } public static ExcelPackage FakeAnExistingDocument() { var retVal = new ExcelPackage(); var worksheet = retVal.Workbook.Worksheets.Add("IAmANormalSheet"); worksheet.Cells[1, 1].Value = "I am a normal sheet"; worksheet.Cells[2, 1].Value = "with completly irrelevant data in it!"; return retVal; } } } ```
ac03ac51-f461-437a-9f1f-14cb3d5e99e0
{ "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 osu.Game.Rulesets.Mania.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Mania.Objects { public abstract class ManiaHitObject : HitObject, IHasColumn { public int Column { get; set; } } } ``` Add siblings, will be used in generator branches.
```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 osu.Game.Rulesets.Mania.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Mania.Objects { public abstract class ManiaHitObject : HitObject, IHasColumn { public int Column { get; set; } /// <summary> /// The number of other <see cref="ManiaHitObject"/> that start at /// the same time as this hit object. /// </summary> public int Siblings { get; set; } } } ```
9d2cedf6-e23d-47b8-830f-009d9002d728
{ "language": "C#" }
```c# using LtiLibrary.Core.Common; using Newtonsoft.Json; namespace LtiLibrary.Core.Outcomes.v2 { /// <summary> /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources /// and from which they GET the list of LineItems associated with a a given learning context. /// </summary> public class LineItemContainer : JsonLdObject { public LineItemContainer() { Type = LtiConstants.LineItemContainerType; } /// <summary> /// Optional indication of which resource is the subject for the members of the container. /// </summary> [JsonProperty("membershipSubject")] public LineItemMembershipSubject LineItemMembershipSubject { get; set; } } } ``` Simplify property name for LineItemMembershipSubject
```c# using LtiLibrary.Core.Common; using Newtonsoft.Json; namespace LtiLibrary.Core.Outcomes.v2 { /// <summary> /// A LineItemContainer defines the endpoint to which clients POST new LineItem resources /// and from which they GET the list of LineItems associated with a a given learning context. /// </summary> public class LineItemContainer : JsonLdObject { public LineItemContainer() { Type = LtiConstants.LineItemContainerType; } /// <summary> /// Optional indication of which resource is the subject for the members of the container. /// </summary> [JsonProperty("membershipSubject")] public LineItemMembershipSubject MembershipSubject { get; set; } } } ```
d68e3d13-1a1a-4228-8ae0-827502f22d5c
{ "language": "C#" }
```c# using System.Collections.Generic; using Nest.Domain; using Newtonsoft.Json; using System.Linq.Expressions; using System; using System.Linq; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("name")] public string State { get; set;} [JsonProperty("primary")] public bool Primary { get; set;} [JsonProperty("node")] public string Node { get; set;} [JsonProperty("relocating_node")] public string RelocatingNode { get; set;} [JsonProperty("shard")] public int Shard { get; set;} [JsonProperty("index")] public string Index { get; set;} } }``` Fix wrong property mapping in SearchShard
```c# using Nest.Domain; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization.OptIn)] public interface ISearchShardsResponse : IResponse { [JsonProperty("shards")] IEnumerable<IEnumerable<SearchShard>> Shards { get; } [JsonProperty("nodes")] IDictionary<string, SearchNode> Nodes { get; } } public class SearchShardsResponse : BaseResponse, ISearchShardsResponse { public IEnumerable<IEnumerable<SearchShard>> Shards { get; internal set; } public IDictionary<string, SearchNode> Nodes { get; internal set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchNode { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("transport_address")] public string TransportAddress { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class SearchShard { [JsonProperty("state")] public string State { get; set; } [JsonProperty("primary")] public bool Primary { get; set; } [JsonProperty("node")] public string Node { get; set; } [JsonProperty("relocating_node")] public string RelocatingNode { get; set; } [JsonProperty("shard")] public int Shard { get; set; } [JsonProperty("index")] public string Index { get; set; } } }```
6c5754f0-a7c9-4e2f-a484-d7efa5ddf141
{ "language": "C#" }
```c# using HotChocolate.Types; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual; using Snowflake.Framework.Remoting.GraphQL.Schema; using Snowflake.Services; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem { public class FilesystemQueries : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Query"); descriptor.Field("filesystem") .Argument("directoryPath", a => a.Type<OSDirectoryPathType>().Description("The path to explore.")) .Resolver(context => { var path = context.Argument<DirectoryInfo>("directoryPath"); if (path == null) return DriveInfo.GetDrives(); if (path.Exists) return path; return null; }) .Type<OSDirectoryContentsInterface>() .Description("Provides normalized OS-dependent filesystem access." + "Returns null if the specified path does not exist."); } } } ``` Clarify behaviour on non-Windows systems
```c# using HotChocolate.Types; using Microsoft.DotNet.PlatformAbstractions; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem; using Snowflake.Framework.Remoting.GraphQL.Model.Filesystem.Contextual; using Snowflake.Framework.Remoting.GraphQL.Schema; using Snowflake.Services; using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Snowflake.Support.GraphQLFrameworkQueries.Queries.Filesystem { public class FilesystemQueries : ObjectTypeExtension { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Query"); descriptor.Field("filesystem") .Argument("directoryPath", a => a.Type<OSDirectoryPathType>() .Description("The path to explore. If this is null, returns a listing of drives on Windows, " + "or the root directory on a Unix-like system.")) .Resolver(context => { var path = context.Argument<DirectoryInfo>("directoryPath"); if (path == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return DriveInfo.GetDrives(); if (path == null && (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) return new DirectoryInfo("/"); if (path?.Exists ?? false) return path; return null; }) .Type<OSDirectoryContentsInterface>() .Description("Provides normalized OS-dependent filesystem access." + "Returns null if the specified path does not exist."); } } } ```
e0ab5b9b-6646-4f67-bf5a-b7538329d31c
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Tiny-JSON")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Robert Gering")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.1.2")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] ``` Increase assembly version to 1.2.0
```c# using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Tiny-JSON")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Robert Gering")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.2.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] ```
01ec78fa-19bb-4ac6-bc74-7867434c0cb6
{ "language": "C#" }
```c# using System.Collections.Concurrent; using System.Collections.Generic; namespace Utility.Extensions { public static class ConcurrentDictionaryExtensions { public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key) { TValue value; return dictionary.TryRemove(key, out value); } /// <remarks> /// This is a hack but is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can (not 100%!) /// </remarks> public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value) { ICollection<KeyValuePair<TKey, TValue>> collection = dictionary; return collection.Remove(new KeyValuePair<TKey, TValue>(key, value)); } } } ``` Change try remove key pair method semantics
```c# using System.Collections.Concurrent; using System.Collections.Generic; namespace Utility.Extensions { public static class ConcurrentDictionaryExtensions { public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key) { TValue value; return dictionary.TryRemove(key, out value); } /// <remarks> /// HACK: is atomic at time of writing! Unlikely to change but a unit test exists to test it as best it can. /// </remarks> public static bool TryRemove<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value) { return collection.Remove(new KeyValuePair<TKey, TValue>(key, value)); } } } ```
ceabde4a-f1b0-43c9-a2d3-4d08f57a9768
{ "language": "C#" }
```c# using IdeaWeb.Controllers; using Microsoft.AspNetCore.Mvc; using NUnit.Framework; namespace IdeaWeb.Test { [TestFixture] public class HomeControllerTests { HomeController _controller; [SetUp] public void SetUp() { _controller = new HomeController(); } [Test] public void IndexReturnsIdeasView() { IActionResult result = _controller.Index(); Assert.That(result, Is.Not.Null); } } } ``` Use the in-memory database for testing the home controller
```c# using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdeaWeb.Controllers; using IdeaWeb.Data; using IdeaWeb.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using NUnit.Framework; namespace IdeaWeb.Test { [TestFixture] public class HomeControllerTests { const int NUM_IDEAS = 10; HomeController _controller; [SetUp] public void SetUp() { // Create unique database names based on the test id var options = new DbContextOptionsBuilder<IdeaContext>() .UseInMemoryDatabase(TestContext.CurrentContext.Test.ID) .Options; // Seed the in-memory database using (var context = new IdeaContext(options)) { for(int i = 1; i <= NUM_IDEAS; i++) { context.Add(new Idea { Name = $"Idea name {i}", Description = $"Description {i}", Rating = i % 3 + 1 }); } context.SaveChanges(); } // Use a clean copy of the context within the tests _controller = new HomeController(new IdeaContext(options)); } [Test] public async Task IndexReturnsListOfIdeas() { ViewResult result = await _controller.Index() as ViewResult; Assert.That(result?.Model, Is.Not.Null); Assert.That(result.Model, Has.Count.EqualTo(NUM_IDEAS)); IEnumerable<Idea> ideas = result.Model as IEnumerable<Idea>; Idea idea = ideas?.FirstOrDefault(); Assert.That(idea, Is.Not.Null); Assert.That(idea.Name, Is.EqualTo("Idea name 1")); Assert.That(idea.Description, Does.Contain("1")); Assert.That(idea.Rating, Is.EqualTo(2)); } } } ```
3815ff07-4878-47a6-8fe8-e25f76aa5d93
{ "language": "C#" }
```c# namespace DependencyInjection.Console { internal class PatternApp { private readonly PatternWriter _patternWriter; private readonly PatternGenerator _patternGenerator; public PatternApp(bool useColours) { _patternWriter = new PatternWriter(useColours); _patternGenerator = new PatternGenerator(); } public void Run() { var pattern = _patternGenerator.Generate(10, 10); _patternWriter.Write(pattern); } } }``` Adjust initial size to look nicer
```c# namespace DependencyInjection.Console { internal class PatternApp { private readonly PatternWriter _patternWriter; private readonly PatternGenerator _patternGenerator; public PatternApp(bool useColours) { _patternWriter = new PatternWriter(useColours); _patternGenerator = new PatternGenerator(); } public void Run() { var pattern = _patternGenerator.Generate(25, 15); _patternWriter.Write(pattern); } } }```
12c528b7-3763-441f-9a39-5278150e40cb
{ "language": "C#" }
```c# using Xunit; namespace EmotionAPI.Tests { public class EmotionAPIClientTests : EmotionAPITestsBase { [Fact] public void Can_Create_EmotionAPIClient_Controller() { var controller = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotNull(controller); Assert.NotEmpty(controller.OcpApimSubscriptionKey); } } } ``` Split test into two separate tests
```c# using Xunit; namespace EmotionAPI.Tests { public class EmotionAPIClientTests : EmotionAPITestsBase { [Fact] public void Can_Create_EmotionAPIClient_Class() { var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotNull(sut); } [Fact] public void OcpApimSubscriptionKey_Is_Being_Set() { var sut = new EmotionAPIClient(mockOcpApimSubscriptionKey); Assert.NotEmpty(sut.OcpApimSubscriptionKey); } } } ```
733305b2-a05d-4503-9a46-db36e415981c
{ "language": "C#" }
```c# using System.Windows.Forms; using CefSharp; namespace TweetDuck.Core.Handling{ class KeyboardHandlerBase : IKeyboardHandler{ protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){ return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){ if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){ return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers); } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){ return false; } } } ``` Add keyboard shortcut to open dev tools (Ctrl+Shift+I)
```c# using System.Windows.Forms; using CefSharp; using TweetDuck.Core.Controls; using TweetDuck.Core.Other; using TweetDuck.Core.Utils; namespace TweetDuck.Core.Handling{ class KeyboardHandlerBase : IKeyboardHandler{ protected virtual bool HandleRawKey(IWebBrowser browserControl, IBrowser browser, Keys key, CefEventFlags modifiers){ if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I){ if (BrowserUtils.HasDevTools){ browser.ShowDevTools(); } else{ browserControl.AsControl().InvokeSafe(() => { string extraMessage; if (Program.IsPortable){ extraMessage = "Please download the portable installer, select the folder with your current installation of TweetDuck Portable, and tick 'Install dev tools' during the installation process."; } else{ extraMessage = "Please download the installer, and tick 'Install dev tools' during the installation process. The installer will automatically find and update your current installation of TweetDuck."; } FormMessage.Information("Dev Tools", "You do not have dev tools installed. "+extraMessage, FormMessage.OK); }); } return true; } return false; } bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut){ if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("chrome-devtools://")){ return HandleRawKey(browserControl, browser, (Keys)windowsKeyCode, modifiers); } return false; } bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey){ return false; } } } ```
1b46a46b-2786-4b06-bd4f-3f8cc9f7949e
{ "language": "C#" }
```c# using System; using System.Web.Mvc; using Orchard.Localization; using Orchard.ContentManagement; using Orchard.Pages.Services; using Orchard.Pages.ViewModels; using Orchard.Security; namespace Orchard.Pages.Controllers { [ValidateInput(false)] public class PageController : Controller, IUpdateModel { private readonly IPageService _pageService; private readonly ISlugConstraint _slugConstraint; public PageController( IOrchardServices services, IPageService pageService, ISlugConstraint slugConstraint) { Services = services; _pageService = pageService; _slugConstraint = slugConstraint; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } private Localizer T { get; set; } public ActionResult Item(string slug) { if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page"))) return new HttpUnauthorizedResult(); if (slug == null) { throw new ArgumentNullException("slug"); } //var correctedSlug = _slugConstraint.LookupPublishedSlug(pageSlug); var page = _pageService.Get(slug); var model = new PageViewModel { Page = Services.ContentManager.BuildDisplayModel(page, "Detail") }; return View(model); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }``` Fix pages slug to not be case sensitive when used in url
```c# using System; using System.Web.Mvc; using Orchard.Localization; using Orchard.ContentManagement; using Orchard.Mvc.Results; using Orchard.Pages.Services; using Orchard.Pages.ViewModels; using Orchard.Security; namespace Orchard.Pages.Controllers { [ValidateInput(false)] public class PageController : Controller { private readonly IPageService _pageService; private readonly ISlugConstraint _slugConstraint; public PageController(IOrchardServices services, IPageService pageService, ISlugConstraint slugConstraint) { Services = services; _pageService = pageService; _slugConstraint = slugConstraint; T = NullLocalizer.Instance; } public IOrchardServices Services { get; set; } private Localizer T { get; set; } public ActionResult Item(string slug) { if (!Services.Authorizer.Authorize(StandardPermissions.AccessFrontEnd, T("Couldn't view page"))) return new HttpUnauthorizedResult(); var correctedSlug = _slugConstraint.LookupPublishedSlug(slug); if (correctedSlug == null) return new NotFoundResult(); var page = _pageService.Get(correctedSlug); if (page == null) return new NotFoundResult(); var model = new PageViewModel { Page = Services.ContentManager.BuildDisplayModel(page, "Detail") }; return View(model); } } }```
ee33404b-df0d-4db7-88e1-33abed1f8e13
{ "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; namespace osu.Game.Screens.Play { public static class GameplayClockExtensions { /// <summary> /// The rate of gameplay when playback is at 100%. /// This excludes any seeking / user adjustments. /// </summary> public static double GetTrueGameplayRate(this IGameplayClock clock) { // To handle rewind, we still want to maintain the same direction as the underlying clock. double rate = Math.Sign(clock.Rate); return rate * clock.GameplayAdjustments.AggregateFrequency.Value * clock.GameplayAdjustments.AggregateTempo.Value; } } } ``` Fix case of zero rate calculating a zero true gameplay rate
```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; namespace osu.Game.Screens.Play { public static class GameplayClockExtensions { /// <summary> /// The rate of gameplay when playback is at 100%. /// This excludes any seeking / user adjustments. /// </summary> public static double GetTrueGameplayRate(this IGameplayClock clock) { // To handle rewind, we still want to maintain the same direction as the underlying clock. double rate = clock.Rate == 0 ? 1 : Math.Sign(clock.Rate); return rate * clock.GameplayAdjustments.AggregateFrequency.Value * clock.GameplayAdjustments.AggregateTempo.Value; } } } ```
ae49bc93-673d-4475-b196-94e473370d76
{ "language": "C#" }
```c# using OpenTK.Input; namespace MonoHaven.Input { public abstract class InputEvent { private readonly KeyModifiers mods; protected InputEvent() { mods = GetCurrentKeyModifiers(); } public bool Handled { get; set; } public KeyModifiers Modifiers { get { return mods; } } private static KeyModifiers GetCurrentKeyModifiers() { var mods = (KeyModifiers)0; var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Key.LShift) || keyboardState.IsKeyDown(Key.RShift)) mods |= KeyModifiers.Shift; if (keyboardState.IsKeyDown(Key.LAlt) || keyboardState.IsKeyDown(Key.RAlt)) mods |= KeyModifiers.Alt; if (keyboardState.IsKeyDown(Key.ControlLeft) || keyboardState.IsKeyDown(Key.ControlRight)) mods |= KeyModifiers.Control; return mods; } } } ``` Allow to use input event arguments in the event handlers
```c# using System; using OpenTK.Input; namespace MonoHaven.Input { public abstract class InputEvent : EventArgs { private readonly KeyModifiers mods; protected InputEvent() { mods = GetCurrentKeyModifiers(); } public bool Handled { get; set; } public KeyModifiers Modifiers { get { return mods; } } private static KeyModifiers GetCurrentKeyModifiers() { var mods = (KeyModifiers)0; var keyboardState = Keyboard.GetState(); if (keyboardState.IsKeyDown(Key.LShift) || keyboardState.IsKeyDown(Key.RShift)) mods |= KeyModifiers.Shift; if (keyboardState.IsKeyDown(Key.LAlt) || keyboardState.IsKeyDown(Key.RAlt)) mods |= KeyModifiers.Alt; if (keyboardState.IsKeyDown(Key.ControlLeft) || keyboardState.IsKeyDown(Key.ControlRight)) mods |= KeyModifiers.Control; return mods; } } } ```
6d8d97ad-8768-40d5-a403-5dac79870596
{ "language": "C#" }
```c# using Newtonsoft.Json; using ShopifySharp.Converters; using System.Runtime.Serialization; namespace ShopifySharp.Enums { [JsonConverter(typeof(NullableEnumConverter<ShopifyAuthorizationScope>))] public enum ShopifyAuthorizationScope { [EnumMember(Value = "read_content")] ReadContent, [EnumMember(Value = "write_content")] WriteContent, [EnumMember(Value = "read_themes")] ReadThemes, [EnumMember(Value = "write_themes")] WriteThemes, [EnumMember(Value = "read_products")] ReadProducts, [EnumMember(Value = "write_products")] WriteProducts, [EnumMember(Value = "read_customers")] ReadCustomers, [EnumMember(Value = "write_customers")] WriteCustomers, [EnumMember(Value = "read_orders")] ReadOrders, [EnumMember(Value = "write_orders")] WriteOrders, [EnumMember(Value = "read_script_tags")] ReadScriptTags, [EnumMember(Value = "write_script_tags")] WriteScriptTags, [EnumMember(Value = "read_fulfillments")] ReadFulfillments, [EnumMember(Value = "write_fulfillments")] WriteFulfillments, [EnumMember(Value = "read_shipping")] ReadShipping, [EnumMember(Value = "write_shipping")] WriteShipping } } ``` Add missing authorization scopes read_analytics, read_users and write_users
```c# using Newtonsoft.Json; using ShopifySharp.Converters; using System.Runtime.Serialization; namespace ShopifySharp.Enums { [JsonConverter(typeof(NullableEnumConverter<ShopifyAuthorizationScope>))] public enum ShopifyAuthorizationScope { [EnumMember(Value = "read_content")] ReadContent, [EnumMember(Value = "write_content")] WriteContent, [EnumMember(Value = "read_themes")] ReadThemes, [EnumMember(Value = "write_themes")] WriteThemes, [EnumMember(Value = "read_products")] ReadProducts, [EnumMember(Value = "write_products")] WriteProducts, [EnumMember(Value = "read_customers")] ReadCustomers, [EnumMember(Value = "write_customers")] WriteCustomers, [EnumMember(Value = "read_orders")] ReadOrders, [EnumMember(Value = "write_orders")] WriteOrders, [EnumMember(Value = "read_script_tags")] ReadScriptTags, [EnumMember(Value = "write_script_tags")] WriteScriptTags, [EnumMember(Value = "read_fulfillments")] ReadFulfillments, [EnumMember(Value = "write_fulfillments")] WriteFulfillments, [EnumMember(Value = "read_shipping")] ReadShipping, [EnumMember(Value = "write_shipping")] WriteShipping, [EnumMember(Value = "read_analytics")] ReadAnalytics, [EnumMember(Value = "read_users")] ReadUsers, [EnumMember(Value = "write_users")] WriteUsers } } ```
760f914c-0c47-40f5-936f-a2dfc784d61a
{ "language": "C#" }
```c# using SlugityLib.Configuration; namespace SlugityLib.Tests { public class CustomSlugityConfig : ISlugityConfig { public CustomSlugityConfig() { TextCase = TextCase.LowerCase; StripStopWords = false; MaxLength = 30; StringSeparator = ' '; ReplacementCharacters = new CharacterReplacement(); } public TextCase TextCase { get; set; } public char StringSeparator { get; set; } public int? MaxLength { get; set; } public CharacterReplacement ReplacementCharacters { get; set; } public bool StripStopWords { get; set; } } }``` Add vscode to git ignore
```c# namespace SlugityLib.Tests { public class CustomSlugityConfig : ISlugityConfig { public CustomSlugityConfig() { TextCase = TextCase.LowerCase; StripStopWords = false; MaxLength = 30; StringSeparator = ' '; ReplacementCharacters = new CharacterReplacement(); } public TextCase TextCase { get; set; } public char StringSeparator { get; set; } public int? MaxLength { get; set; } public CharacterReplacement ReplacementCharacters { get; set; } public bool StripStopWords { get; set; } } }```
c1b19d5e-3b08-4b7a-8385-14181103f148
{ "language": "C#" }
```c# <div class="panel" id="error-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1 id="error-title">Error!</h1> <p id="error-message"> Oh no! </p> </div> </div>``` Fix error dialog close button not working
```c# <div class="panel" id="error-panel"> <div class="panel-inner"> <div class="panel-close"> <a href="#" id="error-panel-close"><i class="fa fa-fw fa-times"></i></a> </div> <h1 id="error-title">Error!</h1> <p id="error-message"> <img src="http://i.imgur.com/ne6uoFj.png" style="margin-bottom: 10px; width: 100%;"/><br /> Uh, I can explain... </p> </div> </div>```
3a167953-034d-45a4-b21a-7aee1499ba49
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IFilterMyBlogPosts, IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/feed"); } } public bool Filter(SyndicationItem item) { return item.Categories?.Any(c => c.Name.ToLowerInvariant().Contains("powershell")) ?? false; } public string FeedLanguageCode => "en"; } } ``` Remove filter (default will work)
```c# using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/feed"); } } public string FeedLanguageCode => "en"; } } ```
6822d085-d2dc-4853-bcd2-5f8c93901a6b
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; namespace SharpRaven.Utilities { public class CircularBuffer<T> { private readonly int size; private readonly Queue<T> queue; public CircularBuffer(int size = 100) { this.size = size; queue = new Queue<T>(); } public List<T> ToList() { return queue.ToList(); } public void Clear() { queue.Clear(); } public void Add(T item) { if (queue.Count >= size) queue.Dequeue(); queue.Enqueue(item); } public bool IsEmpty() { return queue.Count <= 0; } } } ``` Refactor to a thread-safe queue.
```c# using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace SharpRaven.Utilities { public class CircularBuffer<T> { private readonly int size; private ConcurrentQueue<T> queue; public CircularBuffer(int size = 100) { this.size = size; queue = new ConcurrentQueue<T>(); } public List<T> ToList() { var listReturn = this.queue.ToList(); return listReturn.Skip(Math.Max(0, listReturn.Count - size)).ToList(); } public void Clear() { queue = new ConcurrentQueue<T>(); } public void Add(T item) { if (queue.Count >= size) { T result; this.queue.TryDequeue(out result); } queue.Enqueue(item); } public bool IsEmpty() { return queue.Count <= 0; } } } ```
d0a13514-aa6e-4b4e-b178-5914dadbe403
{ "language": "C#" }
```c# using System; using Nancy.Helpers; namespace Nancy.ViewEngines.Razor { /// <summary> /// An html string that is encoded. /// </summary> public class EncodedHtmlString : IHtmlString { /// <summary> /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly. /// </summary> public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty); private readonly Lazy<string> encoderFactory; /// <summary> /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class. /// </summary> /// <param name="value">The value.</param> public EncodedHtmlString(string value) { encoderFactory = new Lazy<string>(() => HttpUtility.HtmlEncode(value)); } /// <summary> /// Returns an HTML-encoded string. /// </summary> /// <returns>An HTML-encoded string.</returns> public string ToHtmlString() { return encoderFactory.Value; } public static implicit operator EncodedHtmlString(string value) { return new EncodedHtmlString(value); } } }``` Move using-statements within namespace declaration.
```c# namespace Nancy.ViewEngines.Razor { using System; using Nancy.Helpers; /// <summary> /// An html string that is encoded. /// </summary> public class EncodedHtmlString : IHtmlString { /// <summary> /// Represents the empty <see cref="EncodedHtmlString"/>. This field is readonly. /// </summary> public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty); private readonly string encodedValue; /// <summary> /// Initializes a new instance of the <see cref="EncodedHtmlString"/> class. /// </summary> /// <param name="value">The encoded value.</param> public EncodedHtmlString(string value) { encodedValue = HttpUtility.HtmlEncode(value); } /// <summary> /// Returns an HTML-encoded string. /// </summary> /// <returns>An HTML-encoded string.</returns> public string ToHtmlString() { return encodedValue; } public static implicit operator EncodedHtmlString(string value) { return new EncodedHtmlString(value); } } } ```
16b9446f-249f-48c4-96c8-056ee764afbf
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Vipr.Core; namespace Vipr { internal static class FileWriter { public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null) { if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath)) Directory.CreateDirectory(outputDirectoryPath); var fileTasks = new List<Task>(); foreach (var file in textFilesToWrite) { var filePath = file.RelativePath; if (!string.IsNullOrWhiteSpace(outputDirectoryPath)) filePath = Path.Combine(outputDirectoryPath, filePath); if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) && !Path.IsPathRooted(filePath)) filePath = Path.Combine(Environment.CurrentDirectory, filePath); if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); fileTasks.Add(WriteToDisk(filePath, file.Contents)); } await Task.WhenAll(fileTasks); } public static async Task WriteToDisk(string filePath, string output) { StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8); await sw.WriteAsync(output); sw.Close(); } } }``` Add case for locked files
```c# using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Vipr.Core; namespace Vipr { internal static class FileWriter { public static async void WriteAsync(IEnumerable<TextFile> textFilesToWrite, string outputDirectoryPath = null) { if (!string.IsNullOrWhiteSpace(outputDirectoryPath) && !Directory.Exists(outputDirectoryPath)) Directory.CreateDirectory(outputDirectoryPath); var fileTasks = new List<Task>(); foreach (var file in textFilesToWrite) { var filePath = file.RelativePath; if (!string.IsNullOrWhiteSpace(outputDirectoryPath)) filePath = Path.Combine(outputDirectoryPath, filePath); if (!String.IsNullOrWhiteSpace(Environment.CurrentDirectory) && !Path.IsPathRooted(filePath)) filePath = Path.Combine(Environment.CurrentDirectory, filePath); if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); fileTasks.Add(WriteToDisk(filePath, file.Contents)); } await Task.WhenAll(fileTasks); } /** * Write the file to disk. If the file is locked for editing, * sleep until available */ public static async Task WriteToDisk(string filePath, string output) { for (int tries = 0; tries < 10; tries++) { StreamWriter sw = null; try { using (sw = new StreamWriter(filePath, false, Encoding.UTF8)) { await sw.WriteAsync(output); break; } } // If the file is currently locked for editing, sleep // This shouldn't be hit if the generator is running correctly, // however, files are currently being overwritten several times catch (IOException) { Thread.Sleep(5); } } } } }```
b12f77a5-a84f-408f-8c54-14a7faa78324
{ "language": "C#" }
```c# namespace Gu.Analyzers.Benchmarks.Benchmarks { using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Diagnostics; public abstract class Analyzer { private readonly CompilationWithAnalyzers compilation; protected Analyzer(DiagnosticAnalyzer analyzer) { var project = Factory.CreateProject(analyzer); this.compilation = project.GetCompilationAsync(CancellationToken.None) .Result .WithAnalyzers( ImmutableArray.Create(analyzer), project.AnalyzerOptions, CancellationToken.None); } [Benchmark] public async Task<object> GetAnalyzerDiagnosticsAsync() { return await this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None) .ConfigureAwait(false); } } } ``` Tweak benchmarks, still don't trust the results.
```c# namespace Gu.Analyzers.Benchmarks.Benchmarks { using System.Collections.Immutable; using System.Threading; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Diagnostics; public abstract class Analyzer { private readonly CompilationWithAnalyzers compilation; protected Analyzer(DiagnosticAnalyzer analyzer) { var project = Factory.CreateProject(analyzer); this.compilation = project.GetCompilationAsync(CancellationToken.None) .Result .WithAnalyzers( ImmutableArray.Create(analyzer), project.AnalyzerOptions, CancellationToken.None); } [Benchmark] public object GetAnalyzerDiagnosticsAsync() { return this.compilation.GetAnalyzerDiagnosticsAsync(CancellationToken.None).Result; } } } ```
464e2057-8db8-4782-874c-f30c2c0129a8
{ "language": "C#" }
```c# namespace InfinniPlatform.Sdk.Hosting { /// <summary> /// . /// </summary> public interface IHostAddressParser { /// <summary> /// , . /// </summary> /// <param name="hostNameOrAddress"> .</param> /// <returns> <c>true</c>, ; <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress); /// <summary> /// , . /// </summary> /// <param name="hostNameOrAddress"> .</param> /// <param name="normalizedAddress"> .</param> /// <returns> <c>true</c>, ; <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress); } }``` Fix files encoding to UTF-8
```c# namespace InfinniPlatform.Sdk.Hosting { /// <summary> /// Интерфейс для разбора адресов узлов. /// </summary> public interface IHostAddressParser { /// <summary> /// Определяет, является ли адрес локальным. /// </summary> /// <param name="hostNameOrAddress">Имя узла или его адрес.</param> /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress); /// <summary> /// Определяет, является ли адрес локальным. /// </summary> /// <param name="hostNameOrAddress">Имя узла или его адрес.</param> /// <param name="normalizedAddress">Нормализованный адрес узла.</param> /// <returns>Возвращает <c>true</c>, если адрес является локальным; иначе возвращает <c>false</c>.</returns> bool IsLocalAddress(string hostNameOrAddress, out string normalizedAddress); } }```
40ed9f4b-56ff-464d-8451-ed453df385fc
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunBreadcrumb { public string Message { get; set; } public string Category { get; set; } public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info; public IDictionary CustomData { get; set; } public string ClassName { get; set; } public string MethodName { get; set; } public int LineNumber { get; set; } } } ``` Change LineNumber to nullable so it does not get serialized unless set
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunBreadcrumb { public string Message { get; set; } public string Category { get; set; } public RaygunBreadcrumbs.Level Level { get; set; } = RaygunBreadcrumbs.Level.Info; public IDictionary CustomData { get; set; } public string ClassName { get; set; } public string MethodName { get; set; } public int? LineNumber { get; set; } } } ```
31b74518-83b3-4cfb-8965-9e9dfc7cde53
{ "language": "C#" }
```c# using System.Collections; using System.Reflection; using Assets.Scripts.Props; using UnityEngine; public class AlarmClockHoldableHandler : HoldableHandler { public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller) { clock = Holdable.GetComponentInChildren<AlarmClock>(); } protected override IEnumerator RespondToCommandInternal(string command) { if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break; yield return null; yield return DoInteractionClick(clock.SnoozeButton); } static AlarmClockHoldableHandler() { _alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance); } private static FieldInfo _alarmClockOnField = null; private AlarmClock clock; } ``` Add help message to !alarmclock
```c# using System.Collections; using System.Reflection; using Assets.Scripts.Props; using UnityEngine; public class AlarmClockHoldableHandler : HoldableHandler { public AlarmClockHoldableHandler(KMHoldableCommander commander, FloatingHoldable holdable, IRCConnection connection, CoroutineCanceller canceller) : base(commander, holdable, connection, canceller) { clock = Holdable.GetComponentInChildren<AlarmClock>(); HelpMessage = "Snooze the alarm clock with !{0} snooze"; HelpMessage += TwitchPlaySettings.data.AllowSnoozeOnly ? " (Current Twitch play settings forbids turning the Alarm clock back on.)" : " Alarm clock may also be turned back on with !{0} snooze"; } protected override IEnumerator RespondToCommandInternal(string command) { if ((TwitchPlaySettings.data.AllowSnoozeOnly && (!(bool) _alarmClockOnField.GetValue(clock)))) yield break; yield return null; yield return DoInteractionClick(clock.SnoozeButton); } static AlarmClockHoldableHandler() { _alarmClockOnField = typeof(AlarmClock).GetField("isOn", BindingFlags.NonPublic | BindingFlags.Instance); } private static FieldInfo _alarmClockOnField = null; private AlarmClock clock; } ```
614594bf-2c53-4ef9-abca-1ea0cec93c85
{ "language": "C#" }
```c# using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name); } } }``` Use Enum.Parse overload available in PCL
```c# using System; namespace EvilDICOM.Core.Helpers { public class EnumHelper { public static T StringToEnum<T>(string name) { return (T) Enum.Parse(typeof (T), name, false); } } }```
d770a34d-078e-4c59-995d-3a52783fbb30
{ "language": "C#" }
```c# using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.UI.GameComponents { /// <summary> /// Represents a rectangular button that can be clicked in a game. /// </summary> public class Button : DrawableGameComponent { public SpriteFont Font { get; set; } public Color TextColor { get; set; } public string Text { get; set; } public Rectangle Bounds { get; set; } public Color BackgroundColor { get; set; } private Texture2D ButtonTexture; private readonly SpriteBatch spriteBatch; public Button(Game game, SpriteFont font, Color textColor, string text, Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game) { this.Font = font; this.TextColor = textColor; this.Text = text; this.Bounds = bounds; this.BackgroundColor = backgroundColor; this.spriteBatch = spriteBatch; } protected override void LoadContent() { this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1); this.ButtonTexture.SetData<Color>(new Color[] { Color.White }); } public override void Draw(GameTime gameTime) { // Draw the button background. spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor); // Draw the button text. spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor); base.Draw(gameTime); } } } ``` Tag release with updated version number.
```c# using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.UI.GameComponents { /// <summary> /// Represents a rectangular button that can be clicked in a game. /// </summary> public class Button : DrawableGameComponent { public SpriteFont Font { get; set; } public Color TextColor { get; set; } public string Text { get; set; } public Rectangle Bounds { get; set; } public Color BackgroundColor { get; set; } private Texture2D ButtonTexture; private readonly SpriteBatch spriteBatch; public Button(Game game, SpriteFont font, Color textColor, string text, Rectangle bounds, Color backgroundColor, SpriteBatch spriteBatch) : base(game) { this.Font = font; this.TextColor = textColor; this.Text = text; this.Bounds = bounds; this.BackgroundColor = backgroundColor; this.spriteBatch = spriteBatch; } protected override void LoadContent() { this.ButtonTexture = new Texture2D(Game.GraphicsDevice, 1, 1); this.ButtonTexture.SetData<Color>(new Color[] { Color.White }); } public override void Draw(GameTime gameTime) { // Draw the button background. spriteBatch.Draw(ButtonTexture, Bounds, BackgroundColor); // Draw the button text. spriteBatch.DrawString(Font, Text, new Vector2(Bounds.X + 5, Bounds.Y + 5), TextColor); base.Draw(gameTime); } } } ```
13112b82-4280-478f-a417-14d01a861053
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using NutzCode.Libraries.Web.StreamProvider; namespace NutzCode.CloudFileSystem { public class AuthorizationFactory { private static AuthorizationFactory _instance; public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory()); [Import(typeof(IAppAuthorization))] public IAppAuthorization AuthorizationProvider { get; set; } public AuthorizationFactory(string dll=null) { Assembly assembly = Assembly.GetEntryAssembly(); string codebase = assembly.CodeBase; UriBuilder uri = new UriBuilder(codebase); string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path).Replace("/", "\\")); if (dirname != null) { AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(assembly)); if (dll!=null) catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll)); var container = new CompositionContainer(catalog); container.ComposeParts(this); } } } } ``` Handle dir separator better for Mono
```c# using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using NutzCode.Libraries.Web.StreamProvider; namespace NutzCode.CloudFileSystem { public class AuthorizationFactory { private static AuthorizationFactory _instance; public static AuthorizationFactory Instance => _instance ?? (_instance = new AuthorizationFactory()); [Import(typeof(IAppAuthorization))] public IAppAuthorization AuthorizationProvider { get; set; } public AuthorizationFactory(string dll=null) { Assembly assembly = Assembly.GetEntryAssembly(); string codebase = assembly.CodeBase; UriBuilder uri = new UriBuilder(codebase); string dirname = Pri.LongPath.Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path) .Replace("/", $"{System.IO.Path.DirectorySeparatorChar}")); if (dirname != null) { AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(assembly)); if (dll!=null) catalog.Catalogs.Add(new DirectoryCatalog(dirname, dll)); var container = new CompositionContainer(catalog); container.ComposeParts(this); } } } } ```
4afe0270-3777-42dc-9ca5-b06f58d129d8
{ "language": "C#" }
```c# namespace EFRepository { /// <summary> /// IRepository /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> public interface IRepository<TEntity> where TEntity : class { /// <summary> /// Adds the specified data. /// </summary> /// <param name="data">The data.</param> void Add(TEntity data); /// <summary> /// Saves the changes. /// </summary> /// <returns></returns> int SaveChanges(); } }``` Add add range funciton to interface
```c# using System.Collections.Generic; namespace EFRepository { /// <summary> /// IRepository /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> public interface IRepository<TEntity> where TEntity : class { /// <summary> /// Adds the specified data. /// </summary> /// <param name="data">The data.</param> void Add(TEntity data); /// <summary> /// Adds the range. /// </summary> /// <param name="datalist">The datalist.</param> void AddRange(IEnumerable<TEntity> datalist); /// <summary> /// Saves the changes. /// </summary> /// <returns></returns> int SaveChanges(); } }```
0a15286f-22eb-467f-a682-ae4cd83904db
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReturnToBounds : MonoBehaviour { [SerializeField] Transform frontBounds = null; [SerializeField] Transform backBounds = null; [SerializeField] Transform leftBounds = null; [SerializeField] Transform rightBounds = null; [SerializeField] Transform bottomBounds = null; [SerializeField] Transform topBounds = null; Vector3 positionAtStart; // Start is called before the first frame update void Start() { positionAtStart = transform.position; } // Update is called once per frame void Update() { if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x || transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y || transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z) { transform.position = positionAtStart; } } } ``` Make demo script comply with guidelines
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Examples.Experimental.Demos { public class ReturnToBounds : MonoBehaviour { [SerializeField] private Transform frontBounds = null; public Transform FrontBounds { get => frontBounds; set => frontBounds = value; } [SerializeField] private Transform backBounds = null; public Transform BackBounds { get => backBounds; set => backBounds = value; } [SerializeField] private Transform leftBounds = null; public Transform LeftBounds { get => leftBounds; set => leftBounds = value; } [SerializeField] private Transform rightBounds = null; public Transform RightBounds { get => rightBounds; set => rightBounds = value; } [SerializeField] private Transform bottomBounds = null; public Transform BottomBounds { get => bottomBounds; set => bottomBounds = value; } [SerializeField] private Transform topBounds = null; public Transform TopBounds { get => topBounds; set => topBounds = value; } private Vector3 positionAtStart; // Start is called before the first frame update void Start() { positionAtStart = transform.position; } // Update is called once per frame void Update() { if (transform.position.x > rightBounds.position.x || transform.position.x < leftBounds.position.x || transform.position.y > topBounds.position.y || transform.position.y < bottomBounds.position.y || transform.position.z > backBounds.position.z || transform.position.z < frontBounds.position.z) { transform.position = positionAtStart; } } } } ```
a854f35a-256d-4822-a62d-a501aff872f3
{ "language": "C#" }
```c# using System; using System.Linq; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(ArraySegment<byte> data, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, afi); } public byte Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public int GetByteLength() { return 1 + (Length + 7) / 8; } public void DecodeFromBytes(ArraySegment<byte> data, Bgp.AddressFamily afi) { Length = data.ElementAt(0); if (Length <= 0) return; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Buffer.BlockCopy(data.ToArray(), 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } } ``` Change ctor parameter to byte array
```c# using System; using System.Net; namespace BmpListener.Bgp { public class IPAddrPrefix { public IPAddrPrefix(byte[] data, AddressFamily afi = AddressFamily.IP) { DecodeFromBytes(data, afi); } public byte Length { get; private set; } public IPAddress Prefix { get; private set; } public override string ToString() { return ($"{Prefix}/{Length}"); } public int GetByteLength() { return 1 + (Length + 7) / 8; } public void DecodeFromBytes(byte[] data, AddressFamily afi) { Length = data.ElementAt(0); if (Length <= 0) return; var byteLength = (Length + 7) / 8; var ipBytes = afi == AddressFamily.IP ? new byte[4] : new byte[16]; Buffer.BlockCopy(data, 1, ipBytes, 0, byteLength); Prefix = new IPAddress(ipBytes); } } } ```
a926168a-a8a0-4d40-b2d3-0a2005f9ce5e
{ "language": "C#" }
```c# using System; using System.Net.Http; using System.Threading.Tasks; namespace Archon.WebApi { public abstract class Link { public Authorization Authorization { get; set; } public HttpRequestMessage CreateRequest() { var req = CreateRequestInternal(); if (Authorization != null) req.Headers.Authorization = Authorization.AsHeader(); return req; } protected abstract HttpRequestMessage CreateRequestInternal(); } public abstract class Link<TResponse> : Link { public Task<TResponse> ParseResponseAsync(HttpResponseMessage response) { if (response == null) throw new ArgumentNullException("response"); return ParseResponseInternal(response); } protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response); } }``` Use current principal if provided for auth
```c# using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Archon.WebApi { public abstract class Link { public Authorization Authorization { get; set; } public HttpRequestMessage CreateRequest() { var req = CreateRequestInternal(); var authToken = GetAuthToken(); if (authToken != null) req.Headers.Authorization = authToken.AsHeader(); return req; } Authorization GetAuthToken() { if (Authorization != null) return Authorization; var token = Thread.CurrentPrincipal as AuthToken; if (token != null) return Authorization.Bearer(token.Token); return null; } protected abstract HttpRequestMessage CreateRequestInternal(); } public abstract class Link<TResponse> : Link { public Task<TResponse> ParseResponseAsync(HttpResponseMessage response) { if (response == null) throw new ArgumentNullException("response"); return ParseResponseInternal(response); } protected abstract Task<TResponse> ParseResponseInternal(HttpResponseMessage response); } }```
49d600d0-04f3-4e49-b28a-cb862bb90e7d
{ "language": "C#" }
```c# <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> @RenderSection("styles", false) </head> <body> <div class="container"> <h1 class="text-center">@ViewBag.Title</h1> @RenderBody() </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> @RenderSection("scripts", false) </body> </html> ``` Update Bootstrap package in v5 test pages to v5.2.2
```c# <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewBag.Title - Atata.Bootstrap.TestApp v5</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"> @RenderSection("styles", false) </head> <body> <div class="container"> <h1 class="text-center">@ViewBag.Title</h1> @RenderBody() </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script> @RenderSection("scripts", false) </body> </html> ```
9532d87b-e217-4574-993e-f9cf2e3446d8
{ "language": "C#" }
```c# using System; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using AdmoInstallerCustomAction; using System.Windows; namespace AdmoTests.CustomActionTests { [TestClass] public class CustomActionTests { [TestMethod] public void TestMethod1() { //Will have to use gui testing tools here //ManualResetEvent syncEvent = new ManualResetEvent(false); //Thread t = new Thread(() => //{ // var app = new Application(); // app.Run(new DownloadRuntimeWPF()); // // syncEvent.Set(); //}); //t.SetApartmentState(ApartmentState.STA); //t.Start(); //t.Join(); } } } ``` Test to run gui on STA thread
```c# using System; using System.Threading; using Admo; using Microsoft.VisualStudio.TestTools.UnitTesting; using AdmoInstallerCustomAction; using System.Windows; namespace AdmoTests.CustomActionTests { [TestClass] public class CustomActionTests { [TestMethod] public void TestRunWPFOnSTAThread() { //Will have to use gui testing tools here Thread t = new Thread(() => { var app = new Application(); app.Run(new DownloadRuntimeWPF()); }); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Abort(); } } } ```
34b475f3-d01f-4e1d-878d-0cd11f4497d2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int p0) { ScenarioContext.Current.Pending(); } [When(@"I print the number")] public void WhenIPrintTheNumber() { ScenarioContext.Current.Pending(); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(int p0) { ScenarioContext.Current.Pending(); } } } ``` Implement first step of automation layer
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using TechTalk.SpecFlow; namespace FizzBuzz.Specification.AutomationLayer { [Binding] public class StepDefinitions { private int currentNumber; [Given(@"the current number is '(.*)'")] public void GivenTheCurrentNumberIs(int currentNumber) { this.currentNumber = currentNumber; } [When(@"I print the number")] public void WhenIPrintTheNumber() { ScenarioContext.Current.Pending(); } [Then(@"the result is '(.*)'")] public void ThenTheResultIs(int p0) { ScenarioContext.Current.Pending(); } } } ```
c81fd80c-b307-43a3-b49f-f50c0ec0fb07
{ "language": "C#" }
```c# using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Install.InstallSteps; using Umbraco.Cms.Core.Install.Models; using Umbraco.Cms.Infrastructure.Install; using Umbraco.Cms.Infrastructure.Install.InstallSteps; using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.DependencyInjection { public static partial class UmbracoBuilderExtensions { /// <summary> /// Adds the services for the Umbraco installer /// </summary> internal static IUmbracoBuilder AddInstaller(this IUmbracoBuilder builder) { // register the installer steps builder.Services.AddScoped<InstallSetupStep, NewInstallStep>(); builder.Services.AddScoped<InstallSetupStep, UpgradeStep>(); builder.Services.AddScoped<InstallSetupStep, FilePermissionsStep>(); builder.Services.AddScoped<InstallSetupStep, TelemetryIdentifierStep>(); builder.Services.AddScoped<InstallSetupStep, DatabaseConfigureStep>(); builder.Services.AddScoped<InstallSetupStep, DatabaseInstallStep>(); builder.Services.AddScoped<InstallSetupStep, DatabaseUpgradeStep>(); builder.Services.AddScoped<InstallSetupStep, CompleteInstallStep>(); builder.Services.AddTransient<InstallStepCollection>(); builder.Services.AddUnique<InstallHelper>(); return builder; } } } ``` Fix integration tests - register PackageMigrationRunner
```c# using Microsoft.Extensions.DependencyInjection; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Install.InstallSteps; using Umbraco.Cms.Core.Install.Models; using Umbraco.Cms.Infrastructure.Install; using Umbraco.Cms.Infrastructure.Install.InstallSteps; using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.DependencyInjection { public static partial class UmbracoBuilderExtensions { /// <summary> /// Adds the services for the Umbraco installer /// </summary> internal static IUmbracoBuilder AddInstaller(this IUmbracoBuilder builder) { // register the installer steps builder.Services.AddScoped<InstallSetupStep, NewInstallStep>(); builder.Services.AddScoped<InstallSetupStep, UpgradeStep>(); builder.Services.AddScoped<InstallSetupStep, FilePermissionsStep>(); builder.Services.AddScoped<InstallSetupStep, TelemetryIdentifierStep>(); builder.Services.AddScoped<InstallSetupStep, DatabaseConfigureStep>(); builder.Services.AddScoped<InstallSetupStep, DatabaseInstallStep>(); builder.Services.AddScoped<InstallSetupStep, DatabaseUpgradeStep>(); builder.Services.AddScoped<InstallSetupStep, CompleteInstallStep>(); builder.Services.AddTransient<InstallStepCollection>(); builder.Services.AddUnique<InstallHelper>(); builder.Services.AddTransient<PackageMigrationRunner>(); return builder; } } } ```
eb94251b-b6f5-4232-8785-cb86a2a9bffd
{ "language": "C#" }
```c# using System.Threading.Tasks; using Microsoft.Owin; using System.Linq; using System; using Foundation.Api.Implementations; using System.Threading; namespace Foundation.Api.Middlewares { public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware { public OwinCacheResponseMiddleware() { } public OwinCacheResponseMiddleware(OwinMiddleware next) : base(next) { } public override async Task OnActionExecutingAsync(IOwinContext owinContext) { if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Cache-Control"); owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Pragma"); owinContext.Response.Headers.Add("Pragma", new[] { "public" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Expires"); owinContext.Response.Headers.Add("Expires", new[] { "31536000" }); await base.OnActionExecutingAsync(owinContext); } } }``` Set expires header to max when response is intented to be cached, so browsers will not use try-get pattern for those resources next time.
```c# using System.Threading.Tasks; using Microsoft.Owin; using System.Linq; using System; using Foundation.Api.Implementations; namespace Foundation.Api.Middlewares { public class OwinCacheResponseMiddleware : DefaultOwinActionFilterMiddleware { public OwinCacheResponseMiddleware() { } public OwinCacheResponseMiddleware(OwinMiddleware next) : base(next) { } public override async Task OnActionExecutingAsync(IOwinContext owinContext) { if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Cache-Control", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Cache-Control"); owinContext.Response.Headers.Add("Cache-Control", new[] { "public", "max-age=31536000" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Pragma", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Pragma"); owinContext.Response.Headers.Add("Pragma", new[] { "public" }); if (owinContext.Response.Headers.Any(h => string.Equals(h.Key, "Expires", StringComparison.InvariantCultureIgnoreCase))) owinContext.Response.Headers.Remove("Expires"); owinContext.Response.Headers.Add("Expires", new[] { "max" }); await base.OnActionExecutingAsync(owinContext); } } }```