doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
c84b9bae-f356-4a2e-8bfd-303bf191dfb5
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Drawing; using System.IO; using ValveKeyValue; namespace GUI.Utils { internal static class Settings { public class AppConfig { public List<string> GameSearchPaths { get; set; } = new List<string>(); public string BackgroundColor { get; set; } = string.Empty; public string OpenDirectory { get; set; } = string.Empty; public string SaveDirectory { get; set; } = string.Empty; } private const string SettingsFilePath = "settings.txt"; public static AppConfig Config { get; set; } = new AppConfig(); public static Color BackgroundColor { get; set; } = Color.FromArgb(60, 60, 60); public static void Load() { if (!File.Exists(SettingsFilePath)) { Save(); return; } using (var stream = new FileStream(SettingsFilePath, FileMode.Open, FileAccess.Read)) { Config = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize<AppConfig>(stream, KVSerializerOptions.DefaultOptions); } BackgroundColor = ColorTranslator.FromHtml(Config.BackgroundColor); } public static void Save() { Config.BackgroundColor = ColorTranslator.ToHtml(BackgroundColor); using (var stream = new FileStream(SettingsFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Serialize(stream, Config, nameof(ValveResourceFormat)); } } } } ``` Save settings.txt to same folder as the assembly
```c# using System.Collections.Generic; using System.Drawing; using System.IO; using ValveKeyValue; namespace GUI.Utils { internal static class Settings { public class AppConfig { public List<string> GameSearchPaths { get; set; } = new List<string>(); public string BackgroundColor { get; set; } = string.Empty; public string OpenDirectory { get; set; } = string.Empty; public string SaveDirectory { get; set; } = string.Empty; } private static string SettingsFilePath; public static AppConfig Config { get; set; } = new AppConfig(); public static Color BackgroundColor { get; set; } = Color.FromArgb(60, 60, 60); public static void Load() { SettingsFilePath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "settings.txt"); if (!File.Exists(SettingsFilePath)) { Save(); return; } using (var stream = new FileStream(SettingsFilePath, FileMode.Open, FileAccess.Read)) { Config = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize<AppConfig>(stream, KVSerializerOptions.DefaultOptions); } BackgroundColor = ColorTranslator.FromHtml(Config.BackgroundColor); } public static void Save() { Config.BackgroundColor = ColorTranslator.ToHtml(BackgroundColor); using (var stream = new FileStream(SettingsFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Serialize(stream, Config, nameof(ValveResourceFormat)); } } } } ```
bb25253c-47f0-450b-abf5-cc802c06b3cd
{ "language": "C#" }
```c# using System; using System.Linq; using downr.Services; using Microsoft.AspNetCore.Mvc; namespace downr.Controllers { public class HomeController : Controller { IYamlIndexer _indexer; public HomeController(IYamlIndexer indexer) { _indexer = indexer; } [Route("{id?}")] public IActionResult Index(string id) { // if no slug was provided show the last one if (string.IsNullOrEmpty(id)) return RedirectToAction("Index", "Posts", new { slug = _indexer.Metadata.ElementAt(0).Slug }); // if the slug was provided AND found, redirect to it if (_indexer.Metadata.Any(x => x.Slug == id)) return RedirectToAction("Index", "Posts", new { slug = _indexer.Metadata.ElementAt(0).Slug }); else // no match was found, show the last one return RedirectToAction("Index", "Posts", new { slug = _indexer.Metadata.ElementAt(0).Slug }); } } } ``` Fix logic in home index to go to a slug if provided
```c# using System; using System.Linq; using downr.Services; using Microsoft.AspNetCore.Mvc; namespace downr.Controllers { public class HomeController : Controller { IYamlIndexer _indexer; public HomeController(IYamlIndexer indexer) { _indexer = indexer; } [Route("{id?}")] public IActionResult Index(string id) { //Go to a slug if provided otherwise go to latest. var slug = _indexer.Metadata.FirstOrDefault(x => x.Slug == id)?.Slug; return RedirectToAction("Index", "Posts", new { slug = slug ?? _indexer.Metadata.ElementAt(0).Slug }); } } } ```
81fd6818-a176-433b-84ca-5bbe1546f714
{ "language": "C#" }
```c# <div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> </div>``` Change GC Handicapping sticky note
```c# <div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> came into effect 3 April, 2017 </p> </div> </div> </div>```
35d5d1e9-b1ef-4981-9b20-0c858c75667a
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { public class RunCodeActionsHandlerTests : AbstractLiveShareRequestHandlerTests { [WpfFact] public async Task TestRunCodeActionsAsync() { var markup = @"class A { void M() { {|caret:|}int i = 1; } }"; var (solution, ranges) = CreateTestSolution(markup); var codeActionLocation = ranges["caret"].First(); var results = await TestHandleAsync<LSP.ExecuteCommandParams, object>(solution, CreateExecuteCommandParams(codeActionLocation)); Assert.True((bool)results); } private static LSP.ExecuteCommandParams CreateExecuteCommandParams(LSP.Location location) => new LSP.ExecuteCommandParams() { Command = "_liveshare.remotecommand.Roslyn", Arguments = new object[] { JObject.FromObject(new LSP.Command() { CommandIdentifier = "Roslyn.RunCodeAction", Arguments = new RunCodeActionParams[] { CreateRunCodeActionParams("Use implicit type", location) } }) } }; } } ``` Update tests to pass new required title parameter.
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { public class RunCodeActionsHandlerTests : AbstractLiveShareRequestHandlerTests { [WpfFact] public async Task TestRunCodeActionsAsync() { var markup = @"class A { void M() { {|caret:|}int i = 1; } }"; var (solution, ranges) = CreateTestSolution(markup); var codeActionLocation = ranges["caret"].First(); var results = await TestHandleAsync<LSP.ExecuteCommandParams, object>(solution, CreateExecuteCommandParams(codeActionLocation, "Use implicit type")); Assert.True((bool)results); } private static LSP.ExecuteCommandParams CreateExecuteCommandParams(LSP.Location location, string title) => new LSP.ExecuteCommandParams() { Command = "_liveshare.remotecommand.Roslyn", Arguments = new object[] { JObject.FromObject(new LSP.Command() { CommandIdentifier = "Roslyn.RunCodeAction", Arguments = new RunCodeActionParams[] { CreateRunCodeActionParams(title, location) }, Title = title }) } }; } } ```
c5843b41-2294-41da-8c97-12c5946e547d
{ "language": "C#" }
```c# using Loupe.Extensibility; using Loupe.Extensibility.Client; namespace Loupe.Extension.Export { /// <summary> /// Top-level class for integrating with the Loupe framework /// </summary> [LoupeExtension(ConfigurationEditor = typeof(ExportConfigurationDialog), MachineConfiguration = typeof(ExportAddInConfiguration))] public class ExtentionDefinition : IExtensionDefinition { /// <summary> /// Called to register the extension. /// </summary> /// <param name="context">A standard interface to the hosting environment for the Extension, provided to all the different extensions that get loaded.</param><param name="definitionContext">Used to register the various types used by the extension.</param> /// <remarks> /// <para> /// If any exception is thrown during this call this Extension will not be loaded. /// </para> /// <para> /// Register each of the other extension types that should be available to end users through appropriate calls to /// the definitionContext. These objects will be created and initialized as required and provided the same IExtensionContext object instance provided to this /// method to enable coordination between all of the components. /// </para> /// <para> /// After registration the extension definition object is unloaded and disposed. /// </para> /// </remarks> public void Register(IGlobalContext context, IExtensionDefinitionContext definitionContext) { //we have to register all of our types during this call or they won't be used at all. definitionContext.RegisterSessionAnalyzer(typeof(SessionExporter)); definitionContext.RegisterSessionCommand(typeof(SessionExporter)); } } } ``` Correct extension definition configuration value
```c# using Loupe.Extensibility; using Loupe.Extensibility.Client; namespace Loupe.Extension.Export { /// <summary> /// Top-level class for integrating with the Loupe framework /// </summary> [LoupeExtension(ConfigurationEditor = typeof(ExportConfigurationDialog), CommonConfiguration = typeof(ExportAddInConfiguration))] public class ExtentionDefinition : IExtensionDefinition { /// <summary> /// Called to register the extension. /// </summary> /// <param name="context">A standard interface to the hosting environment for the Extension, provided to all the different extensions that get loaded.</param><param name="definitionContext">Used to register the various types used by the extension.</param> /// <remarks> /// <para> /// If any exception is thrown during this call this Extension will not be loaded. /// </para> /// <para> /// Register each of the other extension types that should be available to end users through appropriate calls to /// the definitionContext. These objects will be created and initialized as required and provided the same IExtensionContext object instance provided to this /// method to enable coordination between all of the components. /// </para> /// <para> /// After registration the extension definition object is unloaded and disposed. /// </para> /// </remarks> public void Register(IGlobalContext context, IExtensionDefinitionContext definitionContext) { //we have to register all of our types during this call or they won't be used at all. definitionContext.RegisterSessionAnalyzer(typeof(SessionExporter)); definitionContext.RegisterSessionCommand(typeof(SessionExporter)); } } } ```
d8292751-5aa0-43dd-a508-e6b820ac4b13
{ "language": "C#" }
```c# using Microsoft.PowerShell.EditorServices.Session; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Event; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Message; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Response; using Nito.AsyncEx; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Transport.Stdio.Request { [MessageTypeName("initialize")] public class InitializeRequest : RequestBase<InitializeRequestArguments> { public override async Task ProcessMessage( EditorSession editorSession, MessageWriter messageWriter) { // Send the Initialized event first so that we get breakpoints await messageWriter.WriteMessage( new InitializedEvent()); // Now send the Initialize response to continue setup await messageWriter.WriteMessage( this.PrepareResponse( new InitializeResponse())); } } public class InitializeRequestArguments { public string AdapterId { get; set; } public bool LinesStartAt1 { get; set; } public string PathFormat { get; set; } public bool SourceMaps { get; set; } public string GeneratedCodeDirectory { get; set; } } }``` Add separate log file for debugging service
```c# using Microsoft.PowerShell.EditorServices.Session; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Event; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Message; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Response; using Microsoft.PowerShell.EditorServices.Utility; using Nito.AsyncEx; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Transport.Stdio.Request { [MessageTypeName("initialize")] public class InitializeRequest : RequestBase<InitializeRequestArguments> { public override async Task ProcessMessage( EditorSession editorSession, MessageWriter messageWriter) { // TODO: Remove this behavior in the near future -- // Create the debug service log in a separate file // so that there isn't a conflict with the default // log file. Logger.Initialize("DebugService.log", LogLevel.Verbose); // Send the Initialized event first so that we get breakpoints await messageWriter.WriteMessage( new InitializedEvent()); // Now send the Initialize response to continue setup await messageWriter.WriteMessage( this.PrepareResponse( new InitializeResponse())); } } public class InitializeRequestArguments { public string AdapterId { get; set; } public bool LinesStartAt1 { get; set; } public string PathFormat { get; set; } public bool SourceMaps { get; set; } public string GeneratedCodeDirectory { get; set; } } }```
12a4bb71-e848-4396-bb80-85d1dfed4ade
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public class EstimateQuery { public string username { get; set; } } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do if(query != null) { return Ok(query.username); } else { return Ok("Add a username!"); } } } } ``` Check username for null too.
```c# using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public class EstimateQuery { public string username { get; set; } } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do if(query != null && query.username != null) { return Ok(query.username); } else { return Ok("Add a username!"); } } } } ```
18edeb35-6b5d-434e-aaa0-257a324d3330
{ "language": "C#" }
```c# using System; using System.Text; namespace Manos.Server { public interface IHttpResponse { IHttpTransaction Transaction { get; } HttpHeaders Headers { get; } HttpResponseStream Stream { get; } Encoding Encoding { get; } int StatusCode { get; set; } bool WriteStatusLine { get; set; } bool WriteHeaders { get; set; } void Write (string str); void Write (string str, params object [] prms); void WriteLine (string str); void WriteLine (string str, params object [] prms); void Write (byte [] data); void SendFile (string file); void Finish (); void SetHeader (string name, string value); void SetCookie (string name, HttpCookie cookie); HttpCookie SetCookie (string name, string value); HttpCookie SetCookie (string name, string value, string domain); HttpCookie SetCookie (string name, string value, DateTime expires); HttpCookie SetCookie (string name, string value, string domain, DateTime expires); HttpCookie SetCookie (string name, string value, TimeSpan max_age); HttpCookie SetCookie (string name, string value, string domain, TimeSpan max_age); void Redirect (string url); } } ``` Add the writer to the interface.
```c# using System; using System.IO; using System.Text; namespace Manos.Server { public interface IHttpResponse { IHttpTransaction Transaction { get; } HttpHeaders Headers { get; } HttpResponseStream Stream { get; } StreamWriter Writer { get; } Encoding Encoding { get; } int StatusCode { get; set; } bool WriteStatusLine { get; set; } bool WriteHeaders { get; set; } void Write (string str); void Write (string str, params object [] prms); void WriteLine (string str); void WriteLine (string str, params object [] prms); void Write (byte [] data); void SendFile (string file); void Finish (); void SetHeader (string name, string value); void SetCookie (string name, HttpCookie cookie); HttpCookie SetCookie (string name, string value); HttpCookie SetCookie (string name, string value, string domain); HttpCookie SetCookie (string name, string value, DateTime expires); HttpCookie SetCookie (string name, string value, string domain, DateTime expires); HttpCookie SetCookie (string name, string value, TimeSpan max_age); HttpCookie SetCookie (string name, string value, string domain, TimeSpan max_age); void Redirect (string url); } } ```
7d7d55dc-0e05-4fd3-8847-c1a018c28c87
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Giles.Core.Configuration { [Serializable] public class Filter { public Filter() { } public Filter(string convertToFilter) { foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(entry.Key))) { Type = entry.Value; Name = convertToFilter.Replace(entry.Key, string.Empty).Trim(); break; } if (!string.IsNullOrWhiteSpace(Name)) return; Name = convertToFilter.Trim(); Type = FilterType.Inclusive; } public string Name { get; set; } public FilterType Type { get; set; } public string NameDll { get { return Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? Name : String.Format("{0}.dll", Name); } } public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType> { {"-i", FilterType.Inclusive}, {"-e", FilterType.Exclusive} }; } public enum FilterType { Inclusive, Exclusive } }``` Make sure there is a space between the -* and the filtered namespace to prevent any accidental replacements
```c# using System; using System.Collections.Generic; using System.Linq; namespace Giles.Core.Configuration { [Serializable] public class Filter { public Filter() { } public Filter(string convertToFilter) { foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(string.Format(" {0}" ,entry.Key)))) { Type = entry.Value; Name = convertToFilter.Replace(string.Format(" {0}", entry.Key), string.Empty).Trim(); break; } if (!string.IsNullOrWhiteSpace(Name)) return; Name = convertToFilter.Trim(); Type = FilterType.Inclusive; } public string Name { get; set; } public FilterType Type { get; set; } public string NameDll { get { return Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? Name : String.Format("{0}.dll", Name); } } public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType> { {"-i", FilterType.Inclusive}, {"-e", FilterType.Exclusive} }; } public enum FilterType { Inclusive, Exclusive } }```
df364e9d-5d1e-4338-8ef2-dd1d2c7c0a13
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCLibraryManagementSystem.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } } }``` Fix merge conflict with maitisoumyajit
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCLibraryManagementSystem.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } } } ```
af5b98f5-9ac5-4b69-8f2b-c4c3363ea6f1
{ "language": "C#" }
```c# using System; using System.Windows; using System.Windows.Controls; using vmPing.Classes; namespace vmPing.Views { /// <summary> /// Interaction logic for IsolatedPingWindow.xaml /// </summary> public partial class IsolatedPingWindow : Window { private int SelStart = 0; private int SelLength = 0; public IsolatedPingWindow(Probe pingItem) { InitializeComponent(); pingItem.IsolatedWindow = this; DataContext = pingItem; } private void History_TextChanged(object sender, TextChangedEventArgs e) { History.SelectionStart = SelStart; History.SelectionLength = SelLength; History.ScrollToEnd(); } private void History_SelectionChanged(object sender, RoutedEventArgs e) { SelStart = History.SelectionStart; SelLength = History.SelectionLength; } private void Window_Closed(object sender, EventArgs e) { (DataContext as Probe).IsolatedWindow = null; DataContext = null; } } } ``` Use dispatcher begininvoke for textbox scroll
```c# using System; using System.Windows; using System.Windows.Controls; using vmPing.Classes; namespace vmPing.Views { /// <summary> /// Interaction logic for IsolatedPingWindow.xaml /// </summary> public partial class IsolatedPingWindow : Window { private int SelStart = 0; private int SelLength = 0; public IsolatedPingWindow(Probe pingItem) { InitializeComponent(); pingItem.IsolatedWindow = this; DataContext = pingItem; } private void History_TextChanged(object sender, TextChangedEventArgs e) { History.SelectionStart = SelStart; History.SelectionLength = SelLength; Application.Current.Dispatcher.BeginInvoke( new Action(() => History.ScrollToEnd())); } private void History_SelectionChanged(object sender, RoutedEventArgs e) { SelStart = History.SelectionStart; SelLength = History.SelectionLength; } private void Window_Closed(object sender, EventArgs e) { (DataContext as Probe).IsolatedWindow = null; DataContext = null; } } } ```
a2a4605c-bfb4-4c90-84dc-6339be6be8a3
{ "language": "C#" }
```c# using System; namespace NuGet { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477"; public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669"; public static readonly string DefaultGalleryServerUrl = "http://go.microsoft.com/fwlink/?LinkID=207106"; public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet"; } } ``` Update default publishing url to point to v2 feed.
```c# using System; namespace NuGet { public static class NuGetConstants { public static readonly string DefaultFeedUrl = "https://go.microsoft.com/fwlink/?LinkID=230477"; public static readonly string V1FeedUrl = "https://go.microsoft.com/fwlink/?LinkID=206669"; public static readonly string DefaultGalleryServerUrl = "https://www.nuget.org"; public static readonly string DefaultSymbolServerUrl = "http://nuget.gw.symbolsource.org/Public/NuGet"; } } ```
0ad68951-9ab8-4945-a4f7-26d58f5067a0
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AppHarbor { class Program { static void Main(string[] args) { } } } ``` Initialize a WindowsContainer when program starts
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Castle.Windsor; namespace AppHarbor { class Program { static void Main(string[] args) { var container = new WindsorContainer(); } } } ```
b6ce5672-6bc2-4349-a918-d6122e823dd8
{ "language": "C#" }
```c# using System.Windows; using Dogstar.Properties; namespace Dogstar { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { void Application_Startup(object sender, StartupEventArgs e) { if (Settings.Default.UpgradeCheck) { Settings.Default.Upgrade(); Settings.Default.UpgradeCheck = false; Settings.Default.Save(); } foreach (var arg in e.Args) { switch (arg) { case "-pso2": Helper.LaunchGame(); Shutdown(); break; } } } private void Application_Exit(object sender, ExitEventArgs e) { if (e.ApplicationExitCode == 0) { Settings.Default.Save(); } } } } ``` Save game settings on close.
```c# using System.Windows; using Dogstar.Properties; namespace Dogstar { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { void Application_Startup(object sender, StartupEventArgs e) { if (Settings.Default.UpgradeCheck) { Settings.Default.Upgrade(); Settings.Default.UpgradeCheck = false; Settings.Default.Save(); } foreach (var arg in e.Args) { switch (arg) { case "-pso2": Helper.LaunchGame(); Shutdown(); break; } } } private void Application_Exit(object sender, ExitEventArgs e) { if (e.ApplicationExitCode == 0) { Settings.Default.Save(); if (Settings.Default.IsGameInstalled) { PsoSettings.Save(); } } } } } ```
00fc5a5b-301b-47c1-8f00-71bc00aa2f19
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects.Drawables { public class DrawableSpinnerTick : DrawableOsuHitObject { private bool hasBonusPoints; /// <summary> /// Whether this judgement has a bonus of 1,000 points additional to the numeric result. /// Set when a spin occured after the spinner has completed. /// </summary> public bool HasBonusPoints { get => hasBonusPoints; internal set { hasBonusPoints = value; Samples.Volume.Value = ((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints ? 1 : 0; } } public override bool DisplayResult => false; public DrawableSpinnerTick(SpinnerTick spinnerTick) : base(spinnerTick) { } /// <summary> /// Apply a judgement result. /// </summary> /// <param name="hit">Whether to apply a <see cref="HitResult.Great"/> result, <see cref="HitResult.Miss"/> otherwise.</param> internal void TriggerResult(bool hit) { HitObject.StartTime = Time.Current; ApplyResult(r => r.Type = hit ? HitResult.Great : HitResult.Miss); } } } ``` Fix spinner bonus ticks samples not actually playing
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects.Drawables { public class DrawableSpinnerTick : DrawableOsuHitObject { private bool hasBonusPoints; /// <summary> /// Whether this judgement has a bonus of 1,000 points additional to the numeric result. /// Set when a spin occured after the spinner has completed. /// </summary> public bool HasBonusPoints { get => hasBonusPoints; internal set { hasBonusPoints = value; ((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints = value; Samples.Volume.Value = value ? 1 : 0; } } public override bool DisplayResult => false; public DrawableSpinnerTick(SpinnerTick spinnerTick) : base(spinnerTick) { } /// <summary> /// Apply a judgement result. /// </summary> /// <param name="hit">Whether to apply a <see cref="HitResult.Great"/> result, <see cref="HitResult.Miss"/> otherwise.</param> internal void TriggerResult(bool hit) { HitObject.StartTime = Time.Current; ApplyResult(r => r.Type = hit ? HitResult.Great : HitResult.Miss); } } } ```
7c307aca-fc00-42b0-90b8-02a9f859515b
{ "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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.Graphics { public class DetailSettings : SettingsSubsection { protected override string Header => "Detail Settings"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Storyboards", Bindable = config.GetBindable<bool>(OsuSetting.ShowStoryboard) }, new SettingsCheckbox { LabelText = "Rotate cursor when dragging", Bindable = config.GetBindable<bool>(OsuSetting.CursorRotation) }, new SettingsEnumDropdown<ScreenshotFormat> { LabelText = "Screenshot format", Bindable = config.GetBindable<ScreenshotFormat>(OsuSetting.ScreenshotFormat) }, new SettingsCheckbox { LabelText = "Capture menu cursor", Bindable = config.GetBindable<bool>(OsuSetting.ScreenshotCaptureMenuCursor) } }; } } } ``` Reword options item to include "screenshot"
```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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.Graphics { public class DetailSettings : SettingsSubsection { protected override string Header => "Detail Settings"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Storyboards", Bindable = config.GetBindable<bool>(OsuSetting.ShowStoryboard) }, new SettingsCheckbox { LabelText = "Rotate cursor when dragging", Bindable = config.GetBindable<bool>(OsuSetting.CursorRotation) }, new SettingsEnumDropdown<ScreenshotFormat> { LabelText = "Screenshot format", Bindable = config.GetBindable<ScreenshotFormat>(OsuSetting.ScreenshotFormat) }, new SettingsCheckbox { LabelText = "Show menu cursor in screenshots", Bindable = config.GetBindable<bool>(OsuSetting.ScreenshotCaptureMenuCursor) } }; } } } ```
187ab8e6-d3a6-4ba9-ba68-2d61fcf41efc
{ "language": "C#" }
```c# using System; using GAIT.Utilities.Logging; using NLog; using Topshelf; using static GAIT.Utilities.GeneralBootstrapper; namespace Rik.CodeCamp.Host { internal class CodeCampControl : ServiceControl { private Bootstrapper _bootstrapper; private readonly ILogger _logger; public CodeCampControl() { _logger = LoggingFactory.Create(GetType()); } public bool Start(HostControl hostControl) { try { _bootstrapper = new Bootstrapper(); //var worker = _bootstrapper.Resolve<IWorker>(); //return worker.Start(); } catch (Exception exception) { _logger.Fatal(exception, "Start failed!!! "); } return false; } public bool Stop(HostControl hostControl) { try { _bootstrapper?.Dispose(); CancelAll.Cancel(); } catch (Exception exception) { _logger.Fatal(exception, "Stop failed!!! "); } return false; } } }``` Add worker resolve and start Start
```c# using System; using GAIT.Utilities.Logging; using NLog; using Rik.CodeCamp.Core; using Topshelf; using static GAIT.Utilities.GeneralBootstrapper; namespace Rik.CodeCamp.Host { internal class CodeCampControl : ServiceControl { private Bootstrapper _bootstrapper; private readonly ILogger _logger; public CodeCampControl() { _logger = LoggingFactory.Create(GetType()); } public bool Start(HostControl hostControl) { try { _bootstrapper = new Bootstrapper(); var worker = _bootstrapper.Resolve<IWorker>(); return worker.Start(); } catch (Exception exception) { _logger.Fatal(exception, "Start failed!!! "); } return false; } public bool Stop(HostControl hostControl) { try { _bootstrapper?.Dispose(); CancelAll.Cancel(); } catch (Exception exception) { _logger.Fatal(exception, "Stop failed!!! "); } return false; } } }```
cd47307c-a350-4b2b-bad9-fe5bcc94f8f6
{ "language": "C#" }
```c# using System; using System.Windows; using SteamAccountSwitcher.Properties; namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for Options.xaml /// </summary> public partial class Options : Window { public Options() { InitializeComponent(); Settings.Default.Save(); } private void menuItemImport_OnClick(object sender, EventArgs e) { AccountDataHelper.ImportAccounts(); } private void menuItemExport_OnClick(object sender, EventArgs e) { AccountDataHelper.ExportAccounts(); } private void btnOK_Click(object sender, RoutedEventArgs e) { SettingsHelper.SaveSettings(); DialogResult = true; } private void btnCancel_Click(object sender, RoutedEventArgs e) { Settings.Default.Reload(); DialogResult = true; } } }``` Set DialogResult to false on Options cancel
```c# using System; using System.Windows; using SteamAccountSwitcher.Properties; namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for Options.xaml /// </summary> public partial class Options : Window { public Options() { InitializeComponent(); Settings.Default.Save(); } private void menuItemImport_OnClick(object sender, EventArgs e) { AccountDataHelper.ImportAccounts(); } private void menuItemExport_OnClick(object sender, EventArgs e) { AccountDataHelper.ExportAccounts(); } private void btnOK_Click(object sender, RoutedEventArgs e) { SettingsHelper.SaveSettings(); DialogResult = true; } private void btnCancel_Click(object sender, RoutedEventArgs e) { Settings.Default.Reload(); DialogResult = false; } } }```
60ef7697-57cb-4f5e-9d74-c9885cba6565
{ "language": "C#" }
```c# using System; namespace FractionCalculator { using Class; public class TestProgram { public static void Main() { try { Fraction fraction1 = new Fraction(22, 7); Fraction fraction2 = new Fraction(40, 4); Fraction result = fraction1 + fraction2; Console.WriteLine(result.Numerator); Console.WriteLine(result.Denominator); Console.WriteLine(result); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } } } } ``` Add more one catch block for ArgumentException
```c# using System; namespace FractionCalculator { using Class; public class TestProgram { public static void Main() { try { Fraction fraction1 = new Fraction(22, 7); Fraction fraction2 = new Fraction(40, 4); Fraction result = fraction1 + fraction2; Console.WriteLine(result.Numerator); Console.WriteLine(result.Denominator); Console.WriteLine(result); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } } } } ```
3ff84a0e-4bde-4f72-ae8e-e4090e8749e5
{ "language": "C#" }
```c# //----------------------------------------------------------------------- // <copyright file="AsyncOperationTest.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AsyncEnum35Sample.Test.Unit { using System; using System.Collections.Generic; using Xunit; public class AsyncOperationTest { public AsyncOperationTest() { } [Fact] public void Set_result_in_ctor_and_break_completes_sync() { SetResultInCtorOperation op = new SetResultInCtorOperation(1234); IAsyncResult result = op.Start(null, null); Assert.True(result.IsCompleted); Assert.True(result.CompletedSynchronously); Assert.Equal(1234, SetResultInCtorOperation.End(result)); } private abstract class TestAsyncOperation : AsyncOperation<int> { protected TestAsyncOperation() { } } private sealed class SetResultInCtorOperation : TestAsyncOperation { public SetResultInCtorOperation(int result) { this.Result = result; } protected override IEnumerator<Step> Steps() { yield break; } } } } ``` Set result in enumerator and break completes sync
```c# //----------------------------------------------------------------------- // <copyright file="AsyncOperationTest.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AsyncEnum35Sample.Test.Unit { using System; using System.Collections.Generic; using Xunit; public class AsyncOperationTest { public AsyncOperationTest() { } [Fact] public void Set_result_in_ctor_and_break_completes_sync() { SetResultInCtorOperation op = new SetResultInCtorOperation(1234); IAsyncResult result = op.Start(null, null); Assert.True(result.IsCompleted); Assert.True(result.CompletedSynchronously); Assert.Equal(1234, SetResultInCtorOperation.End(result)); } [Fact] public void Set_result_in_enumerator_and_break_completes_sync() { SetResultInEnumeratorOperation op = new SetResultInEnumeratorOperation(1234); IAsyncResult result = op.Start(null, null); Assert.True(result.IsCompleted); Assert.True(result.CompletedSynchronously); Assert.Equal(1234, SetResultInEnumeratorOperation.End(result)); } private abstract class TestAsyncOperation : AsyncOperation<int> { protected TestAsyncOperation() { } } private sealed class SetResultInCtorOperation : TestAsyncOperation { public SetResultInCtorOperation(int result) { this.Result = result; } protected override IEnumerator<Step> Steps() { yield break; } } private sealed class SetResultInEnumeratorOperation : TestAsyncOperation { private readonly int result; public SetResultInEnumeratorOperation(int result) { this.result = result; } protected override IEnumerator<Step> Steps() { this.Result = this.result; yield break; } } } } ```
f3241ea7-d368-4b51-b36b-af9de3bbfa1f
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IHighlightingService))] [Shared] internal class HighlightingService : IHighlightingService { private readonly List<Lazy<IHighlighter, LanguageMetadata>> _highlighters; [ImportingConstructor] public HighlightingService( [ImportMany] IEnumerable<Lazy<IHighlighter, LanguageMetadata>> highlighters) { _highlighters = highlighters.ToList(); } public IEnumerable<TextSpan> GetHighlights( SyntaxNode root, int position, CancellationToken cancellationToken) { return _highlighters.Where(h => h.Metadata.Language == root.Language) .Select(h => h.Value.GetHighlights(root, position, cancellationToken)) .WhereNotNull() .Flatten() .Distinct(); } } } ``` Change high lighting crash to NFW
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IHighlightingService))] [Shared] internal class HighlightingService : IHighlightingService { private readonly List<Lazy<IHighlighter, LanguageMetadata>> _highlighters; [ImportingConstructor] public HighlightingService( [ImportMany] IEnumerable<Lazy<IHighlighter, LanguageMetadata>> highlighters) { _highlighters = highlighters.ToList(); } public IEnumerable<TextSpan> GetHighlights( SyntaxNode root, int position, CancellationToken cancellationToken) { try { return _highlighters.Where(h => h.Metadata.Language == root.Language) .Select(h => h.Value.GetHighlights(root, position, cancellationToken)) .WhereNotNull() .Flatten() .Distinct(); } catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) { // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988 // We still couldn't identify the root cause for the linked bug above. // Since high lighting failure is not important enough to crash VS, change crash to NFW. return SpecializedCollections.EmptyEnumerable<TextSpan>(); } } } } ```
067936a3-1fb8-4dee-853c-2716cc2f0d03
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Text; using System.Threading.Tasks; namespace SendEmailWithLogo { class Program { static void Main(string[] args) { var toAddress = "somewhere@mailinator.com"; var fromAddress = "you@host.com"; var message = "your message goes here"; // create the email var mailMessage = new MailMessage(); mailMessage.To.Add(toAddress); mailMessage.Subject = "Sending emails is easy"; mailMessage.From = new MailAddress(fromAddress); mailMessage.Body = message; // send it (settings in web.config / app.config) var smtp = new SmtpClient(); smtp.Send(mailMessage); } } } ``` Include company logo in email
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Text; using System.Threading.Tasks; namespace SendEmailWithLogo { class Program { static void Main(string[] args) { var toAddress = "somewhere@mailinator.com"; var fromAddress = "you@host.com"; var pathToLogo = @"Content\logo.png"; var pathToTemplate = @"Content\Template.html"; var messageText = File.ReadAllText(pathToTemplate); // replace placeholder messageText = ReplacePlaceholdersWithValues(messageText); // create the email var mailMessage = new MailMessage(); mailMessage.To.Add(toAddress); mailMessage.Subject = "Sending emails is easy"; mailMessage.From = new MailAddress(fromAddress); mailMessage.IsBodyHtml = true; mailMessage.AlternateViews.Add(CreateHtmlMessage(messageText, pathToLogo)); // send it (settings in web.config / app.config) var smtp = new SmtpClient(); smtp.Send(mailMessage); } private static AlternateView CreateHtmlMessage(string messageText, string pathToLogo) { LinkedResource inline = new LinkedResource(pathToLogo); inline.ContentId = "companyLogo"; AlternateView alternateView = AlternateView.CreateAlternateViewFromString(messageText, null, MediaTypeNames.Text.Html); alternateView.LinkedResources.Add(inline); return alternateView; } private static string ReplacePlaceholdersWithValues(string messageText) { // use the dynamic values instead of the hardcoded ones in this example messageText = messageText.Replace("$AMOUNT$", "$12.50"); messageText = messageText.Replace("$DATE$", DateTime.Now.ToShortDateString()); messageText = messageText.Replace("$INVOICE$", "25639"); messageText = messageText.Replace("$TRANSACTION$", "TRX2017-WEB-01"); return messageText; } } } ```
4fc1d392-0300-4886-9b92-c9f323e4807f
{ "language": "C#" }
```c# using System; using System.Linq; using System.ServiceProcess; namespace PolymeliaDeployController { using System.Configuration; using System.Data.Entity; using Microsoft.Owin.Hosting; using PolymeliaDeploy; using PolymeliaDeploy.Controller; using PolymeliaDeploy.Data; using PolymeliaDeploy.Network; static class Program { static void Main(string[] args) { Database.SetInitializer<PolymeliaDeployDbContext>(null); DeployServices.ReportClient = new ReportLocalClient(); var service = new Service(); if (args.Any(arg => arg == "/c")) { using (CreateServiceHost()) { Console.WriteLine("Started"); Console.ReadKey(); Console.WriteLine("Stopping"); return; } } ServiceBase.Run(service); } internal static IDisposable CreateServiceHost() { var localIpAddress = IPAddressRetriever.LocalIPAddress(); var portNumber = ConfigurationManager.AppSettings["ControllerPort"]; var controllUri = string.Format("http://{0}:{1}", localIpAddress, portNumber); return WebApplication.Start<Startup>(controllUri); } } } ``` Check Environment.UserInteractive instead of /c argument.
```c# using System; using System.Linq; using System.ServiceProcess; namespace PolymeliaDeployController { using System.Configuration; using System.Data.Entity; using Microsoft.Owin.Hosting; using PolymeliaDeploy; using PolymeliaDeploy.Controller; using PolymeliaDeploy.Data; using PolymeliaDeploy.Network; static class Program { static void Main(string[] args) { Database.SetInitializer<PolymeliaDeployDbContext>(null); DeployServices.ReportClient = new ReportLocalClient(); var service = new Service(); if (Environment.UserInteractive) { using (CreateServiceHost()) { Console.WriteLine("Started"); Console.ReadKey(); Console.WriteLine("Stopping"); return; } } ServiceBase.Run(service); } internal static IDisposable CreateServiceHost() { var localIpAddress = IPAddressRetriever.LocalIPAddress(); var portNumber = ConfigurationManager.AppSettings["ControllerPort"]; var controllUri = string.Format("http://{0}:{1}", localIpAddress, portNumber); return WebApplication.Start<Startup>(controllUri); } } } ```
a474b2aa-9089-4ddc-9bd9-64a1236dd189
{ "language": "C#" }
```c# using System; using System.Xml; using System.Xml.Linq; using Rainbow.Model; namespace Rainbow.Diff.Fields { public class XmlComparison : FieldTypeBasedComparison { public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (string.IsNullOrWhiteSpace(field1.Value) && string.IsNullOrWhiteSpace(field2.Value)) return true; if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false; try { var x1 = XElement.Parse(field1.Value); var x2 = XElement.Parse(field2.Value); return XNode.DeepEquals(x1, x2); } catch (XmlException xe) { throw new InvalidOperationException($"Unable to compare {field1.NameHint ?? field2.NameHint} field due to invalid XML value.", xe); } } public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" }; } } ``` Fix error that aborted sync when invalid XML was present in an XML formatted field (e.g. a malformed rules field in the stock master db)
```c# using System.Xml; using System.Xml.Linq; using Rainbow.Model; using Sitecore.Diagnostics; namespace Rainbow.Diff.Fields { public class XmlComparison : FieldTypeBasedComparison { public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (string.IsNullOrWhiteSpace(field1.Value) && string.IsNullOrWhiteSpace(field2.Value)) return true; if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false; try { var x1 = XElement.Parse(field1.Value); var x2 = XElement.Parse(field2.Value); return XNode.DeepEquals(x1, x2); } catch (XmlException xe) { Log.Error($"Field {field1.NameHint ?? field2.NameHint} contained an invalid XML value. Falling back to string comparison.", xe, this); return new DefaultComparison().AreEqual(field1, field2); } } public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" }; } } ```
8508deff-9eb2-4132-81ea-82e38e5c519a
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Serilog.Core; using Serilog.Debugging; using Serilog.Events; using Serilog.Sinks.Graylog.Core; using Serilog.Sinks.Graylog.Core.Transport; namespace Serilog.Sinks.Graylog { public class GraylogSink : ILogEventSink { private readonly Lazy<IGelfConverter> _converter; private readonly Lazy<ITransport> _transport; public GraylogSink(GraylogSinkOptions options) { ISinkComponentsBuilder sinkComponentsBuilder = new SinkComponentsBuilder(options); _transport = new Lazy<ITransport>(() => sinkComponentsBuilder.MakeTransport()); _converter = new Lazy<IGelfConverter>(() => sinkComponentsBuilder.MakeGelfConverter()); } public void Emit(LogEvent logEvent) { try { Task.Run(() => EmitAsync(logEvent)).GetAwaiter().GetResult(); } catch (Exception exc) { SelfLog.WriteLine("Oops something going wrong {0}", exc); } } private Task EmitAsync(LogEvent logEvent) { JObject json = _converter.Value.GetGelfJson(logEvent); string payload = json.ToString(Newtonsoft.Json.Formatting.None); return _transport.Value.Send(payload); } } }``` Fix increase connections to transport
```c# using System; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Serilog.Core; using Serilog.Debugging; using Serilog.Events; using Serilog.Sinks.Graylog.Core; using Serilog.Sinks.Graylog.Core.Transport; namespace Serilog.Sinks.Graylog { public class GraylogSink : ILogEventSink, IDisposable { private readonly Lazy<IGelfConverter> _converter; private readonly Lazy<ITransport> _transport; public GraylogSink(GraylogSinkOptions options) { ISinkComponentsBuilder sinkComponentsBuilder = new SinkComponentsBuilder(options); _transport = new Lazy<ITransport>(() => sinkComponentsBuilder.MakeTransport()); _converter = new Lazy<IGelfConverter>(() => sinkComponentsBuilder.MakeGelfConverter()); } public void Dispose() { _transport.Value.Dispose(); } public void Emit(LogEvent logEvent) { try { Task.Run(() => EmitAsync(logEvent)).GetAwaiter().GetResult(); } catch (Exception exc) { SelfLog.WriteLine("Oops something going wrong {0}", exc); } } private Task EmitAsync(LogEvent logEvent) { JObject json = _converter.Value.GetGelfJson(logEvent); string payload = json.ToString(Newtonsoft.Json.Formatting.None); return _transport.Value.Send(payload); } } } ```
a262f527-bd5e-4e65-b911-aeaf07a5b27b
{ "language": "C#" }
```c# using NServiceBus; public static class ConfigBuilder { public static EndpointConfiguration BuildDefaultConfig(string endpointName) { var configuration = new EndpointConfiguration(endpointName); configuration.SendFailedMessagesTo("error"); configuration.UsePersistence<InMemoryPersistence>(); configuration.UseTransport<LearningTransport>(); configuration.PurgeOnStartup(true); var recoverability = configuration.Recoverability(); recoverability.Delayed( customizations: settings => { settings.NumberOfRetries(0); }); recoverability.Immediate( customizations: settings => { settings.NumberOfRetries(0); }); return configuration; } }``` Revert "disable retries in tests"
```c# using NServiceBus; public static class ConfigBuilder { public static EndpointConfiguration BuildDefaultConfig(string endpointName) { var configuration = new EndpointConfiguration(endpointName); configuration.SendFailedMessagesTo("error"); configuration.UsePersistence<InMemoryPersistence>(); configuration.UseTransport<LearningTransport>(); configuration.PurgeOnStartup(true); return configuration; } }```
95a7fa90-467b-49dd-b0fa-3e2524a369b2
{ "language": "C#" }
```c# using System.Windows; using System.Windows.Controls; namespace Certify.UI.Controls.ManagedCertificate { public partial class TestProgress : UserControl { protected Certify.UI.ViewModel.ManagedCertificateViewModel ItemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current; protected Certify.UI.ViewModel.AppViewModel AppViewModel => UI.ViewModel.AppViewModel.Current; public TestProgress() { InitializeComponent(); DataContext = ItemViewModel; } private void TextBlock_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { // copy text to clipboard if (sender != null) { var text = (sender as TextBlock).Text; Clipboard.SetText(text); MessageBox.Show("Copied to clipboard"); } } } } ``` Fix exception on clipboard access contention
```c# using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace Certify.UI.Controls.ManagedCertificate { public partial class TestProgress : UserControl { protected Certify.UI.ViewModel.ManagedCertificateViewModel ItemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current; protected Certify.UI.ViewModel.AppViewModel AppViewModel => UI.ViewModel.AppViewModel.Current; public TestProgress() { InitializeComponent(); DataContext = ItemViewModel; } private async Task<bool> WaitForClipboard(string text) { // if running under terminal services etc the clipboard can take multiple attempts to set // https://stackoverflow.com/questions/68666/clipbrd-e-cant-open-error-when-setting-the-clipboard-from-net for (var i = 0; i < 10; i++) { try { Clipboard.SetText(text); return true; } catch { } await Task.Delay(50); } return false; } private async void TextBlock_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { // copy text to clipboard if (sender != null) { var text = (sender as TextBlock).Text; var copiedOK = await WaitForClipboard(text); if (copiedOK) { MessageBox.Show("Copied to clipboard"); } else { MessageBox.Show("Another process is preventing access to the clipboard. Please try again."); } } } } } ```
ce751b2f-fd91-4e77-b19c-e31353c565c9
{ "language": "C#" }
```c# #region License /* Copyright [2011] [Jeffrey Cameron] 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. */ #endregion using System; using System.Globalization; using gherkin; namespace PicklesDoc.Pickles { public class LanguageServices { private readonly CultureInfo currentCulture; public LanguageServices(Configuration configuration) { if (!string.IsNullOrEmpty(configuration.Language)) this.currentCulture = CultureInfo.GetCultureInfo(configuration.Language); } private java.util.List GetKeywords(string key) { return this.GetLanguage().keywords(key); } public string GetKeyword(string key) { var keywords = this.GetKeywords("background"); if (keywords != null && !keywords.isEmpty()) { return keywords.get(0).ToString(); } return null; } private I18n GetLanguage() { if (this.currentCulture == null) return new I18n("en"); return new I18n(this.currentCulture.TwoLetterISOLanguageName); } } }``` Use GherkinDialectProvider instead of I18n
```c# #region License /* Copyright [2011] [Jeffrey Cameron] 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. */ #endregion using System; using System.Globalization; using System.Linq; using Gherkin3; namespace PicklesDoc.Pickles { public class LanguageServices { private readonly CultureInfo currentCulture; private readonly GherkinDialectProvider dialectProvider; public LanguageServices(Configuration configuration) { if (!string.IsNullOrEmpty(configuration.Language)) this.currentCulture = CultureInfo.GetCultureInfo(configuration.Language); this.dialectProvider = new GherkinDialectProvider(); } private string[] GetBackgroundKeywords() { return this.GetLanguage().BackgroundKeywords; } public string GetKeyword(string key) { var keywords = this.GetBackgroundKeywords(); return keywords.FirstOrDefault(); } private GherkinDialect GetLanguage() { if (this.currentCulture == null) return this.dialectProvider.GetDialect("en", null); return this.dialectProvider.GetDialect(this.currentCulture.TwoLetterISOLanguageName, null); } } }```
9ade7e45-f712-4dfe-ac38-5cf39b863af9
{ "language": "C#" }
```c# namespace BScript.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Text; using BScript.Language; public class NewExpression : IExpression { private IExpression expression; private IList<IExpression> argexprs; public NewExpression(IExpression expression, IList<IExpression> argexprs) { this.expression = expression; this.argexprs = argexprs; } public IExpression Expression { get { return this.expression; } } public IList<IExpression> ArgumentExpressions { get { return this.argexprs; } } public object Evaluate(Context context) { var type = (Type)this.expression.Evaluate(context); IList<object> args = new List<object>(); foreach (var argexpr in this.argexprs) args.Add(argexpr.Evaluate(context)); return Activator.CreateInstance(type, args.ToArray()); } } } ``` Fix new expression with dot name
```c# namespace BScript.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Text; using BScript.Language; using BScript.Utilities; public class NewExpression : IExpression { private IExpression expression; private IList<IExpression> argexprs; public NewExpression(IExpression expression, IList<IExpression> argexprs) { this.expression = expression; this.argexprs = argexprs; } public IExpression Expression { get { return this.expression; } } public IList<IExpression> ArgumentExpressions { get { return this.argexprs; } } public object Evaluate(Context context) { Type type; if (this.expression is DotExpression) type = TypeUtilities.GetType(((DotExpression)this.expression).FullName); else type = (Type)this.expression.Evaluate(context); IList<object> args = new List<object>(); foreach (var argexpr in this.argexprs) args.Add(argexpr.Evaluate(context)); return Activator.CreateInstance(type, args.ToArray()); } } } ```
affd31c0-a194-4905-8102-67f44f2f35b9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; using NBi.Xml.Items; using System.IO; using NBi.Core.Batch; using NBi.Xml.Settings; namespace NBi.Xml.Decoration.Command { public class SqlRunXml : DecorationCommandXml, IBatchRunCommand { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("path")] public string InternalPath { get; set; } [XmlIgnore] public string FullPath { get { var fullPath = string.Empty; if (!Path.IsPathRooted(InternalPath) || string.IsNullOrEmpty(Settings.BasePath)) fullPath = InternalPath + Name; else fullPath = Settings.BasePath + InternalPath + Name; return fullPath; } } [XmlAttribute("connectionString")] public string SpecificConnectionString { get; set; } [XmlIgnore] public string ConnectionString { get { if (!String.IsNullOrWhiteSpace(SpecificConnectionString)) return SpecificConnectionString; if (Settings != null && Settings.GetDefault(SettingsXml.DefaultScope.Decoration) != null) return Settings.GetDefault(SettingsXml.DefaultScope.Decoration).ConnectionString; return string.Empty; } } public SqlRunXml() { } } } ``` Fix it also for sql-run
```c# using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; using NBi.Xml.Items; using System.IO; using NBi.Core.Batch; using NBi.Xml.Settings; namespace NBi.Xml.Decoration.Command { public class SqlRunXml : DecorationCommandXml, IBatchRunCommand { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("path")] public string InternalPath { get; set; } [XmlIgnore] public string FullPath { get { var fullPath = string.Empty; if (!Path.IsPathRooted(InternalPath) || string.IsNullOrEmpty(Settings.BasePath)) fullPath = InternalPath + Name; else fullPath = Settings.BasePath + InternalPath + Name; return fullPath; } } [XmlAttribute("connectionString")] public string SpecificConnectionString { get; set; } [XmlIgnore] public string ConnectionString { get { if (!string.IsNullOrEmpty(SpecificConnectionString) && SpecificConnectionString.StartsWith("@")) return Settings.GetReference(SpecificConnectionString.Remove(0, 1)).ConnectionString; if (!String.IsNullOrWhiteSpace(SpecificConnectionString)) return SpecificConnectionString; if (Settings != null && Settings.GetDefault(SettingsXml.DefaultScope.Decoration) != null) return Settings.GetDefault(SettingsXml.DefaultScope.Decoration).ConnectionString; return string.Empty; } } public SqlRunXml() { } } } ```
dac32345-0444-487e-8617-1349c00462f8
{ "language": "C#" }
```c# @model System.Linq.IQueryable<ForumSystem.Web.ViewModels.Answers.AnswerViewModel> @using ForumSystem.Web.ViewModels.Answers; @foreach (var answer in Model) { <div class="panel panel-success"> <div class="panel-heading"> <h3> @answer.Post.Title </h3> </div> <div class="panel-body"> <div class="panel-body"> <p>@Html.Raw(answer.Content)</p> @if (@answer.Author != null) { <p>@answer.Author.Email</p> } else { @Html.Display("Anonymous") } </div> <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Tooltip on left"> @Html.ActionLink("Delete", "Delete", "Answer", new { id = answer.Id }, null) </button> </div> </div> } ``` Update view of all answers
```c# @model System.Linq.IQueryable<ForumSystem.Web.ViewModels.Answers.AnswerViewModel> @using ForumSystem.Web.ViewModels.Answers; <div class="panel panel-success"> <div class="panel-heading"> <h3> @Html.ActionLink(Model.FirstOrDefault().Post.Title, "Display", "Questions", new { id = Model.FirstOrDefault().PostId, url = "new" }, null) </h3> </div> <div class="panel-body"> @foreach (var answer in Model) { <div class="panel-body"> <span class="glyphicon glyphicon-user" aria-hidden="true"></span> <p>@Html.Raw(answer.Content)</p> @if (@answer.Author != null) { <p>@answer.Author.Email</p> } else { @Html.Display("Anonymous") } </div> <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Tooltip on left"> @Html.ActionLink("Delete", "Delete", "Answer", new { id = answer.Id }, null) </button> } </div> </div>```
ec267cd0-16b3-4efa-a949-1a2d1cfcfe00
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps.Formats; namespace osu.Game.Skinning { public class LegacySkinDecoder : LegacyDecoder<LegacySkinConfiguration> { public LegacySkinDecoder() : base(1) { } protected override void ParseLine(LegacySkinConfiguration skin, Section section, string line) { if (section != Section.Colours) { line = StripComments(line); var pair = SplitKeyVal(line); switch (section) { case Section.General: switch (pair.Key) { case @"Name": skin.SkinInfo.Name = pair.Value; return; case @"Author": skin.SkinInfo.Creator = pair.Value; return; case @"Version": if (pair.Value == "latest" || pair.Value == "User") skin.LegacyVersion = LegacySkinConfiguration.LATEST_VERSION; else if (decimal.TryParse(pair.Value, out var version)) skin.LegacyVersion = version; return; } break; } if (!string.IsNullOrEmpty(pair.Key)) skin.ConfigDictionary[pair.Key] = pair.Value; } base.ParseLine(skin, section, line); } } } ``` Fix incorrect skin version case
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps.Formats; namespace osu.Game.Skinning { public class LegacySkinDecoder : LegacyDecoder<LegacySkinConfiguration> { public LegacySkinDecoder() : base(1) { } protected override void ParseLine(LegacySkinConfiguration skin, Section section, string line) { if (section != Section.Colours) { line = StripComments(line); var pair = SplitKeyVal(line); switch (section) { case Section.General: switch (pair.Key) { case @"Name": skin.SkinInfo.Name = pair.Value; return; case @"Author": skin.SkinInfo.Creator = pair.Value; return; case @"Version": if (pair.Value == "latest") skin.LegacyVersion = LegacySkinConfiguration.LATEST_VERSION; else if (decimal.TryParse(pair.Value, out var version)) skin.LegacyVersion = version; return; } break; } if (!string.IsNullOrEmpty(pair.Key)) skin.ConfigDictionary[pair.Key] = pair.Value; } base.ParseLine(skin, section, line); } } } ```
13afce8f-d17c-4a88-9db9-269ff9f537c0
{ "language": "C#" }
```c# using KafkaNet; using KafkaNet.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace kafka_tests.Fakes { public class FakeKafkaConnection : IKafkaConnection { private Uri _address; public Func<ProduceResponse> ProduceResponseFunction; public Func<MetadataResponse> MetadataResponseFunction; public FakeKafkaConnection(Uri address) { _address = address; } public int MetadataRequestCallCount { get; set; } public int ProduceRequestCallCount { get; set; } public Uri KafkaUri { get { return _address; } } public bool ReadPolling { get { return true; } } public Task SendAsync(byte[] payload) { throw new NotImplementedException(); } public Task<List<T>> SendAsync<T>(IKafkaRequest<T> request) { var tcs = new TaskCompletionSource<List<T>>(); if (typeof(T) == typeof(ProduceResponse)) { ProduceRequestCallCount++; tcs.SetResult(new List<T> { (T)(object)ProduceResponseFunction() }); } else if (typeof(T) == typeof(MetadataResponse)) { MetadataRequestCallCount++; tcs.SetResult(new List<T> { (T)(object)MetadataResponseFunction() }); } return tcs.Task; } public void Dispose() { } } } ``` Fix fake not replicating actual behaviour
```c# using KafkaNet; using KafkaNet.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace kafka_tests.Fakes { public class FakeKafkaConnection : IKafkaConnection { private Uri _address; public Func<ProduceResponse> ProduceResponseFunction; public Func<MetadataResponse> MetadataResponseFunction; public FakeKafkaConnection(Uri address) { _address = address; } public int MetadataRequestCallCount { get; set; } public int ProduceRequestCallCount { get; set; } public Uri KafkaUri { get { return _address; } } public bool ReadPolling { get { return true; } } public Task SendAsync(byte[] payload) { throw new NotImplementedException(); } public Task<List<T>> SendAsync<T>(IKafkaRequest<T> request) { var task = new Task<List<T>>(() => { if (typeof(T) == typeof(ProduceResponse)) { ProduceRequestCallCount++; return new List<T> { (T)(object)ProduceResponseFunction() }; } else if (typeof(T) == typeof(MetadataResponse)) { MetadataRequestCallCount++; return new List<T> { (T)(object)MetadataResponseFunction() }; } return null; }); task.Start(); return task; } public void Dispose() { } } } ```
cefdcd70-e50a-429c-8093-cf209ab9d49f
{ "language": "C#" }
```c# using System; using System.IO; using DataTool.ToolLogic.List; using Utf8Json; using Utf8Json.Resolvers; using static DataTool.Helper.IO; using static DataTool.Helper.Logger; namespace DataTool.JSON { public class JSONTool { internal void OutputJSON(object jObj, ListFlags toolFlags) { CompositeResolver.RegisterAndSetAsDefault(new IJsonFormatter[] { new ResourceGUIDFormatter() }, new[] { StandardResolver.Default }); byte[] json = JsonSerializer.NonGeneric.Serialize(jObj.GetType(), jObj); if (!string.IsNullOrWhiteSpace(toolFlags.Output)) { byte[] pretty = JsonSerializer.PrettyPrintByteArray(json); Log("Writing to {0}", toolFlags.Output); CreateDirectoryFromFile(toolFlags.Output); using (Stream file = File.OpenWrite(toolFlags.Output)) { file.SetLength(0); file.Write(pretty, 0, pretty.Length); } } else { Console.Error.WriteLine(JsonSerializer.PrettyPrint(json)); } } } } ``` Append .json to end of filename when outputting JSON
```c# using System; using System.IO; using DataTool.ToolLogic.List; using Utf8Json; using Utf8Json.Resolvers; using static DataTool.Helper.IO; using static DataTool.Helper.Logger; namespace DataTool.JSON { public class JSONTool { internal void OutputJSON(object jObj, ListFlags toolFlags) { CompositeResolver.RegisterAndSetAsDefault(new IJsonFormatter[] { new ResourceGUIDFormatter() }, new[] { StandardResolver.Default }); byte[] json = JsonSerializer.NonGeneric.Serialize(jObj.GetType(), jObj); if (!string.IsNullOrWhiteSpace(toolFlags.Output)) { byte[] pretty = JsonSerializer.PrettyPrintByteArray(json); Log("Writing to {0}", toolFlags.Output); CreateDirectoryFromFile(toolFlags.Output); var fileName = !toolFlags.Output.EndsWith(".json") ? $"{toolFlags.Output}.json" : toolFlags.Output; using (Stream file = File.OpenWrite(fileName)) { file.SetLength(0); file.Write(pretty, 0, pretty.Length); } } else { Console.Error.WriteLine(JsonSerializer.PrettyPrint(json)); } } } } ```
80f23140-d7b0-4454-93d9-ee52ed41de52
{ "language": "C#" }
```c# // Copyright 2013 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.Linq; using NUnit.Framework; namespace NodaTime.Test { /// <summary> /// Tests for DateTimeZoneProviders. /// </summary> public class DateTimeZoneProvidersTest { [Test] public void TzdbProviderUsesTzdbSource() { Assert.IsTrue(DateTimeZoneProviders.Tzdb.VersionId.StartsWith("TZDB: ")); } [Test] public void AllTzdbTimeZonesLoad() { var allZones = DateTimeZoneProviders.Tzdb.Ids.Select(id => DateTimeZoneProviders.Tzdb[id]).ToList(); // Just to stop the variable from being lonely. In reality, it's likely there'll be a breakpoint here to inspect a particular zone... Assert.IsTrue(allZones.Count > 50); } [Test] public void BclProviderUsesTimeZoneInfoSource() { Assert.IsTrue(DateTimeZoneProviders.Bcl.VersionId.StartsWith("TimeZoneInfo: ")); } } } ``` Add test for delegation in obsolete property
```c# // Copyright 2013 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.Linq; using NodaTime.Testing.TimeZones; using NodaTime.Xml; using NUnit.Framework; namespace NodaTime.Test { /// <summary> /// Tests for DateTimeZoneProviders. /// </summary> public class DateTimeZoneProvidersTest { [Test] public void TzdbProviderUsesTzdbSource() { Assert.IsTrue(DateTimeZoneProviders.Tzdb.VersionId.StartsWith("TZDB: ")); } [Test] public void AllTzdbTimeZonesLoad() { var allZones = DateTimeZoneProviders.Tzdb.Ids.Select(id => DateTimeZoneProviders.Tzdb[id]).ToList(); // Just to stop the variable from being lonely. In reality, it's likely there'll be a breakpoint here to inspect a particular zone... Assert.IsTrue(allZones.Count > 50); } [Test] public void BclProviderUsesTimeZoneInfoSource() { Assert.IsTrue(DateTimeZoneProviders.Bcl.VersionId.StartsWith("TimeZoneInfo: ")); } [Test] public void SerializationDelegatesToXmlSerializerSettings() { var original = XmlSerializationSettings.DateTimeZoneProvider; try { #pragma warning disable CS0618 // Type or member is obsolete var provider1 = new FakeDateTimeZoneSource.Builder().Build().ToProvider(); DateTimeZoneProviders.Serialization = provider1; Assert.AreSame(provider1, XmlSerializationSettings.DateTimeZoneProvider); var provider2 = new FakeDateTimeZoneSource.Builder().Build().ToProvider(); XmlSerializationSettings.DateTimeZoneProvider = provider2; Assert.AreSame(provider2, DateTimeZoneProviders.Serialization); #pragma warning restore CS0618 // Type or member is obsolete } finally { XmlSerializationSettings.DateTimeZoneProvider = original; } } } } ```
7d10fc85-2b53-4175-9649-7a7bfa643d1e
{ "language": "C#" }
```c# using System; using Newtonsoft.Json; namespace ErgastApi.Responses.Models { public class Driver { [JsonProperty("driverId")] public string DriverId { get; private set; } /// <summary> /// Drivers who participated in the 2014 season onwards have a permanent driver number. /// However, this may differ from the value of the number attribute of the Result element in earlier seasons /// or where the reigning champion has chosen to use "1" rather than his permanent driver number. /// </summary> [JsonProperty("permanentNumber")] public int? PermanentNumber { get; private set; } [JsonProperty("code")] public string Code { get; private set; } [JsonProperty("url")] public string WikiUrl { get; private set; } public string FullName => $"{FirstName} {LastName}"; [JsonProperty("givenName")] public string FirstName { get; private set; } [JsonProperty("familyName")] public string LastName { get; private set; } [JsonProperty("dateOfBirth")] public DateTime DateOfBirth { get; private set; } [JsonProperty("nationality")] public string Nationality { get; private set; } } }``` Support drivers without a date of birth
```c# using System; using Newtonsoft.Json; namespace ErgastApi.Responses.Models { public class Driver { [JsonProperty("driverId")] public string DriverId { get; private set; } /// <summary> /// Drivers who participated in the 2014 season onwards have a permanent driver number. /// However, this may differ from the value of the number attribute of the Result element in earlier seasons /// or where the reigning champion has chosen to use "1" rather than his permanent driver number. /// </summary> [JsonProperty("permanentNumber")] public int? PermanentNumber { get; private set; } [JsonProperty("code")] public string Code { get; private set; } [JsonProperty("url")] public string WikiUrl { get; private set; } public string FullName => $"{FirstName} {LastName}"; [JsonProperty("givenName")] public string FirstName { get; private set; } [JsonProperty("familyName")] public string LastName { get; private set; } [JsonProperty("dateOfBirth")] public DateTime? DateOfBirth { get; private set; } [JsonProperty("nationality")] public string Nationality { get; private set; } } }```
e8739899-f942-4188-bcb8-d40c3d14f71e
{ "language": "C#" }
```c# using System.Linq.Expressions; using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation; namespace NHibernate.Linq.ExpressionTransformers { /// <summary> /// Remove redundant casts to the same type or to superclass (upcast) in <see cref="ExpressionType.Convert"/>, <see cref=" ExpressionType.ConvertChecked"/> /// and <see cref="ExpressionType.TypeAs"/> <see cref="UnaryExpression"/>s /// </summary> public class RemoveRedundantCast : IExpressionTransformer<UnaryExpression> { private static readonly ExpressionType[] _supportedExpressionTypes = new[] { ExpressionType.TypeAs, ExpressionType.Convert, ExpressionType.ConvertChecked, }; public Expression Transform(UnaryExpression expression) { if (expression.Type != typeof(object) && expression.Type.IsAssignableFrom(expression.Operand.Type) && expression.Method != null && !expression.IsLiftedToNull) { return expression.Operand; } return expression; } public ExpressionType[] SupportedExpressionTypes { get { return _supportedExpressionTypes; } } } }``` Fix typo in last commit
```c# using System.Linq.Expressions; using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation; namespace NHibernate.Linq.ExpressionTransformers { /// <summary> /// Remove redundant casts to the same type or to superclass (upcast) in <see cref="ExpressionType.Convert"/>, <see cref=" ExpressionType.ConvertChecked"/> /// and <see cref="ExpressionType.TypeAs"/> <see cref="UnaryExpression"/>s /// </summary> public class RemoveRedundantCast : IExpressionTransformer<UnaryExpression> { private static readonly ExpressionType[] _supportedExpressionTypes = new[] { ExpressionType.TypeAs, ExpressionType.Convert, ExpressionType.ConvertChecked, }; public Expression Transform(UnaryExpression expression) { if (expression.Type != typeof(object) && expression.Type.IsAssignableFrom(expression.Operand.Type) && expression.Method == null && !expression.IsLiftedToNull) { return expression.Operand; } return expression; } public ExpressionType[] SupportedExpressionTypes { get { return _supportedExpressionTypes; } } } }```
fe2fb59b-44a8-484d-9fae-85ee3dc1e74c
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.ServiceBus; namespace Microsoft.Azure.WebJobs.Script.Description { public class EventHubBindingMetadata : BindingMetadata { [AllowNameResolution] public string Path { get; set; } public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder) { if (configBuilder == null) { throw new ArgumentNullException("configBuilder"); } EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration; string connectionString = null; if (!string.IsNullOrEmpty(Connection)) { connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection); } if (this.IsTrigger) { string eventProcessorHostName = Guid.NewGuid().ToString(); string storageConnectionString = configBuilder.Config.StorageConnectionString; var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost( eventProcessorHostName, this.Path, Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName, connectionString, storageConnectionString); eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost); } else { var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString( connectionString, this.Path); eventHubConfig.AddEventHubClient(this.Path, client); } } } } ``` Support EventHub Consumer Groups in Script
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.ServiceBus; namespace Microsoft.Azure.WebJobs.Script.Description { public class EventHubBindingMetadata : BindingMetadata { [AllowNameResolution] public string Path { get; set; } // Optional Consumer group public string ConsumerGroup { get; set; } public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder) { if (configBuilder == null) { throw new ArgumentNullException("configBuilder"); } EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration; string connectionString = null; if (!string.IsNullOrEmpty(Connection)) { connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection); } if (this.IsTrigger) { string eventProcessorHostName = Guid.NewGuid().ToString(); string storageConnectionString = configBuilder.Config.StorageConnectionString; string consumerGroup = this.ConsumerGroup; if (consumerGroup == null) { consumerGroup = Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName; } var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost( eventProcessorHostName, this.Path, consumerGroup, connectionString, storageConnectionString); eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost); } else { var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString( connectionString, this.Path); eventHubConfig.AddEventHubClient(this.Path, client); } } } } ```
9d42edd2-2b9d-43e7-b960-e88153c7757c
{ "language": "C#" }
```c# using Topshelf; namespace MiNET.Service { public class MiNetService { private MiNetServer _server; private void Start() { _server = new MiNetServer(); _server.StartServer(); } private void Stop() { _server.StopServer(); } private static void Main(string[] args) { HostFactory.Run(host => { host.Service<MiNetService>(s => { s.ConstructUsing(construct => new MiNetService()); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); }); host.RunAsLocalService(); host.SetDisplayName("MiNET Service"); host.SetDescription("MiNET MineCraft Pocket Edition server."); host.SetServiceName("MiNET"); }); } } } ``` Fix mono support on startup. Bypass TopShelf service framework.
```c# using System; using Topshelf; namespace MiNET.Service { public class MiNetService { private MiNetServer _server; private void Start() { _server = new MiNetServer(); _server.StartServer(); } private void Stop() { _server.StopServer(); } private static void Main(string[] args) { if (IsRunningOnMono()) { var service = new MiNetService(); service.Start(); Console.WriteLine("MiNET runing. Press <enter> to stop service.."); Console.ReadLine(); service.Stop(); } HostFactory.Run(host => { host.Service<MiNetService>(s => { s.ConstructUsing(construct => new MiNetService()); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); }); host.RunAsLocalService(); host.SetDisplayName("MiNET Service"); host.SetDescription("MiNET MineCraft Pocket Edition server."); host.SetServiceName("MiNET"); }); } public static bool IsRunningOnMono() { return Type.GetType("Mono.Runtime") != null; } } }```
b3a01615-89da-40c1-916e-8c1d69da9819
{ "language": "C#" }
```c# using System.Text; namespace Microsoft.Build.Logging.StructuredLogger { public class StringWriter { public static string GetString(object rootNode) { var sb = new StringBuilder(); WriteNode(rootNode, sb, 0); return sb.ToString(); } private static void WriteNode(object rootNode, StringBuilder sb, int indent = 0) { Indent(sb, indent); var text = rootNode.ToString(); // when we injest strings we normalize on \n to save space. // when the strings leave our app via clipboard, bring \r\n back so that notepad works text = text.Replace("\n", "\r\n"); sb.AppendLine(text); var treeNode = rootNode as TreeNode; if (treeNode != null && treeNode.HasChildren) { if (treeNode.HasChildren) { foreach (var child in treeNode.Children) { WriteNode(child, sb, indent + 1); } } } } private static void Indent(StringBuilder sb, int indent) { for (int i = 0; i < indent * 4; i++) { sb.Append(' '); } } } } ``` Fix NRE when copying nodes when the ToString() is null
```c# using System.Text; namespace Microsoft.Build.Logging.StructuredLogger { public class StringWriter { public static string GetString(object rootNode) { var sb = new StringBuilder(); WriteNode(rootNode, sb, 0); return sb.ToString(); } private static void WriteNode(object rootNode, StringBuilder sb, int indent = 0) { Indent(sb, indent); var text = rootNode.ToString() ?? ""; // when we injest strings we normalize on \n to save space. // when the strings leave our app via clipboard, bring \r\n back so that notepad works text = text.Replace("\n", "\r\n"); sb.AppendLine(text); var treeNode = rootNode as TreeNode; if (treeNode != null && treeNode.HasChildren) { if (treeNode.HasChildren) { foreach (var child in treeNode.Children) { WriteNode(child, sb, indent + 1); } } } } private static void Indent(StringBuilder sb, int indent) { for (int i = 0; i < indent * 4; i++) { sb.Append(' '); } } } } ```
1bf0724a-540f-4ad7-811c-88738a79a72c
{ "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 osuTK; using osuTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { /// <summary> /// A single follow point positioned between two adjacent <see cref="DrawableOsuHitObject"/>s. /// </summary> public class FollowPoint : Container, IAnimationTimeReference { private const float width = 8; public override bool RemoveWhenNotAlive => false; public FollowPoint() { Origin = Anchor.Centre; Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new CircularContainer { Masking = true, AutoSizeAxes = Axes.Both, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }, Child = new Box { Size = new Vector2(width), Blending = BlendingParameters.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, Alpha = 0.5f, } }, confineMode: ConfineMode.NoScaling); } public double AnimationStartTime { get; set; } } } ``` Remove stray default value specification
```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 osuTK; using osuTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { /// <summary> /// A single follow point positioned between two adjacent <see cref="DrawableOsuHitObject"/>s. /// </summary> public class FollowPoint : Container, IAnimationTimeReference { private const float width = 8; public override bool RemoveWhenNotAlive => false; public FollowPoint() { Origin = Anchor.Centre; Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new CircularContainer { Masking = true, AutoSizeAxes = Axes.Both, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }, Child = new Box { Size = new Vector2(width), Blending = BlendingParameters.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, Alpha = 0.5f, } }); } public double AnimationStartTime { get; set; } } } ```
37fa0aee-891a-4304-ada9-4230c6c457af
{ "language": "C#" }
```c# Hello @ViewData.Model.FirstName,<br /><br /> Thank you for signing up for Rambla! You have taken the first step towards expanding your rentability.<br /><br /> @{ string URL = Url.Action("activateaccount", "Account", new RouteValueDictionary(new { id = ViewData.Model.ActivationId }), Request.Url.Scheme.ToString(), Request.Url.Host); } Please click <a href="@URL">here</a> to activate your account.<br /><br /> Regards,<br /> Rambla Team``` Update verbiage on user registration email
```c# @{ string URL = Url.Action("activateaccount", "Account", new RouteValueDictionary(new { id = ViewData.Model.ActivationId }), Request.Url.Scheme.ToString(), Request.Url.Host); } <p>Hi @ViewData.Model.FirstName,</p> <p>Welcome to <strong>Rambla</strong>, a marketplace that facilitates sharing of items between you and your community members. We're excited to have you as a member and can't wait to see what you have to share.</p> <p>As a new member, here are a few suggestions to get you started with Rambla:</p> <ul> <li> Dig out that hammer drill that you do not need right now or that snowboard that you do not use too often and post it on <strong>Rambla</strong>. In fact, any unused item in your house can be of use to someone belonging to your community. </li> <li> Need a sleeping bag for your annual camping trip or an outdoor patio heater for your Christmas party? Search for it on <strong>Rambla</strong> There is always someone who has an item you are looking for and is willing to share it with you. </li> <li> Help your fellow community members find your stuff by using big images, writing thoughtful descriptions and addressing their queries promptly. You might just get rewarded for your exceptional conduct with a small gift from us. :-) </li> </ul> <p>To get started with your <strong>Rambla</strong> experience, please click <a href="@URL">here</a> to activate your account.</p> <p>Thanks for joining and happy sharing!</p> <p>- The Rambla Team</p>```
ba64f067-05df-4595-941d-39444392740c
{ "language": "C#" }
```c# using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Utilities; namespace DanTup.DartVS { [Export(typeof(IBraceCompletionDefaultProvider))] [ContentType(DartContentTypeDefinition.DartContentType)] [BracePair('{', '}')] class BraceCompletionProvider : IBraceCompletionDefaultProvider { } } ``` Support completion of parens and indexes too.
```c# using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Utilities; namespace DanTup.DartVS { [Export(typeof(IBraceCompletionDefaultProvider))] [ContentType(DartContentTypeDefinition.DartContentType)] [BracePair('{', '}')] [BracePair('(', ')')] [BracePair('[', ']')] class BraceCompletionProvider : IBraceCompletionDefaultProvider { } } ```
76a2b60b-fa11-4d66-80c6-6a9e7c5cc605
{ "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 System; using osu.Game.Graphics; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModSuddenDeath : Mod, IApplicableToScoreProcessor { public override string Name => "Sudden Death"; public override string ShortenedName => "SD"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_suddendeath; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Miss a note and fail."; public override double ScoreMultiplier => 1; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) }; public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { scoreProcessor.FailConditions += FailCondition; } protected virtual bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Combo.Value != scoreProcessor.HighestCombo.Value; } } ``` Fix SD not failing for the first note
```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 System; using osu.Game.Graphics; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModSuddenDeath : Mod, IApplicableToScoreProcessor { public override string Name => "Sudden Death"; public override string ShortenedName => "SD"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_suddendeath; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Miss a note and fail."; public override double ScoreMultiplier => 1; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) }; public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { scoreProcessor.FailConditions += FailCondition; } protected virtual bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Combo.Value == 0; } } ```
a4b22ebe-2f1e-4814-9540-771b32d3b837
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace LessMsi.Cli { internal class ShowHelpCommand : LessMsiCommand { public override void Run(List<string> args) { ShowHelp(""); } public static void ShowHelp(string errorMessage) { string helpString = @"Usage: lessmsi <command> [options] <msi_name> [<path_to_extract\>] [file_names] Commands: x Extracts all or specified files from the specified msi_name. l Lists the contents of the specified msi table as CSV to stdout. v Lists the value of the ProductVersion Property in the msi (typically this is the version of the MSI). o Opens the specified msi_name in the GUI. h Shows this help page. For more information see http://lessmsi.activescott.com "; if (!string.IsNullOrEmpty(errorMessage)) { helpString = "\r\nError: " + errorMessage + "\r\n\r\n" + helpString; } Console.WriteLine(helpString); } } }``` Add help for -t switch
```c# using System; using System.Collections.Generic; namespace LessMsi.Cli { internal class ShowHelpCommand : LessMsiCommand { public override void Run(List<string> args) { ShowHelp(""); } public static void ShowHelp(string errorMessage) { string helpString = @"Usage: lessmsi <command> [options] <msi_name> [<path_to_extract\>] [file_names] Commands: x Extracts all or specified files from the specified msi_name. l Lists the contents of the specified msi table as CSV to stdout. Table is specified with -t switch. Example: lessmsi l -t Component c:\foo.msi v Lists the value of the ProductVersion Property in the msi (typically this is the version of the MSI). o Opens the specified msi_name in the GUI. h Shows this help page. For more information see http://lessmsi.activescott.com "; if (!string.IsNullOrEmpty(errorMessage)) { helpString = "\r\nError: " + errorMessage + "\r\n\r\n" + helpString; } Console.WriteLine(helpString); } } }```
87fe17f0-98f7-44b6-af42-9ddd58718ef2
{ "language": "C#" }
```c# using CefSharp; namespace TweetDck.Core.Handling{ class ContextMenuNotification : ContextMenuBase{ public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){ model.Clear(); base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model); RemoveSeparatorIfLast(model); } public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags){ return false; } } } ``` Fix context menu not running any actions in notification Form
```c# using CefSharp; namespace TweetDck.Core.Handling{ class ContextMenuNotification : ContextMenuBase{ public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){ model.Clear(); base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model); RemoveSeparatorIfLast(model); } } } ```
7739c317-264b-4611-9f63-da2de3e99ff7
{ "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("MonoGameUtils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonoGameUtils")] [assembly: AssemblyCopyright("")] [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("4ecedc75-1f2d-4915-9efe-368a5d104e41")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.4.0")] [assembly: AssemblyFileVersion("1.0.4.0")]``` Increment version number for new build.
```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("MonoGameUtils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonoGameUtils")] [assembly: AssemblyCopyright("")] [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("4ecedc75-1f2d-4915-9efe-368a5d104e41")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.5.0")] [assembly: AssemblyFileVersion("1.0.5.0")]```
ab36a2f8-83fe-4914-89f7-e66d4a6855e5
{ "language": "C#" }
```c# using UnityEngine; namespace Pear.InteractionEngine.Interactions { /// <summary> /// Copies interactions from the current object to the supplied objects /// </summary> public class CopyInteractions: MonoBehaviour { [Tooltip("Objects that interactions will be copied to")] public GameObject[] CopyTo; private void Awake() { if (CopyTo != null) { //Copy alkl interactions from the current object to the specified object foreach (GameObject copyTo in CopyTo) Interaction.CopyAll(gameObject, copyTo); } } } } ``` Copy interactions from the given object
```c# using UnityEngine; namespace Pear.InteractionEngine.Interactions { /// <summary> /// Copies interactions from the current object to the supplied objects /// </summary> public class CopyInteractions: MonoBehaviour { [Tooltip("Objects that interactions will be copied to")] public GameObject[] CopyTo; [Tooltip("Objects that the interactions will be copied from")] public GameObject[] CopyFrom; private void Awake() { if (CopyTo != null) { // Copy all interactions from the current object to the specified object foreach (GameObject copyTo in CopyTo) Interaction.CopyAll(gameObject, copyTo); } if(CopyFrom != null) { // Copy all interactions from the specified objects to this game object foreach (GameObject copyFrom in CopyFrom) Interaction.CopyAll(copyFrom, gameObject); } } } } ```
c2da94b5-dbbf-4e4d-a0a6-c269320339df
{ "language": "C#" }
```c# @model WebEditor.Models.Create @{ ViewBag.Title = "New Game"; } @section scripts { <script src="@Url.Content("~/Scripts/GameNew.js")" type="text/javascript"></script> } @using (Html.BeginForm()) { @Html.ValidationSummary(true, "Unable to create game. Please correct the errors below.") <div> <div class="editor-label"> @Html.LabelFor(m => m.GameName) </div> <div class="editor-field"> @Html.TextBoxFor(m => m.GameName, new { style = "width: 300px" }) @Html.ValidationMessageFor(m => m.GameName) </div> <div class="editor-label"> @Html.LabelFor(m => m.SelectedType) </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedType, new SelectList(Model.AllTypes, Model.SelectedType)) @Html.ValidationMessageFor(m => m.SelectedType) </div> <div class="editor-label"> @Html.LabelFor(m => m.SelectedTemplate) </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedTemplate, new SelectList(Model.AllTemplates, Model.SelectedTemplate)) @Html.ValidationMessageFor(m => m.SelectedTemplate) </div> <p> <button id="submit-button" type="submit">Create</button> </p> </div> }``` Hide game type for now
```c# @model WebEditor.Models.Create @{ ViewBag.Title = "New Game"; } @section scripts { <script src="@Url.Content("~/Scripts/GameNew.js")" type="text/javascript"></script> } @using (Html.BeginForm()) { @Html.ValidationSummary(true, "Unable to create game. Please correct the errors below.") <div> <div class="editor-label"> @Html.LabelFor(m => m.GameName): </div> <div class="editor-field"> @Html.TextBoxFor(m => m.GameName, new { style = "width: 300px" }) @Html.ValidationMessageFor(m => m.GameName) </div> <div style="display: none"> <div class="editor-label"> @Html.LabelFor(m => m.SelectedType): </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedType, new SelectList(Model.AllTypes, Model.SelectedType)) @Html.ValidationMessageFor(m => m.SelectedType) </div> </div> <div class="editor-label"> @Html.LabelFor(m => m.SelectedTemplate): </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedTemplate, new SelectList(Model.AllTemplates, Model.SelectedTemplate)) @Html.ValidationMessageFor(m => m.SelectedTemplate) </div> <p> <button id="submit-button" type="submit">Create</button> </p> </div> }```
3ab4c1a0-fb45-4a2e-aaaf-137e6ac090ce
{ "language": "C#" }
```c# using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private PhoneNumber _phoneNumber; private Email _email; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, PhoneNumber phoneNumber, Email email) { _name = name; _age = age; _organization = organization; _phoneNumber = phoneNumber; _email = email; } #endregion } }``` Allow for multiple phone numbers and email addresses
```c# using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } } ```
b0c72201-81e0-4539-bc9d-379a4bab6fed
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace Leeroy { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service() }; ServiceBase.Run(ServicesToRun); } } } ``` Allow debugging without running as a service.
```c# using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; namespace Leeroy { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { if (args.FirstOrDefault() == "/test") { Overseer overseer = new Overseer(new CancellationTokenSource().Token, "BradleyGrainger", "Configuration", "master"); overseer.Run(null); } else { ServiceBase.Run(new ServiceBase[] { new Service() }); } } } } ```
1ea11353-0879-4239-8d95-757fe54689b7
{ "language": "C#" }
```c# Order: 10 Description: Tutorials to get you up and running quickly RedirectFrom: - docs/overview - docs/overview/features --- @Html.Partial("_ChildPages")``` Add link to resources to Getting Started guide
```c# Order: 10 Description: Tutorials to get you up and running quickly RedirectFrom: - docs/overview - docs/overview/features --- <div class="alert alert-info"> <p> See also <a href="/community/resources/">Community Resources</a> for a lot of helpful courses, videos, presentations and blog posts which can help you get started with Cake. </p> </div> @Html.Partial("_ChildPages")```
383450f4-a8f7-453d-9585-3b3fede93429
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TextMatch")] [assembly: AssemblyDescription("A library for matching texts with Lucene query expressions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TextMatch")] [assembly: AssemblyCopyright("Copyright © 2015 Cris Almodovar")] [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("2fe43f0a-b8c0-4de3-b2d5-6fc207385f7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.0.0")] ``` Change version number to 0.6.5
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TextMatch")] [assembly: AssemblyDescription("A library for matching texts with Lucene query expressions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TextMatch")] [assembly: AssemblyCopyright("Copyright © 2015 Cris Almodovar")] [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("2fe43f0a-b8c0-4de3-b2d5-6fc207385f7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.6.5.0")] [assembly: AssemblyFileVersion("0.6.5.0")] ```
c8f2cbf2-1329-4160-b172-086a89a0c171
{ "language": "C#" }
```c# /* Copyright 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using JetBrains.Annotations; namespace AudioWorks.Commands.Tests { [UsedImplicitly] public sealed class ModuleFixture : IDisposable { const string _moduleProject = "AudioWorks.Commands"; [NotNull] internal Runspace Runspace { get; } public ModuleFixture() { var state = InitialSessionState.CreateDefault(); // This bypasses the execution policy (InitialSessionState.ExecutionPolicy isn't available with PowerShell 5) state.AuthorizationManager = new AuthorizationManager("Microsoft.PowerShell"); state.ImportPSModule( Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).FullName, _moduleProject)); Runspace = RunspaceFactory.CreateRunspace(state); Runspace.Open(); } public void Dispose() { Runspace.Close(); } } }``` Revert change that broke tests on Windows PowerShell.
```c# /* Copyright 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using JetBrains.Annotations; namespace AudioWorks.Commands.Tests { [UsedImplicitly] public sealed class ModuleFixture : IDisposable { const string _moduleProject = "AudioWorks.Commands"; [NotNull] internal Runspace Runspace { get; } public ModuleFixture() { var state = InitialSessionState.CreateDefault(); // This bypasses the execution policy (InitialSessionState.ExecutionPolicy isn't available with PowerShell 5) state.AuthorizationManager = new AuthorizationManager("Microsoft.PowerShell"); state.ImportPSModule(new[] { Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).FullName, _moduleProject) }); Runspace = RunspaceFactory.CreateRunspace(state); Runspace.Open(); } public void Dispose() { Runspace.Close(); } } }```
690d7578-7a69-458f-b4ff-f0b69b9a37fd
{ "language": "C#" }
```c# using Xunit.Abstractions; namespace Cascara.Tests { public abstract class CascaraTestFramework { public CascaraTestFramework(ITestOutputHelper output) { Output = output; } protected ITestOutputHelper Output { get; } } } ``` Add static methods for building XML data strings
```c# using System; using System.Xml.Linq; using Xunit.Abstractions; namespace Cascara.Tests { public abstract class CascaraTestFramework { protected static string BuildXmlElement(string name, params Tuple<string, string>[] attrs) { return BuildXmlElement(name, "", attrs); } protected static string BuildXmlElement(string name, string innerData, params Tuple<string, string>[] attrs) { string attrString = ""; foreach (Tuple<string, string> t in attrs) { attrString += string.Format(" {0}='{1}'", t.Item1, t.Item2); } return string.Format("<{0}{1}>{2}</{0}>", name, attrString, innerData); } protected static XElement ParseXmlElement(string data) { XDocument doc = XDocument.Parse(data, LoadOptions.SetLineInfo); return doc.Root; } public CascaraTestFramework(ITestOutputHelper output) { Output = output; } protected ITestOutputHelper Output { get; } } } ```
cd4d873c-842e-46ef-9ad4-35a11be9d274
{ "language": "C#" }
```c# using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Intro Settings")] public class IntroData { [DisplayName("Duration")] public int Duration { get; set; } = -1; [DisplayName("Reversable")] public bool Reversable { get; set; } = false; [DisplayName("Activate")] public bool Activate { get; set; } = false; [DisplayName("Stay Open")] public bool HideOnFinish { get; set; } = true; [DisplayName("Execute Finish Action")] public bool ExecuteFinishAction { get; set; } = true; } }``` Fix intro settings "Hide On Finish" option name
```c# using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Intro Settings")] public class IntroData { [DisplayName("Duration")] public int Duration { get; set; } = -1; [DisplayName("Reversable")] public bool Reversable { get; set; } = false; [DisplayName("Activate")] public bool Activate { get; set; } = false; [DisplayName("Hide On Finish")] public bool HideOnFinish { get; set; } = true; [DisplayName("Execute Finish Action")] public bool ExecuteFinishAction { get; set; } = true; } }```
4c67aed8-8bac-42c9-8ca1-8d1f6f67e57e
{ "language": "C#" }
```c# using IO = System.IO; namespace dokas.EncodingConverter.Logic { internal sealed class FileData { public string Path { get; private set; } public string Name { get; private set; } public string Extension { get; private set; } public FileData(string path) { Path = path; Name = IO.Path.GetFileName(path); Extension = IO.Path.GetExtension(path); } } } ``` Implement Equals/GetHashCode to comply with Distinct
```c# using System; using IO = System.IO; namespace dokas.EncodingConverter.Logic { internal sealed class FileData { public string Path { get; private set; } public string Name { get; private set; } public string Extension { get; private set; } public FileData(string path) { if (path == null) { throw new ArgumentNullException("path"); } Path = path; Name = IO.Path.GetFileName(path); Extension = IO.Path.GetExtension(path); } public override bool Equals(object obj) { var otherFileData = obj as FileData; return otherFileData != null && Path.Equals(otherFileData.Path); } public override int GetHashCode() { return Path.GetHashCode(); } } } ```
27df204d-4018-4af9-a6ee-a62f2f181970
{ "language": "C#" }
```c# @model Kooboo.CMS.Sites.ABTest.ABPageSetting @using Kooboo.CMS.Sites.ABTest; @{ ViewBag.Title = "Edit A/B page setting"; Layout = "~/Views/Shared/Blank.cshtml"; } @section Panel{ <ul class="panel"> <li> <a data-ajaxform=""> @Html.IconImage("save") @("Save".Localize())</a> </li> <li> <a href="@ViewContext.RequestContext.GetRequestValue("return")"> @Html.IconImage("cancel") @("Back".Localize())</a> </li> </ul> } <div class="block common-form"> <h1 class="title">@ViewBag.Title</h1> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <table> <tbody> @Html.DisplayFor(o => o.RuleName) @Html.HiddenFor(o => o.RuleName) @Html.DisplayFor(o => o.MainPage) @Html.EditorFor(o => o.Items) @Html.EditorFor(o => o.ABTestGoalPage, new { HtmlAttributes = new { @class = "medium" } }) </tbody> </table> } </div> ``` Make available to change the rule when editing A/B page setting.
```c# @model Kooboo.CMS.Sites.ABTest.ABPageSetting @using Kooboo.CMS.Sites.ABTest; @{ ViewBag.Title = "Edit A/B page setting"; Layout = "~/Views/Shared/Blank.cshtml"; } @section Panel{ <ul class="panel"> <li> <a data-ajaxform=""> @Html.IconImage("save") @("Save".Localize())</a> </li> <li> <a href="@ViewContext.RequestContext.GetRequestValue("return")"> @Html.IconImage("cancel") @("Back".Localize())</a> </li> </ul> } <div class="block common-form"> <h1 class="title">@ViewBag.Title</h1> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <table> <tbody> @Html.EditorFor(o => o.RuleName) @Html.DisplayFor(o => o.MainPage) @Html.EditorFor(o => o.Items) @Html.EditorFor(o => o.ABTestGoalPage, new { HtmlAttributes = new { @class = "medium" } }) </tbody> </table> } </div> ```
9b4ed07d-6657-4cfa-a137-fe0c252657c3
{ "language": "C#" }
```c# #region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // 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. // #endregion -- License Terms -- using System; namespace MsgPack.Rpc { internal sealed class ExceptionModifiers { public static readonly ExceptionModifiers IsMatrioshkaInner = new ExceptionModifiers(); private ExceptionModifiers() { } } } ``` Fix that the flag prevents serialization.
```c# #region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // 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. // #endregion -- License Terms -- using System; namespace MsgPack.Rpc { internal static class ExceptionModifiers { public static readonly object IsMatrioshkaInner = String.Intern( typeof( ExceptionModifiers ).FullName + ".IsMatrioshkaInner" ); } } ```
c2836452-f548-4e7e-af83-20204e07eb69
{ "language": "C#" }
```c# #region Copyright © 2014 Ricardo Amaral /* * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. */ #endregion using CefSharp; namespace SlackUI { internal class BrowserRequestHandler : IRequestHandler { #region Public Methods public bool GetAuthCredentials(IWebBrowser browser, bool isProxy, string host, int port, string realm, string scheme, ref string username, ref string password) { // Let the Chromium web browser handle the event return false; } public ResourceHandler GetResourceHandler(IWebBrowser browser, IRequest request) { // Let the Chromium web browser handle the event return null; } public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, bool isRedirect) { // Disable browser forward/back navigation with keyboard keys if(request.TransitionType == (TransitionType.Explicit | TransitionType.ForwardBack)) { return true; } // Let the Chromium web browser handle the event return false; } public bool OnBeforePluginLoad(IWebBrowser browser, string url, string policyUrl, IWebPluginInfo info) { // Let the Chromium web browser handle the event return false; } public bool OnBeforeResourceLoad(IWebBrowser browser, IRequest request, IResponse response) { // Let the Chromium web browser handle the event return false; } public void OnPluginCrashed(IWebBrowser browser, string pluginPath) { // No implementation required } public void OnRenderProcessTerminated(IWebBrowser browser, CefTerminationStatus status) { // No implementation required } #endregion } } ``` Cover ALL forward/back navigation cases
```c# #region Copyright © 2014 Ricardo Amaral /* * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. */ #endregion using CefSharp; namespace SlackUI { internal class BrowserRequestHandler : IRequestHandler { #region Public Methods public bool GetAuthCredentials(IWebBrowser browser, bool isProxy, string host, int port, string realm, string scheme, ref string username, ref string password) { // Let the Chromium web browser handle the event return false; } public ResourceHandler GetResourceHandler(IWebBrowser browser, IRequest request) { // Let the Chromium web browser handle the event return null; } public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, bool isRedirect) { // Disable browser forward/back navigation with keyboard keys if((request.TransitionType & TransitionType.ForwardBack) != 0) { return true; } // Let the Chromium web browser handle the event return false; } public bool OnBeforePluginLoad(IWebBrowser browser, string url, string policyUrl, IWebPluginInfo info) { // Let the Chromium web browser handle the event return false; } public bool OnBeforeResourceLoad(IWebBrowser browser, IRequest request, IResponse response) { // Let the Chromium web browser handle the event return false; } public void OnPluginCrashed(IWebBrowser browser, string pluginPath) { // No implementation required } public void OnRenderProcessTerminated(IWebBrowser browser, CefTerminationStatus status) { // No implementation required } #endregion } } ```
5c59d622-65df-441a-ad0b-83540a2cbdf8
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private DateTime _dateOfBirth; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name? name, DateTime dateOfBirth, Organization? organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _dateOfBirth = dateOfBirth; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } } ``` Rename Email struct as EmailAddress; refactor as appropriate
```c# using System; using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct EmailAddress { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private DateTime _dateOfBirth; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<EmailAddress> _emailAddresses; #endregion #region Constructors public Patient(Name? name, DateTime dateOfBirth, Organization? organization, List<PhoneNumber> phoneNumbers, List<EmailAddress> emailAddresses) { _name = name; _dateOfBirth = dateOfBirth; _organization = organization; _phoneNumbers = phoneNumbers; _emailAddresses = emailAddresses; } #endregion } } ```
83c8ef04-961b-4904-aa31-67f07d468e9d
{ "language": "C#" }
```c# using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("StripeTests")] ``` Make internals visible to Newtonsoft.Json
```c# using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Newtonsoft.Json")] [assembly: InternalsVisibleTo("StripeTests")] ```
3b81ace2-01d3-4008-9295-25921c49c6d8
{ "language": "C#" }
```c# using Dolstagis.Web; using Dolstagis.Web.Sessions; namespace WebApp { public class HomeModule : Module { public HomeModule() { Services.For<ISessionStore>().Singleton().Use<InMemorySessionStore>(); AddStaticFiles("~/content"); AddViews("~/views"); AddViews("~/errors"); AddHandler<Index>(); } } }``` Use default error messages in demo app.
```c# using Dolstagis.Web; using Dolstagis.Web.Sessions; namespace WebApp { public class HomeModule : Module { public HomeModule() { Services.For<ISessionStore>().Singleton().Use<InMemorySessionStore>(); AddStaticFiles("~/content"); AddViews("~/views"); // Uncomment the following line to use custom error messages. // AddViews("~/errors"); AddHandler<Index>(); } } }```
b51fd9a7-e58e-4f70-a2cc-bc043bd3af32
{ "language": "C#" }
```c# using System; using System.Linq.Expressions; using Xunit; namespace DelegateDecompiler.Tests { public class EnumTests : DecompilerTestsBase { public enum TestEnum { Foo, Bar } [Fact] public void TestEnumParameterEqualsEnumConstant() { Expression<Func<TestEnum, bool>> expected = x => x == TestEnum.Bar; Func<TestEnum, bool> compiled = x => x == TestEnum.Bar; Test(expected, compiled); } [Fact] public void TestEnumConstantEqualsEnumParameter() { Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar == x; Func<TestEnum, bool> compiled = x => TestEnum.Bar == x; Test(expected, compiled); } } }``` Add more tests for enums
```c# using System; using System.Linq.Expressions; using Xunit; namespace DelegateDecompiler.Tests { public class EnumTests : DecompilerTestsBase { public enum TestEnum { Foo, Bar } [Fact] public void TestEnumParameterEqualsEnumConstant() { Expression<Func<TestEnum, bool>> expected = x => x == TestEnum.Bar; Func<TestEnum, bool> compiled = x => x == TestEnum.Bar; Test(expected, compiled); } [Fact] public void TestEnumConstantEqualsEnumParameter() { Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar == x; Func<TestEnum, bool> compiled = x => TestEnum.Bar == x; Test(expected, compiled); } [Fact] public void TestEnumParametersEqual() { Expression<Func<TestEnum, TestEnum, bool>> expected = (x, y) => x == y; Func<TestEnum, TestEnum, bool> compiled = (x, y) => x == y; Test(expected, compiled); } [Fact(Skip = "Needs optimization")] public void TestEnumParameterNotEqualsEnumConstant() { Expression<Func<TestEnum, bool>> expected = x => x != TestEnum.Bar; Func<TestEnum, bool> compiled = x => x != TestEnum.Bar; Test(expected, compiled); } [Fact(Skip = "Needs optimization")] public void TestEnumConstantNotEqualsEnumParameter() { Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar != x; Func<TestEnum, bool> compiled = x => TestEnum.Bar != x; Test(expected, compiled); } [Fact(Skip = "Needs optimization")] public void TestEnumParametersNotEqual() { Expression<Func<TestEnum, TestEnum, bool>> expected = (x, y) => x != y; Func<TestEnum, TestEnum, bool> compiled = (x, y) => x != y; Test(expected, compiled); } } } ```
0702bd9e-2576-479a-bc05-1b756a9b67b8
{ "language": "C#" }
```c# using Ardalis.GuardClauses; using System; using Xunit; namespace GuardClauses.UnitTests { public class GuardAgainsOutOfRange { [Fact] public void DoesNothingGivenInRangeValueUsingShortcutMethod() { Guard.AgainsOutOfRange(2, "index", 1, 5); } [Fact] public void DoesNothingGivenInRangeValueUsingExtensionMethod() { Guard.Against.OutOfRange(2, "index", 1, 5); } [Fact] public void ThrowsGivenOutOfRangeValueUsingShortcutMethod() { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(5, "index", 1, 4)); } [Fact] public void ThrowsGivenOutOfRangeValueUsingExtensionMethod() { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(5, "index", 1, 4)); } } }``` Improve tests with theory test cases
```c# using Ardalis.GuardClauses; using System; using Xunit; namespace GuardClauses.UnitTests { public class GuardAgainsOutOfRange { [Theory] [InlineData(1, 1, 5)] [InlineData(2, 1, 5)] [InlineData(3, 1, 5)] public void DoesNothingGivenInRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo) { Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo); } [Theory] [InlineData(1, 1, 5)] [InlineData(2, 1, 5)] [InlineData(3, 1, 5)] public void DoesNothingGivenInRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo) { Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo); } [Theory] [InlineData(-1, 1, 5)] [InlineData(0, 1, 5)] [InlineData(6, 1, 5)] public void ThrowsGivenOutOfRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo) { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo)); } [Theory] [InlineData(-1, 1, 5)] [InlineData(0, 1, 5)] [InlineData(6, 1, 5)] public void ThrowsGivenOutOfRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo) { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo)); } } }```
3f366ecc-d7c0-47e4-985d-aec2f54c0f15
{ "language": "C#" }
```c# namespace Nancy.Owin.Tests { using System; using global::Owin; using Microsoft.Owin.Testing; using Nancy.Testing; using Xunit; public class AppBuilderExtensionsFixture { /*[Fact] public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests() { // Given var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>()); using(var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper))) { // When var response = server.HttpClient.GetAsync(new Uri("http://localhost/")).Result; // Then Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK); } }*/ public class TestModule : NancyModule { public TestModule() { Get["/"] = _ => HttpStatusCode.OK; } } } }``` Exclude AppBuilder test from running on Mono.
```c# namespace Nancy.Owin.Tests { using System; using global::Owin; using Microsoft.Owin.Testing; using Nancy.Testing; using Xunit; public class AppBuilderExtensionsFixture { #if !__MonoCS__ [Fact] public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests() { // Given var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>()); using(var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper))) { // When var response = server.HttpClient.GetAsync(new Uri("http://localhost/")).Result; // Then Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK); } } #endif public class TestModule : NancyModule { public TestModule() { Get["/"] = _ => HttpStatusCode.OK; } } } }```
b3efab15-9abd-4a3f-a347-be765d14158b
{ "language": "C#" }
```c# using System; using System.Configuration; namespace librato4net { public class AppSettingsLibratoSettings : ILibratoSettings { // ReSharper disable once InconsistentNaming private static readonly AppSettingsLibratoSettings settings = new AppSettingsLibratoSettings(); private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/"; public static AppSettingsLibratoSettings Settings { get { return settings; } } public string Username { get { return ConfigurationManager.AppSettings["Librato.Username"]; } } public string ApiKey { get { return ConfigurationManager.AppSettings["Librato.ApiKey"]; } } public Uri ApiEndpoint { get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); } } public TimeSpan SendInterval { get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); } } } }``` Validate Username and ApiKey from appSettings.
```c# using System; using System.Configuration; namespace librato4net { public class AppSettingsLibratoSettings : ILibratoSettings { // ReSharper disable once InconsistentNaming private static readonly AppSettingsLibratoSettings settings = new AppSettingsLibratoSettings(); private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/"; public static AppSettingsLibratoSettings Settings { get { return settings; } } public string Username { get { var username = ConfigurationManager.AppSettings["Librato.Username"]; if (string.IsNullOrEmpty(username)) { throw new ConfigurationErrorsException("Librato.Username is required and cannot be empty"); } return username; } } public string ApiKey { get { var apiKey = ConfigurationManager.AppSettings["Librato.ApiKey"]; if (string.IsNullOrEmpty(apiKey)) { throw new ConfigurationErrorsException("Librato.ApiKey is required and cannot be empty"); } return apiKey; } } public Uri ApiEndpoint { get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); } } public TimeSpan SendInterval { get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); } } } }```
8a584c3a-638e-4bed-a7b3-72c4543be5ae
{ "language": "C#" }
```c# using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return Width / Height; } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }``` Fix issue where ratio was always returning "1"
```c# using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height); } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }```
9a74eae8-127f-48e0-8619-5cc2b939c99c
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Diagnostics { /// <summary>Provides a set of static methods for working with Exceptions.</summary> internal static class ExceptionHelpers { public static TException InitializeStackTrace<TException>(this TException e) where TException : Exception { Debug.Assert(e != null); Debug.Assert(e.StackTrace == null); try { throw e; } catch { return e; } } } } ``` Change InitializeStackTrace helper to store trace in Data
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Diagnostics { /// <summary>Provides a set of static methods for working with Exceptions.</summary> internal static class ExceptionHelpers { public static TException InitializeStackTrace<TException>(this TException e) where TException : Exception { Debug.Assert(e != null); // Ideally we'd be able to populate e.StackTrace with the current stack trace. // We could throw the exception and catch it, but the populated StackTrace would // not extend beyond this frame. Instead, we grab a stack trace and store it into // the exception's data dictionary, at least making the info available for debugging, // albeit not part of the string returned by e.ToString() or e.StackTrace. e.Data["StackTrace"] = Environment.StackTrace; return e; } } } ```
c8991320-37fd-4355-b895-b777948cc9ac
{ "language": "C#" }
```c# using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Logs() { byte[] data; using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd()); } return File(data, "text/plain"); } } }``` Fix imports on admin logs
```c# using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.IO; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Logs() { byte[] data; using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd()); } return File(data, "text/plain"); } } }```
c7e4b786-94f7-4a27-bd7c-846f4bcbd1c6
{ "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 System.Collections.Generic; namespace osu.Game.Audio { public class SampleInfoList : List<SampleInfo> { public SampleInfoList() { } public SampleInfoList(IEnumerable<SampleInfo> elements) { AddRange(elements); } } }``` Use CRLF instead of LF.
```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 System.Collections.Generic; namespace osu.Game.Audio { public class SampleInfoList : List<SampleInfo> { public SampleInfoList() { } public SampleInfoList(IEnumerable<SampleInfo> elements) { AddRange(elements); } } }```
8f298739-510d-4340-92cc-06440306c86e
{ "language": "C#" }
```c# @model Portal.CMS.Web.Areas.Builder.ViewModels.Build.CustomViewModel @{ ViewBag.Title = "Error"; Layout = ""; } <!DOCTYPE html> <html lang="en-gb"> <head> <title>Portal CMS: @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Framework") <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script> <script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script> @RenderSection("HEADScripts", false) </head> <body> <nav class="navbar navbar-inverse"><div class="container-fluid"><div class="navbar-header"><a class="navbar-brand" href="@Url.Action("Index", "Home", new { area = "" })">Portal CMS</a></div></div></nav> @RenderBody() @RenderSection("DOMScripts", false) @Scripts.Render("~/Resources/JavaScript/Bootstrap") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Modal") @Scripts.Render("~/Resources/JavaScript/Framework/Global") </body> </html>``` Update Error Layout to Standardise Against Standard Layout
```c# @model Portal.CMS.Web.Areas.Builder.ViewModels.Build.CustomViewModel @{ ViewBag.Title = "Error"; Layout = ""; } <!DOCTYPE html> <html lang="en-gb"> <head> <title>Portal CMS: @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Framework") @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body class="page-builder"> <nav class="navbar navbar-inverse"><div class="container-fluid"><div class="navbar-header"><a class="navbar-brand" href="@Url.Action("Index", "Home", new { area = "" })">Portal CMS</a></div></div></nav> @Html.Partial("_NavBar") @RenderBody() @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>```
42dfed95-ac08-4c87-a677-0cb9eb3b5193
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class BackToMenu : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.Escape)){ Application.LoadLevel(0); GameObject GUI; GUI = GameObject.Find("GUISYSTEM"); Destroy(GUI); } } } ``` Destroy NetworkController when going back to menu
```c# using UnityEngine; using System.Collections; public class BackToMenu : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.Escape)){ Application.LoadLevel(0); GameObject guiSys; guiSys = GameObject.Find("GUISYSTEM"); Destroy(guiSys); GameObject networkC; networkC = GameObject.Find("NetworkController"); Destroy(networkC); } } } ```
c4445fe2-1a1a-4bd3-bc5d-4ebe7e42048b
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Commands { public class MSBuildTest { public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath); private string DotNetHostPath { get; } public MSBuildTest(string dotNetHostPath) { DotNetHostPath = dotNetHostPath; } public ICommand CreateCommandForTarget(string target, params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"/t:{target}"); return CreateCommand(newArgs.ToArray()); } private ICommand CreateCommand(params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"msbuild"); ICommand command = Command.Create(DotNetHostPath, newArgs); // Set NUGET_PACKAGES environment variable to match value from build.ps1 command = command.EnvironmentVariable("NUGET_PACKAGES", RepoInfo.PackagesPath); return command; } } }``` Fix NUGET_PACKAGES folder when running tests.
```c# // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Commands { public class MSBuildTest { public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath); private string DotNetHostPath { get; } public MSBuildTest(string dotNetHostPath) { DotNetHostPath = dotNetHostPath; } public ICommand CreateCommandForTarget(string target, params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"/t:{target}"); return CreateCommand(newArgs.ToArray()); } private ICommand CreateCommand(params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"msbuild"); ICommand command = Command.Create(DotNetHostPath, newArgs); // Set NUGET_PACKAGES environment variable to match value from build.ps1 command = command.EnvironmentVariable("NUGET_PACKAGES", Path.Combine(RepoInfo.RepoRoot, "packages")); return command; } } }```
3745c43f-5fed-4c8b-81ea-a0d83be38718
{ "language": "C#" }
```c# using System; using System.Threading; namespace GitHub.Unity { class GitCommitTask : ProcessTask<string> { private const string TaskName = "git commit"; private readonly string arguments; public GitCommitTask(string message, string body, CancellationToken token, IOutputProcessor<string> processor = null) : base(token, processor ?? new SimpleOutputProcessor()) { Guard.ArgumentNotNullOrWhiteSpace(message, "message"); Name = TaskName; arguments = "commit "; arguments += String.Format(" -m \"{0}", message); if (!String.IsNullOrEmpty(body)) arguments += String.Format("{0}{1}", Environment.NewLine, body); arguments += "\""; } public override string ProcessArguments { get { return arguments; } } public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } } } } ``` Split the commit message into the subject line and the body
```c# using System; using System.Threading; namespace GitHub.Unity { class GitCommitTask : ProcessTask<string> { private const string TaskName = "git commit"; private readonly string arguments; public GitCommitTask(string message, string body, CancellationToken token, IOutputProcessor<string> processor = null) : base(token, processor ?? new SimpleOutputProcessor()) { Guard.ArgumentNotNullOrWhiteSpace(message, "message"); Name = TaskName; arguments = "commit "; arguments += String.Format(" -m \"{0}\"", message); if (!String.IsNullOrEmpty(body)) arguments += String.Format(" -m \"{0}\"", body); } public override string ProcessArguments { get { return arguments; } } public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } } } } ```
62f01104-6c1e-4490-8349-3de68f7ca369
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); int usedSpace = 0; foreach (var cell in Cells) { var part = cell.LineAtIndex(index); line.Add(part); usedSpace += part.Length; } return String.Join("", line); } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } } ``` Add dynamic left margin for line parts
```c# using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; private int Width; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; Width = width; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); int usedSpace = 0; foreach (var cell in Cells) { var part = cell.LineAtIndex(index); var spacing = SpacingFor(cell); line.Add(spacing + part); usedSpace += part.Length; } return String.Join("", line); } private string SpacingFor(Cell cell) { return new String(' ', 4); } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } } ```
bc41c4e1-2b25-4032-8765-face80e2f7f0
{ "language": "C#" }
```c# // Copyright ©2017 Simonray (http://github.com/simonray). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using ExchangeRate.Model; using System.Net; using System.Text.RegularExpressions; namespace ExchangeRate.Providers { /// <exclude /> public class GoogleProvider : BaseProvider { /// <exclude /> const string URL = "http://www.google.com/finance/converter?a=1&from={0}&to={1}"; /// <exclude /> public override string Name { get { return "Google"; } } /// <exclude /> public override Rate Fetch(Pair pair) { string url = pair.Construct(URL); var data = new GZipWebClient().DownloadString(url); var result = Regex.Matches(data, "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value; if (result == null) ThrowFormatChanged(); var value = Regex.Match(result, @"[0-9]*(?:\.[0-9]+)?"); if (value == null) ThrowFormatChanged(); return new Rate(double.Parse(value.Value)); } } } ``` Update changes to Google finance url
```c# // Copyright ©2017 Simonray (http://github.com/simonray). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using ExchangeRate.Model; using System.Net; using System.Text.RegularExpressions; namespace ExchangeRate.Providers { /// <exclude /> public class GoogleProvider : BaseProvider { /// <exclude /> const string URL = "http://finance.google.com/finance/converter?a=1&from={0}&to={1}"; /// <exclude /> public override string Name { get { return "Google"; } } /// <exclude /> public override Rate Fetch(Pair pair) { string url = pair.Construct(URL); var data = new GZipWebClient().DownloadString(url); var result = Regex.Matches(data, "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value; if (result == null) ThrowFormatChanged(); var value = Regex.Match(result, @"[0-9]*(?:\.[0-9]+)?"); if (value == null) ThrowFormatChanged(); return new Rate(double.Parse(value.Value)); } } } ```
8ce716fa-5e05-49da-81a3-24b2e5d6c357
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Reflection; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ServiceDescriptorAttribute : Attribute { public ServiceDescriptorAttribute() : this(null) { } public ServiceDescriptorAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Transient) { } public ServiceDescriptorAttribute(Type serviceType, ServiceLifetime lifetime) { ServiceType = serviceType; Lifetime = lifetime; } public Type ServiceType { get; } public ServiceLifetime Lifetime { get; } public IEnumerable<Type> GetServiceTypes(Type fallbackType) { if (ServiceType == null) { yield return fallbackType; var fallbackTypes = fallbackType.GetBaseTypes(); foreach (var type in fallbackTypes) { if (type == typeof(object)) { continue; } yield return type; } yield break; } var fallbackTypeInfo = fallbackType.GetTypeInfo(); var serviceTypeInfo = ServiceType.GetTypeInfo(); if (!serviceTypeInfo.IsAssignableFrom(fallbackTypeInfo)) { throw new InvalidOperationException($@"Type ""{fallbackTypeInfo.FullName}"" is not assignable to ""${serviceTypeInfo.FullName}""."); } yield return ServiceType; } } } ``` Use IsAssignableTo instead of IsAssignableFrom
```c# using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ServiceDescriptorAttribute : Attribute { public ServiceDescriptorAttribute() : this(null) { } public ServiceDescriptorAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Transient) { } public ServiceDescriptorAttribute(Type serviceType, ServiceLifetime lifetime) { ServiceType = serviceType; Lifetime = lifetime; } public Type ServiceType { get; } public ServiceLifetime Lifetime { get; } public IEnumerable<Type> GetServiceTypes(Type fallbackType) { if (ServiceType == null) { yield return fallbackType; var fallbackTypes = fallbackType.GetBaseTypes(); foreach (var type in fallbackTypes) { if (type == typeof(object)) { continue; } yield return type; } yield break; } if (!fallbackType.IsAssignableTo(ServiceType)) { throw new InvalidOperationException($@"Type ""{fallbackType.FullName}"" is not assignable to ""${ServiceType.FullName}""."); } yield return ServiceType; } } } ```
1dcb1b2b-9593-4c90-b780-76ffc7dac339
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { public void OutputMigrationCode(string tableName, IEnumerable<Column> columns) { var writer = Out; writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"); var tableName = "Book"; var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult(); new Table().OutputMigrationCode(tableName, columns); } } } ``` Move parameters from method to constructor
```c# using System; using System.Collections.Generic; using System.Linq; using static System.Console; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode() { var writer = Out; writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() { // nothing here yet } } }"); } } class Program { private static void Main() { var columnsProvider = new ColumnsProvider(@"Server=.\SQLEXPRESS;Database=LearnORM;Trusted_Connection=True;"); var tableName = "Book"; var columns = columnsProvider.GetColumnsAsync("dbo", tableName).GetAwaiter().GetResult(); new Table(tableName, columns).OutputMigrationCode(); } } } ```
b1cfd5f1-9fd3-48e8-a644-70c219120585
{ "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 Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Common; using System.Management.Automation; namespace Microsoft.Azure.Commands.Profile { /// <summary> /// Cmdlet to get current context. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmContext")] [OutputType(typeof(PSAzureContext))] public class GetAzureRMContextCommand : AzureRMCmdlet { public override void ExecuteCmdlet() { WriteObject((PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context); } } } ``` Fix issue where Get-AzureRmContext does not allow user to silently continue
```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 Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Common; using System.Management.Automation; namespace Microsoft.Azure.Commands.Profile { /// <summary> /// Cmdlet to get current context. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmContext")] [OutputType(typeof(PSAzureContext))] public class GetAzureRMContextCommand : AzureRMCmdlet { /// <summary> /// Gets the current default context. /// </summary> protected override AzureContext DefaultContext { get { if (DefaultProfile == null || DefaultProfile.Context == null) { WriteError(new ErrorRecord( new PSInvalidOperationException("Run Login-AzureRmAccount to login."), string.Empty, ErrorCategory.AuthenticationError, null)); } return DefaultProfile.Context; } } public override void ExecuteCmdlet() { WriteObject((PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context); } } } ```
a60cc21a-1ffc-484b-8a5d-cd54ff9ebe99
{ "language": "C#" }
```c# using System; using Agiil.Data; using Agiil.Domain; using Autofac; using NHibernate; using NHibernate.Cfg; namespace Agiil.Bootstrap.Data { public class NHibernateModule : Module { protected override void Load(ContainerBuilder builder) { // Configuration builder .Register((ctx, parameters) => { var factory = ctx.Resolve<ISessionFactoryFactory>(); return factory.GetConfiguration(); }) .SingleInstance(); // ISessionFactory builder .Register((ctx, parameters) => { var config = ctx.Resolve<Configuration>(); return config.BuildSessionFactory(); }) .SingleInstance(); // ISession builder .Register((ctx, parameters) => { var factory = ctx.Resolve<ISessionFactory>(); return factory.OpenSession(); }) .InstancePerMatchingLifetimeScope(ComponentScope.ApplicationConnection); } } } ``` Refactor NHibernate module for clarity
```c# using System; using Agiil.Data; using Agiil.Domain; using Autofac; using NHibernate; using NHibernate.Cfg; namespace Agiil.Bootstrap.Data { public class NHibernateModule : Module { protected override void Load(ContainerBuilder builder) { builder .Register(BuildNHibernateConfiguration) .SingleInstance(); builder .Register(BuildSessionFactory) .SingleInstance(); builder .Register(BuildSession) .InstancePerMatchingLifetimeScope(ComponentScope.ApplicationConnection); } Configuration BuildNHibernateConfiguration(IComponentContext ctx) { var factory = ctx.Resolve<ISessionFactoryFactory>(); return factory.GetConfiguration(); } ISessionFactory BuildSessionFactory(IComponentContext ctx) { var config = ctx.Resolve<Configuration>(); return config.BuildSessionFactory(); } ISession BuildSession(IComponentContext ctx) { var factory = ctx.Resolve<ISessionFactory>(); return factory.OpenSession(); } } } ```
a34d2095-0888-4534-a210-ffe020bbb235
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Vipr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Vipr")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("ViprCliUnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: AssemblyCompanyAttribute("Microsoft")] [assembly: AssemblyVersionAttribute("1.0.0.0")] [assembly: AssemblyFileVersionAttribute("1.0.*")]``` Add InternalsVisibleTo for T4 Tests
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Vipr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Vipr")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("ViprCliUnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: AssemblyCompanyAttribute("Microsoft")] [assembly: AssemblyVersionAttribute("1.0.*")] [assembly: AssemblyFileVersionAttribute("1.0.*")] [assembly: InternalsVisibleTo("T4TemplateWriterTests")] ```
a991042c-75a5-48a2-9271-d19ba9325b35
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DeploymentCockpit.Data.Repositories; using DeploymentCockpit.Interfaces; using DeploymentCockpit.Models; namespace DeploymentCockpit.Data { public class UnitOfWork : IUnitOfWork { private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>(); public UnitOfWork(DeploymentCockpitEntities db) { if (db == null) throw new ArgumentNullException("db"); _db = db; } private readonly DeploymentCockpitEntities _db; public void Commit() { _db.SaveChanges(); } public void Dispose() { _db.Dispose(); } public IRepository<T> Repository<T>() where T : class { var key = typeof(T); if (!_repositories.ContainsKey(key)) _repositories.Add(key, new Repository<T>(_db)); return _repositories[key] as Repository<T>; } } } ``` Put declaration in right place
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DeploymentCockpit.Data.Repositories; using DeploymentCockpit.Interfaces; using DeploymentCockpit.Models; namespace DeploymentCockpit.Data { public class UnitOfWork : IUnitOfWork { private readonly DeploymentCockpitEntities _db; private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>(); public UnitOfWork(DeploymentCockpitEntities db) { if (db == null) throw new ArgumentNullException("db"); _db = db; } public void Commit() { _db.SaveChanges(); } public void Dispose() { _db.Dispose(); } public IRepository<T> Repository<T>() where T : class { var key = typeof(T); if (!_repositories.ContainsKey(key)) _repositories.Add(key, new Repository<T>(_db)); return _repositories[key] as Repository<T>; } } } ```
f84034b2-b608-4a8d-80a5-eb1fbb7dcfbf
{ "language": "C#" }
```c# namespace Cassette.Views { #if NET35 public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } #endif } ``` Move conditional compilation around namespace.
```c# #if NET35 namespace Cassette.Views { public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } } #endif```
c85510ee-bbe4-4fc8-9e9a-816cf7997832
{ "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.Globalization; using NUnit.Framework; using osu.Framework.Localisation; namespace osu.Framework.Tests.Localisation { [TestFixture] public class CultureInfoHelperTest { private const string invariant_culture = "invariant"; private const string current_culture = ""; [TestCase("en-US", true, "en-US")] [TestCase("invalid name", false, invariant_culture)] [TestCase(current_culture, true, current_culture)] [TestCase("ko_KR", false, invariant_culture)] public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName) { CultureInfo expectedCulture; switch (expectedCultureName) { case invariant_culture: expectedCulture = CultureInfo.InvariantCulture; break; case current_culture: expectedCulture = CultureInfo.CurrentCulture; break; default: expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName); break; } bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture); Assert.That(retVal, Is.EqualTo(expectedReturnValue)); Assert.That(culture, Is.EqualTo(expectedCulture)); } } } ``` Update tests with new behaviour
```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.Globalization; using NUnit.Framework; using osu.Framework.Localisation; namespace osu.Framework.Tests.Localisation { [TestFixture] public class CultureInfoHelperTest { private const string invariant_culture = ""; [TestCase("en-US", true, "en-US")] [TestCase("invalid name", false, invariant_culture)] [TestCase(invariant_culture, true, invariant_culture)] [TestCase("ko_KR", false, invariant_culture)] public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName) { CultureInfo expectedCulture; switch (expectedCultureName) { case invariant_culture: expectedCulture = CultureInfo.InvariantCulture; break; default: expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName); break; } bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture); Assert.That(retVal, Is.EqualTo(expectedReturnValue)); Assert.That(culture, Is.EqualTo(expectedCulture)); } } } ```
2d1fee9b-bdee-4f54-b208-05acfb826e9e
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using Plugin.Permissions.Abstractions; namespace Plugin.Media.Abstractions { /// <summary> /// Permission exception. /// </summary> public class MediaPermissionException : Exception { /// <summary> /// Permission required that is missing /// </summary> public Permission[] Permissions { get; } /// <summary> /// Creates a media permission exception /// </summary> /// <param name="permissions"></param> public MediaPermissionException(params Permission[] permissions) : base($"{permissions} permission(s) are required.") { Permissions = permissions; } } } ``` Update the exception to be more developer friendly
```c# using System; using System.Collections.Generic; using System.Text; using Plugin.Permissions.Abstractions; namespace Plugin.Media.Abstractions { /// <summary> /// Permission exception. /// </summary> public class MediaPermissionException : Exception { /// <summary> /// Permission required that is missing /// </summary> public Permission[] Permissions { get; } /// <summary> /// Creates a media permission exception /// </summary> /// <param name="permissions"></param> public MediaPermissionException(params Permission[] permissions) : base() { Permissions = permissions; } /// <summary> /// Gets a message that describes current exception /// </summary> /// <value>The message.</value> public override string Message { get { string missingPermissions = string.Join(", ", Permissions); return $"{missingPermissions} permission(s) are required."; } } } } ```
7b89a616-e403-4925-b188-289098c6d666
{ "language": "C#" }
```c# using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ITraceInjector<HttpHeaders> _injector; private readonly string _serviceName; public TracingHandler(ITraceInjector<HttpHeaders> injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }``` Modify trace injector to http injector
```c# using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ZipkinHttpTraceInjector _injector; private readonly string _serviceName; public TracingHandler(string serviceName) : this(new ZipkinHttpTraceInjector(), serviceName) {} internal TracingHandler(ZipkinHttpTraceInjector injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }```
81f3d170-c548-4f98-a3d6-76daf3e9f188
{ "language": "C#" }
```c# using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.ApiLatestGithubReleaseUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } } ``` Fix master server auto-update with /nightly flag
```c# using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.AppveyorUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } } ```
e9dab18e-ee0d-4f8d-ba94-de7c5a39d907
{ "language": "C#" }
```c# using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String outputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); File.WriteAllText(outputName, mesh.ToString()); // Show the user it worked MessageBox.Show(outputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } } ``` Write data to OBJ and MTL
```c# using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String meshOutputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); String mtlOutputName = meshOutputName.Replace(".obj",".mtl"); String mtlName = mtlOutputName.Substring(mtlOutputName.LastIndexOf("\\")+1); File.WriteAllText(meshOutputName, mesh.GetObjData(mtlName)); File.WriteAllText(mtlOutputName,mesh.GetMtlData()); // Show the user it worked MessageBox.Show(meshOutputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } } ```
1fcbf220-e095-4671-acd2-9e4e9d0d3603
{ "language": "C#" }
```c# //----------------------------------------------------------------------- // <copyright file="IntegrationTests.cs" company="Experian Data Quality"> // Copyright (c) Experian. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.IO; using Xunit; using Xunit.Abstractions; namespace Experian.Qas.Updates.Metadata.WebApi.V1 { public class IntegrationTests { private readonly ITestOutputHelper _output; public IntegrationTests(ITestOutputHelper output) { _output = output; } [Fact(Skip = "Requires access to a dedicated test account.")] public void Program_Downloads_Data_Files() { // Arrange Environment.SetEnvironmentVariable("QAS:ElectronicUpdates:UserName", string.Empty); Environment.SetEnvironmentVariable("QAS:ElectronicUpdates:Password", string.Empty); using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { Console.SetOut(writer); try { // Act Program.MainInternal(); // Assert Assert.True(Directory.Exists("QASData")); Assert.NotEmpty(Directory.GetFiles("QASData", "*", SearchOption.AllDirectories)); } finally { _output.WriteLine(writer.ToString()); } } } } }``` Refactor Program_Downloads_Data_Files() to determine dynamically whether it should be skipped.
```c# //----------------------------------------------------------------------- // <copyright file="IntegrationTests.cs" company="Experian Data Quality"> // Copyright (c) Experian. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Globalization; using System.IO; using Xunit; using Xunit.Abstractions; namespace Experian.Qas.Updates.Metadata.WebApi.V1 { public class IntegrationTests { private readonly ITestOutputHelper _output; public IntegrationTests(ITestOutputHelper output) { _output = output; } [RequiresServiceCredentialsFact] public void Program_Downloads_Data_Files() { // Arrange using (TextWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { Console.SetOut(writer); try { // Act Program.MainInternal(); // Assert Assert.True(Directory.Exists("QASData")); Assert.NotEmpty(Directory.GetFiles("QASData", "*", SearchOption.AllDirectories)); } finally { _output.WriteLine(writer.ToString()); } } } private sealed class RequiresServiceCredentialsFact : FactAttribute { public RequiresServiceCredentialsFact() : base() { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("QAS:ElectronicUpdates:UserName")) || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("QAS:ElectronicUpdates:Password"))) { this.Skip = "No service credentials are configured."; } } } } }```
2ee6ad50-1f9e-42ad-a898-7de3225616e5
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account).Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }``` Fix for balance null ref
```c# using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account)?.Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }```
ec5d2e25-2f08-4b53-b069-4cc2853d6e75
{ "language": "C#" }
```c# using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData) || !System.PartSyncSystemReady) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } } ``` Fix unity call in another thread
```c# using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData)) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } } ```
50920f73-314c-48d5-9dcc-d17e90c86032
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST && (int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } } ``` Work around faulty StatusStrip implementations
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST) { if ((int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } else if ((int)m.Result == HT_CLIENT) { // Work around the implementation returning HT_CLIENT instead of HT_BOTTOMRIGHT int x = unchecked((short)((uint)m.LParam & 0xFFFF)); int y = unchecked((short)((uint)m.LParam >> 16)); Point p = PointToClient(new Point(x, y)); if (p.X >= this.ClientSize.Width - this.ClientSize.Height) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } } } } ```
ec9d8248-92b1-4aee-97a3-9f686bcbbf7e
{ "language": "C#" }
```c# /* Copyright 2017 James Craig Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and"); } } }``` Fix for null values when stripping characters in feeds.
```c# /* Copyright 2017 James Craig Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original?.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and") ?? ""; } } }```
9281b778-d8e1-4f14-acbe-f23e4d688e51
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new LanguageSettings(), new UpdateSettings(), }; } } } ``` Add button to access first run setup on demand
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { [Resolved(CanBeNull = true)] private FirstRunSetupOverlay firstRunSetupOverlay { get; set; } public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new SettingsButton { Text = "Run setup wizard", Action = () => firstRunSetupOverlay?.Show(), }, new LanguageSettings(), new UpdateSettings(), }; } } } ```
5be35892-601d-4af8-8f7a-daa0b3caf516
{ "language": "C#" }
```c# using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4 } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; } } }``` Add calc method for disposible income
```c# using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4, /// <summary> /// Deduction is taken as a percentage of the disposible income (gross pay - payroll taxes) /// </summary> PercentOfDisposibleIncome } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; yield return CalculationType.PercentOfDisposibleIncome; } } }```
38921b60-e0d1-4115-8d14-772a0f44e9e4
{ "language": "C#" }
```c# using System; using System.Windows.Forms; namespace DrawShip.Viewer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var applicationContext = new ApplicationContext(); var runMode = applicationContext.GetRunMode(); runMode.Run(applicationContext); } } } ``` Support invalid certificates (e.g. if Fiddler is in use) and more security protocols (adds Tls1.1 and Tls1.2)
```c# using System; using System.Net; using System.Windows.Forms; namespace DrawShip.Viewer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; var applicationContext = new ApplicationContext(); var runMode = applicationContext.GetRunMode(); runMode.Run(applicationContext); } } } ```
717ece2a-9d17-442f-883d-d7b2cc19b9e8
{ "language": "C#" }
```c# //*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Collections.Generic; namespace Microsoft.NodejsTools.Npm { public class PackageComparer : IComparer<IPackage> { public int Compare(IPackage x, IPackage y) { if (x == y) { return 0; } else if (null == x) { return -1; } else if (null == y) { return 1; } // TODO: should take into account versions! return x.Name.CompareTo(y.Name); } } }``` Split out package equality comparer
```c# //*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Collections.Generic; namespace Microsoft.NodejsTools.Npm { public class PackageComparer : IComparer<IPackage> { public int Compare(IPackage x, IPackage y) { if (x == y) { return 0; } else if (null == x) { return -1; } else if (null == y) { return 1; } // TODO: should take into account versions! return x.Name.CompareTo(y.Name); } } public class PackageEqualityComparer : EqualityComparer<IPackage> { public override bool Equals(IPackage p1, IPackage p2) { return p1.Name == p2.Name && p1.Version == p2.Version && p1.IsBundledDependency == p2.IsBundledDependency && p1.IsDevDependency == p2.IsDevDependency && p1.IsListedInParentPackageJson == p2.IsListedInParentPackageJson && p1.IsMissing == p2.IsMissing && p1.IsOptionalDependency == p2.IsOptionalDependency; } public override int GetHashCode(IPackage obj) { if (obj.Name == null || obj.Version == null) return obj.GetHashCode(); return obj.Name.GetHashCode() ^ obj.Version.GetHashCode(); } } }```
8fe69291-95c4-4329-9c73-06fbd3a48f5c
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; namespace Sketchball.GameComponents { public class SoundManager { private SoundPlayer currentPlayer; private DateTime lastPlay = new DateTime(); /// <summary> /// The minimum interval between to equivalent sounds. /// </summary> private const int MIN_INTERVAL = 400; public void Play(SoundPlayer player) { DateTime now = DateTime.Now; if (currentPlayer != player || (now - lastPlay).TotalMilliseconds > MIN_INTERVAL) { if (currentPlayer != null) currentPlayer.Stop(); currentPlayer = player; currentPlayer.Play(); } } } } ``` Fix soundmanager (forgot to record time)
```c# using System; using System.Collections.Generic; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; namespace Sketchball.GameComponents { public class SoundManager { private SoundPlayer currentPlayer; private DateTime lastPlay = new DateTime(); /// <summary> /// The minimum interval between to equivalent sounds. /// </summary> private const int MIN_INTERVAL = 200; public void Play(SoundPlayer player) { DateTime now = DateTime.Now; if (currentPlayer != player || (now - lastPlay).TotalMilliseconds > MIN_INTERVAL) { if (currentPlayer != null) currentPlayer.Stop(); currentPlayer = player; currentPlayer.Play(); lastPlay = now; } } } } ```
b0cf895f-639d-4215-815f-0cf5ed089f74
{ "language": "C#" }
```c# using System; using System.Diagnostics; namespace IronAHK.Rusty { partial class Core { #region Disk static string[] Glob(string pattern) { return new string[] { }; } #endregion #region Process static Process FindProcess(string name) { int id; if (int.TryParse(name, out id)) return System.Diagnostics.Process.GetProcessById(id); var prc = System.Diagnostics.Process.GetProcessesByName(name); return prc.Length > 0 ? prc[0] : null; } #endregion #region Text static string NormaliseEol(string text, string eol = null) { const string CR = "\r", LF = "\n", CRLF = "\r\n"; eol = eol ?? Environment.NewLine; switch (eol) { case CR: return text.Replace(CRLF, CR).Replace(LF, CR); case LF: return text.Replace(CRLF, LF).Replace(CR, LF); case CRLF: return text.Replace(CR, string.Empty).Replace(LF, CRLF); } return text; } #endregion } } ``` Remove trailing .exe in process name.
```c# using System; using System.Diagnostics; namespace IronAHK.Rusty { partial class Core { #region Disk static string[] Glob(string pattern) { return new string[] { }; } #endregion #region Process static Process FindProcess(string name) { int id; if (int.TryParse(name, out id)) return System.Diagnostics.Process.GetProcessById(id); const string exe = ".exe"; if (name.EndsWith(exe, StringComparison.OrdinalIgnoreCase)) name = name.Substring(0, name.Length - exe.Length); var prc = System.Diagnostics.Process.GetProcessesByName(name); return prc.Length > 0 ? prc[0] : null; } #endregion #region Text static string NormaliseEol(string text, string eol = null) { const string CR = "\r", LF = "\n", CRLF = "\r\n"; eol = eol ?? Environment.NewLine; switch (eol) { case CR: return text.Replace(CRLF, CR).Replace(LF, CR); case LF: return text.Replace(CRLF, LF).Replace(CR, LF); case CRLF: return text.Replace(CR, string.Empty).Replace(LF, CRLF); } return text; } #endregion } } ```