doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
f540f2f3-fb7a-4644-a01e-d49b62020c12
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Judgements { public class ManiaJudgement : Judgement { protected override int NumericResultFor(HitResult result) { switch (result) { default: return 0; case HitResult.Meh: return 50; case HitResult.Ok: return 100; case HitResult.Good: return 200; case HitResult.Great: case HitResult.Perfect: return 300; } } } } ``` Fix 1M score being possible with only GREATs in mania
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mania.Judgements { public class ManiaJudgement : Judgement { protected override int NumericResultFor(HitResult result) { switch (result) { default: return 0; case HitResult.Meh: return 50; case HitResult.Ok: return 100; case HitResult.Good: return 200; case HitResult.Great: return 300; case HitResult.Perfect: return 320; } } } } ```
90d9fee9-db30-45a8-b9e9-b97d75674710
{ "language": "C#" }
```c# using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = AssemblyVersion; this.lastUpdatedBox.Text = LastUpdatedDate.ToString(); this.linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } #region Assembly Attribute Accessors public static string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyProductAttribute)attributes[0]).Product; } } public static string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; if (!string.IsNullOrEmpty(titleAttribute.Title)) { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public static string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } #endregion Assembly Attribute Accessors private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }``` Make the about window have a space in the application name
```c# using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace VigilantCupcake.SubForms { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyTitle; this.labelVersion.Text = AssemblyVersion; this.lastUpdatedBox.Text = LastUpdatedDate.ToString(); this.linkLabel1.Text = Properties.Settings.Default.WebsiteUrl; } public string LatestVersionText { set { latestBox.Text = value; } } #region Assembly Attribute Accessors public static string AssemblyTitle { get { return "Vigilant Cupcake"; } } public static string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public static DateTime LastUpdatedDate { get { return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; } } #endregion Assembly Attribute Accessors private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl); } } }```
7abe9e92-1120-4705-a6b3-d7e8432b3760
{ "language": "C#" }
```c# using System; using System.Net.Http; using System.Windows; using SwitchClient.Classic; using SwitchClient.Hyper; namespace WpfSwitchClient { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { var client = new HttpClient() { BaseAddress = new Uri(String.Format("http://{0}:9090/", Environment.MachineName)) }; //var window = new MainWindow(new SwitchViewModel(new SwitchService(client))); var window = new MainWindow(new SwitchHyperViewModel(client)); window.Show(); } } } ``` Reset VM to be Service based
```c# using System; using System.Net.Http; using System.Windows; using SwitchClient.Classic; using SwitchClient.Hyper; namespace WpfSwitchClient { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { var client = new HttpClient() { BaseAddress = new Uri(String.Format("http://{0}:9090/", Environment.MachineName)) }; var window = new MainWindow(new SwitchViewModel(new SwitchService(client))); //var window = new MainWindow(new SwitchHyperViewModel(client)); window.Show(); } } } ```
d399fbb3-3b8e-4f5f-9b53-26e950e4513e
{ "language": "C#" }
```c# using System; using System.Security.Claims; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using FluentValidation.Mvc; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Azure; using NLog; using NLog.Targets; using SFA.DAS.EAS.Infrastructure.Logging; namespace SFA.DAS.EAS.Web { public class MvcApplication : System.Web.HttpApplication { private readonly Logger _logger = LogManager.GetCurrentClassLogger(); private static RedisTarget _redisTarget; // Required to ensure assembly is copied to output. protected void Application_Start() { LoggingConfig.ConfigureLogging(); TelemetryConfiguration.Active.InstrumentationKey = CloudConfigurationManager.GetSetting("InstrumentationKey"); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; FluentValidationModelValidatorProvider.Configure(); } protected void Application_Error(object sender, EventArgs e) { var exception = Server.GetLastError(); _logger.Error(exception); var tc = new TelemetryClient(); tc.TrackTrace($"{exception.Message} - {exception.InnerException}"); } } } ``` Remove server header form http responses
```c# using System; using System.Security.Claims; using System.Web; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using FluentValidation.Mvc; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Azure; using NLog; using NLog.Targets; using SFA.DAS.EAS.Infrastructure.Logging; namespace SFA.DAS.EAS.Web { public class MvcApplication : System.Web.HttpApplication { private readonly Logger _logger = LogManager.GetCurrentClassLogger(); private static RedisTarget _redisTarget; // Required to ensure assembly is copied to output. protected void Application_Start() { LoggingConfig.ConfigureLogging(); TelemetryConfiguration.Active.InstrumentationKey = CloudConfigurationManager.GetSetting("InstrumentationKey"); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; FluentValidationModelValidatorProvider.Configure(); } protected void Application_BeginRequest(object sender, EventArgs e) { var application = sender as HttpApplication; application?.Context?.Response.Headers.Remove("Server"); } protected void Application_Error(object sender, EventArgs e) { var exception = Server.GetLastError(); _logger.Error(exception); var tc = new TelemetryClient(); tc.TrackTrace($"{exception.Message} - {exception.InnerException}"); } } } ```
4c4ca10e-8093-4247-bf1d-8222efcd2649
{ "language": "C#" }
```c# @inherits UmbracoViewPage<BlockListModel> @using Umbraco.Core.Models.Blocks @{ if (Model?.Layout == null || !Model.Layout.Any()) { return; } } <div class="umb-block-list"> @foreach (var layout in Model.Layout) { if (layout?.Udi == null) { continue; } var data = layout.Data; @Html.Partial("BlockList/Components/" + data.ContentType.Alias, layout) } </div> ``` Update to default Razor snippet we use to help with Block List editor
```c# @inherits UmbracoViewPage<BlockListModel> @using Umbraco.Core.Models.Blocks @{ if (!Model.Any()) { return; } } <div class="umb-block-list"> @foreach (var block in Model) { if (block?.ContentUdi == null) { continue; } var data = block.Content; @Html.Partial("BlockList/Components/" + data.ContentType.Alias, block) } </div> ```
4052077c-9a3f-47bf-9d3c-65daa43a1687
{ "language": "C#" }
```c# using System; namespace PcscDotNet { public class PcscContext : IDisposable { private SCardContext _context; private readonly Pcsc _pcsc; private readonly IPcscProvider _provider; public bool IsDisposed { get; private set; } = false; public bool IsEstablished => _context.HasValue; public Pcsc Pcsc => _pcsc; public PcscContext(Pcsc pcsc) { _pcsc = pcsc; _provider = pcsc.Provider; } public PcscContext(Pcsc pcsc, SCardScope scope) : this(pcsc) { Establish(scope); } ~PcscContext() { Dispose(); } public unsafe PcscContext Establish(SCardScope scope) { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Establish)); if (IsEstablished) throw new InvalidOperationException("Context has been established."); SCardContext context; _provider.SCardEstablishContext(scope, null, null, &context).ThrowIfNotSuccess(); _context = context; return this; } public PcscContext Release() { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Release)); if (IsEstablished) { _provider.SCardReleaseContext(_context).ThrowIfNotSuccess(); _context = SCardContext.Default; } return this; } public void Dispose() { if (IsDisposed) return; Release(); GC.SuppressFinalize(this); IsDisposed = true; } } }``` Change field and variable names from context to handle
```c# using System; namespace PcscDotNet { public class PcscContext : IDisposable { private SCardContext _handle; private readonly Pcsc _pcsc; private readonly IPcscProvider _provider; public bool IsDisposed { get; private set; } = false; public bool IsEstablished => _handle.HasValue; public Pcsc Pcsc => _pcsc; public PcscContext(Pcsc pcsc) { _pcsc = pcsc; _provider = pcsc.Provider; } public PcscContext(Pcsc pcsc, SCardScope scope) : this(pcsc) { Establish(scope); } ~PcscContext() { Dispose(); } public unsafe PcscContext Establish(SCardScope scope) { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Establish)); if (IsEstablished) throw new InvalidOperationException("Context has been established."); SCardContext handle; _provider.SCardEstablishContext(scope, null, null, &handle).ThrowIfNotSuccess(); _handle = handle; return this; } public PcscContext Release() { if (IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(Release)); if (IsEstablished) { _provider.SCardReleaseContext(_handle).ThrowIfNotSuccess(); _handle = SCardContext.Default; } return this; } public void Dispose() { if (IsDisposed) return; Release(); GC.SuppressFinalize(this); IsDisposed = true; } } }```
a097d0be-8ce4-45ca-bbad-e84906ce07eb
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Cursor; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; using osu.Game.Online; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Components { public abstract class ReadyButton : TriangleButton, IHasTooltip { public new readonly BindableBool Enabled = new BindableBool(); private IBindable<BeatmapAvailability> availability; [BackgroundDependencyLoader] private void load(OnlinePlayBeatmapAvailabilityTracker beatmapTracker) { availability = beatmapTracker.Availability.GetBoundCopy(); availability.BindValueChanged(_ => updateState()); Enabled.BindValueChanged(_ => updateState(), true); } private void updateState() => base.Enabled.Value = availability.Value.State == DownloadState.LocallyAvailable && Enabled.Value; public virtual LocalisableString TooltipText { get { if (Enabled.Value) return string.Empty; return "Beatmap not downloaded"; } } } } ``` Fix ready button tooltip showing when locally available
```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.Bindables; using osu.Framework.Graphics.Cursor; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; using osu.Game.Online; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Components { public abstract class ReadyButton : TriangleButton, IHasTooltip { public new readonly BindableBool Enabled = new BindableBool(); private IBindable<BeatmapAvailability> availability; [BackgroundDependencyLoader] private void load(OnlinePlayBeatmapAvailabilityTracker beatmapTracker) { availability = beatmapTracker.Availability.GetBoundCopy(); availability.BindValueChanged(_ => updateState()); Enabled.BindValueChanged(_ => updateState(), true); } private void updateState() => base.Enabled.Value = availability.Value.State == DownloadState.LocallyAvailable && Enabled.Value; public virtual LocalisableString TooltipText { get { if (Enabled.Value) return string.Empty; if (availability.Value.State != DownloadState.LocallyAvailable) return "Beatmap not downloaded"; return string.Empty; } } } } ```
fd182449-d7c2-47ff-bc17-9e363d1a05fa
{ "language": "C#" }
```c# namespace GitFlowVersion { using System.IO; public class GitDirFinder { public static string TreeWalkForGitDir(string currentDirectory) { while (true) { var gitDir = Path.Combine(currentDirectory, @".git"); if (Directory.Exists(gitDir)) { return gitDir; } var parent = Directory.GetParent(currentDirectory); if (parent == null) { break; } currentDirectory = parent.FullName; } return null; } } }``` Make TreeWalkForGitDir() delegate to LibGit2Sharp
```c# namespace GitFlowVersion { using System.IO; using LibGit2Sharp; public class GitDirFinder { public static string TreeWalkForGitDir(string currentDirectory) { string gitDir = Repository.Discover(currentDirectory); if (gitDir != null) { return gitDir.TrimEnd(new []{ Path.DirectorySeparatorChar }); } return null; } } }```
d49e3da0-af2c-4739-84bf-8d941d14bb70
{ "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 Android.App; using Android.Content.PM; using Android.OS; using Android.Views; using osu.Framework.Android; namespace osu.Android { [Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.SensorLandscape, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = true)] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } } ``` Support both landscape and portrait mode
```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 Android.App; using Android.Content.PM; using Android.OS; using Android.Views; using osu.Framework.Android; namespace osu.Android { [Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = true)] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } } ```
97d6fab5-8982-4a7c-a992-66600d0c5437
{ "language": "C#" }
```c# using WootzJs.Mvc.Mvc.Views.Css; using WootzJs.Web; namespace WootzJs.Mvc.Mvc.Views { public class Image : InlineControl { public Image() { } public Image(string source) { Source = source; } public Image(string defaultSource, string highlightedSource) { Source = defaultSource; MouseEntered += () => Source = highlightedSource; MouseExited += () => Source = defaultSource; } public Image(string defaultSource, string highlightedSource, CssColor highlightColor) { Source = defaultSource; MouseEntered += () => { Source = highlightedSource; Style.BackgroundColor = highlightColor; }; MouseExited += () => { Source = defaultSource; Style.BackgroundColor = CssColor.Inherit; }; } public int Width { get { return int.Parse(Node.GetAttribute("width")); } set { Node.SetAttribute("width", value.ToString()); } } public int Height { get { return int.Parse(Node.GetAttribute("height")); } set { Node.SetAttribute("height", value.ToString()); } } public string Source { get { return Node.GetAttribute("src"); } set { Node.SetAttribute("src", value); } } protected override Element CreateNode() { var node = Browser.Document.CreateElement("img"); node.Style.Display = "block"; return node; } } }``` Add ability to set width and height when setting the image
```c# using WootzJs.Mvc.Mvc.Views.Css; using WootzJs.Web; namespace WootzJs.Mvc.Mvc.Views { public class Image : InlineControl { public Image() { } public Image(string source, int? width = null, int? height = null) { Source = source; if (width != null) Width = width.Value; if (height != null) Height = height.Value; } public Image(string defaultSource, string highlightedSource) { Source = defaultSource; MouseEntered += () => Source = highlightedSource; MouseExited += () => Source = defaultSource; } public Image(string defaultSource, string highlightedSource, CssColor highlightColor) { Source = defaultSource; MouseEntered += () => { Source = highlightedSource; Style.BackgroundColor = highlightColor; }; MouseExited += () => { Source = defaultSource; Style.BackgroundColor = CssColor.Inherit; }; } public int Width { get { return int.Parse(Node.GetAttribute("width")); } set { Node.SetAttribute("width", value.ToString()); } } public int Height { get { return int.Parse(Node.GetAttribute("height")); } set { Node.SetAttribute("height", value.ToString()); } } public string Source { get { return Node.GetAttribute("src"); } set { Node.SetAttribute("src", value); } } protected override Element CreateNode() { var node = Browser.Document.CreateElement("img"); node.Style.Display = "block"; return node; } } }```
aba52c69-175a-4a86-a265-a15ff7c45e84
{ "language": "C#" }
```c# using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using Microsoft.Owin; using Foundation.Api.Middlewares.SignalR.Contracts; namespace Foundation.Api.Middlewares.SignalR { public class MessagesHub : Hub { public override async Task OnConnected() { IOwinContext context = new OwinContext(Context.Request.Environment); Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver"); await dependencyResolver.Resolve<IMessagesHubEvents>().OnConnected(this); await base.OnConnected(); } public override async Task OnDisconnected(bool stopCalled) { IOwinContext context = new OwinContext(Context.Request.Environment); Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver"); await dependencyResolver.Resolve<IMessagesHubEvents>().OnDisconnected(this, stopCalled); await base.OnDisconnected(stopCalled); } public override async Task OnReconnected() { IOwinContext context = new OwinContext(Context.Request.Environment); Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver"); await dependencyResolver.Resolve<IMessagesHubEvents>().OnReconnected(this); await base.OnReconnected(); } } }``` Call signalr hub base method in case of exception in user codes of signalr hub events class
```c# using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using Microsoft.Owin; using Foundation.Api.Middlewares.SignalR.Contracts; namespace Foundation.Api.Middlewares.SignalR { public class MessagesHub : Hub { public override async Task OnConnected() { try { IOwinContext context = new OwinContext(Context.Request.Environment); Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver"); await dependencyResolver.Resolve<IMessagesHubEvents>().OnConnected(this); } finally { await base.OnConnected(); } } public override async Task OnDisconnected(bool stopCalled) { try { IOwinContext context = new OwinContext(Context.Request.Environment); Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver"); await dependencyResolver.Resolve<IMessagesHubEvents>().OnDisconnected(this, stopCalled); } finally { await base.OnDisconnected(stopCalled); } } public override async Task OnReconnected() { try { IOwinContext context = new OwinContext(Context.Request.Environment); Core.Contracts.IDependencyResolver dependencyResolver = context.Get<Core.Contracts.IDependencyResolver>("DependencyResolver"); await dependencyResolver.Resolve<IMessagesHubEvents>().OnReconnected(this); } finally { await base.OnReconnected(); } } } }```
d8b764e0-ddbe-475f-b84f-b41c11fec66c
{ "language": "C#" }
```c# using System.Runtime.InteropServices; namespace RebirthTracker { /// <summary> /// Class to keep track of OS-specific configuration settings /// </summary> public static class Configuration { /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return "..\\..\\..\\..\\..\\"; } return "../../../../../../"; } } } ``` Use absolute path on linux
```c# using System.Runtime.InteropServices; namespace RebirthTracker { /// <summary> /// Class to keep track of OS-specific configuration settings /// </summary> public static class Configuration { /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return "..\\..\\..\\..\\..\\"; } return "/var/www/"; } } } ```
81ddaedb-09d4-4ddc-94e9-4c6fdd9f9e78
{ "language": "C#" }
```c# using System; using System.Text; using P2E.Interfaces.Services; namespace P2E.Services { public class UserCredentialsService : IUserCredentialsService { // Syncs console output/input between instance so that only one // instance can request user credentials at any time. private static readonly object LockObject = new object(); public string Loginname { get; private set; } public string Password { get; private set; } public void GetUserCredentials() { // Each instance can request credentials only once. if (HasUserCredentials) return; lock (LockObject) { if (HasUserCredentials) return; Console.Out.Write("Username: "); Loginname = Console.ReadLine(); Console.Out.Write("Password: "); Password = GetPassword(); } } public bool HasUserCredentials => Loginname != null && Password != null; private string GetPassword() { var password = new StringBuilder(); ConsoleKeyInfo key; do { key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { password.Append(key.KeyChar); Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && password.Length > 0) { password.Remove(password.Length - 1, 1); Console.Write("\b \b"); } } } while (key.Key != ConsoleKey.Enter); Console.WriteLine(); return password.ToString(); } } }``` Create a TODO to revert the locking code.
```c# using System; using System.Text; using P2E.Interfaces.Services; namespace P2E.Services { public class UserCredentialsService : IUserCredentialsService { // TODO - revert that stuipd locking idea and introduce a Credentials class instead. // Syncs console output/input between instance so that only one // instance can request user credentials at any time. private static readonly object LockObject = new object(); public string Loginname { get; private set; } public string Password { get; private set; } public void GetUserCredentials() { // Each instance can request credentials only once. if (HasUserCredentials) return; lock (LockObject) { if (HasUserCredentials) return; Console.Out.Write("Username: "); Loginname = Console.ReadLine(); Console.Out.Write("Password: "); Password = GetPassword(); } } public bool HasUserCredentials => Loginname != null && Password != null; private string GetPassword() { var password = new StringBuilder(); ConsoleKeyInfo key; do { key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { password.Append(key.KeyChar); Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && password.Length > 0) { password.Remove(password.Length - 1, 1); Console.Write("\b \b"); } } } while (key.Key != ConsoleKey.Enter); Console.WriteLine(); return password.ToString(); } } }```
45fc3a36-2681-4338-b3d8-46fd25d0cf7c
{ "language": "C#" }
```c# // Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using Nuke.Common.OutputSinks; using Nuke.Common.Utilities; namespace Nuke.Common.BuildServers { [UsedImplicitly] [ExcludeFromCodeCoverage] internal class TeamCityOutputSink : AnsiColorOutputSink { private readonly TeamCity _teamCity; public TeamCityOutputSink(TeamCity teamCity) : base(traceCode: "37", informationCode: "36", warningCode: "33", errorCode: "31", successCode: "32") { _teamCity = teamCity; } public override IDisposable WriteBlock(string text) { return DelegateDisposable.CreateBracket( () => _teamCity.OpenBlock(text), () => _teamCity.CloseBlock(text)); } } } ``` Add duration as statistical value for blocks in TeamCity
```c# // Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using Nuke.Common.OutputSinks; using Nuke.Common.Utilities; using Nuke.Common.Utilities.Collections; namespace Nuke.Common.BuildServers { [UsedImplicitly] [ExcludeFromCodeCoverage] internal class TeamCityOutputSink : AnsiColorOutputSink { private readonly TeamCity _teamCity; public TeamCityOutputSink(TeamCity teamCity) : base(traceCode: "37", informationCode: "36", warningCode: "33", errorCode: "31", successCode: "32") { _teamCity = teamCity; } public override IDisposable WriteBlock(string text) { var stopWatch = new Stopwatch(); return DelegateDisposable.CreateBracket( () => { _teamCity.OpenBlock(text); stopWatch.Start(); }, () => { _teamCity.CloseBlock(text); _teamCity.AddStatisticValue( $"NUKE_DURATION_{text.SplitCamelHumpsWithSeparator("_").ToUpper()}", stopWatch.ElapsedMilliseconds.ToString()); stopWatch.Stop(); }); } } } ```
16bbe3a0-7a7b-4dab-b3d6-a4a6c541cf59
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.UI.StartScreen; using ParkenDD.Api.Models; namespace ParkenDD.Services { public class JumpListService { private readonly ResourceService _resources; private const string ArgumentFormat = "city={0}"; public JumpListService(ResourceService resources) { _resources = resources; } public async void UpdateCityList(IEnumerable<MetaDataCityRow> metaData) { await UpdateCityListAsync(metaData); } public async Task UpdateCityListAsync(IEnumerable<MetaDataCityRow> cities) { if (cities == null) { return; } if (JumpList.IsSupported()) { var jumpList = await JumpList.LoadCurrentAsync(); jumpList.SystemGroupKind = JumpListSystemGroupKind.None; jumpList.Items.Clear(); foreach (var city in cities) { var item = JumpListItem.CreateWithArguments(string.Format(ArgumentFormat, city.Id), city.Name); item.GroupName = _resources.JumpListCitiesHeader; item.Logo = new Uri("ms-appx:///Assets/ParkingIcon.png"); jumpList.Items.Add(item); } await jumpList.SaveAsync(); } } } } ``` Comment out jump list support again as no SDK is out yet... :(
```c# using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.UI.StartScreen; using ParkenDD.Api.Models; namespace ParkenDD.Services { public class JumpListService { private readonly ResourceService _resources; private const string ArgumentFormat = "city={0}"; public JumpListService(ResourceService resources) { _resources = resources; } public async void UpdateCityList(IEnumerable<MetaDataCityRow> metaData) { await UpdateCityListAsync(metaData); } public async Task UpdateCityListAsync(IEnumerable<MetaDataCityRow> cities) { /* if (cities == null) { return; } if (JumpList.IsSupported()) { var jumpList = await JumpList.LoadCurrentAsync(); jumpList.SystemGroupKind = JumpListSystemGroupKind.None; jumpList.Items.Clear(); foreach (var city in cities) { var item = JumpListItem.CreateWithArguments(string.Format(ArgumentFormat, city.Id), city.Name); item.GroupName = _resources.JumpListCitiesHeader; item.Logo = new Uri("ms-appx:///Assets/ParkingIcon.png"); jumpList.Items.Add(item); } await jumpList.SaveAsync(); } */ } } } ```
23a7d1bc-3739-4c4a-81c5-6fee12bf5d55
{ "language": "C#" }
```c# using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using Eto.Forms; namespace Eto.Test.Mac { class Startup { static void Main (string [] args) { AddStyles (); var generator = new Eto.Platform.Mac.Generator (); var app = new TestApplication (generator); app.Run (args); } static void AddStyles () { // support full screen mode! Style.Add<Window, NSWindow> ("main", (widget, control) => { //control.CollectionBehavior |= NSWindowCollectionBehavior.FullScreenPrimary; // not in monomac/master yet.. }); Style.Add<Application, NSApplication> ("application", (widget, control) => { if (control.RespondsToSelector (new Selector ("presentationOptions:"))) { control.PresentationOptions |= NSApplicationPresentationOptions.FullScreen; } }); // other styles Style.Add<TreeView, NSScrollView> ("sectionList", (widget, control) => { control.BorderType = NSBorderType.NoBorder; var table = control.DocumentView as NSTableView; table.SelectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList; }); } } } ``` Support full screen now that core MonoMac supports it
```c# using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; using Eto.Forms; namespace Eto.Test.Mac { class Startup { static void Main (string [] args) { AddStyles (); var generator = new Eto.Platform.Mac.Generator (); var app = new TestApplication (generator); app.Run (args); } static void AddStyles () { // support full screen mode! Style.Add<Window, NSWindow> ("main", (widget, control) => { control.CollectionBehavior |= NSWindowCollectionBehavior.FullScreenPrimary; }); Style.Add<Application, NSApplication> ("application", (widget, control) => { if (control.RespondsToSelector (new Selector ("presentationOptions:"))) { control.PresentationOptions |= NSApplicationPresentationOptions.FullScreen; } }); // other styles Style.Add<TreeView, NSScrollView> ("sectionList", (widget, control) => { control.BorderType = NSBorderType.NoBorder; var table = control.DocumentView as NSTableView; table.SelectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList; }); } } } ```
9602ade7-f4cc-406b-9581-2ff534ae7eec
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using DragonContracts.Models; using Raven.Client; using Raven.Client.Document; using Raven.Client.Embedded; using Raven.Database.Server.Responders; namespace DragonContracts.Base { public class RavenDbController : ApiController { public IDocumentStore Store { get { return LazyDocStore.Value; } } private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() => { var docStore = new EmbeddableDocumentStore() { DataDirectory = "App_Data/Raven" }; docStore.Initialize(); return docStore; }); public IAsyncDocumentSession Session { get; set; } public async override Task<HttpResponseMessage> ExecuteAsync( HttpControllerContext controllerContext, CancellationToken cancellationToken) { using (Session = Store.OpenAsyncSession()) { var result = await base.ExecuteAsync(controllerContext, cancellationToken); await Session.SaveChangesAsync(); return result; } } } }``` Enable raven studio for port 8081
```c# using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using DragonContracts.Models; using Raven.Client; using Raven.Client.Document; using Raven.Client.Embedded; using Raven.Database.Config; using Raven.Database.Server.Responders; namespace DragonContracts.Base { public class RavenDbController : ApiController { private const int RavenWebUiPort = 8081; public IDocumentStore Store { get { return LazyDocStore.Value; } } private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() => { var docStore = new EmbeddableDocumentStore() { DataDirectory = "App_Data/Raven", UseEmbeddedHttpServer = true }; docStore.Configuration.Port = RavenWebUiPort; Raven.Database.Server.NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(RavenWebUiPort); docStore.Initialize(); return docStore; }); public IAsyncDocumentSession Session { get; set; } public async override Task<HttpResponseMessage> ExecuteAsync( HttpControllerContext controllerContext, CancellationToken cancellationToken) { using (Session = Store.OpenAsyncSession()) { var result = await base.ExecuteAsync(controllerContext, cancellationToken); await Session.SaveChangesAsync(); return result; } } } }```
768448be-58ff-4f41-ba7d-dd649f516717
{ "language": "C#" }
```c# #region Usings using System.Linq; using System.Web.Mvc; using NUnit.Framework; using WebApplication.Controllers; using WebApplication.Models; #endregion namespace UnitTests { [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { var formCollection = new FormCollection(); formCollection["Name"] = "Habit"; var habitController = new HabitController(); habitController.Create(formCollection); var habit = ApplicationDbContext.Create().Habits.Single(); Assert.AreEqual("Habit", habit.Name); } } }``` Replace test with test stub
```c# #region Usings using NUnit.Framework; #endregion namespace UnitTests { [TestFixture] public class UnitTest1 { [Test] public void TestMethod1() { Assert.True(true); } } }```
5a9ddeb7-38e2-4775-8812-9e019e12c939
{ "language": "C#" }
```c# using System; using System.Diagnostics; namespace NuGetConsole.Implementation.PowerConsole { /// <summary> /// Represents a host with extra info. /// </summary> class HostInfo : ObjectWithFactory<PowerConsoleWindow> { Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; } public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider) : base(factory) { UtilityMethods.ThrowIfArgumentNull(hostProvider); this.HostProvider = hostProvider; } /// <summary> /// Get the HostName attribute value of this host. /// </summary> public string HostName { get { return HostProvider.Metadata.HostName; } } IWpfConsole _wpfConsole; /// <summary> /// Get/create the console for this host. If not already created, this /// actually creates the (console, host) pair. /// /// Note: Creating the console is handled by this package and mostly will /// succeed. However, creating the host could be from other packages and /// fail. In that case, this console is already created and can be used /// subsequently in limited ways, such as displaying an error message. /// </summary> public IWpfConsole WpfConsole { get { if (_wpfConsole == null) { _wpfConsole = Factory.WpfConsoleService.CreateConsole( Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName); _wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: false); } return _wpfConsole; } } } } ``` Revert accidental change of the async flag.
```c# using System; using System.Diagnostics; namespace NuGetConsole.Implementation.PowerConsole { /// <summary> /// Represents a host with extra info. /// </summary> class HostInfo : ObjectWithFactory<PowerConsoleWindow> { Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; } public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider) : base(factory) { UtilityMethods.ThrowIfArgumentNull(hostProvider); this.HostProvider = hostProvider; } /// <summary> /// Get the HostName attribute value of this host. /// </summary> public string HostName { get { return HostProvider.Metadata.HostName; } } IWpfConsole _wpfConsole; /// <summary> /// Get/create the console for this host. If not already created, this /// actually creates the (console, host) pair. /// /// Note: Creating the console is handled by this package and mostly will /// succeed. However, creating the host could be from other packages and /// fail. In that case, this console is already created and can be used /// subsequently in limited ways, such as displaying an error message. /// </summary> public IWpfConsole WpfConsole { get { if (_wpfConsole == null) { _wpfConsole = Factory.WpfConsoleService.CreateConsole( Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName); _wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: true); } return _wpfConsole; } } } } ```
8c3d7083-af2f-499c-a78d-859c3bcd3f22
{ "language": "C#" }
```c# using UnityEngine; using UnityEditor; namespace UnityBuild { public abstract class BuildSettings { public abstract string binName { get; } public abstract string binPath { get; } public abstract string[] scenesInBuild { get; } public abstract string[] copyToBuild { get; } //// The name of executable file (e.g. mygame.exe, mygame.app) //public const string BIN_NAME = "mygame"; //// The base path where builds are output. //// Path is relative to the Unity project's base folder unless an absolute path is given. //public const string BIN_PATH = "bin"; //// A list of scenes to include in the build. The first listed scene will be loaded first. //public static string[] scenesInBuild = new string[] { // // "Assets/Scenes/scene1.unity", // // "Assets/Scenes/scene2.unity", // // ... //}; //// A list of files/directories to include with the build. //// Paths are relative to Unity project's base folder unless an absolute path is given. //public static string[] copyToBuild = new string[] { // // "DirectoryToInclude/", // // "FileToInclude.txt", // // ... //}; } }``` Add virtual pre/post build methods.
```c# using UnityEngine; using UnityEditor; namespace UnityBuild { public abstract class BuildSettings { public abstract string binName { get; } public abstract string binPath { get; } public abstract string[] scenesInBuild { get; } public abstract string[] copyToBuild { get; } public virtual void PreBuild() { } public virtual void PostBuild() { } } }```
6a486fcc-08ec-494b-84f0-2b5fb0aa9681
{ "language": "C#" }
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LBD2OBJLib.Types { class FixedPoint { public int IntegralPart { get; set; } public int DecimalPart { get; set; } public FixedPoint(byte[] data) { if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); } byte[] _data = new byte[2]; data.CopyTo(_data, 0); var signMask = (byte)128; var integralMask = (byte)112; var firstPartOfDecimalMask = (byte)15; bool isNegative = (_data[0] & signMask) == 128; int integralPart = (_data[0] & integralMask) * (isNegative ? -1 : 1); int decimalPart = (_data[0] & firstPartOfDecimalMask); decimalPart <<= 8; decimalPart += data[1]; IntegralPart = integralPart; DecimalPart = decimalPart; } public override string ToString() { return IntegralPart + "." + DecimalPart; } } } ``` Change mask variables to const values, remove from constructor
```c# using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LBD2OBJLib.Types { class FixedPoint { public int IntegralPart { get; set; } public int DecimalPart { get; set; } const byte SIGN_MASK = 128; const byte INTEGRAL_MASK = 112; const byte MANTISSA_MASK = 15; public FixedPoint(byte[] data) { if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); } byte[] _data = new byte[2]; data.CopyTo(_data, 0); bool isNegative = (_data[0] & SIGN_MASK) == 128; int integralPart = (_data[0] & INTEGRAL_MASK) * (isNegative ? -1 : 1); int decimalPart = (_data[0] & MANTISSA_MASK); decimalPart <<= 8; decimalPart += data[1]; IntegralPart = integralPart; DecimalPart = decimalPart; } public override string ToString() { return IntegralPart + "." + DecimalPart; } } } ```
679e4fd3-9ec0-44b4-882c-8f87d983dbbc
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Platform; using osu.Framework; namespace SampleGame.Desktop { public static class Program { [STAThread] public static void Main() { using (GameHost host = Host.GetSuitableHost(@"sample-game")) using (Game game = new SampleGameGame()) host.Run(game); } } } ``` Add SDL support to SampleGame
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework; using osu.Framework.Platform; namespace SampleGame.Desktop { public static class Program { [STAThread] public static void Main(string[] args) { bool useSdl = args.Contains(@"--sdl"); using (GameHost host = Host.GetSuitableHost(@"sample-game", useSdl: useSdl)) using (Game game = new SampleGameGame()) host.Run(game); } } } ```
ac607b1a-ed02-46d3-b8e3-0f5180ce5e7b
{ "language": "C#" }
```c# using System.Windows.Forms; namespace Palaso.UI.WindowsForms.WritingSystems { public partial class WSPropertiesTabControl : UserControl { private WritingSystemSetupModel _model; public WSPropertiesTabControl() { InitializeComponent(); } public void BindToModel(WritingSystemSetupModel model) { _model = model; _identifiersControl.BindToModel(_model); _fontControl.BindToModel(_model); _keyboardControl.BindToModel(_model); _sortControl.BindToModel(_model); _spellingControl.BindToModel(_model); } } } ``` Hide irrelevant tabs when the Writing System is a voice one.
```c# using System; using System.Windows.Forms; namespace Palaso.UI.WindowsForms.WritingSystems { public partial class WSPropertiesTabControl : UserControl { private WritingSystemSetupModel _model; public WSPropertiesTabControl() { InitializeComponent(); } public void BindToModel(WritingSystemSetupModel model) { if (_model != null) { _model.SelectionChanged -= ModelChanged; _model.CurrentItemUpdated -= ModelChanged; } _model = model; _identifiersControl.BindToModel(_model); _fontControl.BindToModel(_model); _keyboardControl.BindToModel(_model); _sortControl.BindToModel(_model); _spellingControl.BindToModel(_model); if (_model != null) { _model.SelectionChanged+= ModelChanged; _model.CurrentItemUpdated += ModelChanged; } this.Disposed += OnDisposed; } private void ModelChanged(object sender, EventArgs e) { if( !_model.CurrentIsVoice && _tabControl.Controls.Contains(_spellingPage)) { return;// don't mess if we really don't need a change } _tabControl.Controls.Clear(); this._tabControl.Controls.Add(this._identifiersPage); if( !_model.CurrentIsVoice) { this._tabControl.Controls.Add(this._spellingPage); this._tabControl.Controls.Add(this._fontsPage); this._tabControl.Controls.Add(this._keyboardsPage); this._tabControl.Controls.Add(this._sortingPage); } } void OnDisposed(object sender, EventArgs e) { if (_model != null) _model.SelectionChanged -= ModelChanged; } } } ```
974c170e-726c-489b-9898-9d6c5b40ab82
{ "language": "C#" }
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MultiplyIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { Tensor<int> result = new Tensor<int>(); result.SetValue(tensor1.GetValue() * tensor2.GetValue()); return result; } } } ``` Refactor Multiply Integers Operation to use GetValues and CloneWithValues
```c# namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MultiplyIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { int[] values1 = tensor1.GetValues(); int l = values1.Length; int value2 = tensor2.GetValue(); int[] newvalues = new int[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] * value2; return tensor1.CloneWithNewValues(newvalues); } } } ```
81d3ce9a-d959-40b6-906f-5f4d2a20cda1
{ "language": "C#" }
```c# using System; using System.Linq; using System.Threading; using Moq; using SignalR.Client.Transports; using SignalR.Hosting.Memory; using Xunit; namespace SignalR.Client.Tests { public class ConnectionFacts { public class Start { [Fact] public void FailsIfProtocolVersionIsNull() { var connection = new Connection("http://test"); var transport = new Mock<IClientTransport>(); transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = null })); var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait()); var ex = aggEx.Unwrap(); Assert.IsType(typeof(InvalidOperationException), ex); Assert.Equal("Incompatible protocol version.", ex.Message); } } public class Received { [Fact] public void SendingBigData() { var host = new MemoryHost(); host.MapConnection<SampleConnection>("/echo"); var connection = new Connection("http://foo/echo"); var wh = new ManualResetEventSlim(); var n = 0; var target = 20; connection.Received += data => { n++; if (n == target) { wh.Set(); } }; connection.Start(host).Wait(); var conn = host.ConnectionManager.GetConnection<SampleConnection>(); for (int i = 0; i < target; ++i) { var node = new BigData(); conn.Broadcast(node).Wait(); Thread.Sleep(1000); } Assert.True(wh.Wait(TimeSpan.FromMinutes(1)), "Timed out"); } public class BigData { public string[] Dummy { get { return Enumerable.Range(0, 1000).Select(x => new String('*', 500)).ToArray(); } } } public class SampleConnection : PersistentConnection { } } } } ``` Remove sending big data test.
```c# using System; using System.Linq; using System.Threading; using Moq; using SignalR.Client.Transports; using SignalR.Hosting.Memory; using Xunit; namespace SignalR.Client.Tests { public class ConnectionFacts { public class Start { [Fact] public void FailsIfProtocolVersionIsNull() { var connection = new Connection("http://test"); var transport = new Mock<IClientTransport>(); transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = null })); var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait()); var ex = aggEx.Unwrap(); Assert.IsType(typeof(InvalidOperationException), ex); Assert.Equal("Incompatible protocol version.", ex.Message); } } } } ```
9d2b1fef-47ef-4cf0-8186-bd3ac32161b9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using Baseline; using Confluent.Kafka; using Jasper.Configuration; using Jasper.Runtime.Routing; namespace Jasper.ConfluentKafka.Internal { public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration> { //Dictionary<Uri, ProducerConfig> producerConfigs; //public KafkaTopicRouter(Dictionary<Uri, ProducerConfig> producerConfigs) //{ //} public override Uri BuildUriForTopic(string topicName) { var endpoint = new KafkaEndpoint { IsDurable = true, TopicName = topicName }; return endpoint.Uri; } public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName, IEndpoints endpoints) { var uri = BuildUriForTopic(topicName); var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri); return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint); } } } ``` Remove commented code and unused usings
```c# using System; using Baseline; using Jasper.Configuration; using Jasper.Runtime.Routing; namespace Jasper.ConfluentKafka.Internal { public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration> { public override Uri BuildUriForTopic(string topicName) { var endpoint = new KafkaEndpoint { IsDurable = true, TopicName = topicName }; return endpoint.Uri; } public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName, IEndpoints endpoints) { var uri = BuildUriForTopic(topicName); var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri); return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint); } } } ```
b1592876-e366-49e9-b3e2-a879527b7fb8
{ "language": "C#" }
```c# using System.IO; using MiniCover.Model; using Newtonsoft.Json; namespace MiniCover.CommandLine.Options { class CoverageLoadedFileOption : CoverageFileOption { public InstrumentationResult Result { get; private set; } protected override FileInfo PrepareValue(string value) { var fileInfo = base.PrepareValue(value); if (!fileInfo.Exists) throw new FileNotFoundException($"Coverage file does not exist '{fileInfo.FullName}'"); var coverageFileString = File.ReadAllText(fileInfo.FullName); Result = JsonConvert.DeserializeObject<InstrumentationResult>(coverageFileString); return fileInfo; } } }``` Improve error message when coverage is not found
```c# using System.IO; using MiniCover.Exceptions; using MiniCover.Model; using Newtonsoft.Json; namespace MiniCover.CommandLine.Options { class CoverageLoadedFileOption : CoverageFileOption { public InstrumentationResult Result { get; private set; } protected override FileInfo PrepareValue(string value) { var fileInfo = base.PrepareValue(value); if (!fileInfo.Exists) throw new ValidationException($"Coverage file does not exist '{fileInfo.FullName}'"); var coverageFileString = File.ReadAllText(fileInfo.FullName); Result = JsonConvert.DeserializeObject<InstrumentationResult>(coverageFileString); return fileInfo; } } }```
121be4dd-b641-4de6-9edd-a2239a6c6d77
{ "language": "C#" }
```c# using System.Collections; using System.Collections.Generic; using UnityEngine; using Zenject; public class FollowTarget : MonoBehaviour { [Inject] public ForceSelector ForceSelector { get; set; } public Rigidbody targetRb; public float distanceToReset = 0.1f; public float velocityThresh; public float moveToTargetSpeed; public bool isAtTarget; void Update () { isAtTarget = Vector3.Distance(targetRb.transform.position, transform.position) <= distanceToReset; if (targetRb.velocity.magnitude < velocityThresh && !isAtTarget) { transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed); } ForceSelector.IsRunning = isAtTarget; } } ``` Fix force selector reset clipping error.
```c# using System; using System.Collections; using System.Collections.Generic; using UniRx; using UnityEngine; using Zenject; public class FollowTarget : MonoBehaviour { [Inject] public ForceSelector ForceSelector { get; set; } public Rigidbody targetRb; public float velocityThresh; public float moveToTargetSpeed; public float distanceToResume; public float distanceToReset; private IDisposable sub; void Start() { sub = Observable .IntervalFrame(5) .Select(_ => Vector3.Distance(targetRb.transform.position, transform.position)) .Hysteresis((d, referenceDist) => d - referenceDist, distanceToResume, distanceToReset) .Subscribe(isMoving => { ForceSelector.IsRunning = !isMoving; }); } void OnDestroy() { if (sub != null) { sub.Dispose(); sub = null; } } void Update () { if (targetRb.velocity.magnitude < velocityThresh && !ForceSelector.IsRunning) { transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed); } } } ```
ea52fb27-fdd3-44ee-b16e-88de70efa435
{ "language": "C#" }
```c# using Bands.Output; using System; namespace Bands.GettingStarted { class Program { static void Main(string[] args) { Console.WriteLine("Getting started with Bands!"); var payload = new CounterPayload(); var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo); var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand); var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand); outerConsoleBand.Enter(payload); Console.WriteLine("Kinda badass, right?"); Console.Read(); } public static void CallAddTwo(CounterPayload payload) { Console.WriteLine("Calling payload.AddTwo()"); payload.AddTwo(); } } } ``` Remove profanity - don't want to alienate folk
```c# using Bands.Output; using System; namespace Bands.GettingStarted { class Program { static void Main(string[] args) { Console.WriteLine("Getting started with Bands!"); var payload = new CounterPayload(); var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo); var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand); var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand); outerConsoleBand.Enter(payload); Console.WriteLine("Kinda awesome, right?"); Console.Read(); } public static void CallAddTwo(CounterPayload payload) { Console.WriteLine("Calling payload.AddTwo()"); payload.AddTwo(); } } } ```
ba41e364-8f21-4bd3-af07-8a29122d2a37
{ "language": "C#" }
```c# using NUnit.Framework; using System; using System.Linq.Expressions; using TestStack.FluentMVCTesting.Internal; namespace TestStack.FluentMVCTesting.Tests.Internal { [TestFixture] public class ExpressionInspectorShould { [Test] public void Correctly_parse_equality_comparison_with_string_operands() { Expression<Func<string, bool>> func = text => text == "any"; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("text => text == \"any\"", actual); } [Test] public void Correctly_parse_equality_comparison_with_int_operands() { Expression<Func<int, bool>> func = number => number == 5; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("number => number == 5", actual); } } }``` Support for parsing inequality operator with integral operands.
```c# using NUnit.Framework; using System; using System.Linq.Expressions; using TestStack.FluentMVCTesting.Internal; namespace TestStack.FluentMVCTesting.Tests.Internal { [TestFixture] public class ExpressionInspectorShould { [Test] public void Correctly_parse_equality_comparison_with_string_operands() { Expression<Func<string, bool>> func = text => text == "any"; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("text => text == \"any\"", actual); } [Test] public void Correctly_parse_equality_comparison_with_int_operands() { Expression<Func<int, bool>> func = number => number == 5; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("number => number == 5", actual); } [Test] public void Correctly_parse_inequality_comparison_with_int_operands() { Expression<Func<int, bool>> func = number => number != 5; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("number => number != 5", actual); } } }```
4c6beeb3-da89-420f-9e36-ef902dc2e791
{ "language": "C#" }
```c# using indice.Edi.Serialization; using System; using System.Collections.Generic; namespace indice.Edi.Tests.Models { public class Interchange_ORDRSP { public Message_ORDRSP Message { get; set; } } [EdiMessage] public class Message_ORDRSP { [EdiCondition("Z01", Path = "IMD/1/0")] [EdiCondition("Z10", Path = "IMD/1/0")] public List<IMD> IMD_List { get; set; } [EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")] public IMD IMD_Other { get; set; } /// <summary> /// Item Description /// </summary> [EdiSegment, EdiPath("IMD")] public class IMD { [EdiValue(Path = "IMD/0")] public string FieldA { get; set; } [EdiValue(Path = "IMD/1")] public string FieldB { get; set; } [EdiValue(Path = "IMD/2")] public string FieldC { get; set; } } } } ``` Fix failing test ORDRSP after change on Condition stacking behavior
```c# using indice.Edi.Serialization; using System; using System.Collections.Generic; namespace indice.Edi.Tests.Models { public class Interchange_ORDRSP { public Message_ORDRSP Message { get; set; } } [EdiMessage] public class Message_ORDRSP { [EdiCondition("Z01", "Z10", Path = "IMD/1/0")] public List<IMD> IMD_List { get; set; } [EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")] public IMD IMD_Other { get; set; } /// <summary> /// Item Description /// </summary> [EdiSegment, EdiPath("IMD")] public class IMD { [EdiValue(Path = "IMD/0")] public string FieldA { get; set; } [EdiValue(Path = "IMD/1")] public string FieldB { get; set; } [EdiValue(Path = "IMD/2")] public string FieldC { get; set; } } } } ```
be52240b-712b-4776-91d3-a62ed933e0eb
{ "language": "C#" }
```c# using System; using System.Diagnostics; using Serilog; using Topshelf; namespace Thinktecture.Relay.OnPremiseConnectorService { internal static class Program { private static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); try { HostFactory.Run(config => { config.UseSerilog(); config.Service<OnPremisesService>(settings => { settings.ConstructUsing(_ => new OnPremisesService()); settings.WhenStarted(async s => await s.StartAsync().ConfigureAwait(false)); settings.WhenStopped(s => s.Stop()); }); config.RunAsNetworkService(); config.SetDescription("Thinktecture Relay OnPremises Service"); config.SetDisplayName("Thinktecture Relay OnPremises Service"); config.SetServiceName("TTRelayOnPremisesService"); }); } catch (Exception ex) { Log.Logger.Fatal(ex, "Service crashed"); } finally { Log.CloseAndFlush(); } Log.CloseAndFlush(); #if DEBUG if (Debugger.IsAttached) { // ReSharper disable once LocalizableElement Console.WriteLine("\nPress any key to close application window..."); Console.ReadKey(true); } #endif } } } ``` Make sure that On-Premise Connector cleans up on Windows shutdown
```c# using System; using System.Diagnostics; using Serilog; using Topshelf; namespace Thinktecture.Relay.OnPremiseConnectorService { internal static class Program { private static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); try { HostFactory.Run(config => { config.UseSerilog(); config.EnableShutdown(); config.Service<OnPremisesService>(settings => { settings.ConstructUsing(_ => new OnPremisesService()); settings.WhenStarted(async s => await s.StartAsync().ConfigureAwait(false)); settings.WhenStopped(s => s.Stop()); settings.WhenShutdown(s => s.Stop()); }); config.RunAsNetworkService(); config.SetDescription("Thinktecture Relay OnPremises Service"); config.SetDisplayName("Thinktecture Relay OnPremises Service"); config.SetServiceName("TTRelayOnPremisesService"); }); } catch (Exception ex) { Log.Logger.Fatal(ex, "Service crashed"); } finally { Log.CloseAndFlush(); } Log.CloseAndFlush(); #if DEBUG if (Debugger.IsAttached) { // ReSharper disable once LocalizableElement Console.WriteLine("\nPress any key to close application window..."); Console.ReadKey(true); } #endif } } } ```
85a471eb-481b-49f8-a807-515732dd8abf
{ "language": "C#" }
```c# namespace Suriyun.UnityIAP { public class IAPNetworkMessageId { public const short ToServerBuyProductMsgId = 3000; public const short ToServerRequestProducts = 3001; public const short ToClientResponseProducts = 3002; } } ``` Set message id by official's highest
```c# using UnityEngine.Networking; namespace Suriyun.UnityIAP { public class IAPNetworkMessageId { // Developer can changes these Ids to avoid hacking while hosting public const short ToServerBuyProductMsgId = MsgType.Highest + 201; public const short ToServerRequestProducts = MsgType.Highest + 202; public const short ToClientResponseProducts = MsgType.Highest + 203; } } ```
9786ad76-9d42-4044-9ca3-a3c85077cae5
{ "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.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays { public class HoldNoteMask : HitObjectMask { private readonly BodyPiece body; public HoldNoteMask(DrawableHoldNote hold) : base(hold) { Position = hold.Position; var holdObject = hold.HitObject; InternalChildren = new Drawable[] { new NoteMask(hold.Head), new NoteMask(hold.Tail), body = new BodyPiece { AccentColour = Color4.Transparent }, }; holdObject.ColumnChanged += _ => Position = hold.Position; } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; } } } ``` Fix hold note masks not working
```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.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays { public class HoldNoteMask : HitObjectMask { private readonly BodyPiece body; public HoldNoteMask(DrawableHoldNote hold) : base(hold) { var holdObject = hold.HitObject; InternalChildren = new Drawable[] { new HoldNoteNoteMask(hold.Head), new HoldNoteNoteMask(hold.Tail), body = new BodyPiece { AccentColour = Color4.Transparent }, }; holdObject.ColumnChanged += _ => Position = hold.Position; } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; } protected override void Update() { base.Update(); Size = HitObject.DrawSize; Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft); } private class HoldNoteNoteMask : NoteMask { public HoldNoteNoteMask(DrawableNote note) : base(note) { Select(); } protected override void Update() { base.Update(); Position = HitObject.DrawPosition; } } } } ```
6bfee597-c197-4717-b182-2e8eb38c2aae
{ "language": "C#" }
```c# using RimWorld; using Verse; namespace PrepareLanding.Defs { /// <summary> /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing /// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml"). /// </summary> public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld { public override void Activate() { // default behavior base.Activate(); // do not show the main window if in tutorial mode if (TutorSystem.TutorialMode) { Log.Message( "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window."); return; } // show the main window, minimized. PrepareLanding.Instance.MainWindow.Show(true); } } } ``` Fix bug where window instance was null on world map.
```c# using RimWorld; using Verse; namespace PrepareLanding.Defs { /// <summary> /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing /// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml"). /// </summary> public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld { public override void Activate() { // default behavior (go to the world map) base.Activate(); // do not show the main window if in tutorial mode if (TutorSystem.TutorialMode) { Log.Message( "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window."); return; } // don't add a new window if the window is already there; if it's not create a new one. if (PrepareLanding.Instance.MainWindow == null) PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData); // show the main window, minimized. PrepareLanding.Instance.MainWindow.Show(true); } } } ```
1c83a4f4-09a4-481b-a0c9-9290aaf9228c
{ "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.Gameplay { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsSlider<double> { LabelText = "Background dim", Bindable = config.GetBindable<double>(OsuSetting.DimLevel), KeyboardStep = 0.1f }, new SettingsSlider<double> { LabelText = "Background blur", Bindable = config.GetBindable<double>(OsuSetting.BlurLevel), KeyboardStep = 0.1f }, new SettingsCheckbox { LabelText = "Show score overlay", Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface) }, new SettingsCheckbox { LabelText = "Always show key overlay", Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay) }, new SettingsCheckbox { LabelText = "Show approach circle on first \"Hidden\" object", Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility) }, }; } } } ``` Reword settings text to be ruleset agnostic
```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.Gameplay { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsSlider<double> { LabelText = "Background dim", Bindable = config.GetBindable<double>(OsuSetting.DimLevel), KeyboardStep = 0.1f }, new SettingsSlider<double> { LabelText = "Background blur", Bindable = config.GetBindable<double>(OsuSetting.BlurLevel), KeyboardStep = 0.1f }, new SettingsCheckbox { LabelText = "Show score overlay", Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface) }, new SettingsCheckbox { LabelText = "Always show key overlay", Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay) }, new SettingsCheckbox { LabelText = "Increase visibility of first object with \"Hidden\" mod", Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility) }, }; } } } ```
c7e5a9bf-9c19-4257-bb15-b5117b430255
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Linq; using Mirage.Urbanization.ZoneStatisticsQuerying; using System.Collections.Immutable; namespace Mirage.Urbanization.Simulation.Persistence { public class PersistedCityStatisticsCollection { private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty; private PersistedCityStatisticsWithFinancialData _mostRecentStatistics; public void Add(PersistedCityStatisticsWithFinancialData statistics) { _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics); if (_persistedCityStatistics.Count() > 5200) _persistedCityStatistics = _persistedCityStatistics.Dequeue(); _mostRecentStatistics = statistics; } public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics() { return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics); } public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll() { return _persistedCityStatistics; } } }``` Reduce the amount of persisted city statistics
```c# using System.Collections.Generic; using System.Linq; using Mirage.Urbanization.ZoneStatisticsQuerying; using System.Collections.Immutable; namespace Mirage.Urbanization.Simulation.Persistence { public class PersistedCityStatisticsCollection { private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty; private PersistedCityStatisticsWithFinancialData _mostRecentStatistics; public void Add(PersistedCityStatisticsWithFinancialData statistics) { _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics); if (_persistedCityStatistics.Count() > 960) _persistedCityStatistics = _persistedCityStatistics.Dequeue(); _mostRecentStatistics = statistics; } public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics() { return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics); } public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll() { return _persistedCityStatistics; } } }```
a3b22100-9c6a-4218-a711-e8057b39dfa2
{ "language": "C#" }
```c# using FlaUI.Core.Definitions; using FlaUI.Core.Patterns; namespace FlaUI.Core.AutomationElements.PatternElements { /// <summary> /// An element that supports the <see cref="IExpandCollapsePattern"/>. /// </summary> public class ExpandCollapseAutomationElement : AutomationElement { public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement) { } public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern; /// <summary> /// Gets the current expand / collapse state. /// </summary> public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState; /// <summary> /// Expands the element. /// </summary> public void Expand() { ExpandCollapsePattern.Expand(); } /// <summary> /// Collapses the element. /// </summary> public void Collapse() { ExpandCollapsePattern.Expand(); } } } ``` Switch Collapse function to correctly call the Collapse function of the expand pattern
```c# using FlaUI.Core.Definitions; using FlaUI.Core.Patterns; namespace FlaUI.Core.AutomationElements.PatternElements { /// <summary> /// An element that supports the <see cref="IExpandCollapsePattern"/>. /// </summary> public class ExpandCollapseAutomationElement : AutomationElement { public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement) { } public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern; /// <summary> /// Gets the current expand / collapse state. /// </summary> public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState; /// <summary> /// Expands the element. /// </summary> public void Expand() { ExpandCollapsePattern.Expand(); } /// <summary> /// Collapses the element. /// </summary> public void Collapse() { ExpandCollapsePattern.Collapse(); } } } ```
19511e59-5d64-46e6-8054-a8296028c6ee
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Core.Logging; using DAL; using Serilog.Events; using Telegram.Bot; namespace Core.Services.Crosspost { public class TelegramCrosspostService : ICrossPostService { private readonly Core.Logging.ILogger _logger; private readonly string _token; private readonly string _name; public TelegramCrosspostService(string token, string name, ILogger logger) { _logger = logger; _token = token; _name = name; } public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags) { var sb = new StringBuilder(); sb.Append(message); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append(link); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append(string.Join(", ", tags)); try { var bot = new TelegramBotClient(_token); await bot.SendTextMessageAsync(_name, sb.ToString()); _logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`"); } catch (Exception ex) { _logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex); } } } }``` Fix tag line for Telegram
```c# using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Core.Logging; using DAL; using Serilog.Events; using Telegram.Bot; namespace Core.Services.Crosspost { public class TelegramCrosspostService : ICrossPostService { private readonly Core.Logging.ILogger _logger; private readonly string _token; private readonly string _name; public TelegramCrosspostService(string token, string name, ILogger logger) { _logger = logger; _token = token; _name = name; } public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags) { var sb = new StringBuilder(); sb.Append(message); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append(link); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append(string.Join(" ", tags)); try { var bot = new TelegramBotClient(_token); await bot.SendTextMessageAsync(_name, sb.ToString()); _logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`"); } catch (Exception ex) { _logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex); } } } }```
dd4d8b5e-06b9-4cbb-a9a7-402bea098c5a
{ "language": "C#" }
```c# using System.IO; namespace OmniSharp.DotNetTest.Helpers { internal class ProjectPathResolver { public static string GetProjectPathFromFile(string filepath) { // TODO: revisit this logic, too clumsy var projectFolder = Path.GetDirectoryName(filepath); while (!File.Exists(Path.Combine(projectFolder, "project.json"))) { var parent = Path.GetDirectoryName(filepath); if (parent == projectFolder) { break; } else { projectFolder = parent; } } return projectFolder; } } } ``` Fix incorrect project path resolver
```c# using System.IO; namespace OmniSharp.DotNetTest.Helpers { internal class ProjectPathResolver { public static string GetProjectPathFromFile(string filepath) { // TODO: revisit this logic, too clumsy var projectFolder = Path.GetDirectoryName(filepath); while (!File.Exists(Path.Combine(projectFolder, "project.json"))) { var parent = Path.GetDirectoryName(projectFolder); if (parent == projectFolder) { break; } else { projectFolder = parent; } } return projectFolder; } } } ```
b02fb6b7-48a1-4967-be4a-ddd9570a3104
{ "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. #nullable disable using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; namespace osu.Game.Tests.Visual.Gameplay { public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene { protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUp] public void SetUp() => Schedule(() => { SetContents(skin => { var implementation = skin != null ? CreateLegacyImplementation() : CreateDefaultImplementation(); implementation.Anchor = Anchor.Centre; implementation.Origin = Anchor.Centre; return implementation; }); }); protected abstract Drawable CreateDefaultImplementation(); protected abstract Drawable CreateLegacyImplementation(); } } ``` Fix test failure due to triangle skin no longer being null intests
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Skinning; namespace osu.Game.Tests.Visual.Gameplay { public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene { protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUp] public void SetUp() => Schedule(() => { SetContents(skin => { var implementation = skin is not TrianglesSkin ? CreateLegacyImplementation() : CreateDefaultImplementation(); implementation.Anchor = Anchor.Centre; implementation.Origin = Anchor.Centre; return implementation; }); }); protected abstract Drawable CreateDefaultImplementation(); protected abstract Drawable CreateLegacyImplementation(); } } ```
1918cbac-47d9-4a42-a440-8ad94e4e0d41
{ "language": "C#" }
```c# using AutoMapper; using Umbraco.Core.Models; using Umbraco.Web.Composing; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Routing; namespace Umbraco.Web.Models.Mapping { internal class RedirectUrlMapperProfile : Profile { public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor) { CreateMap<IRedirectUrl, ContentRedirectUrl>() .ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture))) .ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#")) .ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key)); } private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.ContentId, item.Culture); } } ``` Revert "the wrong id was used for getting the correct destination url."
```c# using AutoMapper; using Umbraco.Core.Models; using Umbraco.Web.Composing; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Routing; namespace Umbraco.Web.Models.Mapping { internal class RedirectUrlMapperProfile : Profile { public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor) { CreateMap<IRedirectUrl, ContentRedirectUrl>() .ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture))) .ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#")) .ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key)); } private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.Id, item.Culture); } } ```
edcc8ea2-d9df-49fb-861d-b33ca444de67
{ "language": "C#" }
```c# using CommandLine; using CSharpLLVM.Compilation; using System.IO; namespace CSharpLLVM { class Program { /// <summary> /// Entrypoint. /// </summary> /// <param name="args">Arguments.</param> static void Main(string[] args) { Options options = new Options(); Parser parser = new Parser(setSettings); if (parser.ParseArguments(args, options)) { string moduleName = Path.GetFileNameWithoutExtension(options.InputFile); Compiler compiler = new Compiler(options); compiler.Compile(moduleName); } } /// <summary> /// Sets the settings. /// </summary> /// <param name="settings">The settings.</param> private static void setSettings(ParserSettings settings) { settings.MutuallyExclusive = true; } } } ``` Print usage when parsing did not go right.
```c# using CommandLine; using CSharpLLVM.Compilation; using System; using System.IO; namespace CSharpLLVM { class Program { /// <summary> /// Entrypoint. /// </summary> /// <param name="args">Arguments.</param> static void Main(string[] args) { Options options = new Options(); Parser parser = new Parser(setSettings); if (parser.ParseArguments(args, options)) { string moduleName = Path.GetFileNameWithoutExtension(options.InputFile); Compiler compiler = new Compiler(options); compiler.Compile(moduleName); } else { Console.WriteLine(options.GetUsage()); } } /// <summary> /// Sets the settings. /// </summary> /// <param name="settings">The settings.</param> private static void setSettings(ParserSettings settings) { settings.MutuallyExclusive = true; } } } ```
a6ff90d6-e878-4eb7-80e0-a36f6d9d6d06
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Snowflake.Ajax { public class JSResponse : IJSResponse { public IJSRequest Request { get; private set; } public dynamic Payload { get; private set; } public bool Success { get; set; } public JSResponse(IJSRequest request, dynamic payload, bool success = true) { this.Request = request; this.Payload = payload; this.Success = success; } public string GetJson() { return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request); } private static string ProcessJSONP(dynamic output, bool success, IJSRequest request) { if (request.MethodParameters.ContainsKey("jsoncallback")) { return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){ {"payload", output}, {"success", success} }) + ");"; } else { return JsonConvert.SerializeObject(new Dictionary<string, object>(){ {"payload", output}, {"success", success} }); } } } } ``` Add request and 'methodresponse' type in JSON body to account for other response types using the WebSocket APIs
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Snowflake.Ajax { public class JSResponse : IJSResponse { public IJSRequest Request { get; private set; } public dynamic Payload { get; private set; } public bool Success { get; set; } public JSResponse(IJSRequest request, dynamic payload, bool success = true) { this.Request = request; this.Payload = payload; this.Success = success; } public string GetJson() { return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request); } private static string ProcessJSONP(dynamic output, bool success, IJSRequest request) { if (request.MethodParameters.ContainsKey("jsoncallback")) { return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){ {"request", request}, {"payload", output}, {"success", success}, {"type", "methodresponse"} }) + ");"; } else { return JsonConvert.SerializeObject(new Dictionary<string, object>(){ {"request", request}, {"payload", output}, {"success", success}, {"type", "methodresponse"} }); } } } } ```
7f819f54-bed7-4bc0-ad9f-f423e0a7e8d7
{ "language": "C#" }
```c# using System.Web.Mvc; using System.Net; using Newtonsoft.Json; using System.IO; using System.Collections.Generic; using Newtonsoft.Json.Linq; using System.Linq; using System.Web.Caching; using System; namespace Website.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Benefits() { return View(); } public ActionResult Download() { return View(); } public ActionResult Licensing() { return View(); } public ActionResult Support() { return View(); } public ActionResult Contact() { return View(); } public ActionResult Donate() { var contributors = HttpContext.Cache.Get("github.contributors") as IEnumerable<Contributor>; if (contributors == null) { var url = "https://api.github.com/repos/andrewdavey/cassette/contributors"; var client = new WebClient(); var json = client.DownloadString(url); contributors = JsonConvert.DeserializeObject<IEnumerable<Contributor>>(json); HttpContext.Cache.Insert("github.contributors", contributors, null, Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1)); } ViewBag.Contributors = contributors; return View(); } public ActionResult Resources() { return View(); } } public class Contributor { public string avatar_url { get; set; } public string login { get; set; } public string url { get; set; } } } ``` Tidy up github api calling code
```c# using System; using System.Collections.Generic; using System.Net; using System.Web.Caching; using System.Web.Mvc; using Newtonsoft.Json; namespace Website.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Benefits() { return View(); } public ActionResult Download() { return View(); } public ActionResult Licensing() { return View(); } public ActionResult Support() { return View(); } public ActionResult Contact() { return View(); } public ActionResult Donate() { var contributors = GetContributors(); ViewBag.Contributors = contributors; return View(); } IEnumerable<Contributor> GetContributors() { const string cacheKey = "github.contributors"; var contributors = HttpContext.Cache.Get(cacheKey) as IEnumerable<Contributor>; if (contributors != null) return contributors; var json = DownoadContributorsJson(); contributors = JsonConvert.DeserializeObject<IEnumerable<Contributor>>(json); HttpContext.Cache.Insert( cacheKey, contributors, null, Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1) ); return contributors; } static string DownoadContributorsJson() { using (var client = new WebClient()) { return client.DownloadString("https://api.github.com/repos/andrewdavey/cassette/contributors"); } } public ActionResult Resources() { return View(); } } public class Contributor { public string avatar_url { get; set; } public string login { get; set; } public string url { get; set; } } }```
1422cd7f-6d91-4c60-a832-ddee7558e141
{ "language": "C#" }
```c# using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("6.1.*")] [assembly: AssemblyFileVersion("6.1.*")]``` Change version number for breaking change.
```c# using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("6.2.*")] [assembly: AssemblyFileVersion("6.2.*")]```
5329131a-51e8-4a92-88b2-0ca082507fef
{ "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.Management.Compute.Models; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.Compute.Models { enum EncryptionStatus { Encrypted, NotEncrypted, NotMounted, EncryptionInProgress, VMRestartPending, Unknown } class AzureDiskEncryptionStatusContext { public EncryptionStatus OsVolumeEncrypted { get; set; } public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; } public EncryptionStatus DataVolumesEncrypted { get; set; } public string ProgressMessage { get; set; } } } ``` Add DecryptionInProgress for EncryptionStatus enum
```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.Management.Compute.Models; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.Compute.Models { enum EncryptionStatus { Encrypted, NotEncrypted, NotMounted, DecryptionInProgress, EncryptionInProgress, VMRestartPending, Unknown } class AzureDiskEncryptionStatusContext { public EncryptionStatus OsVolumeEncrypted { get; set; } public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; } public EncryptionStatus DataVolumesEncrypted { get; set; } public string ProgressMessage { get; set; } } } ```
66d45c09-a57a-4e0e-be53-05f70199af1b
{ "language": "C#" }
```c# @using CkanDotNet.Api.Model @using CkanDotNet.Web.Models @using CkanDotNet.Web.Models.Helpers @model Package @{ bool editable = Convert.ToBoolean(ViewData["editable"]); string ratingId = GuidHelper.GetUniqueKey(16); } @if (Model.RatingsAverage.HasValue || editable) { <div id="@ratingId" class="rating"> @{ int rating = 0; if (Model.RatingsAverage.HasValue) { rating = (int)Math.Round(Model.RatingsAverage.Value); } } @for (int i = 1; i <= 5; i++) { @Html.RadioButton("newrate", i, rating == i) } </div> <span class="rating-response"></span> } <script language="javascript"> $("#@(ratingId)").stars({ oneVoteOnly: true, @if (!editable) { @:disabled: true, } callback: function(ui, type, value){ var url = "http://@SettingsHelper.GetRepositoryHost()/package/rate/@Model.Name?rating=" + value; $("#@(ratingId)_iframe").get(0).src = url; $(".rating-response").text("Thanks for your rating!"); } }); </script> @if (editable) { <iframe id="@(ratingId)_iframe" width="0" height="0" frameborder="0" src=""></iframe> }``` Add analytics event for package rate
```c# @using CkanDotNet.Api.Model @using CkanDotNet.Web.Models @using CkanDotNet.Web.Models.Helpers @model Package @{ bool editable = Convert.ToBoolean(ViewData["editable"]); string ratingId = GuidHelper.GetUniqueKey(16); } @if (Model.RatingsAverage.HasValue || editable) { <div id="@ratingId" class="rating"> @{ int rating = 0; if (Model.RatingsAverage.HasValue) { rating = (int)Math.Round(Model.RatingsAverage.Value); } } @for (int i = 1; i <= 5; i++) { @Html.RadioButton("newrate", i, rating == i) } </div> <span class="rating-response"></span> } <script language="javascript"> $("#@(ratingId)").stars({ oneVoteOnly: true, @if (!editable) { @:disabled: true, } callback: function(ui, type, value){ var url = "http://@SettingsHelper.GetRepositoryHost()/package/rate/@Model.Name?rating=" + value; $("#@(ratingId)_iframe").get(0).src = url; $(".rating-response").text("Thanks for your rating!"); // Track the rating event in analytics debugger; _gaq.push([ '_trackEvent', 'Package:@Model.Name', 'Rate', value, value]); } }); </script> @if (editable) { <iframe id="@(ratingId)_iframe" width="0" height="0" frameborder="0" src=""></iframe> }```
6a0cdc8b-a28e-447e-b727-eeb92ed695ff
{ "language": "C#" }
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.HUD; using EOLib; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.UIControls { public class StatusBarLabel : XNALabel { private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; private readonly IStatusLabelTextProvider _statusLabelTextProvider; public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider, IStatusLabelTextProvider statusLabelTextProvider) : base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07) { _statusLabelTextProvider = statusLabelTextProvider; } public override void Update(GameTime gameTime) { if (Text != _statusLabelTextProvider.StatusText) { Text = _statusLabelTextProvider.StatusText; Visible = true; } if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) Visible = false; base.Update(gameTime); } private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider) { return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1); } } } ``` Check if status label is constructed before executing update
```c# // Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.HUD; using EOLib; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.UIControls { public class StatusBarLabel : XNALabel { private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; private readonly IStatusLabelTextProvider _statusLabelTextProvider; private readonly bool _constructed; public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider, IStatusLabelTextProvider statusLabelTextProvider) : base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07) { _statusLabelTextProvider = statusLabelTextProvider; _constructed = true; } public override void Update(GameTime gameTime) { if (!_constructed) return; if (Text != _statusLabelTextProvider.StatusText) { Text = _statusLabelTextProvider.StatusText; Visible = true; } if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) Visible = false; base.Update(gameTime); } private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider) { return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1); } } } ```
469f8328-d7d7-47ab-9e91-a7e4176aeba9
{ "language": "C#" }
```c# using System; using System.ServiceModel.Channels; namespace Microsoft.ApplicationInsights.Wcf.Implementation { internal static class WcfExtensions { public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation) { if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) ) { return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name); } return null; } public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation) { if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) ) { return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name); } return null; } } } ``` Handle ObjectDisposedException just in case we do end up trying to read properties of a closed message
```c# using System; using System.ServiceModel.Channels; namespace Microsoft.ApplicationInsights.Wcf.Implementation { internal static class WcfExtensions { public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation) { try { if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) ) { return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name); } } catch ( ObjectDisposedException ) { // WCF message is already disposed, just avoid it } return null; } public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation) { try { if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) ) { return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name); } } catch ( ObjectDisposedException ) { // WCF message is already disposed, just avoid it } return null; } } } ```
7e6bbcb4-6f6c-4439-87be-75d12991c0ff
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Arf.Services; using Microsoft.ProjectOxford.Vision.Contract; namespace Arf.Console { class Program { public static bool IsProcessing; public static void Main(string[] args) { System.Console.ForegroundColor = ConsoleColor.Yellow; System.Console.WriteLine("Please write image Url or local path"); while (true) { if (IsProcessing) continue; System.Console.ResetColor(); var imgPath = System.Console.ReadLine(); Run(imgPath); System.Console.ForegroundColor = ConsoleColor.DarkGray; System.Console.WriteLine("It takes a few time.Please wait!"); System.Console.ResetColor(); } } public static async void Run(string imgPath) { IsProcessing = true; var isUpload = imgPath != null && !imgPath.StartsWith("http"); var service = new VisionService(); var analysisResult = isUpload ? await service.UploadAndDescripteImage(imgPath) : await service.DescripteUrl(imgPath); System.Console.ForegroundColor = ConsoleColor.DarkGreen; System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => s = "#" + s))); System.Console.ResetColor(); IsProcessing = false; } } } ``` Test console Run method updated
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Arf.Services; using Microsoft.ProjectOxford.Vision.Contract; namespace Arf.Console { class Program { public static bool IsProcessing; public static void Main(string[] args) { System.Console.ForegroundColor = ConsoleColor.Yellow; System.Console.WriteLine("Please write image Url or local path"); while (true) { if (IsProcessing) continue; System.Console.ResetColor(); var imgPath = System.Console.ReadLine(); Run(imgPath); System.Console.ForegroundColor = ConsoleColor.DarkGray; System.Console.WriteLine("It takes a few time.Please wait!"); System.Console.ResetColor(); } } public static async void Run(string imgPath) { IsProcessing = true; var isUpload = imgPath != null && !imgPath.StartsWith("http"); var service = new VisionService(); var analysisResult = isUpload ? await service.UploadAndDescripteImage(imgPath) : await service.DescripteUrl(imgPath); System.Console.ForegroundColor = ConsoleColor.DarkGreen; System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => $"#{s}"))); System.Console.ResetColor(); IsProcessing = false; } } } ```
3117b6df-8003-493d-8583-7097f95d4786
{ "language": "C#" }
```c# using System; namespace DarkMultiPlayerServer { public class DarkLog { public static void Debug(string message) { #if DEBUG float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f; Console.WriteLine("[" + currentTime + "] Debug: " + message); #endif } public static void Normal(string message) { float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f; Console.WriteLine("[" + currentTime + "] Normal: " + message); } } } ``` Make debugging output show up on release builds
```c# using System; namespace DarkMultiPlayerServer { public class DarkLog { public static void Debug(string message) { float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f; Console.WriteLine("[" + currentTime + "] Debug: " + message); } public static void Normal(string message) { float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f; Console.WriteLine("[" + currentTime + "] Normal: " + message); } } } ```
e3880579-cef5-460c-b3e2-f7aa7e10b8b9
{ "language": "C#" }
```c# using static System.Console; using CIV.Ccs; using CIV.Interfaces; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var trace = CcsFacade.RandomTrace(processes["Prison"], 450); foreach (var action in trace) { WriteLine(action); } } } } ``` Remove RandomTrace stuff from Main
```c# using static System.Console; using CIV.Ccs; using CIV.Hml; namespace CIV { class Program { static void Main(string[] args) { var text = System.IO.File.ReadAllText(args[0]); var processes = CcsFacade.ParseAll(text); var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)"; var prova = HmlFacade.ParseAll(hmlText); WriteLine(prova.Check(processes["Prison"])); } } } ```
021ea8ff-0a3d-4dbc-a0a0-91e991f0b5d4
{ "language": "C#" }
```c# To: @Model.To From: example@website.com Reply-To: another@website.com Subject: @Model.Subject @* NOTE: There MUST be a blank like after the headers and before the content. *@ Hello, This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString() Message follows: @Model.Message Thanks!``` Fix typo in example comment.
```c# To: @Model.To From: example@website.com Reply-To: another@website.com Subject: @Model.Subject @* NOTE: There MUST be a blank line after the headers and before the content. *@ Hello, This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString() Message follows: @Model.Message Thanks!```
825bab8d-541b-440a-92af-4f7f82cdf50c
{ "language": "C#" }
```c# // Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle010 : Puzzle { /// <inheritdoc /> public override string Question => "Find the sum of all the primes below the specified value."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int max; if (!TryParseInt32(args[0], out max) || max < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } Answer = Enumerable.Range(2, max - 2) .Where((p) => Maths.IsPrime(p)) .Select((p) => (long)p) .Sum(); return 0; } } } ``` Refactor puzzle 10 to not use LINQ
```c# // Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle010 : Puzzle { /// <inheritdoc /> public override string Question => "Find the sum of all the primes below the specified value."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int max; if (!TryParseInt32(args[0], out max) || max < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } long sum = 0; for (int n = 2; n < max - 2; n++) { if (Maths.IsPrime(n)) { sum += n; } } Answer = sum; return 0; } } } ```
0d7c078e-c0cf-438c-84c1-3f5dc28f50eb
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace TramlineFive.Common.Converters { public class TimingConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { string[] timings = (string[])value; StringBuilder builder = new StringBuilder(); foreach (string singleTiming in timings) { TimeSpan timing; if (TimeSpan.TryParse((string)singleTiming, out timing)) { TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay; builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes); } } builder.Remove(builder.Length - 2, 2); return builder.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, string language) { return String.Empty; } } } ``` Fix some arrivals showing negative ETA minutes.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace TramlineFive.Common.Converters { public class TimingConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { string[] timings = (string[])value; StringBuilder builder = new StringBuilder(); foreach (string singleTiming in timings) { TimeSpan timing; if (TimeSpan.TryParse((string)singleTiming, out timing)) { TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay; builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes < 0 ? 0 : timeLeft.Minutes); } } builder.Remove(builder.Length - 2, 2); return builder.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, string language) { return String.Empty; } } } ```
19cf9e0f-ddf6-4ef1-9563-9da6b47bd0cf
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol; using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values; namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model { public abstract class Metric : ICanReportToGoogleAnalytics { public abstract string Name { get; } protected string TrackableName { get { return this.Name.Replace('[', '~').Replace(']', '~'); } } public virtual ParameterTextValue HitType { get { return HitTypeValue.Event; } } public virtual IEnumerable<Parameter> Parameters { get { return new Parameter[] { Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True), Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.TrackableName)) }; } } } } ``` Revert "Try fix for tracking metrics with square brackets in name"
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol; using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values; namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model { public abstract class Metric : ICanReportToGoogleAnalytics { public abstract string Name { get; } public virtual ParameterTextValue HitType { get { return HitTypeValue.Event; } } public virtual IEnumerable<Parameter> Parameters { get { return new Parameter[] { Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True), Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.Name)) }; } } } } ```
cf8da6b6-75b2-4aa8-9299-d7dcf8c84c7f
{ "language": "C#" }
```c# using System; using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using SilentHunter.FileFormats.Dat.Controllers; using SilentHunter.FileFormats.DependencyInjection; namespace SilentHunter.Controllers.Compiler.DependencyInjection { public static class ControllerConfigurerExtensions { public static SilentHunterParsersConfigurer CompileFrom(this ControllerConfigurer controllerConfigurer, string controllerPath, string assemblyName = null, Func<string, bool> ignorePaths = null, params string[] dependencySearchPaths) { AddCSharpCompiler(controllerConfigurer); return controllerConfigurer.FromAssembly(s => { Assembly entryAssembly = Assembly.GetEntryAssembly(); string applicationName = entryAssembly?.GetName().Name ?? "SilentHunter.Controllers"; var assemblyCompiler = new ControllerAssemblyCompiler(s.GetRequiredService<ICSharpCompiler>(), applicationName, controllerPath) { AssemblyName = assemblyName, IgnorePaths = ignorePaths, DependencySearchPaths = dependencySearchPaths }; return new ControllerAssembly(assemblyCompiler.Compile()); }); } private static void AddCSharpCompiler(IServiceCollectionProvider controllerConfigurer) { IServiceCollection services = controllerConfigurer.ServiceCollection; #if NETFRAMEWORK services.TryAddTransient<ICSharpCompiler, CSharpCompiler>(); #else services.TryAddTransient<ICSharpCompiler, RoslynCompiler>(); #endif } } }``` Add option to set app name
```c# using System; using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using SilentHunter.FileFormats.Dat.Controllers; using SilentHunter.FileFormats.DependencyInjection; namespace SilentHunter.Controllers.Compiler.DependencyInjection { public static class ControllerConfigurerExtensions { public static SilentHunterParsersConfigurer CompileFrom(this ControllerConfigurer controllerConfigurer, string controllerPath, string assemblyName = null, string applicationName = null, Func<string, bool> ignorePaths = null, params string[] dependencySearchPaths) { AddCSharpCompiler(controllerConfigurer); return controllerConfigurer.FromAssembly(s => { Assembly entryAssembly = Assembly.GetEntryAssembly(); string appName = applicationName ?? entryAssembly?.GetName().Name ?? "SilentHunter.Controllers"; var assemblyCompiler = new ControllerAssemblyCompiler(s.GetRequiredService<ICSharpCompiler>(), appName, controllerPath) { AssemblyName = assemblyName, IgnorePaths = ignorePaths, DependencySearchPaths = dependencySearchPaths }; return new ControllerAssembly(assemblyCompiler.Compile()); }); } private static void AddCSharpCompiler(IServiceCollectionProvider controllerConfigurer) { IServiceCollection services = controllerConfigurer.ServiceCollection; #if NETFRAMEWORK services.TryAddTransient<ICSharpCompiler, CSharpCompiler>(); #else services.TryAddTransient<ICSharpCompiler, RoslynCompiler>(); #endif } } }```
8e5c10d8-07fc-4fe0-96cd-79e9764fa257
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace LSDStay { public static class PSX { public static Process FindPSX() { Process psx = Process.GetProcessesByName("psxfin").FirstOrDefault(); return psx; } public static IntPtr OpenPSX(Process psx) { int PID = psx.Id; IntPtr psxHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID); } public static void ClosePSX(IntPtr processHandle) { int result = Memory.CloseHandle(processHandle); if (result == 0) { Console.WriteLine("ERROR: Could not close psx handle"); } } } } ``` Add Read and Write methods
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace LSDStay { public static class PSX { public static Process PSXProcess; public static IntPtr PSXHandle; public static bool FindPSX() { PSXProcess = Process.GetProcessesByName("psxfin").FirstOrDefault(); return (PSXProcess != null); } public static bool OpenPSX() { int PID = PSXProcess.Id; PSXHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID); return (PSXHandle != null); } public static void ClosePSX(IntPtr processHandle) { int result = Memory.CloseHandle(processHandle); if (result == 0) { Console.WriteLine("ERROR: Could not close psx handle"); } } public static string Read(IntPtr address, ref byte[] buffer) { int bytesRead = 0; int absoluteAddress = Memory.PSXGameOffset + (int)address; //IntPtr absoluteAddressPtr = new IntPtr(absoluteAddress); Memory.ReadProcessMemory((int)PSXHandle, absoluteAddress, buffer, buffer.Length, ref bytesRead); return "Address " + address.ToString("x2") + " contains " + Memory.FormatToHexString(buffer); } public static string Write(IntPtr address, byte[] data) { int bytesWritten; int absoluteAddress = Memory.PSXGameOffset + (int)address; IntPtr absoluteAddressPtr = new IntPtr(absoluteAddress); Memory.WriteProcessMemory(PSXHandle, absoluteAddressPtr, data, (uint)data.Length, out bytesWritten); return "Address " + address.ToString("x2") + " is now " + Memory.FormatToHexString(data); } } } ```
fe7f23b3-9357-412e-9ffa-5b3185783332
{ "language": "C#" }
```c# using Xunit; namespace VulkanCore.Tests { public class SizeTest { [Fact] public void ImplicitConversions() { const int intVal = 1; const long longVal = 2; Size intSize = intVal; Size longSize = longVal; Assert.Equal(intVal, intSize); Assert.Equal(longVal, longSize); } } } ``` Fix Size test using explicit conversions for assertions
```c# using Xunit; namespace VulkanCore.Tests { public class SizeTest { [Fact] public void ImplicitConversions() { const int intVal = 1; const long longVal = 2; Size intSize = intVal; Size longSize = longVal; Assert.Equal(intVal, (int)intSize); Assert.Equal(longVal, (long)longSize); } } } ```
0b87e5cc-458f-46e6-ac56-7fd4f7a904c4
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork { [Serializable] public class Neuron : INeuron { private readonly ISoma _soma; private readonly IAxon _axon; public Neuron(ISoma soma, IAxon axon) { _soma = soma; _axon = axon; } public virtual double CalculateActivationFunction() { return 0.0; } public void Process() { _axon.ProcessSignal(_soma.CalculateSummation()); } } } ``` Add static factory method for neuron
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork { [Serializable] public class Neuron : INeuron { private readonly ISoma _soma; private readonly IAxon _axon; private Neuron(ISoma soma, IAxon axon) { _soma = soma; _axon = axon; } public static INeuron Create(ISoma soma, IAxon axon) { return new Neuron(soma, axon); } public void Process() { _axon.ProcessSignal(_soma.CalculateSummation()); } } } ```
ef09f37c-739a-4e7a-a6cf-e9e163664d47
{ "language": "C#" }
```c# namespace Discore { public enum DiscordMessageType { Default = 0, RecipientAdd = 1, RecipientRemove = 2, Call = 3, ChannelNameChange = 4, ChannelIconChange = 5, ChannelPinnedMessage = 6, GuildMemberJoin = 7 } } ``` Add message types for nitro boosting and channel following
```c# namespace Discore { public enum DiscordMessageType { Default = 0, RecipientAdd = 1, RecipientRemove = 2, Call = 3, ChannelNameChange = 4, ChannelIconChange = 5, ChannelPinnedMessage = 6, GuildMemberJoin = 7, UserPremiumGuildSubscription = 8, UserPremiumGuildSubscriptionTier1 = 9, UserPremiumGuildSubscriptionTier2 = 10, UserPremiumGuildSubscriptionTier3 = 11, ChannelFollowAdd = 12 } } ```
913d1ecd-b169-4cb9-ba14-763ceff57a3e
{ "language": "C#" }
```c# using NUnit.Framework; using Rivet.Operations; namespace Rivet.Test.Operations { [TestFixture] public sealed class NewUserDefinedFunctionTestFixture { const string SchemaName = "schemaName"; const string FunctionName = "functionName"; const string Definition = "as definition"; [SetUp] public void SetUp() { } [Test] public void ShouldSetPropertiesForNewStoredProcedure() { var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition); Assert.AreEqual(SchemaName, op.SchemaName); Assert.AreEqual(FunctionName, op.Name); Assert.AreEqual(Definition, op.Definition); } [Test] public void ShouldWriteQueryForNewStoredProcedure() { var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition); const string expectedQuery = "create function [schemaName].[functionName] as definition"; Assert.AreEqual(expectedQuery, op.ToQuery()); } } }``` Rename function name in test fixture
```c# using NUnit.Framework; using Rivet.Operations; namespace Rivet.Test.Operations { [TestFixture] public sealed class NewUserDefinedFunctionTestFixture { const string SchemaName = "schemaName"; const string FunctionName = "functionName"; const string Definition = "as definition"; [SetUp] public void SetUp() { } [Test] public void ShouldSetPropertiesForNewUserDefinedFunction() { var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition); Assert.AreEqual(SchemaName, op.SchemaName); Assert.AreEqual(FunctionName, op.Name); Assert.AreEqual(Definition, op.Definition); } [Test] public void ShouldWriteQueryForNewUserDefinedFunction() { var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition); const string expectedQuery = "create function [schemaName].[functionName] as definition"; Assert.AreEqual(expectedQuery, op.ToQuery()); } } }```
721a59b5-e079-4a8c-9ae8-feeda035243a
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using Grpc.Core; using Hello; namespace HelloServer { class HelloServerImpl : HelloService.HelloServiceBase { public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context) { return Task.FromResult(new HelloResp { Result = "Hey " + request.Name }); } public override Task<HelloResp> SayHelloStrict(HelloReq request, ServerCallContext context) { if (request.Name.Length >= 10) { const string msg = "Length of `Name` cannot be more than 10 characters"; throw new RpcException(new Status(StatusCode.InvalidArgument, msg)); } return Task.FromResult(new HelloResp { Result = "Hey " + request.Name }); } } class Program { const int Port = 50051; public static void Main(string[] args) { Server server = new Server { Services = { HelloService.BindService(new HelloServerImpl()) }, Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("Hello server listening on port " + Port); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); server.ShutdownAsync().Wait(); } } } ``` Update server to send proper response
```c# using System; using System.Threading.Tasks; using Grpc.Core; using Hello; namespace HelloServer { class HelloServerImpl : HelloService.HelloServiceBase { public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context) { return Task.FromResult(new HelloResp { Result = "Hey, " + request.Name + "!"}); } public override Task<HelloResp> SayHelloStrict(HelloReq request, ServerCallContext context) { if (request.Name.Length >= 10) { const string msg = "Length of `Name` cannot be more than 10 characters"; throw new RpcException(new Status(StatusCode.InvalidArgument, msg)); } return Task.FromResult(new HelloResp { Result = "Hey, " + request.Name + "!"}); } } class Program { const int Port = 50051; public static void Main(string[] args) { Server server = new Server { Services = { HelloService.BindService(new HelloServerImpl()) }, Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("Hello server listening on port " + Port); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); server.ShutdownAsync().Wait(); } } } ```
f30ab874-be8c-4915-b3db-fe76b6e30e87
{ "language": "C#" }
```c# namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity { } } ``` Add basic fields in Charge's PMD 3DS field
```c# namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity { [JsonProperty("succeeded")] public bool Succeeded { get; set; } [JsonProperty("version")] public string Version { get; set; } } } ```
899ab7fa-f2f5-4c55-899d-601eae7de593
{ "language": "C#" }
```c# using System.Text; using AzureStorage.Blob; using Common; namespace CompetitionPlatform.Data.AzureRepositories.Settings { public static class GeneralSettingsReader { public static T ReadGeneralSettings<T>(string connectionString, string container, string fileName) { var settingsStorage = new AzureBlobStorage(connectionString); var settingsData = settingsStorage.GetAsync(container, fileName).Result.ToBytes(); var str = Encoding.UTF8.GetString(settingsData); return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str); } } } ``` Add a method to get settings from a url.
```c# using System.Net.Http; using System.Text; using AzureStorage.Blob; using Common; using Newtonsoft.Json; namespace CompetitionPlatform.Data.AzureRepositories.Settings { public static class GeneralSettingsReader { public static T ReadGeneralSettings<T>(string connectionString, string container, string fileName) { var settingsStorage = new AzureBlobStorage(connectionString); var settingsData = settingsStorage.GetAsync(container, fileName).Result.ToBytes(); var str = Encoding.UTF8.GetString(settingsData); return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str); } public static T ReadGeneralSettingsFromUrl<T>(string settingsUrl) { var httpClient = new HttpClient(); var settingsString = httpClient.GetStringAsync(settingsUrl).Result; var serviceBusSettings = JsonConvert.DeserializeObject<T>(settingsString); return serviceBusSettings; } } } ```
e24dd198-a7b6-42c5-b5eb-9d7e2c12e890
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Platform { [Ignore("This test does not cover correct GL context acquire/release when run headless.")] public class TestSceneExecutionModes : FrameworkTestScene { private Bindable<ExecutionMode> executionMode; [BackgroundDependencyLoader] private void load(FrameworkConfigManager configManager) { executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); } [Test] public void ToggleModeSmokeTest() { AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded, 2); } } } ``` Add test covering horrible fail scenario
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Platform; using osu.Framework.Threading; namespace osu.Framework.Tests.Visual.Platform { [Ignore("This test does not cover correct GL context acquire/release when run headless.")] public class TestSceneExecutionModes : FrameworkTestScene { private Bindable<ExecutionMode> executionMode; [BackgroundDependencyLoader] private void load(FrameworkConfigManager configManager) { executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode); } [Test] public void ToggleModeSmokeTest() { AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded, 2); } [Test] public void TestRapidSwitching() { ScheduledDelegate switchStep = null; int switchCount = 0; AddStep("install quick switch step", () => { switchStep = Scheduler.AddDelayed(() => { executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded; switchCount++; }, 0, true); }); AddUntilStep("switch count sufficiently high", () => switchCount > 1000); AddStep("remove", () => switchStep.Cancel()); } } } ```
447fda0b-8fbb-4c3b-b680-5da8ef98404e
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Osu.Objects.Drawables { public class DrawableSpinnerTick : DrawableOsuHitObject { public override bool DisplayResult => false; protected DrawableSpinner DrawableSpinner => (DrawableSpinner)ParentHitObject; public DrawableSpinnerTick() : base(null) { } public DrawableSpinnerTick(SpinnerTick spinnerTick) : base(spinnerTick) { } protected override double MaximumJudgementOffset => DrawableSpinner.HitObject.Duration; /// <summary> /// Apply a judgement result. /// </summary> /// <param name="hit">Whether this tick was reached.</param> internal void TriggerResult(bool hit) => ApplyResult(r => r.Type = hit ? r.Judgement.MaxResult : r.Judgement.MinResult); } } ``` Fix spinenr tick samples not positioned at centre
```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; namespace osu.Game.Rulesets.Osu.Objects.Drawables { public class DrawableSpinnerTick : DrawableOsuHitObject { public override bool DisplayResult => false; protected DrawableSpinner DrawableSpinner => (DrawableSpinner)ParentHitObject; public DrawableSpinnerTick() : this(null) { } public DrawableSpinnerTick(SpinnerTick spinnerTick) : base(spinnerTick) { Anchor = Anchor.Centre; Origin = Anchor.Centre; } protected override double MaximumJudgementOffset => DrawableSpinner.HitObject.Duration; /// <summary> /// Apply a judgement result. /// </summary> /// <param name="hit">Whether this tick was reached.</param> internal void TriggerResult(bool hit) => ApplyResult(r => r.Type = hit ? r.Judgement.MaxResult : r.Judgement.MinResult); } } ```
fa797716-2775-4894-880d-87cb32f6fe01
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace BlueprintBaseName._1 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } } ``` Fix compile error in .NET Core 3.1 version of ASP.NET Core Web App blueprint
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace BlueprintBaseName._1 { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } } ```
f67090e6-f46a-4fbb-83e7-2bdc919f2216
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace NBi.GenbiL { class GenerationState { public DataTable TestCases { get; set; } public IEnumerable<string> Variables { get; set; } public string Template { get; set; } } } ``` Define a state that is modified by the actions
```c# using System; using System.Collections.Generic; using System.Linq; using NBi.Service; namespace NBi.GenbiL { public class GenerationState { public TestCasesManager TestCases { get; private set; } public TemplateManager Template { get; private set; } public SettingsManager Settings { get; private set; } public TestListManager List { get; private set; } public TestSuiteManager Suite { get; private set; } public GenerationState() { TestCases = new TestCasesManager(); Template = new TemplateManager(); Settings = new SettingsManager(); List = new TestListManager(); Suite = new TestSuiteManager(); } } } ```
14bf4a03-4f19-4cdb-8218-9e0696fa092b
{ "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.Linq; using osu.Framework.Development; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log($"⏳ Currently loading components ({loading_components.Count()})"); foreach (var c in loading_components) Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread.Name}"); loading_components.Clear(); Logger.Log("🧵 Task schedulers"); Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString()); Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString()); } } } } ``` Fix potentially null reference if drawable was not assigned a `LoadThread` yet
```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.Linq; using osu.Framework.Development; using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Lists; namespace osu.Framework.Logging { internal static class LoadingComponentsLogger { private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>(); public static void Add(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Add(component); } public static void Remove(Drawable component) { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) loading_components.Remove(component); } public static void LogAndFlush() { if (!DebugUtils.IsDebugBuild) return; lock (loading_components) { Logger.Log($"⏳ Currently loading components ({loading_components.Count()})"); foreach (var c in loading_components) { Logger.Log($"- {c.GetType().ReadableName(),-16} LoadState:{c.LoadState,-5} Thread:{c.LoadThread?.Name ?? "none"}"); } loading_components.Clear(); Logger.Log("🧵 Task schedulers"); Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString()); Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString()); } } } } ```
8168667c-c7e7-4e47-803e-8c2c694109fd
{ "language": "C#" }
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi; namespace osu.Game.Screens.Select { public class MatchSongSelect : SongSelect, IMultiplayerScreen { public Action<PlaylistItem> Selected; public string ShortTitle => "song selection"; protected override bool OnStart() { var item = new PlaylistItem { Beatmap = Beatmap.Value.BeatmapInfo, Ruleset = Ruleset.Value, }; item.RequiredMods.AddRange(SelectedMods.Value); Selected?.Invoke(item); if (IsCurrentScreen) Exit(); return true; } } } ``` Fix incorrect ruleset being sent to API
```c# // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi; namespace osu.Game.Screens.Select { public class MatchSongSelect : SongSelect, IMultiplayerScreen { public Action<PlaylistItem> Selected; public string ShortTitle => "song selection"; protected override bool OnStart() { var item = new PlaylistItem { Beatmap = Beatmap.Value.BeatmapInfo, Ruleset = Ruleset.Value, RulesetID = Ruleset.Value.ID ?? 0 }; item.RequiredMods.AddRange(SelectedMods.Value); Selected?.Invoke(item); if (IsCurrentScreen) Exit(); return true; } } } ```
62f2930e-b171-4a3a-9630-d66e65cb9036
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { /// <summary> /// Payload sent when a client is begining a warp to a new area. /// Contains client ID information and information about the warp itself. /// </summary> [WireDataContract] [SubCommand60(SubCommand60OperationCode.GameStartWarpToArea)] public sealed class Sub60StartNewWarpCommand : BaseSubCommand60, IMessageContextIdentifiable { //TODO: Is this client id? [WireMember(1)] public byte Identifier { get; } [WireMember(2)] public byte Unused1 { get; } /// <summary> /// The zone ID that the user is teleporting to. /// </summary> [WireMember(3)] public short ZoneId { get; } //Unused2 was padding, not sent in the payload. public Sub60StartNewWarpCommand() { //Calc static 32bit size CommandSize = 8 / 4; } } } ``` Revert "Cleaned up 0x60 0x21 warp packet model"
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { /// <summary> /// Payload sent when a client is begining a warp to a new area. /// Contains client ID information and information about the warp itself. /// </summary> [WireDataContract] [SubCommand60(SubCommand60OperationCode.GameStartWarpToArea)] public sealed class Sub60StartNewWarpCommand : BaseSubCommand60, IMessageContextIdentifiable { //TODO: Is this client id? [WireMember(1)] public byte Identifier { get; } [WireMember(2)] public byte Unused1 { get; } /// <summary> /// The zone ID that the user is teleporting to. /// </summary> [WireMember(3)] public short ZoneId { get; } //TODO: What is this? [WireMember(4)] public short Unused2 { get; } public Sub60StartNewWarpCommand() { //Calc static 32bit size CommandSize = 8 / 4; } } } ```
c00b8d71-aef3-4088-b499-324efc3e4baf
{ "language": "C#" }
```c# using System; using System.Windows.Forms; using osu_StreamCompanion.Code.Core; using osu_StreamCompanion.Code.Helpers; namespace osu_StreamCompanion.Code.Modules.ModParser { public partial class ModParserSettings : UserControl { private Settings _settings; private bool init = true; public ModParserSettings(Settings settings) { _settings = settings; _settings.SettingUpdated+= SettingUpdated; this.Enabled = _settings.Get("EnableMemoryScanner", true); InitializeComponent(); textBox_Mods.Text = _settings.Get("NoModsDisplayText", "None"); radioButton_longMods.Checked = _settings.Get("UseLongMods", false); radioButton_shortMods.Checked = !radioButton_longMods.Checked; init = false; } private void SettingUpdated(object sender, SettingUpdated settingUpdated) { this.BeginInvoke((MethodInvoker) (() => { if (settingUpdated.Name == "EnableMemoryScanner") this.Enabled = _settings.Get("EnableMemoryScanner", true); })); } private void textBox_Mods_TextChanged(object sender, EventArgs e) { if (init) return; _settings.Add("NoModsDisplayText", textBox_Mods.Text); } private void radioButton_longMods_CheckedChanged(object sender, EventArgs e) { if (init) return; if (((RadioButton)sender).Checked) { _settings.Add("UseLongMods", radioButton_longMods.Checked); } } } } ``` Make sure that beginInvoke target exists
```c# using System; using System.Windows.Forms; using osu_StreamCompanion.Code.Core; using osu_StreamCompanion.Code.Helpers; namespace osu_StreamCompanion.Code.Modules.ModParser { public partial class ModParserSettings : UserControl { private Settings _settings; private bool init = true; public ModParserSettings(Settings settings) { _settings = settings; _settings.SettingUpdated += SettingUpdated; this.Enabled = _settings.Get("EnableMemoryScanner", true); InitializeComponent(); textBox_Mods.Text = _settings.Get("NoModsDisplayText", "None"); radioButton_longMods.Checked = _settings.Get("UseLongMods", false); radioButton_shortMods.Checked = !radioButton_longMods.Checked; init = false; } private void SettingUpdated(object sender, SettingUpdated settingUpdated) { if (this.IsHandleCreated) this.BeginInvoke((MethodInvoker)(() => { if (settingUpdated.Name == "EnableMemoryScanner") this.Enabled = _settings.Get("EnableMemoryScanner", true); })); } private void textBox_Mods_TextChanged(object sender, EventArgs e) { if (init) return; _settings.Add("NoModsDisplayText", textBox_Mods.Text); } private void radioButton_longMods_CheckedChanged(object sender, EventArgs e) { if (init) return; if (((RadioButton)sender).Checked) { _settings.Add("UseLongMods", radioButton_longMods.Checked); } } } } ```
1bb1db1e-28b6-4ace-aab1-db8b8462c5c2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Anagrams.Models; namespace Anagrams { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); DictionaryCache.Reader = new DictionaryReader(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }``` Use API to override the location of the dictionary file in the dictionary cache from our Web applicatoin
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Anagrams.Models; namespace Anagrams { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); DictionaryCache.Reader = new DictionaryReader(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); DictionaryCache.SetPath(HttpContext.Current.Server.MapPath(@"Content/wordlist.txt")); } } }```
189fc47f-ed39-4789-977d-7c6a66441f5d
{ "language": "C#" }
```c# using Avalonia.Data.Converters; using Avalonia.Media; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using WalletWasabi.Gui.Controls.WalletExplorer; using WalletWasabi.Gui.Models; using WalletWasabi.Models.ChaumianCoinJoin; namespace WalletWasabi.Gui.Converters { public class CoinStatusForegroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is SmartCoinStatus status) { switch (status) { case SmartCoinStatus.MixingOutputRegistration: case SmartCoinStatus.MixingSigning: case SmartCoinStatus.MixingInputRegistration: case SmartCoinStatus.MixingOnWaitingList: case SmartCoinStatus.MixingWaitingForConfirmation: return Brushes.Black; default: return Brushes.White; } } throw new InvalidOperationException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } } ``` Make round states foreground white
```c# using Avalonia.Data.Converters; using Avalonia.Media; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using WalletWasabi.Gui.Controls.WalletExplorer; using WalletWasabi.Gui.Models; using WalletWasabi.Models.ChaumianCoinJoin; namespace WalletWasabi.Gui.Converters { public class CoinStatusForegroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is SmartCoinStatus status) { switch (status) { case SmartCoinStatus.MixingInputRegistration: case SmartCoinStatus.MixingOnWaitingList: case SmartCoinStatus.MixingWaitingForConfirmation: return Brushes.Black; default: return Brushes.White; } } throw new InvalidOperationException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } } ```
69b30aa3-839a-454b-bbfe-9b7f0033698c
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Threading.Tasks; namespace Mond.Libraries.Async { internal class Scheduler : TaskScheduler { private List<Task> _tasks; public Scheduler() { _tasks = new List<Task>(); } public void Run() { int count; lock (_tasks) { count = _tasks.Count; } if (count == 0) return; while (--count >= 0) { Task task; lock (_tasks) { if (_tasks.Count == 0) return; task = _tasks[0]; _tasks.RemoveAt(0); } if (!TryExecuteTask(task)) _tasks.Add(task); } } protected override IEnumerable<Task> GetScheduledTasks() { lock (_tasks) { return _tasks.ToArray(); } } protected override void QueueTask(Task task) { lock (_tasks) { _tasks.Add(task); } } protected override bool TryDequeue(Task task) { lock (_tasks) { return _tasks.Remove(task); } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; } } } ``` Fix async deadlock on Mono
```c# using System.Collections.Generic; using System.Threading.Tasks; namespace Mond.Libraries.Async { internal class Scheduler : TaskScheduler { private List<Task> _tasks; public Scheduler() { _tasks = new List<Task>(); } public void Run() { int count; lock (_tasks) { count = _tasks.Count; } if (count == 0) return; while (--count >= 0) { Task task; lock (_tasks) { if (_tasks.Count == 0) return; task = _tasks[0]; _tasks.RemoveAt(0); } if (TryExecuteTask(task)) continue; lock (_tasks) { _tasks.Add(task); } } } protected override IEnumerable<Task> GetScheduledTasks() { lock (_tasks) { return _tasks.ToArray(); } } protected override void QueueTask(Task task) { lock (_tasks) { _tasks.Add(task); } } protected override bool TryDequeue(Task task) { lock (_tasks) { return _tasks.Remove(task); } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (taskWasPreviouslyQueued) { if (TryDequeue(task)) return TryExecuteTask(task); return false; } return TryExecuteTask(task); } } } ```
6ead92aa-da3d-4990-92b2-2eb0e50b4265
{ "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("FreenetTray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FreenetTray")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("220ea49e-e109-4bb4-86c6-ef477f1584e7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Set neutral language to English
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("FreenetTray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FreenetTray")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("220ea49e-e109-4bb4-86c6-ef477f1584e7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en")] ```
dce25e08-a69b-4058-9b3f-62183ccdea97
{ "language": "C#" }
```c# using RimWorld; using UnityEngine; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { public static class AncestorUtils { public static int DaysToTicks(float days) { return Mathf.RoundToInt(days * GenDate.TicksPerDay); } public static int HoursToTicks(float hours) { return Mathf.RoundToInt(hours * GenDate.TicksPerHour); } } } ``` Add function to get start of season
```c# using Verse; using RimWorld; using UnityEngine; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { public static class AncestorUtils { public static int DaysToTicks(float days) { return Mathf.RoundToInt(days * GenDate.TicksPerDay); } public static int HoursToTicks(float hours) { return Mathf.RoundToInt(hours * GenDate.TicksPerHour); } public static long EstStartOfSeasonAt(long ticks) { var currentDayTicks = (int)(GenDate.CurrentDayPercent * GenDate.TicksPerDay); var dayOfSeason = GenDate.DayOfSeasonZeroBasedAt(ticks); var currentSeasonDayTicks = DaysToTicks(dayOfSeason); return ticks - currentDayTicks - currentSeasonDayTicks; } } } ```
30757074-2672-4132-9481-664e423a2c32
{ "language": "C#" }
```c# namespace Hypermedia.Client.Reader.ProblemJson { using System; using System.Net.Http; using global::Hypermedia.Client.Exceptions; using global::Hypermedia.Client.Resolver; using Newtonsoft.Json; public static class ProblemJsonReader { public static bool TryReadProblemJson(HttpResponseMessage result, out ProblemDescription problemDescription) { problemDescription = null; if (result.Content == null) { return false; } try { var content = result.Content.ReadAsStringAsync().Result; problemDescription = JsonConvert.DeserializeObject<ProblemDescription>(content); // TODO inject deserializer } catch (Exception) { return false; } return true; } } } ``` Fix TryReadProblemJson: ensure problem json could be read and an object was created
```c# namespace Hypermedia.Client.Reader.ProblemJson { using System; using System.Net.Http; using global::Hypermedia.Client.Exceptions; using global::Hypermedia.Client.Resolver; using Newtonsoft.Json; public static class ProblemJsonReader { public static bool TryReadProblemJson(HttpResponseMessage result, out ProblemDescription problemDescription) { problemDescription = null; if (result.Content == null) { return false; } try { var content = result.Content.ReadAsStringAsync().Result; problemDescription = JsonConvert.DeserializeObject<ProblemDescription>(content); // TODO inject deserializer } catch (Exception) { return false; } return problemDescription != null; } } } ```
93f24fba-9396-4118-ba17-39d8a37fe070
{ "language": "C#" }
```c# // // Program.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using Xwt; using Deblocus.Views; namespace Deblocus { public static class Program { [STAThread] public static void Main() { Application.Initialize(ToolkitType.Gtk); var mainWindow = new MainWindow(); mainWindow.Show(); Application.Run(); mainWindow.Dispose(); Application.Dispose(); } } } ``` Add error message on exception
```c# // // Program.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using Xwt; using Deblocus.Views; namespace Deblocus { public static class Program { [STAThread] public static void Main() { Application.Initialize(ToolkitType.Gtk); Application.UnhandledException += ApplicationException; var mainWindow = new MainWindow(); mainWindow.Show(); Application.Run(); mainWindow.Dispose(); Application.Dispose(); } private static void ApplicationException (object sender, ExceptionEventArgs e) { MessageDialog.ShowError("Unknown error. Please contact with the developer.\n" + e.ErrorException); } } } ```
6aae15ff-30cd-404d-8869-3996a11b23f5
{ "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("Recurly Client Library")] [assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Recurly, Inc.")] [assembly: AssemblyProduct("Recurly")] [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("25932cc0-45c7-4db4-b8d5-dd172555522c")] // 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.4.2.2")] [assembly: AssemblyFileVersion("1.4.2.2")] ``` Increase client version to 1.4.2.3
```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("Recurly Client Library")] [assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Recurly, Inc.")] [assembly: AssemblyProduct("Recurly")] [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("25932cc0-45c7-4db4-b8d5-dd172555522c")] // 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.4.2.3")] [assembly: AssemblyFileVersion("1.4.2.3")] ```
1a80e0cb-a2ec-4eae-a705-47060ca174b4
{ "language": "C#" }
```c# using System.Diagnostics; using Sitecore.Configuration; using Sitecore.DataBlaster.Load.Sql; namespace Sitecore.DataBlaster.Load.Processors { public class SyncHistoryTable : ISyncInTransaction { public void Process(BulkLoadContext loadContext, BulkLoadSqlContext sqlContext) { if (!loadContext.UpdateHistory.GetValueOrDefault()) return; if (loadContext.ItemChanges.Count == 0) return; // In Sitecore 9, history engine is disabled by default if (!HistoryEngineEnabled(loadContext)) { loadContext.Log.Warn($"Skipped updating history because history engine is not enabled"); return; } var stopwatch = Stopwatch.StartNew(); var sql = sqlContext.GetEmbeddedSql(loadContext, "Sql.09.UpdateHistory.sql"); sqlContext.ExecuteSql(sql, commandProcessor: cmd => cmd.Parameters.AddWithValue("@UserName", Sitecore.Context.User.Name)); loadContext.Log.Info($"Updated history: {(int) stopwatch.Elapsed.TotalSeconds}s"); } private bool HistoryEngineEnabled(BulkLoadContext context) { var db = Factory.GetDatabase(context.Database, true); return db.Engines.HistoryEngine.Storage != null; } } }``` Change log lvl for history engine disable logging
```c# using System.Diagnostics; using Sitecore.Configuration; using Sitecore.DataBlaster.Load.Sql; namespace Sitecore.DataBlaster.Load.Processors { public class SyncHistoryTable : ISyncInTransaction { public void Process(BulkLoadContext loadContext, BulkLoadSqlContext sqlContext) { if (!loadContext.UpdateHistory.GetValueOrDefault()) return; if (loadContext.ItemChanges.Count == 0) return; // In Sitecore 9, history engine is disabled by default if (!HistoryEngineEnabled(loadContext)) { loadContext.Log.Info($"Skipped updating history because history engine is not enabled."); return; } var stopwatch = Stopwatch.StartNew(); var sql = sqlContext.GetEmbeddedSql(loadContext, "Sql.09.UpdateHistory.sql"); sqlContext.ExecuteSql(sql, commandProcessor: cmd => cmd.Parameters.AddWithValue("@UserName", Sitecore.Context.User.Name)); loadContext.Log.Info($"Updated history: {(int) stopwatch.Elapsed.TotalSeconds}s"); } private bool HistoryEngineEnabled(BulkLoadContext context) { var db = Factory.GetDatabase(context.Database, true); return db.Engines.HistoryEngine.Storage != null; } } }```
00cdffa9-9d83-4cfd-b368-0202316195ea
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Drawing; using System.IO; namespace GUI.Utils { internal static class Settings { public static List<string> GameSearchPaths { get; } = new List<string>(); public static Color BackgroundColor { get; set; } = Color.Black; public static void Load() { // TODO: Be dumb about it for now. if (!File.Exists("gamepaths.txt")) { return; } GameSearchPaths.AddRange(File.ReadAllLines("gamepaths.txt")); } public static void Save() { File.WriteAllLines("gamepaths.txt", GameSearchPaths); } } } ``` Change default background color to be more grey
```c# using System.Collections.Generic; using System.Drawing; using System.IO; namespace GUI.Utils { internal static class Settings { public static List<string> GameSearchPaths { get; } = new List<string>(); public static Color BackgroundColor { get; set; } public static void Load() { BackgroundColor = Color.FromArgb(60, 60, 60); // TODO: Be dumb about it for now. if (!File.Exists("gamepaths.txt")) { return; } GameSearchPaths.AddRange(File.ReadAllLines("gamepaths.txt")); } public static void Save() { File.WriteAllLines("gamepaths.txt", GameSearchPaths); } } } ```
2671dfb9-17bc-4989-a08f-210b3786cd06
{ "language": "C#" }
```c# using System.Collections.Generic; using System; namespace MicroORM.Entity { internal sealed class EntityInfo { internal EntityInfo() { this.EntityState = EntityState.None; this.EntityHashSet = new Dictionary<string, string>(); this.LastCallTime = DateTime.Now; } internal bool CanBeRemoved { get { return DateTime.Now.Subtract(this.LastCallTime) > TimeSpan.FromMinutes(2); } } internal EntityState EntityState { get; set; } internal Dictionary<string, string> EntityHashSet { get; set; } internal DateTime LastCallTime { get; set; } } } ``` Rollback functionality and hash computing
```c# using System; using System.Collections.Generic; using System.Linq; using MicroORM.Materialization; using MicroORM.Reflection; using MicroORM.Mapping; namespace MicroORM.Entity { internal sealed class EntityInfo { internal EntityInfo() { this.EntityState = EntityState.None; this.ValueSnapshot = new Dictionary<string, int>(); this.ChangesSnapshot = new Dictionary<string, int>(); this.LastCallTime = DateTime.Now; } internal bool CanBeRemoved { get { return DateTime.Now.Subtract(this.LastCallTime) > TimeSpan.FromMinutes(2); } } internal EntityState EntityState { get; set; } internal Dictionary<string, int> ValueSnapshot { get; set; } internal Dictionary<string, int> ChangesSnapshot { get; set; } internal DateTime LastCallTime { get; set; } internal void ClearChanges() { this.ChangesSnapshot.Clear(); } internal void MergeChanges() { foreach (var change in this.ChangesSnapshot) { this.ValueSnapshot[change.Key] = change.Value; } ClearChanges(); } internal void ComputeSnapshot<TEntity>(TEntity entity) { this.ValueSnapshot = EntityHashSetManager.ComputeEntityHashSet(entity); } internal KeyValuePair<string, object>[] ComputeUpdateValues<TEntity>(TEntity entity) { Dictionary<string, int> entityHashSet = EntityHashSetManager.ComputeEntityHashSet(entity); KeyValuePair<string, object>[] entityValues = RemoveUnusedPropertyValues<TEntity>(entity); Dictionary<string, object> valuesToUpdate = new Dictionary<string, object>(); foreach (var kvp in entityHashSet) { var oldHash = this.ValueSnapshot[kvp.Key]; if (oldHash.Equals(kvp.Value) == false) { valuesToUpdate.Add(kvp.Key, entityValues.FirstOrDefault(kvp1 => kvp1.Key == kvp.Key).Value); this.ChangesSnapshot.Add(kvp.Key, kvp.Value); } } return valuesToUpdate.ToArray(); } private KeyValuePair<string, object>[] RemoveUnusedPropertyValues<TEntity>(TEntity entity) { KeyValuePair<string, object>[] entityValues = ParameterTypeDescriptor.ToKeyValuePairs(new object[] { entity }); TableInfo tableInfo = TableInfo<TEntity>.GetTableInfo; return entityValues.Where(kvp => tableInfo.DbTable.DbColumns.Any(column => column.Name == kvp.Key)).ToArray(); } } } ```
4a42c728-aaad-4b24-9dfe-c1df3ce89a5e
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Sawczyn.EFDesigner.EFModel { internal static class Messages { private static readonly string MessagePaneTitle = "Entity Framework Designer"; private static IVsOutputWindow _outputWindow; private static IVsOutputWindow OutputWindow => _outputWindow ?? (_outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow); private static IVsOutputWindowPane _outputWindowPane; private static IVsOutputWindowPane OutputWindowPane { get { if (_outputWindowPane == null) { Guid paneGuid = new Guid(Constants.EFDesignerOutputPane); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); if (_outputWindowPane == null) { OutputWindow?.CreatePane(ref paneGuid, MessagePaneTitle, 1, 1); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); } } return _outputWindowPane; } } public static void AddError(string message) { OutputWindowPane?.OutputString($"Error: {message}"); OutputWindowPane?.Activate(); } public static void AddWarning(string message) { OutputWindowPane?.OutputString($"Warning: {message}"); OutputWindowPane?.Activate(); } public static void AddMessage(string message) { OutputWindowPane?.OutputString(message); OutputWindowPane?.Activate(); } } } ``` Format for output window message changed
```c# using System; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Sawczyn.EFDesigner.EFModel { internal static class Messages { private static readonly string MessagePaneTitle = "Entity Framework Designer"; private static IVsOutputWindow _outputWindow; private static IVsOutputWindow OutputWindow => _outputWindow ?? (_outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow); private static IVsOutputWindowPane _outputWindowPane; private static IVsOutputWindowPane OutputWindowPane { get { if (_outputWindowPane == null) { Guid paneGuid = new Guid(Constants.EFDesignerOutputPane); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); if (_outputWindowPane == null) { OutputWindow?.CreatePane(ref paneGuid, MessagePaneTitle, 1, 1); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); } } return _outputWindowPane; } } public static void AddError(string message) { AddMessage(message, "Error"); } public static void AddWarning(string message) { AddMessage(message, "Warning"); } public static void AddMessage(string message, string prefix = null) { OutputWindowPane?.OutputString($"{(string.IsNullOrWhiteSpace(prefix) ? "" : prefix + ": ")}{message}{(message.EndsWith("\n") ? "" : "\n")}"); OutputWindowPane?.Activate(); } } } ```
1926c1d5-9ffd-44d2-b07a-37ef9446dc67
{ "language": "C#" }
```c# using System; using System.Web; using System.Web.Mvc; using Orchard.DisplayManagement; using Orchard.DisplayManagement.Descriptors; using Orchard.Localization; using Orchard.Mvc.Html; namespace Orchard.Core.Common { public class Shapes : IShapeTableProvider { public Shapes() { T = NullLocalizer.Instance; } public Localizer T { get; set; } public void Discover(ShapeTableBuilder builder) { builder.Describe("Body_Editor") .OnDisplaying(displaying => { string flavor = displaying.Shape.EditorFlavor; displaying.ShapeMetadata.Alternates.Add("Body_Editor__" + flavor); }); } [Shape] public IHtmlString PublishedState(dynamic Display, DateTime createdDateTimeUtc, DateTime? publisheddateTimeUtc) { if (!publisheddateTimeUtc.HasValue) { return T("Draft"); } return Display.DateTime(DateTimeUtc: createdDateTimeUtc); } [Shape] public IHtmlString PublishedWhen(dynamic Display, DateTime? dateTimeUtc) { if (dateTimeUtc == null) return T("as a Draft"); return Display.DateTimeRelative(DateTimeUtc: dateTimeUtc); } } } ``` Allow custom date format when displaying published state
```c# using System; using System.Web; using System.Web.Mvc; using Orchard.DisplayManagement; using Orchard.DisplayManagement.Descriptors; using Orchard.Localization; using Orchard.Mvc.Html; namespace Orchard.Core.Common { public class Shapes : IShapeTableProvider { public Shapes() { T = NullLocalizer.Instance; } public Localizer T { get; set; } public void Discover(ShapeTableBuilder builder) { builder.Describe("Body_Editor") .OnDisplaying(displaying => { string flavor = displaying.Shape.EditorFlavor; displaying.ShapeMetadata.Alternates.Add("Body_Editor__" + flavor); }); } [Shape] public IHtmlString PublishedState(dynamic Display, DateTime createdDateTimeUtc, DateTime? publisheddateTimeUtc, LocalizedString customDateFormat) { if (!publisheddateTimeUtc.HasValue) { return T("Draft"); } return Display.DateTime(DateTimeUtc: createdDateTimeUtc, CustomFormat: customDateFormat); } [Shape] public IHtmlString PublishedWhen(dynamic Display, DateTime? dateTimeUtc) { if (dateTimeUtc == null) return T("as a Draft"); return Display.DateTimeRelative(DateTimeUtc: dateTimeUtc); } } } ```
b33731c3-4274-4999-9842-615401e03704
{ "language": "C#" }
```c# using Arduino; using ArduinoWindowsRemoteControl.Repositories; using Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArduinoWindowsRemoteControl.Services { /// <summary> /// Service that returns parsers for different remote input devices /// </summary> public class RemoteCommandParserService { #region Private Fields private DictionaryRepository _dictionaryRepository; #endregion #region Constructor public RemoteCommandParserService() { _dictionaryRepository = new DictionaryRepository(); } #endregion #region Public Methods public ArduinoRemoteCommandParser LoadArduinoCommandParser(string filename) { var dictionary = _dictionaryRepository.Load<int, RemoteCommand>(filename); return new ArduinoRemoteCommandParser(dictionary); } public void SaveArduinoCommandParser(ArduinoRemoteCommandParser commandParser, string filename) { } #endregion } } ``` Add ability to save commands mapping
```c# using Arduino; using ArduinoWindowsRemoteControl.Repositories; using Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArduinoWindowsRemoteControl.Services { /// <summary> /// Service that returns parsers for different remote input devices /// </summary> public class RemoteCommandParserService { #region Private Fields private DictionaryRepository _dictionaryRepository; #endregion #region Constructor public RemoteCommandParserService() { _dictionaryRepository = new DictionaryRepository(); } #endregion #region Public Methods public ArduinoRemoteCommandParser LoadArduinoCommandParser(string filename) { var dictionary = _dictionaryRepository.Load<int, RemoteCommand>(filename); return new ArduinoRemoteCommandParser(dictionary); } public void SaveArduinoCommandParser(ArduinoRemoteCommandParser commandParser, string filename) { _dictionaryRepository.Save(commandParser.CommandsMapping, filename); } #endregion } } ```
5fa2ed5b-7093-4c01-95fa-7f7ab1089642
{ "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.Bindables; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { /// <summary> /// Note that this should not be used for timing correctness. /// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information. /// </summary> public class SliderTailCircle : SliderCircle { private readonly IBindable<int> pathVersion = new Bindable<int>(); public SliderTailCircle(Slider slider) { pathVersion.BindTo(slider.Path.Version); pathVersion.BindValueChanged(_ => Position = slider.EndPosition); } protected override HitWindows CreateHitWindows() => HitWindows.Empty; public override Judgement CreateJudgement() => new SliderRepeat.SliderRepeatJudgement(); } } ``` Remove slider tail circle judgement requirements
```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.Bindables; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { /// <summary> /// Note that this should not be used for timing correctness. /// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information. /// </summary> public class SliderTailCircle : SliderCircle { private readonly IBindable<int> pathVersion = new Bindable<int>(); public SliderTailCircle(Slider slider) { pathVersion.BindTo(slider.Path.Version); pathVersion.BindValueChanged(_ => Position = slider.EndPosition); } protected override HitWindows CreateHitWindows() => HitWindows.Empty; public override Judgement CreateJudgement() => new SliderTailJudgement(); public class SliderTailJudgement : OsuJudgement { protected override int NumericResultFor(HitResult result) => 0; public override bool AffectsCombo => false; } } } ```
e24712a7-bc62-4b7e-ae7f-b2115cb849e6
{ "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.Statistics; using System; using System.Collections.Generic; using osu.Framework.Audio; namespace osu.Framework.Threading { public class AudioThread : GameThread { public AudioThread() : base(name: "Audio") { OnNewFrame = onNewFrame; } internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[] { StatisticsCounterType.TasksRun, StatisticsCounterType.Tracks, StatisticsCounterType.Samples, StatisticsCounterType.SChannels, StatisticsCounterType.Components, }; private readonly List<AudioManager> managers = new List<AudioManager>(); private void onNewFrame() { lock (managers) { for (var i = 0; i < managers.Count; i++) { var m = managers[i]; m.Update(); } } } public void RegisterManager(AudioManager manager) { lock (managers) { if (managers.Contains(manager)) throw new InvalidOperationException($"{manager} was already registered"); managers.Add(manager); } } public void UnregisterManager(AudioManager manager) { lock (managers) managers.Remove(manager); } protected override void PerformExit() { base.PerformExit(); lock (managers) { // AudioManager's disposal triggers an un-registration while (managers.Count > 0) managers[0].Dispose(); } ManagedBass.Bass.Free(); } } } ``` Fix audio thread not exiting correctly
```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.Statistics; using System; using System.Collections.Generic; using osu.Framework.Audio; namespace osu.Framework.Threading { public class AudioThread : GameThread { public AudioThread() : base(name: "Audio") { OnNewFrame = onNewFrame; } internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[] { StatisticsCounterType.TasksRun, StatisticsCounterType.Tracks, StatisticsCounterType.Samples, StatisticsCounterType.SChannels, StatisticsCounterType.Components, }; private readonly List<AudioManager> managers = new List<AudioManager>(); private void onNewFrame() { lock (managers) { for (var i = 0; i < managers.Count; i++) { var m = managers[i]; m.Update(); } } } public void RegisterManager(AudioManager manager) { lock (managers) { if (managers.Contains(manager)) throw new InvalidOperationException($"{manager} was already registered"); managers.Add(manager); } } public void UnregisterManager(AudioManager manager) { lock (managers) managers.Remove(manager); } protected override void PerformExit() { base.PerformExit(); lock (managers) { foreach (var manager in managers) manager.Dispose(); managers.Clear(); } ManagedBass.Bass.Free(); } } } ```
139f6c1a-5ed6-400d-80ee-bb3c25ec9b0d
{ "language": "C#" }
```c# // <copyright file="RavenDBViewModelHelper.cs" company="Cognisant"> // Copyright (c) Cognisant. All rights reserved. // </copyright> namespace CR.ViewModels.Persistence.RavenDB { /// <summary> /// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>. /// </summary> // ReSharper disable once InconsistentNaming internal static class RavenDBViewModelHelper { /// <summary> /// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored. /// </summary> /// <typeparam name="TEntity">The type of the View Model.</typeparam> /// <param name="key">The key of the view model.</param> /// <returns>The ID of the RavenDB document.</returns> internal static string MakeId<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}"; } } ``` Add missing changes for last commit
```c# // <copyright file="RavenDBViewModelHelper.cs" company="Cognisant"> // Copyright (c) Cognisant. All rights reserved. // </copyright> namespace CR.ViewModels.Persistence.RavenDB { /// <summary> /// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>. /// </summary> // ReSharper disable once InconsistentNaming internal static class RavenDBViewModelHelper { /// <summary> /// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored. /// </summary> /// <typeparam name="TEntity">The type of the View Model.</typeparam> /// <param name="key">The key of the view model.</param> /// <returns>The ID of the RavenDB document.</returns> // ReSharper disable once InconsistentNaming internal static string MakeID<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}"; } } ```
f477ec5f-538c-441f-b648-5216d64c80ae
{ "language": "C#" }
```c# @using CkanDotNet.Web.Models.Helpers <div class="container"> <h2 class="container-title">Comments</h2> <div class="container-content"> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname @if (SettingsHelper.GetDisqusDeveloperModeEnabled()) { <text>var disqus_developer = 1; // developer mode is on</text> } /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div> ``` Add support for dynamic resizing of iframe when disqus forum loads
```c# @using CkanDotNet.Web.Models.Helpers <div class="container"> <h2 class="container-title">Comments</h2> <div class="container-content"> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname @if (SettingsHelper.GetDisqusDeveloperModeEnabled()) { <text>var disqus_developer = 1; // developer mode is on</text> } @if (SettingsHelper.GetIframeEnabled()) { <text> function disqus_config() { this.callbacks.onNewComment = [function() { resizeFrame() }]; this.callbacks.onReady = [function() { resizeFrame() }]; } </text> } /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div> ```
98ca1803-e614-487d-9007-50dfb5ed98db
{ "language": "C#" }
```c# /* * Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library 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 * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using uhttpsharp.Embedded; namespace uhttpsharpdemo { class Program { static void Main(string[] args) { HttpServer.Instance.StartUp(); Console.ReadLine(); } } } ``` Change the port to 8000 so we can run as non-admin.
```c# /* * Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library 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 * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using uhttpsharp.Embedded; namespace uhttpsharpdemo { class Program { static void Main(string[] args) { HttpServer.Instance.Port = 8000; HttpServer.Instance.StartUp(); Console.ReadLine(); } } } ```
3afba943-ccd0-4a3f-9f48-a3c1d1f47017
{ "language": "C#" }
```c# namespace ExcelX.AddIn.Command { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExcelX.AddIn.Config; using Excel = Microsoft.Office.Interop.Excel; /// <summary> /// 「方眼紙」コマンド /// </summary> public class MakeGridCommand : ICommand { /// <summary> /// コマンドを実行します。 /// </summary> public void Execute() { // グリッドサイズはピクセル指定 var size = ConfigDocument.Current.Edit.Grid.Size; // ワークシートを取得 var application = Globals.ThisAddIn.Application; Excel.Workbook book = application.ActiveWorkbook; Excel.Worksheet sheet = book.ActiveSheet; // すべてのセルサイズを同一に設定 Excel.Range all = sheet.Cells; all.ColumnWidth = size * 0.118; all.RowHeight = size * 0.75; } } } ``` Fix dependency of environment gap
```c# namespace ExcelX.AddIn.Command { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExcelX.AddIn.Config; using Excel = Microsoft.Office.Interop.Excel; /// <summary> /// 「方眼紙」コマンド /// </summary> public class MakeGridCommand : ICommand { /// <summary> /// コマンドを実行します。 /// </summary> public void Execute() { // グリッドサイズはピクセル指定 var size = ConfigDocument.Current.Edit.Grid.Size; // ワークシートを取得 var application = Globals.ThisAddIn.Application; Excel.Workbook book = application.ActiveWorkbook; Excel.Worksheet sheet = book.ActiveSheet; // 環境値の取得 var cell = sheet.Range["A1"]; double x1 = 10, x2 = 20, y1, y2, a, b; cell.ColumnWidth = x1; y1 = cell.Width; cell.ColumnWidth = x2; y2 = cell.Width; a = (y2 - y1) / (x2 - x1); b = y2 - (y2 - y1) / (x2 - x1) * x2; // すべてのセルサイズを同一に設定 Excel.Range all = sheet.Cells; all.ColumnWidth = (size * 0.75 - b) / a; all.RowHeight = size * 0.75; } } } ```
0abe8b08-cdbc-40be-9e52-fd534ef37bff
{ "language": "C#" }
```c# using System.Text.RegularExpressions; namespace Sep.Git.Tfs { public static class GitTfsConstants { public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase); public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase); public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$"); public const string DefaultRepositoryId = "default"; // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123 public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}"; public static readonly Regex TfsCommitInfoRegex = new Regex("^\\s*" + "git-tfs-id:\\s+" + "\\[(?<url>.+)\\]" + "(?<repository>.+);" + "C(?<changeset>\\d+)" + "\\s*$"); } } ``` Create a prefix for Git-Tfs metadata
```c# using System.Text.RegularExpressions; namespace Sep.Git.Tfs { public static class GitTfsConstants { public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase); public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase); public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$"); public const string DefaultRepositoryId = "default"; public const string GitTfsPrefix = "git-tfs"; // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123 public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}"; public static readonly Regex TfsCommitInfoRegex = new Regex("^\\s*" + GitTfsPrefix + "-id:\\s+" + "\\[(?<url>.+)\\]" + "(?<repository>.+);" + "C(?<changeset>\\d+)" + "\\s*$"); } } ```
f8bbec11-39c7-447c-87eb-6511a0075346
{ "language": "C#" }
```c# using VkNet.Utils; namespace VkNet.Model { /// <summary> /// Информация об аудиоальбоме. /// </summary> /// <remarks> /// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>. /// </remarks> public class AudioAlbum { /// <summary> /// Идентификатор владельца альбома. /// </summary> public long? OwnerId { get; set; } /// <summary> /// Идентификатор альбома. /// </summary> public long? AlbumId { get; set; } /// <summary> /// Название альбома. /// </summary> public string Title { get; set; } #region Методы /// <summary> /// Разобрать из json. /// </summary> /// <param name="response">Ответ сервера.</param> /// <returns></returns> internal static AudioAlbum FromJson(VkResponse response) { var album = new AudioAlbum { OwnerId = response["owner_id"], AlbumId = response["id"], Title = response["title"] }; return album; } #endregion } }``` Add support for older versions API
```c# using VkNet.Utils; namespace VkNet.Model { /// <summary> /// Информация об аудиоальбоме. /// </summary> /// <remarks> /// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>. /// </remarks> public class AudioAlbum { /// <summary> /// Идентификатор владельца альбома. /// </summary> public long? OwnerId { get; set; } /// <summary> /// Идентификатор альбома. /// </summary> public long? AlbumId { get; set; } /// <summary> /// Название альбома. /// </summary> public string Title { get; set; } #region Методы /// <summary> /// Разобрать из json. /// </summary> /// <param name="response">Ответ сервера.</param> /// <returns></returns> internal static AudioAlbum FromJson(VkResponse response) { var album = new AudioAlbum { OwnerId = response["owner_id"], AlbumId = response["album_id"] ?? response["id"], Title = response["title"] }; return album; } #endregion } }```
5fe6c34a-c42f-46d3-ac47-4a4541196de2
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using NQuery.Syntax; namespace NQuery.Authoring.Completion.Providers { internal sealed class TypeCompletionProvider : ICompletionProvider { public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position) { var syntaxTree = semanticModel.Compilation.SyntaxTree; var token = syntaxTree.Root.FindTokenOnLeft(position); var castExpression = token.Parent.AncestorsAndSelf() .OfType<CastExpressionSyntax>() .FirstOrDefault(c => c.AsKeyword.Span.End <= position); if (castExpression == null) return Enumerable.Empty<CompletionItem>(); return from typeName in SyntaxFacts.GetTypeNames() select GetCompletionItem(typeName); } private static CompletionItem GetCompletionItem(string typeName) { return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type); } } }``` Fix handling of CAST in type completion provider
```c# using System; using System.Collections.Generic; using System.Linq; using NQuery.Syntax; namespace NQuery.Authoring.Completion.Providers { internal sealed class TypeCompletionProvider : ICompletionProvider { public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position) { var syntaxTree = semanticModel.Compilation.SyntaxTree; var token = syntaxTree.Root.FindTokenOnLeft(position); var castExpression = token.Parent.AncestorsAndSelf() .OfType<CastExpressionSyntax>() .FirstOrDefault(c => !c.AsKeyword.IsMissing && c.AsKeyword.Span.End <= position); if (castExpression == null) return Enumerable.Empty<CompletionItem>(); return from typeName in SyntaxFacts.GetTypeNames() select GetCompletionItem(typeName); } private static CompletionItem GetCompletionItem(string typeName) { return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type); } } }```
b116ab44-8b49-4d78-9740-716c9863e0f2
{ "language": "C#" }
```c# using Microsoft.Office365.ReportingWebServiceClient.Utils; using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Microsoft.Office365.ReportingWebServiceClient { /// <summary> /// This is representing an object of the RWS Report returned /// </summary> public class ReportObject { protected Dictionary<string, string> properties = new Dictionary<string, string>(); public DateTime Date { get; set; } public virtual void LoadFromXml(XmlNode node) { properties = new Dictionary<string, string>(); foreach (XmlNode p in node) { string key = p.Name.Replace("d:", ""); properties[key] = p.InnerText.ToString(); } this.Date = StringUtil.TryParseDateTime(TryGetValue("Date"), DateTime.MinValue); } public string ConvertToXml() { string retval = null; StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true })) { new XmlSerializer(this.GetType()).Serialize(writer, this); } retval = sb.ToString(); return retval; } protected string TryGetValue(string key) { if (properties.ContainsKey(key)) { return properties[key]; } return null; } } }``` Test Commit for a GitHub from VS2015
```c# using Microsoft.Office365.ReportingWebServiceClient.Utils; using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Microsoft.Office365.ReportingWebServiceClient { /// <summary> /// This is representing an object of the RWS Report returned /// </summary> public class ReportObject { protected Dictionary<string, string> properties = new Dictionary<string, string>(); // This is a Date property public DateTime Date { get; set; } public virtual void LoadFromXml(XmlNode node) { properties = new Dictionary<string, string>(); foreach (XmlNode p in node) { string key = p.Name.Replace("d:", ""); properties[key] = p.InnerText.ToString(); } this.Date = StringUtil.TryParseDateTime(TryGetValue("Date"), DateTime.MinValue); } public string ConvertToXml() { string retval = null; StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true })) { new XmlSerializer(this.GetType()).Serialize(writer, this); } retval = sb.ToString(); return retval; } protected string TryGetValue(string key) { if (properties.ContainsKey(key)) { return properties[key]; } return null; } } }```
adfcd70e-a9af-4495-987b-667d013ed6c1
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.LazyLoad { [Serializable] public class AParent : Csla.BusinessBase<AParent> { private Guid _id; public Guid Id { get { return _id; } set { _id = value; PropertyHasChanged(); } } private AChildList _children; public AChildList ChildList { get { if (_children == null) { _children = new AChildList(); for (int count = 0; count < EditLevel; count++) ((Csla.Core.IUndoableObject)_children).CopyState(EditLevel); } return _children; } } public AChildList GetChildList() { return _children; } public int EditLevel { get { return base.EditLevel; } } protected override object GetIdValue() { return _id; } public AParent() { _id = Guid.NewGuid(); } } } ``` Fix bug with n-level undo of child objects.
```c# using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.LazyLoad { [Serializable] public class AParent : Csla.BusinessBase<AParent> { private Guid _id; public Guid Id { get { return _id; } set { _id = value; PropertyHasChanged(); } } private static PropertyInfo<AChildList> ChildListProperty = RegisterProperty<AChildList>(typeof(AParent), new PropertyInfo<AChildList>("ChildList", "Child list")); public AChildList ChildList { get { if (!FieldManager.FieldExists(ChildListProperty)) LoadProperty<AChildList>(ChildListProperty, new AChildList()); return GetProperty<AChildList>(ChildListProperty); } } //private AChildList _children; //public AChildList ChildList //{ // get // { // if (_children == null) // { // _children = new AChildList(); // for (int count = 0; count < EditLevel; count++) // ((Csla.Core.IUndoableObject)_children).CopyState(EditLevel); // } // return _children; // } //} public AChildList GetChildList() { if (FieldManager.FieldExists(ChildListProperty)) return ReadProperty<AChildList>(ChildListProperty); else return null; //return _children; } public int EditLevel { get { return base.EditLevel; } } protected override object GetIdValue() { return _id; } public AParent() { _id = Guid.NewGuid(); } } } ```
8b45afb2-559a-45ce-acc5-eb5f1522b3b9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace ExoWeb.Templates.MicrosoftAjax { /// <summary> /// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports /// parsing and loading templates using the Microsoft AJAX syntax. /// </summary> internal class AjaxPage : Page { internal AjaxPage() { IsIE = HttpContext.Current != null && HttpContext.Current.Request.Browser.IsBrowser("IE"); } int nextControlId; internal string NextControlId { get { return "exo" + nextControlId++; } } internal bool IsIE { get; private set; } public override ITemplate Parse(string name, string template) { return Template.Parse(name, template); } public override IEnumerable<ITemplate> ParseTemplates(string source, string template) { return Block.Parse(source, template).OfType<ITemplate>(); } public override IEnumerable<ITemplate> LoadTemplates(string path) { return Template.Load(path).Cast<ITemplate>(); } } } ``` Check the user-agent string for "Trident" in order to identify IE11 as an IE browser. This is only needed for a workaround for comments within select elements in IE below version 10 and should be abandoned when possible.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace ExoWeb.Templates.MicrosoftAjax { /// <summary> /// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports /// parsing and loading templates using the Microsoft AJAX syntax. /// </summary> internal class AjaxPage : Page { internal AjaxPage() { IsIE = HttpContext.Current != null && (HttpContext.Current.Request.Browser.IsBrowser("IE") || (!string.IsNullOrEmpty(HttpContext.Current.Request.UserAgent) && HttpContext.Current.Request.UserAgent.Contains("Trident"))); } int nextControlId; internal string NextControlId { get { return "exo" + nextControlId++; } } internal bool IsIE { get; private set; } public override ITemplate Parse(string name, string template) { return Template.Parse(name, template); } public override IEnumerable<ITemplate> ParseTemplates(string source, string template) { return Block.Parse(source, template).OfType<ITemplate>(); } public override IEnumerable<ITemplate> LoadTemplates(string path) { return Template.Load(path).Cast<ITemplate>(); } } } ```