doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
31de7e93-3a66-489d-b5ae-4f017fd4b58a
{ "language": "C#" }
```c# using System.Runtime.Remoting.Messaging; namespace Criteo.Profiling.Tracing { internal static class TraceContext { private const string TraceCallContextKey = "crto_trace"; public static Trace Get() { return CallContext.LogicalGetData(TraceCallContextKey) as Trace; } public static void Set(Trace trace) { CallContext.LogicalSetData(TraceCallContextKey, trace); } public static void Clear() { CallContext.FreeNamedDataSlot(TraceCallContextKey); } } } ``` Add check for Mono for LogicalCallContext
```c# using System; using System.Runtime.Remoting.Messaging; namespace Criteo.Profiling.Tracing { internal static class TraceContext { private const string TraceCallContextKey = "crto_trace"; private static readonly bool IsRunningOnMono = (Type.GetType("Mono.Runtime") != null); public static Trace Get() { if (IsRunningOnMono) return null; return CallContext.LogicalGetData(TraceCallContextKey) as Trace; } public static void Set(Trace trace) { if (IsRunningOnMono) return; CallContext.LogicalSetData(TraceCallContextKey, trace); } public static void Clear() { if (IsRunningOnMono) return; CallContext.FreeNamedDataSlot(TraceCallContextKey); } } } ```
08023bf8-0661-4c53-b708-26affd7184b9
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Collections.Immutable; using Octokit; using NSubstitute; using NUnit.Framework; using GitHub.Extensions; public class ApiExceptionExtensionsTests { public class TheIsGitHubApiExceptionMethod { [TestCase("Not-GitHub-Request-Id", false)] [TestCase("X-GitHub-Request-Id", true)] [TestCase("x-github-request-id", true)] public void NoGitHubRequestId(string key, bool expect) { var ex = CreateApiException(new Dictionary<string, string> { { key, "ANYTHING" } }); var result = ApiExceptionExtensions.IsGitHubApiException(ex); Assert.That(result, Is.EqualTo(expect)); } static ApiException CreateApiException(Dictionary<string, string> headers) { var response = Substitute.For<IResponse>(); response.Headers.Returns(headers.ToImmutableDictionary()); var ex = new ApiException(response); return ex; } } } ``` Add test when IResponse not set
```c# using System.Collections.Generic; using System.Collections.Immutable; using Octokit; using NSubstitute; using NUnit.Framework; using GitHub.Extensions; public class ApiExceptionExtensionsTests { public class TheIsGitHubApiExceptionMethod { [TestCase("Not-GitHub-Request-Id", false)] [TestCase("X-GitHub-Request-Id", true)] [TestCase("x-github-request-id", true)] public void NoGitHubRequestId(string key, bool expect) { var ex = CreateApiException(new Dictionary<string, string> { { key, "ANYTHING" } }); var result = ApiExceptionExtensions.IsGitHubApiException(ex); Assert.That(result, Is.EqualTo(expect)); } [Test] public void NoResponse() { var ex = new ApiException(); var result = ApiExceptionExtensions.IsGitHubApiException(ex); Assert.That(result, Is.EqualTo(false)); } static ApiException CreateApiException(Dictionary<string, string> headers) { var response = Substitute.For<IResponse>(); response.Headers.Returns(headers.ToImmutableDictionary()); var ex = new ApiException(response); return ex; } } } ```
84e64b44-759e-4f2e-a22a-b7320ae3a6dc
{ "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.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(); protected override void OnCreate(Bundle savedInstanceState) { // The default current directory on android is '/'. // On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage. // In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory. System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } } ``` Allow rotation lock on Android to function properly
```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.FullUser, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = false)] public class OsuGameActivity : AndroidGameActivity { protected override Framework.Game CreateGame() => new OsuGameAndroid(); protected override void OnCreate(Bundle savedInstanceState) { // The default current directory on android is '/'. // On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage. // In order to have a consistent current directory on all devices the full path of the app data directory is set as the current directory. System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); } } } ```
c38c4a7d-a3f9-4c78-875e-a29cfbaf8540
{ "language": "C#" }
```c# using Gtk; using Mono.Addins; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.AddinMaker.AddinBrowser { class AddinBrowserWidget : VBox { ExtensibleTreeView treeView; public AddinBrowserWidget (AddinRegistry registry) { Registry = registry; Build (); foreach (var addin in registry.GetAddins ()) { treeView.AddChild (addin); } } void Build () { //TODO: make extensible? treeView = new ExtensibleTreeView ( new NodeBuilder[] { new AddinNodeBuilder (), new ExtensionFolderNodeBuilder (), new ExtensionNodeBuilder (), new ExtensionPointNodeBuilder (), new ExtensionPointFolderNodeBuilder (), new DependencyFolderNodeBuilder (), new DependencyNodeBuilder (), }, new TreePadOption[0] ); treeView.Tree.Selection.Mode = SelectionMode.Single; PackStart (treeView, true, true, 0); ShowAll (); } public void SetToolbar (DocumentToolbar toolbar) { } public AddinRegistry Registry { get; private set; } } } ``` Add detail panel, currently empty
```c# using Gtk; using Mono.Addins; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.AddinMaker.AddinBrowser { class AddinBrowserWidget : HPaned { ExtensibleTreeView treeView; public AddinBrowserWidget (AddinRegistry registry) { Registry = registry; Build (); foreach (var addin in registry.GetAddins ()) { treeView.AddChild (addin); } } void Build () { //TODO: make extensible? treeView = new ExtensibleTreeView ( new NodeBuilder[] { new AddinNodeBuilder (), new ExtensionFolderNodeBuilder (), new ExtensionNodeBuilder (), new ExtensionPointNodeBuilder (), new ExtensionPointFolderNodeBuilder (), new DependencyFolderNodeBuilder (), new DependencyNodeBuilder (), }, new TreePadOption[0] ); treeView.Tree.Selection.Mode = SelectionMode.Single; treeView.WidthRequest = 300; Pack1 (treeView, false, false); SetDetail (null); ShowAll (); } void SetDetail (Widget detail) { var child2 = Child2; if (child2 != null) { Remove (child2); } detail = detail ?? new Label (); detail.WidthRequest = 300; detail.Show (); Pack2 (detail, true, false); } public void SetToolbar (DocumentToolbar toolbar) { } public AddinRegistry Registry { get; private set; } } } ```
e0863198-29b5-4837-a5bc-4ee93b0b336c
{ "language": "C#" }
```c# using System; using System.Net; using System.Threading; using System.Threading.Tasks; using TirkxDownloader.Framework; namespace TirkxDownloader.Models { public class DetailProvider { public async Task GetFileDetail(DownloadInfo detail, CancellationToken ct) { try { var request = (HttpWebRequest)HttpWebRequest.Create(detail.DownloadLink); request.Method = "HEAD"; var response = await request.GetResponseAsync(ct); detail.FileSize = response.ContentLength; } catch (OperationCanceledException) { } } public bool FillCredential(string doamin) { throw new NotImplementedException(); } } } ``` Fix download didn't start by close response in getFileDetail, implement FillCredential method
```c# using System; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using TirkxDownloader.Framework; using TirkxDownloader.Models; namespace TirkxDownloader.Models { public class DetailProvider { private AuthorizationManager _authenticationManager; public DetailProvider(AuthorizationManager authenticationManager) { _authenticationManager = authenticationManager; } public async Task GetFileDetail(DownloadInfo detail, CancellationToken ct) { try { var request = (HttpWebRequest)HttpWebRequest.Create(detail.DownloadLink); request.Method = "HEAD"; var response = await request.GetResponseAsync(ct); detail.FileSize = response.ContentLength; response.Close(); } catch (OperationCanceledException) { } } public async Task FillCredential(HttpWebRequest request) { string targetDomain = ""; string domain = request.Host; AuthorizationInfo authorizationInfo = _authenticationManager.GetCredential(domain); using (StreamReader str = new StreamReader("Target domain.dat", Encoding.UTF8)) { string storedDomian; while ((storedDomian = await str.ReadLineAsync()) != null) { if (storedDomian.Like(domain)) { targetDomain = storedDomian; // if it isn't wildcards, it done if (!storedDomian.Contains("*")) { break; } } } } AuthorizationInfo credential = _authenticationManager.GetCredential(targetDomain); if (credential != null) { var netCredential = new NetworkCredential(credential.Username, credential.Password, domain); request.Credentials = netCredential; } else { // if no credential was found, try to use default credential request.UseDefaultCredentials = true; } } } } ```
ddbbe4ff-1774-4d3c-a95c-ae6867eea138
{ "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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] [Ignore("HUD components broken, remove when fixed.")] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent); }); } } } ``` Remove the ignore attribute once again
```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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent); }); } } } ```
547ca63c-277c-4221-b4b8-d17dc1ec0891
{ "language": "C#" }
```c# <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script> <script> var data = (function ($) { var getData = (function() { $.ajax({ method: "GET", url: "GetMammals", dataType: "json", success: function (response) { print(response); }, failure: function (response) { alert(response.d); } }); }); function print(data) { document.write( data.Dog.Name + ": " + data.Dog.Type + " / " + data.Cat.Name + ": " + data.Cat.Type ); } return { getData: getData } })(jQuery); </script> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <script> data.getData(); </script> </div> </body> </html> ``` Fix 404 error when calling GetMammals, incorrect route
```c# <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script> <script> var data = (function ($) { var getData = (function() { $.ajax({ method: "GET", url: "@Url.Action("GetMammals", "Home")", dataType: "json", success: function (response) { print(response); }, failure: function (response) { alert(response.d); } }); }); function print(data) { document.write( data.Dog.Name + ": " + data.Dog.Type + " / " + data.Cat.Name + ": " + data.Cat.Type ); } return { getData: getData } })(jQuery); </script> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <script> data.getData(); </script> </div> </body> </html> ```
f07366af-c2b5-4b7e-afd4-8ffc3fd9fe1b
{ "language": "C#" }
```c# using ServiceStack.ServiceHost; namespace License.Manager.Core.Model { [Route("/customers", "POST")] [Route("/customers/{Id}", "PUT, DELETE")] [Route("/customers/{Id}", "GET, OPTIONS")] public class Customer : EntityBase { public string Name { get; set; } public string Company { get; set; } public string Email { get; set; } } }``` Add response DTO marker interface for service documentation
```c# using ServiceStack.ServiceHost; namespace License.Manager.Core.Model { [Route("/customers", "POST")] [Route("/customers/{Id}", "PUT, DELETE")] [Route("/customers/{Id}", "GET, OPTIONS")] public class Customer : EntityBase, IReturn<Customer> { public string Name { get; set; } public string Company { get; set; } public string Email { get; set; } } }```
d7c22e20-d90c-40dd-b276-2d0f62351b71
{ "language": "C#" }
```c# /***************************************************************************** * * ReoGrid - .NET Spreadsheet Control * * https://reogrid.net/ * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * Author: Jing Lu <jingwood at unvell.com> * * Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com> * Copyright (c) 2012-2016 unvell.com, all rights reserved. * ****************************************************************************/ #if PRINT #if WPF using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Xps; using System.Windows.Xps.Packaging; using unvell.ReoGrid.Print; namespace unvell.ReoGrid.Print { partial class PrintSession { internal void Init() { } public void Dispose() { } /// <summary> /// Start output document to printer. /// </summary> public void Print() { throw new NotImplementedException("WPF Print is not implemented yet. Try use Windows Form version to print document as XPS file."); } } } namespace unvell.ReoGrid { partial class Worksheet { } } #endif // WPF #endif // PRINT``` Fix compiling error on .net451
```c# /***************************************************************************** * * ReoGrid - .NET Spreadsheet Control * * https://reogrid.net/ * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * Author: Jing Lu <jingwood at unvell.com> * * Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com> * Copyright (c) 2012-2016 unvell.com, all rights reserved. * ****************************************************************************/ #if PRINT #if WPF using System; using System.Collections.Generic; using System.Linq; using System.Text; using unvell.ReoGrid.Print; namespace unvell.ReoGrid.Print { partial class PrintSession { internal void Init() { } public void Dispose() { } /// <summary> /// Start output document to printer. /// </summary> public void Print() { throw new NotImplementedException("WPF Print is not implemented yet. Try use Windows Form version to print document as XPS file."); } } } namespace unvell.ReoGrid { partial class Worksheet { } } #endif // WPF #endif // PRINT```
9b9a354d-fcfb-4917-abb2-129c139f899c
{ "language": "C#" }
```c# namespace TraktApiSharp.Objects.Get.Shows { using Newtonsoft.Json; /// <summary> /// The air time of a Trakt show. /// </summary> public class TraktShowAirs { /// <summary> /// The day of week on which the show airs. /// </summary> [JsonProperty(PropertyName = "day")] public string Day { get; set; } /// <summary> /// The time of day at which the show airs. /// </summary> [JsonProperty(PropertyName = "time")] public string Time { get; set; } /// <summary> /// The time zone id (Olson) for the location in which the show airs. /// </summary> [JsonProperty(PropertyName = "timezone")] public string TimeZoneId { get; set; } } } ``` Add documentation for show airs.
```c# namespace TraktApiSharp.Objects.Get.Shows { using Newtonsoft.Json; /// <summary>The air time of a Trakt show.</summary> public class TraktShowAirs { /// <summary>Gets or sets the day of week on which the show airs.</summary> [JsonProperty(PropertyName = "day")] public string Day { get; set; } /// <summary>Gets or sets the time of day at which the show airs.</summary> [JsonProperty(PropertyName = "time")] public string Time { get; set; } /// <summary>Gets or sets the time zone id (Olson) for the location in which the show airs.</summary> [JsonProperty(PropertyName = "timezone")] public string TimeZoneId { get; set; } } } ```
a26730af-bb00-4737-8f66-b771fefba61b
{ "language": "C#" }
```c# using LanguageExt; using static LanguageExt.Prelude; using System; using System.Reactive.Linq; using System.Threading; using Xunit; namespace LanguageExtTests { public class DelayTests { [Fact] public void DelayTest1() { var span = TimeSpan.FromMilliseconds(500); var till = DateTime.Now.Add(span); var v = 0; delay(() => 1, span).Subscribe(x => v = x); while( DateTime.Now < till.AddMilliseconds(20) ) { Assert.True(v == 0); Thread.Sleep(1); } while (DateTime.Now < till.AddMilliseconds(100)) { Thread.Sleep(1); } Assert.True(v == 1); } } } ``` Remove delay test for CI for now
```c# using LanguageExt; using static LanguageExt.Prelude; using System; using System.Reactive.Linq; using System.Threading; using Xunit; namespace LanguageExtTests { public class DelayTests { #if !CI [Fact] public void DelayTest1() { var span = TimeSpan.FromMilliseconds(500); var till = DateTime.Now.Add(span); var v = 0; delay(() => 1, span).Subscribe(x => v = x); while( DateTime.Now < till ) { Assert.True(v == 0); Thread.Sleep(1); } while (DateTime.Now < till.AddMilliseconds(100)) { Thread.Sleep(1); } Assert.True(v == 1); } #endif } } ```
9f56bc58-b63e-4ff0-9f61-b7aa6880ef98
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace OS2Indberetning { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //// Turns off self reference looping when serializing models in API controlllers //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //// Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } } ``` Add debug logging and injection of "Accept-Charset" header that is required when running on Mono
```c# using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Http.ExceptionHandling; using System.Web.Http.Controllers; using System.Net.Http.Headers; using System.Diagnostics; using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute; namespace OS2Indberetning { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); #if DEBUG GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new DebugExceptionLogger()); GlobalConfiguration.Configuration.Filters.Add(new AddAcceptCharsetHeaderActionFilter()); #endif //// Turns off self reference looping when serializing models in API controlllers //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //// Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } #if DEBUG public class AddAcceptCharsetHeaderActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { // Inject "Accept-Charset" header into the client request, // since apparently this is required when running on Mono // See: https://github.com/OData/odata.net/issues/165 actionContext.Request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("UTF-8")); base.OnActionExecuting(actionContext); } } public class DebugExceptionLogger : ExceptionLogger { public override void Log(ExceptionLoggerContext context) { Debug.WriteLine(context.Exception); } } #endif } ```
82ded0eb-9cb9-4b4f-a7ee-86ea04b58888
{ "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.Diagnostics; using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuations to a scheduler instance. /// </summary> internal class GameThreadSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public int TotalTasksRun => scheduler.TotalTasksRun; public GameThreadSynchronizationContext(GameThread gameThread) { scheduler = new GameThreadScheduler(gameThread); } public override void Send(SendOrPostCallback d, object? state) { var del = scheduler.Add(() => d(state)); Debug.Assert(del != null); while (del.State == ScheduledDelegate.RunState.Waiting) { if (scheduler.IsMainThread) scheduler.Update(); else Thread.Sleep(1); } } public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state)); public void RunWork() => scheduler.Update(); } } ``` Add xmldoc describing `SynchronizationContext` behaviour
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using System.Threading; #nullable enable namespace osu.Framework.Threading { /// <summary> /// A synchronisation context which posts all continuations to an isolated scheduler instance. /// </summary> /// <remarks> /// This implementation roughly follows the expectations set out for winforms/WPF as per /// https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/february/msdn-magazine-parallel-computing-it-s-all-about-the-synchronizationcontext. /// - Calls to <see cref="Post"/> are guaranteed to run asynchronously. /// - Calls to <see cref="Send"/> will run inline when they can. /// - Order of execution is guaranteed (in our case, it is guaranteed over <see cref="Send"/> and <see cref="Post"/> calls alike). /// - To enforce the above, calling <see cref="Send"/> will flush any pending work until the newly queued item has been completed. /// </remarks> internal class GameThreadSynchronizationContext : SynchronizationContext { private readonly Scheduler scheduler; public int TotalTasksRun => scheduler.TotalTasksRun; public GameThreadSynchronizationContext(GameThread gameThread) { scheduler = new GameThreadScheduler(gameThread); } public override void Send(SendOrPostCallback callback, object? state) { var scheduledDelegate = scheduler.Add(() => callback(state)); Debug.Assert(scheduledDelegate != null); while (scheduledDelegate.State == ScheduledDelegate.RunState.Waiting) { if (scheduler.IsMainThread) scheduler.Update(); else Thread.Sleep(1); } } public override void Post(SendOrPostCallback callback, object? state) => scheduler.Add(() => callback(state)); public void RunWork() => scheduler.Update(); } } ```
0d898845-539e-4fc0-b2dd-d41464a3312c
{ "language": "C#" }
```c# using System; namespace MultiMiner.Xgminer.Api { public class DeviceInformation { public DeviceInformation() { Status = String.Empty; } public string Kind { get; set; } public string Name { get; set; } public int Index { get; set; } public bool Enabled { get; set; } public string Status { get; set; } public double Temperature { get; set; } public int FanSpeed { get; set; } public int FanPercent { get; set; } public int GpuClock { get; set; } public int MemoryClock { get; set; } public double GpuVoltage { get; set; } public int GpuActivity { get; set; } public int PowerTune { get; set; } public double AverageHashrate { get; set; } public double CurrentHashrate { get; set; } public int AcceptedShares { get; set; } public int RejectedShares { get; set; } public int HardwareErrors { get; set; } public double Utility { get; set; } public string Intensity { get; set; } //string, might be D public int PoolIndex { get; set; } } } ``` Fix a null reference error using cgminer as a backend
```c# using System; namespace MultiMiner.Xgminer.Api { public class DeviceInformation { public DeviceInformation() { Status = String.Empty; Name = String.Empty; //cgminer may / does not return this } public string Kind { get; set; } public string Name { get; set; } public int Index { get; set; } public bool Enabled { get; set; } public string Status { get; set; } public double Temperature { get; set; } public int FanSpeed { get; set; } public int FanPercent { get; set; } public int GpuClock { get; set; } public int MemoryClock { get; set; } public double GpuVoltage { get; set; } public int GpuActivity { get; set; } public int PowerTune { get; set; } public double AverageHashrate { get; set; } public double CurrentHashrate { get; set; } public int AcceptedShares { get; set; } public int RejectedShares { get; set; } public int HardwareErrors { get; set; } public double Utility { get; set; } public string Intensity { get; set; } //string, might be D public int PoolIndex { get; set; } } } ```
33fddf8e-b305-4db4-a597-08520a36d980
{ "language": "C#" }
```c# using System; using Newtonsoft.Json.Linq; namespace Saule.Serialization { internal class ResourceDeserializer { private readonly JToken _object; private readonly Type _target; public ResourceDeserializer(JToken @object, Type target) { _object = @object; _target = target; } public object Deserialize() { return ToFlatStructure(_object).ToObject(_target); } private JToken ToFlatStructure(JToken json) { var array = json["data"] as JArray; if (array == null) { var obj = json["data"] as JObject; if (obj == null) { return null; } return SingleToFlatStructure(json["data"] as JObject); } var result = new JArray(); foreach (var child in array) { result.Add(SingleToFlatStructure(child as JObject)); } return result; } private JToken SingleToFlatStructure(JObject child) { var result = new JObject(); if (child["id"] != null) { result["id"] = child["id"]; } foreach (var attr in child["attributes"] ?? new JArray()) { var prop = attr as JProperty; result.Add(prop?.Name.ToPascalCase(), prop?.Value); } foreach (var rel in child["relationships"] ?? new JArray()) { var prop = rel as JProperty; result.Add(prop?.Name.ToPascalCase(), ToFlatStructure(prop?.Value)); } return result; } } }``` Fix failing style check... second attempt
```c# using System; using Newtonsoft.Json.Linq; namespace Saule.Serialization { internal class ResourceDeserializer { private readonly JToken _object; private readonly Type _target; public ResourceDeserializer(JToken @object, Type target) { _object = @object; _target = target; } public object Deserialize() { return ToFlatStructure(_object).ToObject(_target); } private JToken ToFlatStructure(JToken json) { var array = json["data"] as JArray; if (array == null) { var obj = json["data"] as JObject; if (obj == null) { return null; } return SingleToFlatStructure(json["data"] as JObject); } var result = new JArray(); foreach (var child in array) { result.Add(SingleToFlatStructure(child as JObject)); } return result; } private JToken SingleToFlatStructure(JObject child) { var result = new JObject(); if (child["id"] != null) { result["id"] = child["id"]; } foreach (var attr in child["attributes"] ?? new JArray()) { var prop = attr as JProperty; result.Add(prop?.Name.ToPascalCase(), prop?.Value); } foreach (var rel in child["relationships"] ?? new JArray()) { var prop = rel as JProperty; result.Add(prop?.Name.ToPascalCase(), ToFlatStructure(prop?.Value)); } return result; } } }```
7debafdf-89b4-4b41-bc7f-74adc8b41ea5
{ "language": "C#" }
```c# using UnityEngine; namespace UnityTouchRecorder { public class TouchRecorderController : MonoBehaviour { UnityTouchRecorderPlugin plugin = new UnityTouchRecorderPlugin(); [SerializeField] TouchRecorderView view; void Awake() { Object.DontDestroyOnLoad(gameObject); view.OpenMenuButton.onClick.AddListener(() => { view.SetMenuActive(!view.IsMenuActive); }); view.StartRecordingButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.StartRecording(); }); view.PlayButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Play(view.Repeat, view.Interval); }); view.StopButton.onClick.AddListener(() => { view.OpenMenuButton.gameObject.SetActive(true); view.StopButton.gameObject.SetActive(false); plugin.StopRecording(); plugin.Stop(); }); } } }``` Clear record before start new recording
```c# using UnityEngine; namespace UnityTouchRecorder { public class TouchRecorderController : MonoBehaviour { UnityTouchRecorderPlugin plugin = new UnityTouchRecorderPlugin(); [SerializeField] TouchRecorderView view; void Awake() { Object.DontDestroyOnLoad(gameObject); view.OpenMenuButton.onClick.AddListener(() => { view.SetMenuActive(!view.IsMenuActive); }); view.StartRecordingButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Clear(); plugin.StartRecording(); }); view.PlayButton.onClick.AddListener(() => { view.SetMenuActive(false); view.OpenMenuButton.gameObject.SetActive(false); view.StopButton.gameObject.SetActive(true); plugin.Play(view.Repeat, view.Interval); }); view.StopButton.onClick.AddListener(() => { view.OpenMenuButton.gameObject.SetActive(true); view.StopButton.gameObject.SetActive(false); plugin.StopRecording(); plugin.Stop(); }); } } }```
4158d08f-ce40-4357-90f0-1f034004b42a
{ "language": "C#" }
```c# using UnityEngine; using UnityEditor; using System; using System.IO; using System.Collections; public class CaptureWindow : EditorWindow{ private string saveFileName = string.Empty; private string saveDirPath = string.Empty; [MenuItem("Window/Capture Editor")] private static void Capture() { EditorWindow.GetWindow (typeof(CaptureWindow)).Show (); } void OnGUI() { EditorGUILayout.LabelField ("OUTPUT FOLDER PATH:"); EditorGUILayout.LabelField (saveDirPath + "/"); if (string.IsNullOrEmpty (saveDirPath)) { saveDirPath = Application.dataPath; } if (GUILayout.Button("Select output directory")) { string path = EditorUtility.OpenFolderPanel("select directory", saveDirPath, Application.dataPath); if (!string.IsNullOrEmpty(path)) { saveDirPath = path; } } if (GUILayout.Button("Open output directory")) { System.Diagnostics.Process.Start (saveDirPath); } // insert blank line GUILayout.Label (""); if (GUILayout.Button("Take screenshot")) { var outputPath = saveDirPath + "/" + DateTime.Now.ToString ("yyyyMMddHHmmss") + ".png"; ScreenCapture.CaptureScreenshot (outputPath); Debug.Log ("Export scrennshot at " + outputPath); } } } ``` Change output path, change screentshot image file name.
```c# using UnityEngine; using UnityEditor; using System; public class CaptureWindow : EditorWindow { private string saveFileName = string.Empty; private string saveDirPath = string.Empty; [MenuItem("Window/Screenshot Capture")] private static void Capture() { EditorWindow.GetWindow(typeof(CaptureWindow)).Show(); } private void OnGUI() { EditorGUILayout.LabelField("Output Folder Path : "); EditorGUILayout.LabelField(saveDirPath + "/"); if (string.IsNullOrEmpty(saveDirPath)) { saveDirPath = Application.dataPath + "/.."; } if (GUILayout.Button("Select output directory")) { string path = EditorUtility.OpenFolderPanel("select directory", saveDirPath, Application.dataPath); if (!string.IsNullOrEmpty(path)) { saveDirPath = path; } } if (GUILayout.Button("Open output directory")) { System.Diagnostics.Process.Start(saveDirPath); } // insert blank line GUILayout.Label(""); if (GUILayout.Button("Take screenshot")) { var resolution = GetMainGameViewSize(); int x = (int)resolution.x; int y = (int)resolution.y; var outputPath = saveDirPath + "/" + DateTime.Now.ToString($"{x}x{y}_yyyy_MM_dd_HH_mm_ss") + ".png"; ScreenCapture.CaptureScreenshot(outputPath); Debug.Log("Export scrennshot at " + outputPath); } } public static Vector2 GetMainGameViewSize() { System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor"); System.Reflection.MethodInfo GetSizeOfMainGameView = T.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); System.Object Res = GetSizeOfMainGameView.Invoke(null, null); return (Vector2)Res; } }```
30749b34-bcf9-4d61-97bc-8252944c8ee3
{ "language": "C#" }
```c# // Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IKeyboardHandler { bool OnKeyEvent(IWebBrowser browser, KeyType type, int code, CefEventFlags modifiers, bool isSystemKey); bool OnPreKeyEvent(IWebBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, bool isKeyboardShortcut); } } ``` Make OnPreKeyEvent isKeyboardShortcut a ref param
```c# // Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IKeyboardHandler { bool OnKeyEvent(IWebBrowser browser, KeyType type, int code, CefEventFlags modifiers, bool isSystemKey); bool OnPreKeyEvent(IWebBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut); } } ```
9defe451-59bb-4cfd-94d1-a26335d0f178
{ "language": "C#" }
```c# /** * Language Patches Framework * Translates the game into different Languages * Copyright (c) 2016 Thomas P. * Licensed under the terms of the MIT License */ using System; namespace LanguagePatches { /// <summary> /// A class that represents a text translation /// </summary> public class Translation { /// <summary> /// The original message, uses Regex syntax /// </summary> public String text { get; set; } /// <summary> /// The replacement message, uses String.Format syntax /// </summary> public String translation { get; set; } /// <summary> /// Creates a new Translation component from a config node /// </summary> /// <param name="node">The config node where the </param> public Translation(ConfigNode node) { // Check for original text if (!node.HasValue("text")) throw new Exception("The config node is missing the text value!"); // Check for translation if (!node.HasValue("translation")) throw new Exception("The config node is missing the translation value!"); // Assign the new texts text = node.GetValue("text"); translation = node.GetValue("translation"); } } } ``` Use placeholder expressions, {nr} doesn't work because of ConfigNode beign weird
```c# /** * Language Patches Framework * Translates the game into different Languages * Copyright (c) 2016 Thomas P. * Licensed under the terms of the MIT License */ using System; using System.Text.RegularExpressions; namespace LanguagePatches { /// <summary> /// A class that represents a text translation /// </summary> public class Translation { /// <summary> /// The original message, uses Regex syntax /// </summary> public String text { get; set; } /// <summary> /// The replacement message, uses String.Format syntax /// </summary> public String translation { get; set; } /// <summary> /// Creates a new Translation component from a config node /// </summary> /// <param name="node">The config node where the </param> public Translation(ConfigNode node) { // Check for original text if (!node.HasValue("text")) throw new Exception("The config node is missing the text value!"); // Check for translation if (!node.HasValue("translation")) throw new Exception("The config node is missing the translation value!"); // Assign the new texts text = node.GetValue("text"); translation = node.GetValue("translation"); // Replace variable placeholders translation = Regex.Replace(translation, @"@(\d*)", "{$1}"); } } } ```
66ecca2e-6fc8-4bb0-9de8-89865ed4fa56
{ "language": "C#" }
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } } ``` Update server side API for single multiple answer question
```c# using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRepository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var questions = _dbContext.SingleMultipleAnswerQuestion.ToList(); return questions; } /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption); _dbContext.SaveChanges(); } } } ```
eaea4b49-890d-4f0f-b43a-f1fc4a9ec456
{ "language": "C#" }
```c# namespace Bakery.Configuration.Properties { using System; public class PropertyNotFoundException : Exception { private readonly String propertyName; public PropertyNotFoundException(String propertyName) { this.propertyName = propertyName; } public override String Message { get { return $"Property \"${propertyName}\" not found."; } } } } ``` Remove erroneous "$" symbol from "bling string."
```c# namespace Bakery.Configuration.Properties { using System; public class PropertyNotFoundException : Exception { private readonly String propertyName; public PropertyNotFoundException(String propertyName) { this.propertyName = propertyName; } public override String Message { get { return $"Property \"{propertyName}\" not found."; } } } } ```
337a3f58-33bd-4f8e-b2b1-b27c2430130b
{ "language": "C#" }
```c# using System.ComponentModel; using System.Windows; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 150; Style.FramePadding = new Thickness(0); } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "http://"; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }``` Change default Search URL Prefix
```c# using System.ComponentModel; using System.Windows; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 150; Style.FramePadding = new Thickness(0); } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "https://www.google.com/search?q="; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }```
d1de5458-7914-48da-8c2d-e75cc5ea0b28
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; namespace Exceptionless.Core.Extensions { public static class UriExtensions { public static string ToQueryString(this NameValueCollection collection) { return collection.AsKeyValuePairs().ToQueryString(); } public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) { return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={pair.Value}", "&"); } /// <summary> /// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence. /// </summary> private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) { return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key))); } public static string GetBaseUrl(this Uri uri) { return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath; } } }``` Fix encoding issue while the query string parameters contains Chinese characters
```c# using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; namespace Exceptionless.Core.Extensions { public static class UriExtensions { public static string ToQueryString(this NameValueCollection collection) { return collection.AsKeyValuePairs().ToQueryString(); } public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) { return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={System.Web.HttpUtility.UrlEncode(pair.Value)}", "&"); } /// <summary> /// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence. /// </summary> private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) { return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key))); } public static string GetBaseUrl(this Uri uri) { return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath; } } }```
83f34ed9-c5fa-4a30-bb8d-8e2793c05d23
{ "language": "C#" }
```c# // Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Test { public class TestUserProfileService : IProfileService { private readonly ILogger<TestUserProfileService> _logger; private readonly TestUserStore _users; public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger) { _users = users; _logger = logger; } public Task GetProfileDataAsync(ProfileDataRequestContext context) { _logger.LogDebug("Get profile called for subject {subject} from client {client} with claim types{claimTypes} via {caller}", context.Subject.GetSubjectId(), context.Client.ClientName ?? context.Client.ClientId, context.RequestedClaimTypes, context.Caller); if (context.RequestedClaimTypes.Any()) { var user = _users.FindBySubjectId(context.Subject.GetSubjectId()); context.AddFilteredClaims(user.Claims); } return Task.FromResult(0); } public Task IsActiveAsync(IsActiveContext context) { context.IsActive = true; return Task.FromResult(0); } } }``` Make TestUserProfile service more derivation friendly
```c# // Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Test { public class TestUserProfileService : IProfileService { protected readonly ILogger Logger; protected readonly TestUserStore Users; public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger) { Users = users; Logger = logger; } public virtual Task GetProfileDataAsync(ProfileDataRequestContext context) { Logger.LogDebug("Get profile called for subject {subject} from client {client} with claim types {claimTypes} via {caller}", context.Subject.GetSubjectId(), context.Client.ClientName ?? context.Client.ClientId, context.RequestedClaimTypes, context.Caller); if (context.RequestedClaimTypes.Any()) { var user = Users.FindBySubjectId(context.Subject.GetSubjectId()); context.AddFilteredClaims(user.Claims); } return Task.FromResult(0); } public virtual Task IsActiveAsync(IsActiveContext context) { context.IsActive = true; return Task.FromResult(0); } } }```
38b1f42e-fbf7-4a44-8d4d-15bdad547bfc
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterfaceV2; using osu.Game.Screens.Edit.Setup; namespace osu.Game.Rulesets.Mania.Edit.Setup { public class ManiaSetupSection : RulesetSetupSection { private LabelledSwitchButton specialStyle; public ManiaSetupSection() : base(new ManiaRuleset().RulesetInfo) { } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { specialStyle = new LabelledSwitchButton { Label = "Use special (N+1) style", Current = { Value = Beatmap.BeatmapInfo.SpecialStyle } } }; } protected override void LoadComplete() { base.LoadComplete(); specialStyle.Current.BindValueChanged(_ => updateBeatmap()); } private void updateBeatmap() { Beatmap.BeatmapInfo.SpecialStyle = specialStyle.Current.Value; } } } ``` Add description for mania special style
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterfaceV2; using osu.Game.Screens.Edit.Setup; namespace osu.Game.Rulesets.Mania.Edit.Setup { public class ManiaSetupSection : RulesetSetupSection { private LabelledSwitchButton specialStyle; public ManiaSetupSection() : base(new ManiaRuleset().RulesetInfo) { } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { specialStyle = new LabelledSwitchButton { Label = "Use special (N+1) style", Description = "Changes one column to act as a classic \"scratch\" or \"special\" column, which can be moved around by the user's skin (to the left/right/centre). Generally used in 5k (4+1) or 8key (7+1) configurations.", Current = { Value = Beatmap.BeatmapInfo.SpecialStyle } } }; } protected override void LoadComplete() { base.LoadComplete(); specialStyle.Current.BindValueChanged(_ => updateBeatmap()); } private void updateBeatmap() { Beatmap.BeatmapInfo.SpecialStyle = specialStyle.Current.Value; } } } ```
0ddb41a6-a630-4ed8-ac4b-c9fb899c3237
{ "language": "C#" }
```c# namespace dotless.Core.Plugins { using System; using Parser.Infrastructure.Nodes; using Parser.Tree; using Utils; using System.ComponentModel; [Description("Automatically spins all colors in a less file"), DisplayName("ColorSpin")] public class ColorSpinPlugin : VisitorPlugin { public double Spin { get; set; } public ColorSpinPlugin(double spin) { Spin = spin; } public override VisitorPluginType AppliesTo { get { return VisitorPluginType.AfterEvaluation; } } public override Node Execute(Node node, out bool visitDeeper) { visitDeeper = true; if(node is Color) { var color = node as Color; var hslColor = HslColor.FromRgbColor(color); hslColor.Hue += Spin/360.0d; var newColor = hslColor.ToRgbColor(); //node = new Color(newColor.R, newColor.G, newColor.B); color.R = newColor.R; color.G = newColor.G; color.B = newColor.B; } return node; } } }``` Refactor away property setter usages to allow Color to be immutable.
```c# namespace dotless.Core.Plugins { using Parser.Infrastructure.Nodes; using Parser.Tree; using Utils; using System.ComponentModel; [Description("Automatically spins all colors in a less file"), DisplayName("ColorSpin")] public class ColorSpinPlugin : VisitorPlugin { public double Spin { get; set; } public ColorSpinPlugin(double spin) { Spin = spin; } public override VisitorPluginType AppliesTo { get { return VisitorPluginType.AfterEvaluation; } } public override Node Execute(Node node, out bool visitDeeper) { visitDeeper = true; var color = node as Color; if (color == null) return node; var hslColor = HslColor.FromRgbColor(color); hslColor.Hue += Spin/360.0d; var newColor = hslColor.ToRgbColor(); return newColor.ReducedFrom<Color>(color); } } }```
e58ff4ab-d16b-4d57-b9e8-c422b732f275
{ "language": "C#" }
```c# namespace SIM.Tool.Windows.MainWindowComponents { using System.IO; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Core; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; [UsedImplicitly] public class CreateSupportPatchButton : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { if (instance == null) { WindowHelper.ShowMessage("Choose an instance first"); return; } var product = instance.Product; Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first."); var version = product.Version + "." + product.Update; CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/CreatePatch.application?p1={version}&p2={instance.Name}&p3={instance.WebRootPath}"); NuGetHelper.UpdateSettings(); NuGetHelper.GeneratePackages(new FileInfo(product.PackagePath)); foreach (var module in instance.Modules) { NuGetHelper.GeneratePackages(new FileInfo(module.PackagePath)); } } #endregion } }``` Add support of Patch Creator 1.0.0.9
```c# namespace SIM.Tool.Windows.MainWindowComponents { using System; using System.IO; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Core; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; [UsedImplicitly] public class CreateSupportPatchButton : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { if (instance == null) { WindowHelper.ShowMessage("Choose an instance first"); return; } var product = instance.Product; Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first."); var version = product.Version + "." + product.Update; var args = new[] { version, instance.Name, instance.WebRootPath }; var dir = Environment.ExpandEnvironmentVariables("%APPDATA%\\Sitecore\\CreatePatch"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllLines(Path.Combine(dir, "args.txt"), args); CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/CreatePatch.application"); NuGetHelper.UpdateSettings(); NuGetHelper.GeneratePackages(new FileInfo(product.PackagePath)); foreach (var module in instance.Modules) { NuGetHelper.GeneratePackages(new FileInfo(module.PackagePath)); } } #endregion } }```
9d60ae57-fa34-42c4-ace6-83115d877457
{ "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.Screens.Select; using osuTK; namespace osu.Game.Tests.Visual.SongSelect { public class TestSceneDifficultyRangeFilterControl : OsuTestScene { [Test] public void TestBasic() { Child = new DifficultyRangeFilterControl { Width = 200, Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(3), }; } } } ``` Fix new test failing on headless runs
```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.Screens.Select; using osuTK; namespace osu.Game.Tests.Visual.SongSelect { public class TestSceneDifficultyRangeFilterControl : OsuTestScene { [Test] public void TestBasic() { AddStep("create control", () => { Child = new DifficultyRangeFilterControl { Width = 200, Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(3), }; }); } } } ```
b594bf2c-39f9-4fd3-bd62-487295a006e0
{ "language": "C#" }
```c# // // DnxProjectConfiguration.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using MonoDevelop.Projects; namespace MonoDevelop.Dnx { public class DnxProjectConfiguration : DotNetProjectConfiguration { public DnxProjectConfiguration (string name) : base (name) { } public DnxProjectConfiguration () { } } } ``` Use external console when running DNX apps.
```c# // // DnxProjectConfiguration.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (c) 2015 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using MonoDevelop.Projects; namespace MonoDevelop.Dnx { public class DnxProjectConfiguration : DotNetProjectConfiguration { public DnxProjectConfiguration (string name) : base (name) { ExternalConsole = true; } public DnxProjectConfiguration () { ExternalConsole = true; } } } ```
24d74725-7f99-4b10-bcb6-536668643f05
{ "language": "C#" }
```c# @model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td>@Html.DisplayFor(_ => model.TotalScore)</td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>``` Add indicator to APFT list
```c# @model IEnumerable<APFT> <div class="page-header"> <h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1> </div> <table class="table table-striped" id="dt"> <thead> <tr> <th>Soldier</th> <th>Date</th> <th>Score</th> <th>Result</th> <th>Details</th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td> <a href="@Url.Action("Index", new { date = model.Date })"> @Html.DisplayFor(_ => model.Date) </a> </td> <td> @Html.DisplayFor(_ => model.TotalScore) @if(model.IsAlternateAerobicEvent) { <span class="label">Alt. Aerobic</span> } </td> <td> @if (model.IsPassing) { <span class="label label-success">Passing</span> } else { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>```
0046ccaa-599f-4857-aa52-b73511a842c9
{ "language": "C#" }
```c# using System; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetAnalyser.UnitTest { [TestClass] public class MetaTest { private const int ExpectedMinimumTests = 836; [TestMethod] public void ListAllTests() { Assembly assembly = GetType().Assembly; var count = 0; foreach (Type type in assembly.ExportedTypes) { var testClassAttrib = type.GetCustomAttribute<TestClassAttribute>(); if (testClassAttrib != null) { foreach (MethodInfo method in type.GetMethods()) { if (method.GetCustomAttribute<TestMethodAttribute>() != null) { Console.WriteLine("{0} {1} - {2}", ++count, type.FullName, method.Name); } } } } } [TestMethod] public void NoDecreaseInTests() { int count = CountTests(); Console.WriteLine(count); Assert.IsTrue(count >= ExpectedMinimumTests); } [TestMethod] public void UpdateNoDecreaseInTests() { int count = CountTests(); Assert.IsFalse(count > ExpectedMinimumTests + 10, "Update the minimum expected number of tests to " + count); } private int CountTests() { Assembly assembly = GetType().Assembly; int count = (from type in assembly.ExportedTypes let testClassAttrib = type.GetCustomAttribute<TestClassAttribute>() where testClassAttrib != null select type.GetMethods().Count(method => method.GetCustomAttribute<TestMethodAttribute>() != null)).Sum(); return count; } } }``` Increase number of tests total
```c# using System; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BudgetAnalyser.UnitTest { [TestClass] public class MetaTest { private const int ExpectedMinimumTests = 868; [TestMethod] public void ListAllTests() { Assembly assembly = GetType().Assembly; var count = 0; foreach (Type type in assembly.ExportedTypes) { var testClassAttrib = type.GetCustomAttribute<TestClassAttribute>(); if (testClassAttrib != null) { foreach (MethodInfo method in type.GetMethods()) { if (method.GetCustomAttribute<TestMethodAttribute>() != null) { Console.WriteLine("{0} {1} - {2}", ++count, type.FullName, method.Name); } } } } } [TestMethod] public void NoDecreaseInTests() { int count = CountTests(); Console.WriteLine(count); Assert.IsTrue(count >= ExpectedMinimumTests); } [TestMethod] public void UpdateNoDecreaseInTests() { int count = CountTests(); Assert.IsFalse(count > ExpectedMinimumTests + 10, "Update the minimum expected number of tests to " + count); } private int CountTests() { Assembly assembly = GetType().Assembly; int count = (from type in assembly.ExportedTypes let testClassAttrib = type.GetCustomAttribute<TestClassAttribute>() where testClassAttrib != null select type.GetMethods().Count(method => method.GetCustomAttribute<TestMethodAttribute>() != null)).Sum(); return count; } } }```
32bd0c87-78dc-48aa-b076-00c7f95d0b08
{ "language": "C#" }
```c# using System; using Agiil.Data; using Agiil.Domain.Data; using Autofac; using CSF.Data; using CSF.Data.Entities; using CSF.Data.NHibernate; namespace Agiil.Bootstrap.Data { public class DataModule : Module { protected override void Load(ContainerBuilder builder) { builder .RegisterType<NHibernateQuery>() .As<IQuery>(); builder .RegisterType<NHibernatePersister>() .As<IPersister>(); builder .RegisterType<DatabaseCreator>() .As<IDatabaseCreator>(); builder .RegisterType<DevelopmentInitialDataCreator>() .As<IInitialDataCreator>(); builder .RegisterGeneric(typeof(GenericRepository<>)) .As(typeof(IRepository<>)); builder .RegisterType<TransactionCreator>() .As<ITransactionCreator>(); builder .RegisterType<HardcodedDatabaseConfiguration>() .As<IDatabaseConfiguration>(); } } } ``` Add repository to bootstrap registrations
```c# using System; using Agiil.Data; using Agiil.Domain.Data; using Autofac; using CSF.Data; using CSF.Data.Entities; using CSF.Data.NHibernate; namespace Agiil.Bootstrap.Data { public class DataModule : Module { protected override void Load(ContainerBuilder builder) { builder .RegisterType<NHibernateQuery>() .As<IQuery>(); builder .RegisterType<NHibernatePersister>() .As<IPersister>(); builder .RegisterType<DatabaseCreator>() .As<IDatabaseCreator>(); builder .RegisterType<DevelopmentInitialDataCreator>() .As<IInitialDataCreator>(); builder .RegisterGeneric(typeof(GenericRepository<>)) .As(typeof(IRepository<>)); builder .RegisterType<Repository>() .As<IRepository>(); builder .RegisterType<TransactionCreator>() .As<ITransactionCreator>(); builder .RegisterType<HardcodedDatabaseConfiguration>() .As<IDatabaseConfiguration>(); } } } ```
2955bb10-1c5a-4515-bb94-005550175646
{ "language": "C#" }
```c# using System; using System.IO; using System.Runtime.InteropServices; using Windows.Storage; namespace Urho.UWP { public static class UwpUrhoInitializer { internal static void OnInited() { var folder = ApplicationData.Current.LocalFolder.Path; } } } ``` Add warning for UWP that it works only in x86 yet
```c# using System; using System.IO; using System.Runtime.InteropServices; using Windows.Storage; namespace Urho.UWP { public static class UwpUrhoInitializer { internal static void OnInited() { var folder = ApplicationData.Current.LocalFolder.Path; if (IntPtr.Size == 8) { throw new NotSupportedException("x86_64 is not supported yet. Please use x86."); } } } } ```
7fff1345-68cd-4862-984b-801a0ced5351
{ "language": "C#" }
```c# @inherits UmbracoViewPage<MenuViewModel> <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@Model.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in Model.MenuItems) { var selected = Model.Content.Path.Split(',').Select(int.Parse).Contains(item.Id); <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div>``` Change menu partial view type
```c# @model MenuViewModel <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@Model.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in Model.MenuItems) { var selected = Model.Content.Path.Split(',').Select(int.Parse).Contains(item.Id); <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div>```
789201b7-3754-495f-ace2-02160d103fe0
{ "language": "C#" }
```c# using System; using System.Runtime.InteropServices; using UnityEngine; namespace com.adjust.sdk.oaid { #if UNITY_ANDROID public class AdjustOaidAndroid { private static AndroidJavaClass ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); public static void ReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("readOaid"); } public static void DoNotReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("doNotReadOaid"); } } #endif } ``` Use new OAID reading method
```c# using System; using System.Runtime.InteropServices; using UnityEngine; namespace com.adjust.sdk.oaid { #if UNITY_ANDROID public class AdjustOaidAndroid { private static AndroidJavaClass ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); private static AndroidJavaObject ajoCurrentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"); public static void ReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("readOaid", ajoCurrentActivity); } public static void DoNotReadOaid() { if (ajcAdjustOaid == null) { ajcAdjustOaid = new AndroidJavaClass("com.adjust.sdk.oaid.AdjustOaid"); } ajcAdjustOaid.CallStatic("doNotReadOaid"); } } #endif } ```
17e74cac-06fd-4002-8253-7e63115cbb58
{ "language": "C#" }
```c# using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Python for .NET")] [assembly: AssemblyVersion("4.0.0.1")] [assembly: AssemblyDefaultAlias("Python.Runtime.dll")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyCopyright("MIT License")] [assembly: AssemblyFileVersion("2.0.0.2")] [assembly: NeutralResourcesLanguage("en")] #if PYTHON27 [assembly: AssemblyTitle("Python.Runtime for Python 2.7")] [assembly: AssemblyDescription("Python Runtime for Python 2.7")] #elif PYTHON33 [assembly: AssemblyTitle("Python.Runtime for Python 3.3")] [assembly: AssemblyDescription("Python Runtime for Python 3.3")] #elif PYTHON34 [assembly: AssemblyTitle("Python.Runtime for Python 3.4")] [assembly: AssemblyDescription("Python Runtime for Python 3.4")] #elif PYTHON35 [assembly: AssemblyTitle("Python.Runtime for Python 3.5")] [assembly: AssemblyDescription("Python Runtime for Python 3.5")] #elif PYTHON36 [assembly: AssemblyTitle("Python.Runtime for Python 3.6")] [assembly: AssemblyDescription("Python Runtime for Python 3.6")] #elif PYTHON37 [assembly: AssemblyTitle("Python.Runtime for Python 3.7")] [assembly: AssemblyDescription("Python Runtime for Python 3.7")] #endif ``` Make internals (in particular Runtime.*) visible to the tests.
```c# using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Python for .NET")] [assembly: AssemblyVersion("4.0.0.1")] [assembly: AssemblyDefaultAlias("Python.Runtime.dll")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyCopyright("MIT License")] [assembly: AssemblyFileVersion("2.0.0.2")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo("Python.EmbeddingTest")] ```
7a667670-630b-416e-932c-67e847d48df7
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { // Custom attribute to indicating a TypeDef is a discardable attribute. public class DiscardableAttribute : Attribute { public DiscardableAttribute() { } } } ``` Fix FxCop warning CA1018 (attributes should have AttributeUsage)
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { // Custom attribute to indicating a TypeDef is a discardable attribute. [AttributeUsage(AttributeTargets.All)] public class DiscardableAttribute : Attribute { public DiscardableAttribute() { } } } ```
67c0edaf-770d-41cf-bb7e-136a2be5002f
{ "language": "C#" }
```c# using System.Diagnostics.CodeAnalysis; namespace Parsley; public static class ParserExtensions { public static bool TryParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { var parseToEnd = from result in parse from end in Grammar.EndOfInput<TItem>() select result; return TryPartialParse(parseToEnd, input, out int index, out value, out error); } public static bool TryPartialParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, out int index, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { index = 0; value = parse(input, ref index, out var succeeded, out var expectation); if (succeeded) { error = null; #pragma warning disable CS8762 // Parameter must have a non-null value when exiting in some condition. return true; #pragma warning restore CS8762 // Parameter must have a non-null value when exiting in some condition. } error = new ParseError(index, expectation!); return false; } } ``` Rephrase parsing to the end of input in terms of Map.
```c# using System.Diagnostics.CodeAnalysis; namespace Parsley; public static class ParserExtensions { public static bool TryParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { var parseToEnd = Grammar.Map(parse, Grammar.EndOfInput<TItem>(), (result, _) => result); return TryPartialParse(parseToEnd, input, out int index, out value, out error); } public static bool TryPartialParse<TItem, TValue>( this Parser<TItem, TValue> parse, ReadOnlySpan<TItem> input, out int index, [NotNullWhen(true)] out TValue? value, [NotNullWhen(false)] out ParseError? error) { index = 0; value = parse(input, ref index, out var succeeded, out var expectation); if (succeeded) { error = null; #pragma warning disable CS8762 // Parameter must have a non-null value when exiting in some condition. return true; #pragma warning restore CS8762 // Parameter must have a non-null value when exiting in some condition. } error = new ParseError(index, expectation!); return false; } } ```
f07a0b1b-d6a0-45cd-886a-7d5b4b3ed1a3
{ "language": "C#" }
```c# using System.ComponentModel; namespace StackExchange.Opserver.Views.Dashboard { public enum CurrentStatusTypes { [Description("None")] None = 0, Stats = 1, Interfaces = 2, [Description("VM Info")] VMHost = 3, [Description("Elastic")] Elastic = 4, HAProxy = 5, [Description("SQL Instance")] SQLInstance = 6, [Description("Active SQL")] SQLActive = 7, [Description("Top SQL")] SQLTop = 8, [Description("Redis Info")] Redis = 9 } }``` Fix tab names on node views
```c# using System.ComponentModel; namespace StackExchange.Opserver.Views.Dashboard { public enum CurrentStatusTypes { [Description("None")] None = 0, [Description("Stats")] Stats = 1, [Description("Interfaces")] Interfaces = 2, [Description("VM Info")] VMHost = 3, [Description("Elastic")] Elastic = 4, [Description("HAProxy")] HAProxy = 5, [Description("SQL Instance")] SQLInstance = 6, [Description("Active SQL")] SQLActive = 7, [Description("Top SQL")] SQLTop = 8, [Description("Redis Info")] Redis = 9 } }```
9e8a305b-a353-46f2-9b5b-3ebb95423dae
{ "language": "C#" }
```c# @model ReviewOrderViewModel <section id="notes" class="ui-corner-all display-form"> <header class="ui-corner-top ui-widget-header"> <div class="col1 showInNav">Order Notes</div> <div class="col2"> <a href="#" class="button" id="add-note">Add Note</a> </div> </header> <div class="section-contents"> @if (!Model.Comments.Any()) { <span class="notes-not-found">There Are No Notes Attached To This Order</span> } <table class="noicon"> <tbody> @foreach (var notes in Model.Comments.OrderBy(o => o.DateCreated)) { <tr> <td>@notes.DateCreated.ToString("d")</td> <td>@notes.Text</td> <td>@notes.User.FullName</td> </tr> } </tbody> </table> </div> @*<footer class="ui-corner-bottom"></footer>*@ </section> <div id="notes-dialog" title="Add Order Notes" style="display:none;"> <textarea id="notes-box" style="width: 370px; height: 110px;"></textarea> </div> <script id="comment-template" type="text/x-jquery-tmpl"> <tr> <td>${datetime}</td> <td>${txt}</td> <td>${user}</td> </tr> </script> ``` Add the time as a title to the order notes date.
```c# @model ReviewOrderViewModel <section id="notes" class="ui-corner-all display-form"> <header class="ui-corner-top ui-widget-header"> <div class="col1 showInNav">Order Notes</div> <div class="col2"> <a href="#" class="button" id="add-note">Add Note</a> </div> </header> <div class="section-contents"> @if (!Model.Comments.Any()) { <span class="notes-not-found">There Are No Notes Attached To This Order</span> } <table class="noicon"> <tbody> @foreach (var notes in Model.Comments.OrderBy(o => o.DateCreated)) { <tr> <td title="@notes.DateCreated.ToString("T")">@notes.DateCreated.ToString("d")</td> <td>@notes.Text</td> <td>@notes.User.FullName</td> </tr> } </tbody> </table> </div> @*<footer class="ui-corner-bottom"></footer>*@ </section> <div id="notes-dialog" title="Add Order Notes" style="display:none;"> <textarea id="notes-box" style="width: 370px; height: 110px;"></textarea> </div> <script id="comment-template" type="text/x-jquery-tmpl"> <tr> <td>${datetime}</td> <td>${txt}</td> <td>${user}</td> </tr> </script> ```
d3e97184-551f-47e7-b2ca-f2ef678d57b7
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Testing; namespace osu.Framework.Tests { public class AutomatedVisualTestGame : Game { public AutomatedVisualTestGame() { Add(new TestBrowserTestRunner(new TestBrowser())); } } }``` Add resources to the automated tests too
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.IO.Stores; using osu.Framework.Testing; namespace osu.Framework.Tests { public class AutomatedVisualTestGame : Game { [BackgroundDependencyLoader] private void load() { Resources.AddStore(new NamespacedResourceStore<byte[]>(new DllResourceStore(@"osu.Framework.Tests.exe"), "Resources")); } public AutomatedVisualTestGame() { Add(new TestBrowserTestRunner(new TestBrowser())); } } }```
33d77f27-6032-4a59-becd-60beaf56ee8c
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // 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.5")] [assembly: AssemblyFileVersion("1.0.0.6")] ``` Increment version number to sync up with NuGet
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [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("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // 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.7")] [assembly: AssemblyFileVersion("1.0.0.7")] ```
7e547801-7406-48ca-893a-910644e94886
{ "language": "C#" }
```c# using Xunit; namespace Humanizer.Tests { public class NumberToWordsTests { [Fact] public void ToWords() { Assert.Equal("one", 1.ToWords()); Assert.Equal("ten", 10.ToWords()); Assert.Equal("eleven", 11.ToWords()); Assert.Equal("one hundred and twenty-two", 122.ToWords()); Assert.Equal("three thousand five hundred and one", 3501.ToWords()); } [Fact] public void RoundNumbersHaveNoSpaceAtTheEnd() { Assert.Equal("one hundred", 100.ToWords()); Assert.Equal("one thousand", 1000.ToWords()); Assert.Equal("one hundred thousand", 100000.ToWords()); Assert.Equal("one million", 1000000.ToWords()); } } } ``` Convert ToWords' tests to theory
```c# using Xunit; using Xunit.Extensions; namespace Humanizer.Tests { public class NumberToWordsTests { [InlineData(1, "one")] [InlineData(10, "ten")] [InlineData(11, "eleven")] [InlineData(122, "one hundred and twenty-two")] [InlineData(3501, "three thousand five hundred and one")] [InlineData(100, "one hundred")] [InlineData(1000, "one thousand")] [InlineData(100000, "one hundred thousand")] [InlineData(1000000, "one million")] [Theory] public void Test(int number, string expected) { Assert.Equal(expected, number.ToWords()); } } } ```
0d15952b-c863-415e-a02a-0e9387ca4a9f
{ "language": "C#" }
```c# using System; using Business.Core.Profile; namespace Version { class MainClass { public static void Main(string[] args) { Console.WriteLine("Hello World!"); var profile = new Profile(); var sqlitedatabase = new Business.Core.SQLite.Database(profile); Console.WriteLine($"SQLite\t\t{sqlitedatabase.SchemaVersion()}"); sqlitedatabase.Connection.Close(); var pgsqldatabase = new Business.Core.PostgreSQL.Database(profile); Console.WriteLine($"PostgreSQL\t{pgsqldatabase.SchemaVersion()}"); pgsqldatabase.Connection.Close(); var nuodbdatabase = new Business.Core.NuoDB.Database(profile); Console.WriteLine($"NuoDB\t\t{nuodbdatabase.SchemaVersion()}"); nuodbdatabase.Connection.Close(); } } } ``` Use the same type variable for all three database servers
```c# using System; using Business.Core; using Business.Core.Profile; namespace Version { class MainClass { public static void Main(string[] args) { Console.WriteLine("Hello World!"); var profile = new Profile(); IDatabase database; database = new Business.Core.SQLite.Database(profile); Console.WriteLine($"SQLite\t\t{database.SchemaVersion()}"); database.Connection.Close(); database = new Business.Core.PostgreSQL.Database(profile); Console.WriteLine($"PostgreSQL\t{database.SchemaVersion()}"); database.Connection.Close(); database = new Business.Core.NuoDB.Database(profile); Console.WriteLine($"NuoDB\t\t{database.SchemaVersion()}"); database.Connection.Close(); } } } ```
ce6a3479-cb2d-426b-8fc0-75119f5ace96
{ "language": "C#" }
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.4.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.4.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif``` Update OData WebAPI to 5.5.0.0
```c# // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #if !BUILD_GENERATED_VERSION [assembly: AssemblyCompany("Microsoft Corporation.")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] #if !NOT_CLS_COMPLIANT [assembly: CLSCompliant(true)] #endif [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata("Serviceable", "True")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETODATA #if !BUILD_GENERATED_VERSION [assembly: AssemblyVersion("5.5.0.0")] // ASPNETODATA [assembly: AssemblyFileVersion("5.5.0.0")] // ASPNETODATA #endif [assembly: AssemblyProduct("Microsoft OData Web API")] #endif```
d1a76dc5-7ec9-4fe7-9433-ddea04b6b7cc
{ "language": "C#" }
```c# using System; using Xwt.Backends; using Xwt.Drawing; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; #else using Foundation; using AppKit; using ObjCRuntime; #endif namespace Xwt.Mac { public class EmbedNativeWidgetBackend : ViewBackend, IEmbeddedWidgetBackend { NSView innerView; public EmbedNativeWidgetBackend () { } public override void Initialize () { ViewObject = new WidgetView (EventSink, ApplicationContext); if (innerView != null) { var aView = innerView; innerView = null; SetNativeView (aView); } } public void SetContent (object nativeWidget) { if (nativeWidget is NSView) { if (ViewObject == null) innerView = (NSView)nativeWidget; else SetNativeView ((NSView)nativeWidget); } } void SetNativeView (NSView aView) { if (innerView != null) innerView.RemoveFromSuperview (); innerView = aView; innerView.Frame = Widget.Bounds; Widget.AddSubview (innerView); } } } ``` Fix sizing of embedded (wrapped) native NSViews
```c# using System; using Xwt.Backends; using Xwt.Drawing; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; #else using Foundation; using AppKit; using ObjCRuntime; #endif namespace Xwt.Mac { public class EmbedNativeWidgetBackend : ViewBackend, IEmbeddedWidgetBackend { NSView innerView; public EmbedNativeWidgetBackend () { } public override void Initialize () { ViewObject = new WidgetView (EventSink, ApplicationContext); if (innerView != null) { var aView = innerView; innerView = null; SetNativeView (aView); } } public void SetContent (object nativeWidget) { if (nativeWidget is NSView) { if (ViewObject == null) innerView = (NSView)nativeWidget; else SetNativeView ((NSView)nativeWidget); } } void SetNativeView (NSView aView) { if (innerView != null) innerView.RemoveFromSuperview (); innerView = aView; innerView.Frame = Widget.Bounds; innerView.AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable; innerView.TranslatesAutoresizingMaskIntoConstraints = true; Widget.AutoresizesSubviews = true; Widget.AddSubview (innerView); } } } ```
f874d793-cade-41fc-a067-f25645463165
{ "language": "C#" }
```c# using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using SO115App.FakePersistenceJSon.GestioneIntervento; using SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso.GenerazioneCodiciRichiesta; using System; namespace SO115App.FakePersistence.JSon.Utility { public class GeneraCodiceRichiesta : IGeneraCodiceRichiesta { public string Genera(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; string nuovoNumero = GetMaxCodice.GetMax().ToString(); return string.Format("{0}-{1}-{2:D5}", codiceProvincia, ultimeDueCifreAnno, nuovoNumero); } public string GeneraCodiceChiamata(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; int giorno = DateTime.UtcNow.Day; int mese = DateTime.UtcNow.Month; int nuovoNumero = GetMaxCodice.GetMaxCodiceChiamata(); string returnString = string.Format("{0}-{1}-{2}-{3}_{4:D5}", codiceProvincia, giorno, mese, ultimeDueCifreAnno, nuovoNumero); return returnString; } } } ``` Fix - Modificata la generazione del Codice Richiesta e del Codice Chiamata come richiesto nella riunone dell'11-07-2019
```c# using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using SO115App.FakePersistenceJSon.GestioneIntervento; using SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso.GenerazioneCodiciRichiesta; using System; namespace SO115App.FakePersistence.JSon.Utility { public class GeneraCodiceRichiesta : IGeneraCodiceRichiesta { public string Genera(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; string nuovoNumero = GetMaxCodice.GetMax().ToString(); return string.Format("{0}{1}{2:D5}", codiceProvincia.Split('.')[0], ultimeDueCifreAnno, nuovoNumero); } public string GeneraCodiceChiamata(string codiceProvincia, int anno) { int ultimeDueCifreAnno = anno % 100; int giorno = DateTime.UtcNow.Day; int mese = DateTime.UtcNow.Month; int nuovoNumero = GetMaxCodice.GetMaxCodiceChiamata(); string returnString = string.Format("{0}{1}{2}{3}{4:D5}", codiceProvincia.Split('.')[0], giorno, mese, ultimeDueCifreAnno, nuovoNumero); return returnString; } } } ```
4b2b6a10-0d89-4f4c-865f-b38734722c82
{ "language": "C#" }
```c# using System.Web.Script.Serialization; namespace JsonConfig { public static class JsonConfigManager { #region Fields private static readonly IConfigFileLoader ConfigFileLoader = new ConfigFileLoader(); private static dynamic _defaultConfig; #endregion #region Public Members public static dynamic DefaultConfig { get { if (_defaultConfig == null) { _defaultConfig = GetConfig(ConfigFileLoader.LoadDefaultConfigFile()); } return _defaultConfig; } } public static dynamic GetConfig(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); return serializer.Deserialize(json, typeof(object)); } public static dynamic LoadConfig(string filePath) { return GetConfig(ConfigFileLoader.LoadConfigFile(filePath)); } #endregion } } ``` Add comments to public methods
```c# using System.Web.Script.Serialization; namespace JsonConfig { public static class JsonConfigManager { #region Fields private static readonly IConfigFileLoader ConfigFileLoader = new ConfigFileLoader(); private static dynamic _defaultConfig; #endregion #region Public Members /// <summary> /// Gets the default config dynamic object, which should be a file named app.json.config located at the root of your project /// </summary> public static dynamic DefaultConfig { get { if (_defaultConfig == null) { _defaultConfig = GetConfig(ConfigFileLoader.LoadDefaultConfigFile()); } return _defaultConfig; } } /// <summary> /// Get a config dynamic object from the json /// </summary> /// <param name="json">Json string</param> /// <returns>The dynamic config object</returns> public static dynamic GetConfig(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); return serializer.Deserialize(json, typeof(object)); } /// <summary> /// Load a config from a specified file /// </summary> /// <param name="filePath">Config file path</param> /// <returns>The dynamic config object</returns> public static dynamic LoadConfig(string filePath) { return GetConfig(ConfigFileLoader.LoadConfigFile(filePath)); } #endregion } } ```
ae2b0dc8-3b24-4520-ba39-16d3b33fe262
{ "language": "C#" }
```c# @{ if (Layout.IsCartPage != true) { Script.Require("jQuery"); Script.Include("shoppingcart.js", "shoppingcart.min.js"); <div class="shopping-cart-container minicart" data-load="@Url.Action("NakedCart", "ShoppingCart", new {area="Nwazet.Commerce"})" data-update="@Url.Action("AjaxUpdate", "ShoppingCart", new {area="Nwazet.Commerce"})" data-token="@Html.AntiForgeryTokenValueOrchard()"></div> } } ``` Fix to ajax restoration of the cart.
```c# @{ if (Layout.IsCartPage != true) { Script.Require("jQuery"); Script.Include("shoppingcart.js", "shoppingcart.min.js"); <div class="shopping-cart-container minicart" data-load="@Url.Action("NakedCart", "ShoppingCart", new {area="Nwazet.Commerce"})" data-update="@Url.Action("AjaxUpdate", "ShoppingCart", new {area="Nwazet.Commerce"})" data-token="@Html.AntiForgeryTokenValueOrchard()"></div> <script type="text/javascript"> var Nwazet = window.Nwazet || {}; Nwazet.WaitWhileWeRestoreYourCart = "@T("Please wait while we restore your shopping cart...")"; Nwazet.FailedToLoadCart = "@T("Failed to load the cart")"; </script> } } ```
fe2db5bc-9879-4573-801d-003071d40d97
{ "language": "C#" }
```c# using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 15 20 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }``` Change levy run date to 24th
```c# using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using NServiceBus; using SFA.DAS.EmployerFinance.Messages.Commands; namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs { public class ImportLevyDeclarationsJob { private readonly IMessageSession _messageSession; public ImportLevyDeclarationsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 10 24 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ImportLevyDeclarationsCommand()); } } }```
997ddf3e-8afc-4002-ba8f-1447e36ac62d
{ "language": "C#" }
```c# // Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using Microsoft.ApplicationInsights.DependencyCollector; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; internal static class IServiceCollectionExtensions { internal static void DisableApplicationInsights(this IServiceCollection services) { // Disable dependency tracking to work around https://github.com/Microsoft/ApplicationInsights-dotnet-server/pull/1006 services.Configure<TelemetryConfiguration>((p) => p.DisableTelemetry = true); services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>( (module, _) => { module.DisableDiagnosticSourceInstrumentation = true; module.DisableRuntimeInstrumentation = true; module.SetComponentCorrelationHttpHeaders = false; module.IncludeDiagnosticSourceActivities.Clear(); }); } } } ``` Remove Application Insights modules and initializers
```c# // Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using Microsoft.ApplicationInsights.DependencyCollector; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; internal static class IServiceCollectionExtensions { internal static void DisableApplicationInsights(this IServiceCollection services) { // Disable dependency tracking to work around https://github.com/Microsoft/ApplicationInsights-dotnet-server/pull/1006 services.Configure<TelemetryConfiguration>((p) => p.DisableTelemetry = true); services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>( (module, _) => { module.DisableDiagnosticSourceInstrumentation = true; module.DisableRuntimeInstrumentation = true; module.SetComponentCorrelationHttpHeaders = false; module.IncludeDiagnosticSourceActivities.Clear(); }); services.RemoveAll<ITelemetryInitializer>(); services.RemoveAll<ITelemetryModule>(); } } } ```
60aee0da-2504-4a3a-8fa2-7138b11d7f42
{ "language": "C#" }
```c# // ------------------------------------------------------------------------- // Managed wrapper for QSize // Generated from qt-gui.xml on 07/24/2011 11:57:03 // // This file was auto generated. Do not edit. // ------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using Mono.Cxxi; namespace Qt.Gui { [StructLayout (LayoutKind.Sequential)] public struct QSize { public int wd; public int ht; public QSize (int w, int h) { wd = w; ht = h; } } } ``` Remove auto-generated warning from handwritten file
```c# using System; using System.Runtime.InteropServices; using Mono.Cxxi; namespace Qt.Gui { [StructLayout (LayoutKind.Sequential)] public struct QSize { public int wd; public int ht; public QSize (int w, int h) { wd = w; ht = h; } } } ```
b8421a17-6746-484b-821e-a37d3b10f6bb
{ "language": "C#" }
```c# using Ninject; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FunWithNinject.OpenGenerics { [TestFixture] public class OpenGenericsTests { public interface ILogger<T> { Type GenericParam { get; } } public class Logger<T> : ILogger<T> { public Type GenericParam { get { return typeof(T); } } } public class DependsOnLogger { public DependsOnLogger(ILogger<int> intLogger) { GenericParam = intLogger.GenericParam; } public Type GenericParam { get; set; } } [Test] public void OpenGenericBinding() { using (var k = new StandardKernel()) { // Assemble k.Bind(typeof(ILogger<>)).To(typeof(Logger<>)); // Act var dependsOn = k.Get<DependsOnLogger>(); // Assert Assert.AreEqual(typeof(int), dependsOn.GenericParam); } } } } ``` Change the names to be in line with the problem at hand.
```c# using Ninject; using NUnit.Framework; using System; namespace FunWithNinject.OpenGenerics { [TestFixture] public class OpenGenericsTests { [Test] public void OpenGenericBinding() { using (var k = new StandardKernel()) { // Assemble k.Bind(typeof(IAutoCache<>)).To(typeof(AutoCache<>)); // Act var dependsOn = k.Get<DependsOnLogger>(); // Assert Assert.AreEqual(typeof(int), dependsOn.CacheType); } } #region Types public interface IAutoCache<T> { Type CacheType { get; } } public class AutoCache<T> : IAutoCache<T> { public Type CacheType { get { return typeof(T); } } } public class DependsOnLogger { public DependsOnLogger(IAutoCache<int> intCacher) { CacheType = intCacher.CacheType; } public Type CacheType { get; set; } } #endregion } }```
b46f18f6-ac55-45bd-9b08-145f54101948
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sogeti.Capstone.CQS.Integration.Tests { [TestClass] public class EventCommands { [TestMethod] public void CreateEventCommand() { } } } ``` Set up references for event command unit tests
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sogeti.Capstone.CQS.Integration.Tests { [TestClass] public class EventCommands { [TestMethod] public void CreateEventCommand() { } } } ```
af82f663-aa8a-4ab0-a5c6-5bbaed08e002
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }``` Update state to be used after redirect
```c# using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Net; using System.Text; using System.Web; namespace SimpleWAWS.Authentication { public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider { public override string GetLoginUrl(HttpContextBase context) { var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant(); var builder = new StringBuilder(); builder.Append("https://accounts.google.com/o/oauth2/auth"); builder.Append("?response_type=id_token"); builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"]))); builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId); builder.AppendFormat("&scope={0}", "email"); builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()|| context.IsFunctionsPortalRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery)); return builder.ToString(); } protected override string GetValidAudiance() { return AuthSettings.GoogleAppId; } public override string GetIssuerName(string altSecId) { return "Google"; } } }```
d8bd0647-2451-4453-a201-7d9281b0b7b5
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Nether.Data.Leaderboard; namespace Nether.Web.Features.Leaderboard { public class LeaderboardGetResponseModel { public List<LeaderboardEntry> Entries { get; set; } public class LeaderboardEntry { public static implicit operator LeaderboardEntry(GameScore score) { return new LeaderboardEntry { Gamertag = score.Gamertag, Score = score.Score }; } /// <summary> /// Gamertag /// </summary> public string Gamertag { get; set; } /// <summary> /// Scores /// </summary> public int Score { get; set; } } } }``` Add Rank to returned scores
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Nether.Data.Leaderboard; namespace Nether.Web.Features.Leaderboard { public class LeaderboardGetResponseModel { public List<LeaderboardEntry> Entries { get; set; } public class LeaderboardEntry { public static implicit operator LeaderboardEntry(GameScore score) { return new LeaderboardEntry { Gamertag = score.Gamertag, Score = score.Score, Rank = score.Rank }; } /// <summary> /// Gamertag /// </summary> public string Gamertag { get; set; } /// <summary> /// Scores /// </summary> public int Score { get; set; } public long Rank { get; set; } } } }```
1e342cc4-8349-472f-a080-e363004a6369
{ "language": "C#" }
```c# using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Alexa.NET.Management.Api { public class CustomApiEndpoint { [JsonProperty("uri")] public string Uri { get; set; } [JsonProperty("sslCertificateType")] public SslCertificateType SslCertificateType { get; set; } } } ``` Add correct JSON serialization for enum type
```c# using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Text; namespace Alexa.NET.Management.Api { public class CustomApiEndpoint { [JsonProperty("uri")] public string Uri { get; set; } [JsonProperty("sslCertificateType"), JsonConverter(typeof(StringEnumConverter))] public SslCertificateType SslCertificateType { get; set; } } } ```
3fe892e9-1aca-47f0-bc50-1479a3cdcf3d
{ "language": "C#" }
```c# using System; using System.Linq; namespace Stripe.Tests { static class Constants { public const string ApiKey = @"8GSx9IL9MA0iJ3zcitnGCHonrXWiuhMf"; } } ``` Update Stripe test API key from their docs
```c# using System; using System.Linq; namespace Stripe.Tests { static class Constants { public const string ApiKey = @"sk_test_BQokikJOvBiI2HlWgH4olfQ2"; } } ```
56bbf7cc-1c07-4949-8369-90a699c13fc1
{ "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 Senparc.Weixin.MP.CoreSample { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } } ``` Migrate from ASP.NET Core 2.0 to 2.1
```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 Senparc.Weixin.MP.CoreSample { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } } ```
753ce12a-8ad4-4b63-88e3-4d50bc443a31
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Diagnostics; namespace Basics.Structures.Graphs { [DebuggerDisplay("{Source}->{Target}")] public class Edge<T> : IEquatable<Edge<T>> where T : IEquatable<T> { private readonly Lazy<int> _hashCode; public Edge(T source, T target) { Source = source; Target = target; _hashCode = new Lazy<int>(() => { var sourceHashCode = Source.GetHashCode(); return ((sourceHashCode << 5) + sourceHashCode) ^ Target.GetHashCode(); }); } public T Source { get; private set; } public T Target { get; private set; } public bool IsSelfLooped { get { return Source.Equals(Target); } } public static bool operator ==(Edge<T> a, Edge<T> b) { return a.Equals(b); } public static bool operator !=(Edge<T> a, Edge<T> b) { return !a.Equals(b); } public bool Equals(Edge<T> other) { return !Object.ReferenceEquals(other, null) && this.Source.Equals(other.Source) && this.Target.Equals(other.Target); } public override bool Equals(object obj) { return Equals(obj as Edge<T>); } public override int GetHashCode() { return _hashCode.Value; } public override string ToString() { return Source + "->" + Target; } } } ``` Remove laziness from edges' GetHashCode method
```c# using System; using System.Collections.Generic; using System.Diagnostics; namespace Basics.Structures.Graphs { [DebuggerDisplay("{Source}->{Target}")] public class Edge<T> : IEquatable<Edge<T>> where T : IEquatable<T> { public Edge(T source, T target) { Source = source; Target = target; } public T Source { get; private set; } public T Target { get; private set; } public bool IsSelfLooped { get { return Source.Equals(Target); } } public static bool operator ==(Edge<T> a, Edge<T> b) { return a.Equals(b); } public static bool operator !=(Edge<T> a, Edge<T> b) { return !a.Equals(b); } public bool Equals(Edge<T> other) { return !Object.ReferenceEquals(other, null) && this.Source.Equals(other.Source) && this.Target.Equals(other.Target); } public override bool Equals(object obj) { return Equals(obj as Edge<T>); } public override int GetHashCode() { var sourceHashCode = Source.GetHashCode(); return ((sourceHashCode << 5) + sourceHashCode) ^ Target.GetHashCode(); } public override string ToString() { return Source + "->" + Target; } } } ```
bd4a820b-cf96-4703-8f10-e378d48b904d
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace BlogTemplate.Models { public class BlogDataStore { const string StorageFolder = "BlogFiles"; public void SavePost(Post post) { Directory.CreateDirectory(StorageFolder); string outputFilePath = $"{StorageFolder}\\{post.Slug}.xml"; XmlDocument doc = new XmlDocument(); XmlElement rootNode = doc.CreateElement("Post"); doc.AppendChild(rootNode); rootNode.AppendChild(doc.CreateElement("Slug")).InnerText = post.Slug; rootNode.AppendChild(doc.CreateElement("Title")).InnerText = post.Title; rootNode.AppendChild(doc.CreateElement("Body")).InnerText = post.Body; doc.Save(outputFilePath); } } } ``` Add simple method to read back in a Post from disk
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace BlogTemplate.Models { public class BlogDataStore { const string StorageFolder = "BlogFiles"; public void SavePost(Post post) { Directory.CreateDirectory(StorageFolder); string outputFilePath = $"{StorageFolder}\\{post.Slug}.xml"; XmlDocument doc = new XmlDocument(); XmlElement rootNode = doc.CreateElement("Post"); doc.AppendChild(rootNode); rootNode.AppendChild(doc.CreateElement("Slug")).InnerText = post.Slug; rootNode.AppendChild(doc.CreateElement("Title")).InnerText = post.Title; rootNode.AppendChild(doc.CreateElement("Body")).InnerText = post.Body; doc.Save(outputFilePath); } public Post GetPost(string slug) { string expectedFilePath = $"{StorageFolder}\\{slug}.xml"; if(File.Exists(expectedFilePath)) { string fileContent = File.ReadAllText(expectedFilePath); XmlDocument doc = new XmlDocument(); doc.LoadXml(fileContent); Post post = new Post(); post.Slug = doc.GetElementsByTagName("Slug").Item(0).InnerText; post.Title = doc.GetElementsByTagName("Title").Item(0).InnerText; post.Body = doc.GetElementsByTagName("Body").Item(0).InnerText; return post; } return null; } } } ```
f234dcab-9789-40c7-bd2e-247d1ed09d69
{ "language": "C#" }
```c# namespace MassTransit { using AspNetCoreIntegration; using AspNetCoreIntegration.HealthChecks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Monitoring.Health; /// <summary> /// These are the updated extensions compatible with the container registration code. They should be used, for real. /// </summary> public static class HostedServiceConfigurationExtensions { /// <summary> /// Adds the MassTransit <see cref="IHostedService" />, which includes a bus and endpoint health check. /// Use it together with UseHealthCheck to get more detailed diagnostics. /// </summary> /// <param name="services"></param> public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services) { AddHealthChecks(services); return services.AddSingleton<IHostedService, MassTransitHostedService>(); } public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services, IBusControl bus) { AddHealthChecks(services); return services.AddSingleton<IHostedService>(p => new BusHostedService(bus)); } static void AddHealthChecks(IServiceCollection services) { services.AddOptions(); services.AddHealthChecks(); services.AddSingleton<IConfigureOptions<HealthCheckServiceOptions>>(provider => new ConfigureBusHealthCheckServiceOptions(provider.GetServices<IBusHealth>(), new[] {"ready"})); } } } ``` Add identifying tag to MassTransit health checks.
```c# namespace MassTransit { using AspNetCoreIntegration; using AspNetCoreIntegration.HealthChecks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Monitoring.Health; /// <summary> /// These are the updated extensions compatible with the container registration code. They should be used, for real. /// </summary> public static class HostedServiceConfigurationExtensions { /// <summary> /// Adds the MassTransit <see cref="IHostedService" />, which includes a bus and endpoint health check. /// Use it together with UseHealthCheck to get more detailed diagnostics. /// </summary> /// <param name="services"></param> public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services) { AddHealthChecks(services); return services.AddSingleton<IHostedService, MassTransitHostedService>(); } public static IServiceCollection AddMassTransitHostedService(this IServiceCollection services, IBusControl bus) { AddHealthChecks(services); return services.AddSingleton<IHostedService>(p => new BusHostedService(bus)); } static void AddHealthChecks(IServiceCollection services) { services.AddOptions(); services.AddHealthChecks(); services.AddSingleton<IConfigureOptions<HealthCheckServiceOptions>>(provider => new ConfigureBusHealthCheckServiceOptions(provider.GetServices<IBusHealth>(), new[] {"ready", "masstransit"})); } } } ```
d5719511-0f07-460c-9083-f4907115c5b2
{ "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.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { /// <summary> /// A container that adds the ability to shake its contents. /// </summary> public class ShakeContainer : Container { /// <summary> /// Shake the contents of this container. /// </summary> public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } } ``` Reduce shake transform count by one for more aesthetic behaviour
```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.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Graphics.Containers { /// <summary> /// A container that adds the ability to shake its contents. /// </summary> public class ShakeContainer : Container { /// <summary> /// Shake the contents of this container. /// </summary> public void Shake() { const float shake_amount = 8; const float shake_duration = 30; this.MoveToX(shake_amount, shake_duration / 2, Easing.OutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(-shake_amount, shake_duration, Easing.InOutSine).Then() .MoveToX(0, shake_duration / 2, Easing.InSine); } } } ```
72c1a914-6295-4d8b-9acf-312ce8dfa850
{ "language": "C#" }
```c# // Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows; using System.Windows.Input; namespace CefSharp.Wpf { internal class DelegateCommand : ICommand { private readonly Action commandHandler; private readonly Func<bool> canExecuteHandler; public event EventHandler CanExecuteChanged; public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } public void Execute(object parameter) { commandHandler(); } public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } public void RaiseCanExecuteChanged() { if (!Application.Current.Dispatcher.CheckAccess()) { Application.Current.Dispatcher.BeginInvoke((Action) RaiseCanExecuteChanged); return; } if (CanExecuteChanged != null) { CanExecuteChanged(this, new EventArgs()); } } } } ``` Remove call to Application.Current.Dispatcher.CheckAccess() - seems there's a null point happening on a rare instance when Application.Current.Dispatcher is null Rely on parent calling code to execute on the correct thread (which it was already executing on the UI Thread)
```c# // Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Input; namespace CefSharp.Wpf { internal class DelegateCommand : ICommand { private readonly Action commandHandler; private readonly Func<bool> canExecuteHandler; public event EventHandler CanExecuteChanged; public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } public void Execute(object parameter) { commandHandler(); } public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, new EventArgs()); } } } } ```
e8805af2-a521-4219-8450-4ab020db077a
{ "language": "C#" }
```c# @inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation> @if (Model.Invalid) { <div class="text-danger validation-error"> @Model.ErrorMessage </div> } ``` Comment for validation error rendering
```c# @inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation> @* for the NoScript rendering, this is solely rendered server side *@ @if (Model.Invalid) { <div class="text-danger validation-error"> @Model.ErrorMessage </div> } ```
adb0d3ab-5405-4f7f-989e-60edff031880
{ "language": "C#" }
```c# // Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IDownloadHandler { /// <summary> /// Called before a download begins. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">Callback interface used to asynchronously continue a download.</param> /// <returns>Return True to continue the download otherwise return False to cancel the download</returns> void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback); /// <summary> /// Called when a download's status or progress information has been updated. This may be called multiple times before and after <see cref="OnBeforeDownload"/>. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">The callback used to Cancel/Pause/Resume the process</param> /// <returns>Return True to cancel, otherwise False to allow the download to continue.</returns> void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback); } } ``` Remove return xml comments, not valid anymore
```c# // Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { public interface IDownloadHandler { /// <summary> /// Called before a download begins. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">Callback interface used to asynchronously continue a download.</param> void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback); /// <summary> /// Called when a download's status or progress information has been updated. This may be called multiple times before and after <see cref="OnBeforeDownload"/>. /// </summary> /// <param name="browser">The browser instance</param> /// <param name="downloadItem">Represents the file being downloaded.</param> /// <param name="callback">The callback used to Cancel/Pause/Resume the process</param> void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback); } } ```
01f8b389-18bc-4525-a732-4fad60f8bdc8
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null) { Action<IServiceCollection> defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new [] { new KeyValuePair<string, string>("webroot", ".") }) .Build(); var builder = new WebHostBuilder() .UseConfiguration(configuration) .Configure(configureApp) .ConfigureServices(configureServices ?? defaultConfigureServices); return new TestServer(builder); } } }``` Fix content root for non-windows xunit tests with no app domains
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.PlatformAbstractions; namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null) { var contentRootNet451 = PlatformServices.Default.Runtime.OperatingSystemPlatform == Platform.Windows ? "." : "../../../../test/Microsoft.AspNetCore.StaticFiles.Tests"; Action<IServiceCollection> defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new [] { new KeyValuePair<string, string>("webroot", ".") }) .Build(); var builder = new WebHostBuilder() #if NET451 .UseContentRoot(contentRootNet451) #endif .UseConfiguration(configuration) .Configure(configureApp) .ConfigureServices(configureServices ?? defaultConfigureServices); return new TestServer(builder); } } }```
cc91e84b-3b8a-4d3a-a3a1-4e4cf2697115
{ "language": "C#" }
```c# using System; using System.Threading; using NLog; using NLogConfig = NLog.Config; namespace BrowserLog.NLog.Demo { class Program { static void Main(string[] args) { LogManager.Configuration = new NLogConfig.XmlLoggingConfiguration("NLog.config", true); var logger = LogManager.GetLogger("*", typeof(Program)); logger.Info("Hello!"); Thread.Sleep(1000); for (int i = 0; i < 100000; i++) { logger.Info("Hello this is a log from a server-side process!"); Thread.Sleep(100); logger.Warn("Hello this is a warning from a server-side process!"); logger.Debug("... and here is another log again ({0})", i); Thread.Sleep(200); try { ThrowExceptionWithStackTrace(4); } catch (Exception ex) { logger.Error("An error has occured, really?", ex); } Thread.Sleep(1000); } } static void ThrowExceptionWithStackTrace(int depth) { if (depth == 0) { throw new Exception("A fake exception to show an example"); } ThrowExceptionWithStackTrace(--depth); } } } ``` Change obsolete signature for method Error
```c# using System; using System.Threading; using NLog; using NLogConfig = NLog.Config; namespace BrowserLog.NLog.Demo { class Program { static void Main(string[] args) { LogManager.Configuration = new NLogConfig.XmlLoggingConfiguration("NLog.config", true); var logger = LogManager.GetLogger("*", typeof(Program)); logger.Info("Hello!"); Thread.Sleep(1000); for (int i = 0; i < 100000; i++) { logger.Info("Hello this is a log from a server-side process!"); Thread.Sleep(100); logger.Warn("Hello this is a warning from a server-side process!"); logger.Debug("... and here is another log again ({0})", i); Thread.Sleep(200); try { ThrowExceptionWithStackTrace(4); } catch (Exception ex) { logger.Error(ex, "An error has occured, really?"); } Thread.Sleep(1000); } } static void ThrowExceptionWithStackTrace(int depth) { if (depth == 0) { throw new Exception("A fake exception to show an example"); } ThrowExceptionWithStackTrace(--depth); } } } ```
8daa9530-24f3-451f-8bbf-9dba366a6b19
{ "language": "C#" }
```c# using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace food_tracker.DAL { public class WholeDay { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string WholeDayId { get; set; } public DateTime dateTime { get; set; } public double dailyTotal { get; set; } public virtual List<NutritionItem> foodsDuringDay { get; set; } [Obsolete("Only needed for serialization and materialization", true)] public WholeDay() { } public WholeDay(string dayId) { this.WholeDayId = dayId; this.dateTime = DateTime.UtcNow; this.dailyTotal = 0; } } } ``` Change List data type to IEnumerable
```c# using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace food_tracker.DAL { public class WholeDay { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public string WholeDayId { get; set; } public DateTime dateTime { get; set; } public double dailyTotal { get; set; } public virtual IEnumerable<NutritionItem> foodsDuringDay { get; set; } [Obsolete("Only needed for serialization and materialization", true)] public WholeDay() { } public WholeDay(string dayId) { this.WholeDayId = dayId; this.dateTime = DateTime.UtcNow; this.dailyTotal = 0; } } } ```
baa29c52-2415-4163-b7c0-7856ad0ebb23
{ "language": "C#" }
```c# using System; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace Winston.Net { static class Extensions { public static NameValueCollection ParseQueryString(this Uri uri) { var result = new NameValueCollection(); var query = uri.Query; // remove anything other than query string from url if (query.Contains("?")) { query = query.Substring(query.IndexOf('?') + 1); } foreach (string vp in Regex.Split(query, "&")) { var singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { result.Add(singlePair[0], singlePair[1]); } else { // only one key with no value specified in query string result.Add(singlePair[0], string.Empty); } } return result; } } } ``` Add escaping to query string parsing
```c# using System; using System.Collections.Specialized; using System.Text.RegularExpressions; namespace Winston.Net { static class Extensions { public static NameValueCollection ParseQueryString(this Uri uri) { var result = new NameValueCollection(); var query = uri.Query; // remove anything other than query string from url if (query.Contains("?")) { query = query.Substring(query.IndexOf('?') + 1); } foreach (string vp in Regex.Split(query, "&")) { var singlePair = Regex.Split(vp, "="); if (singlePair.Length == 2) { result.Add(Uri.UnescapeDataString(singlePair[0]), Uri.UnescapeDataString(singlePair[1])); } else { // only one key with no value specified in query string result.Add(Uri.UnescapeDataString(singlePair[0]), string.Empty); } } return result; } } } ```
d19a280a-a260-4757-9b27-a3efeefe9e8f
{ "language": "C#" }
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveToNamespace; namespace Microsoft.CodeAnalysis.CSharp.MoveToNamespace { [ExportLanguageService(typeof(AbstractMoveToNamespaceService), LanguageNames.CSharp), Shared] internal class CSharpMoveToNamespaceService : AbstractMoveToNamespaceService<CompilationUnitSyntax, NamespaceDeclarationSyntax, TypeDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveToNamespaceService( [Import(AllowDefault = true)] IMoveToNamespaceOptionsService moveToNamespaceOptionsService) : base(moveToNamespaceOptionsService) { } protected override string GetNamespaceName(NamespaceDeclarationSyntax syntax) => syntax.Name.ToString(); protected override string GetNamespaceName(TypeDeclarationSyntax syntax) => GetNamespaceName(syntax.FirstAncestorOrSelf<NamespaceDeclarationSyntax>()); } } ``` Handle cases where a namespace declaration isn't found in the ancestors of a type declaration
```c# // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveToNamespace; namespace Microsoft.CodeAnalysis.CSharp.MoveToNamespace { [ExportLanguageService(typeof(AbstractMoveToNamespaceService), LanguageNames.CSharp), Shared] internal class CSharpMoveToNamespaceService : AbstractMoveToNamespaceService<CompilationUnitSyntax, NamespaceDeclarationSyntax, TypeDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveToNamespaceService( [Import(AllowDefault = true)] IMoveToNamespaceOptionsService moveToNamespaceOptionsService) : base(moveToNamespaceOptionsService) { } protected override string GetNamespaceName(NamespaceDeclarationSyntax syntax) => syntax.Name.ToString(); protected override string GetNamespaceName(TypeDeclarationSyntax syntax) { var namespaceDecl = syntax.FirstAncestorOrSelf<NamespaceDeclarationSyntax>(); if (namespaceDecl == null) { return string.Empty; } return GetNamespaceName(namespaceDecl); } } } ```
cc8d9743-becb-4a3c-bc96-6a19297cd886
{ "language": "C#" }
```c# using System; using System.Text.RegularExpressions; namespace clipr.Core { internal static class ArgumentValidation { public static bool IsAllowedShortName(char c) { return Char.IsLetter(c); } internal const string IsAllowedShortNameExplanation = "Short arguments must be letters."; public static bool IsAllowedLongName(string name) { return name != null && Regex.IsMatch(name, @"^[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9]$"); } internal const string IsAllowedLongNameExplanation = "Long arguments must begin with a letter, contain a letter, " + "digit, or hyphen, and end with a letter or a digit."; } } ``` Enable underscore in middle of long name.
```c# using System; using System.Text.RegularExpressions; namespace clipr.Core { internal static class ArgumentValidation { public static bool IsAllowedShortName(char c) { return Char.IsLetter(c); } internal const string IsAllowedShortNameExplanation = "Short arguments must be letters."; public static bool IsAllowedLongName(string name) { return name != null && Regex.IsMatch(name, @"^[a-zA-Z][a-zA-Z0-9\-_]*[a-zA-Z0-9]$"); } internal const string IsAllowedLongNameExplanation = "Long arguments must begin with a letter, contain a letter, " + "digit, underscore, or hyphen, and end with a letter or a digit."; } } ```
e6484437-c30b-4e8f-ae66-5e7aa7c8ef97
{ "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.Skinning; #nullable enable namespace osu.Game.Screens.Edit { /// <summary> /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin /// of the map being edited. /// </summary> public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer { private readonly EditorBeatmapSkin? beatmapSkin; public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap) : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap.PlayableBeatmap, editorBeatmap.BeatmapSkin) { beatmapSkin = editorBeatmap.BeatmapSkin; } protected override void LoadComplete() { base.LoadComplete(); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged; } } } ``` Fix editor legacy beatmap skins not receiving transformer
```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.Skinning; #nullable enable namespace osu.Game.Screens.Edit { /// <summary> /// A <see cref="SkinProvidingContainer"/> that fires <see cref="ISkinSource.SourceChanged"/> when users have made a change to the beatmap skin /// of the map being edited. /// </summary> public class EditorSkinProvidingContainer : RulesetSkinProvidingContainer { private readonly EditorBeatmapSkin? beatmapSkin; public EditorSkinProvidingContainer(EditorBeatmap editorBeatmap) : base(editorBeatmap.PlayableBeatmap.BeatmapInfo.Ruleset.CreateInstance(), editorBeatmap.PlayableBeatmap, editorBeatmap.BeatmapSkin?.Skin) { beatmapSkin = editorBeatmap.BeatmapSkin; } protected override void LoadComplete() { base.LoadComplete(); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged += TriggerSourceChanged; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (beatmapSkin != null) beatmapSkin.BeatmapSkinChanged -= TriggerSourceChanged; } } } ```
37702e95-d3ad-46c9-82c1-da29df3dacdc
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } } ``` Add the new managers to the root context.
```c# using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } } ```
c50f857f-f944-4439-8a89-32fce15d5154
{ "language": "C#" }
```c# using System; using System.Web.Mvc; using System.Web.Routing; namespace SimplestMvc5Auth { public class Global : System.Web.HttpApplication { private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }``` Set anti-forgery token unique claim type
```c# using System; using System.Security.Claims; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Routing; namespace SimplestMvc5Auth { public class Global : System.Web.HttpApplication { private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name; } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }```
5cb59113-a7cf-4ea7-af10-c118f40f46ff
{ "language": "C#" }
```c# // Copyright (c) on/off it-solutions gmbh. All rights reserved. // Licensed under the MIT license. See license.txt file in the project root for license information. #pragma warning disable SA1402 // FileMayOnlyContainASingleType #pragma warning disable SA1649 // FileNameMustMatchTypeName namespace InfoCarrierSample { using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; public class Blog { public decimal Id { get; set; } public decimal AuthorId { get; set; } public Author Author { get; set; } public IList<Post> Posts { get; set; } } public class Post { public decimal Id { get; set; } public decimal BlogId { get; set; } public DateTime CreationDate { get; set; } public string Title { get; set; } public Blog Blog { get; set; } } public class Author { public decimal Id { get; set; } public string Name { get; set; } } public class BloggingContext : DbContext { public BloggingContext(DbContextOptions options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Author> Authors { get; set; } } } ``` Use 'long' datatype for IDs in sample applications to avoid warnings.
```c# // Copyright (c) on/off it-solutions gmbh. All rights reserved. // Licensed under the MIT license. See license.txt file in the project root for license information. #pragma warning disable SA1402 // FileMayOnlyContainASingleType #pragma warning disable SA1649 // FileNameMustMatchTypeName namespace InfoCarrierSample { using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; public class Blog { public long Id { get; set; } public long AuthorId { get; set; } public Author Author { get; set; } public IList<Post> Posts { get; set; } } public class Post { public long Id { get; set; } public long BlogId { get; set; } public DateTime CreationDate { get; set; } public string Title { get; set; } public Blog Blog { get; set; } } public class Author { public long Id { get; set; } public string Name { get; set; } } public class BloggingContext : DbContext { public BloggingContext(DbContextOptions options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Author> Authors { get; set; } } } ```
5e72845e-bce3-4839-9c08-94291d15851c
{ "language": "C#" }
```c# using System; namespace HappyFunTimes { public class HFTRuntimeOptions : HFTArgsDirect { public HFTRuntimeOptions(string prefix) : base(prefix) { } public string dataPath = ""; public string url = ""; public string id = ""; public string name = ""; public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games public string controllerFilename = ""; public bool disconnectPlayersIfGameDisconnects = true; public bool installationMode = false; public bool master = false; public bool showInList = true; public bool showMessages; public bool debug; public bool startServer; public bool dns; public bool captivePortal; public string serverPort = ""; public string rendezvousUrl; } } ``` Make hft-server runtime options not based on HFTArgsDirect
```c# using System; namespace HappyFunTimes { public class HFTRuntimeOptions { public string dataPath = ""; public string url = ""; public string id = ""; public string name = ""; public string gameId = "HFTUnity"; // this is kind of left over from when one server supported mutiple games public string controllerFilename = ""; public bool disconnectPlayersIfGameDisconnects = true; public bool installationMode = false; public bool master = false; public bool showInList = true; public bool showMessages; public bool debug; public bool startServer; public bool dns; public bool captivePortal; public string serverPort = ""; public string rendezvousUrl; public string args; } } ```
adc934be-4fca-42bf-81f9-96e3b295de74
{ "language": "C#" }
```c# namespace Fixie.Internal { using System; using System.Text; using System.Text.Json; static class Serialization { public static string Serialize<TMessage>(TMessage message) => Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(message)); public static TMessage Deserialize<TMessage>(string message) => JsonSerializer.Deserialize<TMessage>(new ReadOnlySpan<byte>(Encoding.UTF8.GetBytes(message)))!; } }``` Remove superfluous construction of ReadOnlySpan<byte> from byte[ ]. An implicit cast is available in this context, so the same method overload is in fact called, and the implementation of the implicit cast performs the same construction for us.
```c# namespace Fixie.Internal { using System.Text; using System.Text.Json; static class Serialization { public static string Serialize<TMessage>(TMessage message) => Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(message)); public static TMessage Deserialize<TMessage>(string message) => JsonSerializer.Deserialize<TMessage>(Encoding.UTF8.GetBytes(message))!; } }```
1e749e75-5d40-4387-9b40-9574e48c95eb
{ "language": "C#" }
```c# namespace Microsoft.AspNetCore.Builder { using Routing; using System; public static class RouteBuilderExtensions { /// <summary> /// Allows using typed expression based link generation in ASP.NET Core MVC application. /// </summary> [Obsolete("UseTypedRouting is no longer needed and will be removed in the next version. Call 'AddMvc().AddTypedRouting()' instead.")] public static IRouteBuilder UseTypedRouting(this IRouteBuilder routeBuilder) { return routeBuilder; } } } ``` Remove the obsolete UseTypedRouting method
```c# namespace Microsoft.AspNetCore.Builder { using Routing; using System; public static class RouteBuilderExtensions { } } ```
37bd9be2-1700-4678-9433-6296ff16ceb1
{ "language": "C#" }
```c# namespace Fixie.Samples.Skipped { using System; using System.Reflection; public class CustomConvention : Convention { public CustomConvention() { Classes .InTheSameNamespaceAs(typeof(CustomConvention)) .NameEndsWith("Tests"); Methods .OrderBy(x => x.Name, StringComparer.Ordinal); CaseExecution .Skip(SkipDueToClassLevelSkipAttribute, @case => "Whole class skipped") .Skip(SkipDueToMethodLevelSkipAttribute); ClassExecution .Lifecycle<CreateInstancePerClass>(); } static bool SkipDueToClassLevelSkipAttribute(MethodInfo testMethod) => testMethod.DeclaringType.Has<SkipAttribute>(); static bool SkipDueToMethodLevelSkipAttribute(MethodInfo testMethod) => testMethod.Has<SkipAttribute>(); } }``` Rephrase the Skipped sample to use runtime skips rather than declarative skips, demonstrating how runtime skips are superior: we have case-by-case skippability, implicit skips by conditionally avoiding executing a case, and the ability to avoid instantiating a test class if it is entirely marked as skipped.
```c# namespace Fixie.Samples.Skipped { using System; public class CustomConvention : Convention { public CustomConvention() { Classes .InTheSameNamespaceAs(typeof(CustomConvention)) .NameEndsWith("Tests"); Methods .OrderBy(x => x.Name, StringComparer.Ordinal); ClassExecution .Lifecycle<SkipLifecycle>(); } class SkipLifecycle : Lifecycle { public void Execute(TestClass testClass, Action<CaseAction> runCases) { var skipClass = testClass.Type.Has<SkipAttribute>(); var instance = skipClass ? null : testClass.Construct(); runCases(@case => { var skipMethod = @case.Method.Has<SkipAttribute>(); if (skipClass) @case.Skip("Whole class skipped"); else if (!skipMethod) @case.Execute(instance); }); instance.Dispose(); } } } }```
b5c1fbc1-ac74-4844-993c-b5610c8a50ac
{ "language": "C#" }
```c# using DeveImageOptimizer.State.StoringProcessedDirectories; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace DeveImageOptimizer.Helpers { public static class FileHelperMethods { public static void SafeDeleteTempFile(string path) { try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception ex) { Console.WriteLine($"Warning: Couldn't remove tempfile at path: '{path}'. Exception:{Environment.NewLine}{ex}"); } } public static IEnumerable<FileAndCountOfFilesInDirectory> RecurseFiles(string directory, Func<string, bool> filter = null) { if (filter == null) { filter = t => true; } var files = Directory.GetFiles(directory).Where(filter).ToList(); foreach (var file in files) { yield return new FileAndCountOfFilesInDirectory() { FilePath = file, DirectoryPath = directory, CountOfFilesInDirectory = files.Count }; } var directories = Directory.GetDirectories(directory); foreach (var subDirectory in directories) { var recursedFIles = RecurseFiles(subDirectory, filter); foreach (var subFile in recursedFIles) { yield return subFile; } } } } } ``` Order the files and dirs
```c# using DeveImageOptimizer.State.StoringProcessedDirectories; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace DeveImageOptimizer.Helpers { public static class FileHelperMethods { public static void SafeDeleteTempFile(string path) { try { if (File.Exists(path)) { File.Delete(path); } } catch (Exception ex) { Console.WriteLine($"Warning: Couldn't remove tempfile at path: '{path}'. Exception:{Environment.NewLine}{ex}"); } } public static IEnumerable<FileAndCountOfFilesInDirectory> RecurseFiles(string directory, Func<string, bool> filter = null) { if (filter == null) { filter = t => true; } var files = Directory.GetFiles(directory).Where(filter).OrderBy(t => t).ToList(); foreach (var file in files) { yield return new FileAndCountOfFilesInDirectory() { FilePath = file, DirectoryPath = directory, CountOfFilesInDirectory = files.Count }; } var directories = Directory.GetDirectories(directory).OrderBy(t => t).ToList(); foreach (var subDirectory in directories) { var recursedFIles = RecurseFiles(subDirectory, filter); foreach (var subFile in recursedFIles) { yield return subFile; } } } } } ```
20e5da54-f2b4-4083-a8ea-8f559842db80
{ "language": "C#" }
```c# using System; using System.CodeDom; using Mono.Cecil; namespace PublicApiGenerator { public static class PropertyNameBuilder { public static string AugmentPropertyNameWithPropertyModifierMarkerTemplate(PropertyDefinition propertyDefinition, MemberAttributes getAccessorAttributes, MemberAttributes setAccessorAttributes) { string name = propertyDefinition.Name; if (getAccessorAttributes != setAccessorAttributes || propertyDefinition.DeclaringType.IsInterface) { return name; } var isNew = propertyDefinition.IsNew(typeDef => typeDef?.Properties, e => e.Name.Equals(propertyDefinition.Name, StringComparison.Ordinal)); return ModifierMarkerNameBuilder.Build(propertyDefinition.GetMethod, getAccessorAttributes, isNew, name, CodeNormalizer.PropertyModifierMarkerTemplate); } } } ``` Fix failing test for abstract get-set indexer
```c# using System; using System.CodeDom; using Mono.Cecil; namespace PublicApiGenerator { public static class PropertyNameBuilder { public static string AugmentPropertyNameWithPropertyModifierMarkerTemplate(PropertyDefinition propertyDefinition, MemberAttributes getAccessorAttributes, MemberAttributes setAccessorAttributes) { string name = propertyDefinition.Name; if (getAccessorAttributes != setAccessorAttributes || propertyDefinition.DeclaringType.IsInterface || propertyDefinition.HasParameters) { return name; } var isNew = propertyDefinition.IsNew(typeDef => typeDef?.Properties, e => e.Name.Equals(propertyDefinition.Name, StringComparison.Ordinal)); return ModifierMarkerNameBuilder.Build(propertyDefinition.GetMethod, getAccessorAttributes, isNew, name, CodeNormalizer.PropertyModifierMarkerTemplate); } } } ```
5ff4d05d-481c-4793-a9a9-198b9772ec07
{ "language": "C#" }
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Xunit; namespace Microsoft.AspNet.Mvc { public class MvcOptionsTest { [Fact] public void MaxValidationError_ThrowsIfValueIsOutOfRange() { // Arrange var options = new MvcOptions(); // Act & Assert var ex = Assert.Throws<ArgumentOutOfRangeException>(() => options.MaxModelValidationErrors = -1); Assert.Equal("value", ex.ParamName); } [Fact] public void ThrowsWhenMultipleCacheProfilesWithSameNameAreAdded() { // Arrange var options = new MvcOptions(); options.CacheProfiles.Add("HelloWorld", new CacheProfile { Duration = 10 }); // Act & Assert var ex = Assert.Throws<ArgumentException>( () => options.CacheProfiles.Add("HelloWorld", new CacheProfile { Duration = 5 })); Assert.Equal("An item with the same key has already been added.", ex.Message); } } }``` Remove a test that tests Dictionary
```c# // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Xunit; namespace Microsoft.AspNet.Mvc { public class MvcOptionsTest { [Fact] public void MaxValidationError_ThrowsIfValueIsOutOfRange() { // Arrange var options = new MvcOptions(); // Act & Assert var ex = Assert.Throws<ArgumentOutOfRangeException>(() => options.MaxModelValidationErrors = -1); Assert.Equal("value", ex.ParamName); } } }```
b33b0387-6621-41ba-9077-0eb50bbe22c2
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } } ``` Update server side API for single multiple answer question
```c# using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } } ```
c72c1d1e-e406-4c2b-af86-0c16ec2f0d50
{ "language": "C#" }
```c# using System; using CommandLine; namespace InEngine.Core.Queue.Commands { public class Length : AbstractCommand { public override void Run() { var broker = Broker.Make(); var leftPadding = 15; Warning("Primary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetPrimaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10)); Newline(); Warning("Secondary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetSecondaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10)); Newline(); } } } ``` Use correct queue name in length commands
```c# using System; using CommandLine; namespace InEngine.Core.Queue.Commands { public class Length : AbstractCommand { public override void Run() { var broker = Broker.Make(); var leftPadding = 15; Warning("Primary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetPrimaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetPrimaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetPrimaryFailedQueueLength().ToString().PadLeft(10)); Newline(); Warning("Secondary Queue:"); InfoText("Pending".PadLeft(leftPadding)); Line(broker.GetSecondaryWaitingQueueLength().ToString().PadLeft(10)); InfoText("In-progress".PadLeft(leftPadding)); Line(broker.GetSecondaryProcessingQueueLength().ToString().PadLeft(10)); ErrorText("Failed".PadLeft(leftPadding)); Line(broker.GetSecondaryFailedQueueLength().ToString().PadLeft(10)); Newline(); } } } ```
a3648543-11fc-4a57-9e26-d4d1c6d16771
{ "language": "C#" }
```c# @{ // odd formatting in this file is to cause more attractive results in the output. var items = Enumerable.Cast<dynamic>((System.Collections.IEnumerable)Model); } @{ if (!HasText(Model.Text)) { @DisplayChildren(Model) } else { if ((bool)Model.Selected) { Model.Classes.Add("current"); Model.Classes.Add("active"); // for bootstrap } if (items.Any()) { Model.Classes.Add("dropdown"); // for bootstrap and/or font-awesome Model.BootstrapAttributes = "data-toggle='dropdown'"; Model.BootstrapIcon = "<span class='glyphicon glyphicon-hand-down'></span>"; } @* morphing the shape to keep Model untouched*@ Model.Metadata.Alternates.Clear(); Model.Metadata.Type = "MenuItemLink"; @* render the menu item only if it has some content *@ var renderedMenuItemLink = Display(Model); if (HasText(renderedMenuItemLink)) { var tag = Tag(Model, "li"); @tag.StartElement @renderedMenuItemLink if (items.Any()) { <ul class="dropdown-menu"> @DisplayChildren(Model) </ul> } @tag.EndElement } } }``` Use chevron down for drop downs.
```c# @{ // odd formatting in this file is to cause more attractive results in the output. var items = Enumerable.Cast<dynamic>((System.Collections.IEnumerable)Model); } @{ if (!HasText(Model.Text)) { @DisplayChildren(Model) } else { if ((bool)Model.Selected) { Model.Classes.Add("current"); Model.Classes.Add("active"); // for bootstrap } if (items.Any()) { Model.Classes.Add("dropdown"); // for bootstrap and/or font-awesome Model.BootstrapAttributes = "data-toggle='dropdown'"; Model.BootstrapIcon = "<span class='glyphicon glyphicon-chevron-down'></span>"; } @* morphing the shape to keep Model untouched*@ Model.Metadata.Alternates.Clear(); Model.Metadata.Type = "MenuItemLink"; @* render the menu item only if it has some content *@ var renderedMenuItemLink = Display(Model); if (HasText(renderedMenuItemLink)) { var tag = Tag(Model, "li"); @tag.StartElement @renderedMenuItemLink if (items.Any()) { <ul class="dropdown-menu"> @DisplayChildren(Model) </ul> } @tag.EndElement } } }```
fbf28168-4d4e-4029-8e71-009ec9042987
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Utils; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneStarCounter : OsuTestScene { public TestSceneStarCounter() { StarCounter stars = new StarCounter { Origin = Anchor.Centre, Anchor = Anchor.Centre, Current = 5, }; Add(stars); SpriteText starsLabel = new OsuSpriteText { Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(2), Y = 50, Text = stars.Current.ToString("0.00"), }; Add(starsLabel); AddRepeatStep(@"random value", delegate { stars.Current = RNG.NextSingle() * (stars.StarCount + 1); starsLabel.Text = stars.Current.ToString("0.00"); }, 10); AddStep(@"Stop animation", delegate { stars.StopAnimation(); }); AddStep(@"Reset", delegate { stars.Current = 0; starsLabel.Text = stars.Current.ToString("0.00"); }); } } } ``` Rewrite existing test scene somewhat
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Utils; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK; namespace osu.Game.Tests.Visual.Gameplay { [TestFixture] public class TestSceneStarCounter : OsuTestScene { private readonly StarCounter starCounter; private readonly OsuSpriteText starsLabel; public TestSceneStarCounter() { starCounter = new StarCounter { Origin = Anchor.Centre, Anchor = Anchor.Centre, }; Add(starCounter); starsLabel = new OsuSpriteText { Origin = Anchor.Centre, Anchor = Anchor.Centre, Scale = new Vector2(2), Y = 50, }; Add(starsLabel); setStars(5); AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10); AddStep("stop animation", () => starCounter.StopAnimation()); AddStep("reset", () => setStars(0)); } private void setStars(float stars) { starCounter.Current = stars; starsLabel.Text = starCounter.Current.ToString("0.00"); } } } ```
29939ab4-779f-4645-bc98-f3192fa6f223
{ "language": "C#" }
```c# using Xunit; // This is a work-around for #11. // https://github.com/CXuesong/WikiClientLibrary/issues/11 // We are using Bot Password on CI, which may naturally evade the issue. #if !ENV_CI_BUILD [assembly: CollectionBehavior(DisableTestParallelization = true)] #endif ``` Enable test parallelization on local.
```c# using Xunit; // This is a work-around for #11. // https://github.com/CXuesong/WikiClientLibrary/issues/11 // We are using Bot Password on CI, which may naturally evade the issue. // [assembly: CollectionBehavior(DisableTestParallelization = true)] ```
58cf4bcf-7820-49ac-b54c-1878aec8b93e
{ "language": "C#" }
```c# using System; namespace ProtoCore.Utils { public class Validity { public static void Assert(bool cond) { if (!cond) throw new Exceptions.CompilerInternalException(""); } public static void Assert(bool cond, string message) { if (!cond) throw new Exceptions.CompilerInternalException(message); } private static DateTime? mAppStartupTime = null; public static void AssertExpiry() { //Expires on 30th September 2013 DateTime expires = new DateTime(2013, 9, 30); if(!mAppStartupTime.HasValue) mAppStartupTime = DateTime.Now; if (mAppStartupTime.Value >= expires) throw new ProductExpiredException("DesignScript Technology Preview has expired. Visit http://labs.autodesk.com for more information.", expires); } } public class ProductExpiredException : Exception { public ProductExpiredException(string message, DateTime expirydate) : base(message) { ExpiryDate = expirydate; } public DateTime ExpiryDate { get; private set; } } } ``` Remove expiration date of DesignScript
```c# using System; namespace ProtoCore.Utils { public class Validity { public static void Assert(bool cond) { if (!cond) throw new Exceptions.CompilerInternalException(""); } public static void Assert(bool cond, string message) { if (!cond) throw new Exceptions.CompilerInternalException(message); } private static DateTime? mAppStartupTime = null; public static void AssertExpiry() { //Expires on 30th September 2013 /* DateTime expires = new DateTime(2013, 9, 30); if(!mAppStartupTime.HasValue) mAppStartupTime = DateTime.Now; if (mAppStartupTime.Value >= expires) throw new ProductExpiredException("DesignScript Technology Preview has expired. Visit http://labs.autodesk.com for more information.", expires); */ } } public class ProductExpiredException : Exception { public ProductExpiredException(string message, DateTime expirydate) : base(message) { ExpiryDate = expirydate; } public DateTime ExpiryDate { get; private set; } } } ```
ef8784d9-794e-4671-95d8-a1b2eecc0c1f
{ "language": "C#" }
```c# using System; using System.Dynamic; using System.IO; using System.Net; using Newtonsoft.Json; namespace Rackspace.CloudOffice { public class ApiException : Exception { public dynamic Response { get; private set; } public ApiException(WebException ex) : base(GetErrorMessage(ex), ex) { Response = ParseResponse(ex.Response); } static object ParseResponse(WebResponse response) { if (response == null) return null; using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var raw = reader.ReadToEnd(); try { return JsonConvert.DeserializeObject<ExpandoObject>(raw); } catch { return raw; } } } static string GetErrorMessage(WebException ex) { var r = ex.Response as HttpWebResponse; return r == null ? ex.Message : $"{r.StatusCode:d} - {r.Headers["x-error-message"]}"; } } } ``` Add HttpCode convenience property to exception
```c# using System; using System.Dynamic; using System.IO; using System.Net; using Newtonsoft.Json; namespace Rackspace.CloudOffice { public class ApiException : Exception { public dynamic Response { get; private set; } public HttpStatusCode? HttpCode { get; private set; } public ApiException(WebException ex) : base(GetErrorMessage(ex), ex) { Response = ParseResponse(ex.Response); var webResponse = ex.Response as HttpWebResponse; if (webResponse != null) HttpCode = webResponse.StatusCode; } static object ParseResponse(WebResponse response) { if (response == null) return null; using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var raw = reader.ReadToEnd(); try { return JsonConvert.DeserializeObject<ExpandoObject>(raw); } catch { return raw; } } } static string GetErrorMessage(WebException ex) { var r = ex.Response as HttpWebResponse; return r == null ? ex.Message : $"{r.StatusCode:d} - {r.Headers["x-error-message"]}"; } } } ```
9b702cc9-bdd5-4718-bba8-efd779cd4cd3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; namespace MeidoCommon { public interface IMeidoHook { string Name { get; } string Version { get; } Dictionary<string, string> Help { get; } string Prefix { set; } } public interface IIrcMessage { string Message { get; } string[] MessageArray { get; } string Channel { get; } string Nick { get; } string Ident { get; } string Host { get; } } public interface IMeidoComm { string ConfDir { get; } } public interface IIrcComm { void AddChannelMessageHandler(Action<IIrcMessage> handler); void AddQueryMessageHandler(Action<IIrcMessage> handler); void SendMessage(string target, string message); void DoAction(string target, string action); void SendNotice(string target, string message); string[] GetChannels(); bool IsMe(string nick); } }``` Modify the MeidoHook interface to allow communicating to the plugins they need to stop. That way they can release whatever resources they're holding or stop threads/timers to have running seperate from the main thread. This will make it possible to have MeidoBot stop the entire program from top-down.
```c# using System; using System.Collections.Generic; namespace MeidoCommon { public interface IMeidoHook { // Things the plugin provides us with. string Name { get; } string Version { get; } Dictionary<string, string> Help { get; } // Things we provide to the plugin. string Prefix { set; } // Method to signal to the plugins they need to stop whatever seperate threads they have running. // As well as to save/deserialize whatever it needs to. void Stop(); } public interface IIrcMessage { string Message { get; } string[] MessageArray { get; } string Channel { get; } string Nick { get; } string Ident { get; } string Host { get; } } public interface IMeidoComm { string ConfDir { get; } } public interface IIrcComm { void AddChannelMessageHandler(Action<IIrcMessage> handler); void AddQueryMessageHandler(Action<IIrcMessage> handler); void SendMessage(string target, string message); void DoAction(string target, string action); void SendNotice(string target, string message); string[] GetChannels(); bool IsMe(string nick); } }```
566f76ed-baf6-419c-9bf4-d22319353359
{ "language": "C#" }
```c# using System; using System.Linq; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; namespace AspNet.WebApi.HtmlMicrodataFormatter { public class DocumentationController : ApiController { public IDocumentationProviderEx DocumentationProvider { get; set; } protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); if (DocumentationProvider != null) return; DocumentationProvider = Configuration.Services.GetService(typeof (IDocumentationProvider)) as IDocumentationProviderEx; if (DocumentationProvider == null) { var msg = string.Format("{0} can only be used when {1} is registered as {2} service provider.", typeof(DocumentationController), typeof(WebApiHtmlDocumentationProvider), typeof(IDocumentationProvider)); throw new InvalidOperationException(msg); } } public SimpleApiDocumentation GetDocumentation() { var apiExplorer = Configuration.Services.GetApiExplorer(); var documentation = new SimpleApiDocumentation(); foreach (var api in apiExplorer.ApiDescriptions) { var controllerDescriptor = api.ActionDescriptor.ControllerDescriptor; documentation.Add(controllerDescriptor.ControllerName, api.Simplify(Configuration)); documentation[controllerDescriptor.ControllerName].Documentation = DocumentationProvider.GetDocumentation(controllerDescriptor.ControllerType); } return documentation; } } }``` Make method virtual so clients can decorate behavior.
```c# using System; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; namespace AspNet.WebApi.HtmlMicrodataFormatter { public class DocumentationController : ApiController { public IDocumentationProviderEx DocumentationProvider { get; set; } protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); if (DocumentationProvider != null) return; DocumentationProvider = Configuration.Services.GetService(typeof (IDocumentationProvider)) as IDocumentationProviderEx; if (DocumentationProvider == null) { var msg = string.Format("{0} can only be used when {1} is registered as {2} service provider.", typeof(DocumentationController), typeof(WebApiHtmlDocumentationProvider), typeof(IDocumentationProvider)); throw new InvalidOperationException(msg); } } public virtual SimpleApiDocumentation GetDocumentation() { var apiExplorer = Configuration.Services.GetApiExplorer(); var documentation = new SimpleApiDocumentation(); foreach (var api in apiExplorer.ApiDescriptions) { var controllerDescriptor = api.ActionDescriptor.ControllerDescriptor; documentation.Add(controllerDescriptor.ControllerName, api.Simplify(Configuration)); documentation[controllerDescriptor.ControllerName].Documentation = DocumentationProvider.GetDocumentation(controllerDescriptor.ControllerType); } return documentation; } } }```
525447e0-be8b-4d02-97e3-7111bd97e833
{ "language": "C#" }
```c# using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { if (string.IsNullOrWhiteSpace(directory)) return false; string tmpFile = Path.Combine(directory, Path.GetRandomFileName()); try { using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose)) { // Attempt to write temporary file to the directory } return true; } catch { return false; } } } } ``` Test directory creation access by creating a directory (not a file)
```c# using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { if (string.IsNullOrWhiteSpace(directory)) return false; string tmpDirectory = Path.Combine(directory, "arkade-writeaccess-test"); try { Directory.CreateDirectory(tmpDirectory); return true; } catch { return false; } finally { if (Directory.Exists(tmpDirectory)) Directory.Delete(tmpDirectory); } } } } ```
79358dd8-c72b-48e1-a155-5644a9423089
{ "language": "C#" }
```c# using Pear.InteractionEngine.Utils; using System; using UnityEditor; using UnityEngine; namespace Pear.InteractionEngine.Controllers { [CustomEditor(typeof(ControllerBehaviorBase), true)] [CanEditMultipleObjects] public class ControllerBehaviorEditor : Editor { // The controller property SerializedProperty _controller; void OnEnable() { _controller = serializedObject.FindProperty("_controller"); } /// <summary> /// Attempt to set the controller if it is not set /// </summary> public override void OnInspectorGUI() { serializedObject.Update(); // If a reference to the controller is not set // try to find it on the game object if (_controller.objectReferenceValue == null) { // Get the type of controller by examing the templated argument // pased to the controller behavior Type typeOfController = ReflectionHelpers.GetGenericArgumentTypes(target.GetType(), typeof(IControllerBehavior<>))[0]; // Check to see if this component has a parent controller. Transform parent = ((Component)target).transform.parent; while(_controller.objectReferenceValue == null && parent != null) { _controller.objectReferenceValue = parent.GetComponent(typeOfController); if (_controller.objectReferenceValue == null) parent = parent.parent; } } serializedObject.ApplyModifiedProperties(); DrawDefaultInspector(); } } } ``` Check for parent controller on same object too, not just parents
```c# using Pear.InteractionEngine.Utils; using System; using UnityEditor; using UnityEngine; namespace Pear.InteractionEngine.Controllers { [CustomEditor(typeof(ControllerBehaviorBase), true)] [CanEditMultipleObjects] public class ControllerBehaviorEditor : Editor { // The controller property SerializedProperty _controller; void OnEnable() { _controller = serializedObject.FindProperty("_controller"); } /// <summary> /// Attempt to set the controller if it is not set /// </summary> public override void OnInspectorGUI() { serializedObject.Update(); // If a reference to the controller is not set // try to find it on the game object if (_controller.objectReferenceValue == null) { // Get the type of controller by examing the templated argument // pased to the controller behavior Type typeOfController = ReflectionHelpers.GetGenericArgumentTypes(target.GetType(), typeof(IControllerBehavior<>))[0]; // Check to see if this component has a controller on the same gameobject or one of its parents. Transform objTpCheck = ((Component)target).transform; while(_controller.objectReferenceValue == null && objTpCheck != null) { _controller.objectReferenceValue = objTpCheck.GetComponent(typeOfController); if (_controller.objectReferenceValue == null) objTpCheck = objTpCheck.parent; } } serializedObject.ApplyModifiedProperties(); DrawDefaultInspector(); } } } ```
5c01bec8-7db4-4399-8c0f-9aca88bb4893
{ "language": "C#" }
```c# using System; using System.Linq; using Android.Content; using Android.OS; using Rg.Plugins.Popup.Droid.Impl; using Rg.Plugins.Popup.Droid.Renderers; using Rg.Plugins.Popup.Services; using Xamarin.Forms; namespace Rg.Plugins.Popup { public static class Popup { internal static event EventHandler OnInitialized; internal static bool IsInitialized { get; private set; } internal static Context Context { get; private set; } public static void Init(Context context, Bundle bundle) { LinkAssemblies(); Context = context; IsInitialized = true; OnInitialized?.Invoke(null, EventArgs.Empty); } public static bool SendBackPressed(Action backPressedHandler = null) { var popupNavigationInstance = PopupNavigation.Instance; if (popupNavigationInstance.PopupStack.Count > 0) { var lastPage = popupNavigationInstance.PopupStack.Last(); var isPreventClose = lastPage.DisappearingTransactionTask != null || lastPage.SendBackButtonPressed(); if (!isPreventClose) { Device.BeginInvokeOnMainThread(async () => { await popupNavigationInstance.PopAsync(); }); } return true; } backPressedHandler?.Invoke(); return false; } private static void LinkAssemblies() { if (false.Equals(true)) { var i = new PopupPlatformDroid(); var r = new PopupPageRenderer(null); } } } } ``` Remove correct page on back button press
```c# using System; using System.Linq; using Android.Content; using Android.OS; using Rg.Plugins.Popup.Droid.Impl; using Rg.Plugins.Popup.Droid.Renderers; using Rg.Plugins.Popup.Services; using Xamarin.Forms; namespace Rg.Plugins.Popup { public static class Popup { internal static event EventHandler OnInitialized; internal static bool IsInitialized { get; private set; } internal static Context Context { get; private set; } public static void Init(Context context, Bundle bundle) { LinkAssemblies(); Context = context; IsInitialized = true; OnInitialized?.Invoke(null, EventArgs.Empty); } public static bool SendBackPressed(Action backPressedHandler = null) { var popupNavigationInstance = PopupNavigation.Instance; if (popupNavigationInstance.PopupStack.Count > 0) { var lastPage = popupNavigationInstance.PopupStack.Last(); var isPreventClose = lastPage.DisappearingTransactionTask != null || lastPage.SendBackButtonPressed(); if (!isPreventClose) { Device.BeginInvokeOnMainThread(async () => { await popupNavigationInstance.RemovePageAsync(lastPage); }); } return true; } backPressedHandler?.Invoke(); return false; } private static void LinkAssemblies() { if (false.Equals(true)) { var i = new PopupPlatformDroid(); var r = new PopupPageRenderer(null); } } } } ```
ad5a3e5a-d0bf-4450-9acf-122fa495573a
{ "language": "C#" }
```c# using System.ComponentModel; using System.Runtime.CompilerServices; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 namespace OfflineWorkflowSample { public sealed partial class CustomAppTitleBar : UserControl, INotifyPropertyChanged { private string _title = "ArcGIS Maps Offline"; public string Title { get => _title; set { _title = value; OnPropertyChanged(); } } private Page _containingPage; public CustomAppTitleBar() { this.InitializeComponent(); Window.Current.SetTitleBar(DraggablePart); DataContext = this; } public void EnableBackButton(Page containingPage) { _containingPage = containingPage; BackButton.Visibility = Visibility.Visible; } private void BackButton_OnClick(object sender, RoutedEventArgs e) { if (_containingPage?.Frame != null && _containingPage.Frame.CanGoBack) { _containingPage.Frame.GoBack(); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ``` Set window controls to right color
```c# using System.ComponentModel; using System.Runtime.CompilerServices; using Windows.UI; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 namespace OfflineWorkflowSample { public sealed partial class CustomAppTitleBar : UserControl, INotifyPropertyChanged { private string _title = "ArcGIS Maps Offline"; public string Title { get => _title; set { _title = value; OnPropertyChanged(); } } private Page _containingPage; public CustomAppTitleBar() { this.InitializeComponent(); Window.Current.SetTitleBar(DraggablePart); ApplicationView.GetForCurrentView().TitleBar.ButtonForegroundColor = Colors.Black; DataContext = this; } public void EnableBackButton(Page containingPage) { _containingPage = containingPage; BackButton.Visibility = Visibility.Visible; } private void BackButton_OnClick(object sender, RoutedEventArgs e) { if (_containingPage?.Frame != null && _containingPage.Frame.CanGoBack) { _containingPage.Frame.GoBack(); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } ```
1e29b896-42be-40b3-ae3e-2c4ce61b0306
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Espera.Core { /// <summary> /// This class contains the used keys for Akavache /// </summary> public static class BlobCacheKeys { /// <summary> /// This is the key prefix for song artworks. After the hyphe, the MD5 hash of the artwork /// is attached. /// </summary> public const string Artwork = "artwork-"; /// <summary> /// This is the key for the changelog that is shown after the application is updated. /// </summary> public const string Changelog = "changelog"; } }``` Fix typo and remove usings
```c# namespace Espera.Core { /// <summary> /// This class contains the used keys for Akavache /// </summary> public static class BlobCacheKeys { /// <summary> /// This is the key prefix for song artworks. After the hyphen, the MD5 hash of the artwork /// is attached. /// </summary> public const string Artwork = "artwork-"; /// <summary> /// This is the key for the changelog that is shown after the application is updated. /// </summary> public const string Changelog = "changelog"; } }```
ae011a50-c349-4462-b157-1a82df00af0f
{ "language": "C#" }
```c# using System.Collections.Generic; using Glimpse.Core2.Extensibility; using Glimpse.Core2.Framework; namespace Glimpse.Core2.SerializationConverter { public class GlimpseMetadataConverter:SerializationConverter<GlimpseRequest> { public override IDictionary<string, object> Convert(GlimpseRequest request) { return new Dictionary<string, object> { {"clientId", request.ClientId}, {"dateTime", request.DateTime}, {"duration", request.Duration}, {"parentRequestId", request.ParentRequestId}, {"requestId", request.RequestId}, {"isAjax", request.RequestIsAjax}, {"method", request.RequestHttpMethod}, {"uri", request.RequestUri}, {"contentType", request.ResponseContentType}, {"statusCode", request.ResponseStatusCode}, {"plugins", request.PluginData}, {"userAgent", request.UserAgent} }; } } }``` Adjust the name of the property that the data for a response goes into
```c# using System.Collections.Generic; using Glimpse.Core2.Extensibility; using Glimpse.Core2.Framework; namespace Glimpse.Core2.SerializationConverter { public class GlimpseMetadataConverter:SerializationConverter<GlimpseRequest> { public override IDictionary<string, object> Convert(GlimpseRequest request) { return new Dictionary<string, object> { {"clientId", request.ClientId}, {"dateTime", request.DateTime}, {"duration", request.Duration}, {"parentRequestId", request.ParentRequestId}, {"requestId", request.RequestId}, {"isAjax", request.RequestIsAjax}, {"method", request.RequestHttpMethod}, {"uri", request.RequestUri}, {"contentType", request.ResponseContentType}, {"statusCode", request.ResponseStatusCode}, {"data", request.PluginData}, {"userAgent", request.UserAgent} }; } } }```
737778a1-39ec-4f9b-9a03-6c9484a0f0fe
{ "language": "C#" }
```c# using System; namespace XeroApi.Model { public class Contact : ModelBase { [ItemId] public Guid ContactID { get; set; } [ItemNumber] public string ContactNumber { get; set; } [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } public string ContactStatus { get; set; } public string Name { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string SkypeUserName { get; set; } public string BankAccountDetails { get; set; } public string TaxNumber { get; set; } public string AccountsReceivableTaxType { get; set; } public string AccountsPayableTaxType { get; set; } public Addresses Addresses { get; set; } public Phones Phones { get; set; } public ContactGroups ContactGroups { get; set; } public bool IsSupplier { get; set; } public bool IsCustomer { get; set; } public string DefaultCurrency { get; set; } } public class Contacts : ModelList<Contact> { } }``` Mark IsCustomer and IsSupplier fields as readonly
```c# using System; namespace XeroApi.Model { public class Contact : ModelBase { [ItemId] public Guid ContactID { get; set; } [ItemNumber] public string ContactNumber { get; set; } [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } public string ContactStatus { get; set; } public string Name { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string SkypeUserName { get; set; } public string BankAccountDetails { get; set; } public string TaxNumber { get; set; } public string AccountsReceivableTaxType { get; set; } public string AccountsPayableTaxType { get; set; } public Addresses Addresses { get; set; } public Phones Phones { get; set; } public ContactGroups ContactGroups { get; set; } [ReadOnly] public bool IsSupplier { get; set; } [ReadOnly] public bool IsCustomer { get; set; } public string DefaultCurrency { get; set; } } public class Contacts : ModelList<Contact> { } }```
1a1539d5-618d-46a0-8011-2586c01e73e3
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; namespace Codestellation.Pulsar.Cron { public class CronCalendar { private readonly List<DateTime> _days; public CronCalendar(IEnumerable<DateTime> scheduledDays) { _days = scheduledDays.ToList(); _days.Sort(); } public IEnumerable<DateTime> ScheduledDays { get { return _days; } } public IEnumerable<DateTime> DaysAfter(DateTime point) { var date = point.Date; for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++) { var candidate = _days[dayIndex]; if (date <= candidate) { yield return candidate; } } } public bool ShouldFire(DateTime date) { return _days.Contains(date); } public bool TryFindNextDay(DateTime date, out DateTime closest) { for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++) { var candidate = _days[dayIndex]; if (date < candidate) { closest = candidate; return true; } } closest = DateTime.MinValue; return false; } } }``` Use hash set to assert should fire
```c# using System; using System.Collections.Generic; using System.Linq; namespace Codestellation.Pulsar.Cron { public class CronCalendar { private readonly List<DateTime> _days; private readonly HashSet<DateTime> _dayIndex; public CronCalendar(IEnumerable<DateTime> scheduledDays) { _days = scheduledDays.ToList(); _days.Sort(); _dayIndex = new HashSet<DateTime>(_days); } public IEnumerable<DateTime> ScheduledDays { get { return _days; } } public IEnumerable<DateTime> DaysAfter(DateTime point) { var date = point.Date; for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++) { var candidate = _days[dayIndex]; if (date <= candidate) { yield return candidate; } } } public bool ShouldFire(DateTime date) { return _dayIndex.Contains(date); } public bool TryFindNextDay(DateTime date, out DateTime closest) { for (int dayIndex = 0; dayIndex < _days.Count; dayIndex++) { var candidate = _days[dayIndex]; if (date < candidate) { closest = candidate; return true; } } closest = DateTime.MinValue; return false; } } }```