doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
7aa0947d-eb29-4ec9-8f4a-ad25c08c7372
{ "language": "C#" }
```c# using NutEngine.Physics.Shapes; namespace NutEngine.Physics { public static partial class Collider { public static bool Collide(IBody<IShape> a, IBody<IShape> b, out Manifold manifold) { return Collide((dynamic)a, (dynamic)b, out manifold); } } } ``` Add collide without manifold generation
```c# using NutEngine.Physics.Shapes; namespace NutEngine.Physics { public static partial class Collider { public static bool Collide(IBody<IShape> a, IBody<IShape> b, out Manifold manifold) { return Collide((dynamic)a, (dynamic)b, out manifold); } public static bool Collide(IBody<IShape> a, IBody<IShape> b) { return Collide((dynamic)a, (dynamic)b); } } } ```
5a3c24c1-fc5b-4d4d-a711-d6b26a797bc9
{ "language": "C#" }
```c# using System.Linq; using Xunit; namespace PagedList.Tests { public class SplitAndPartitionFacts { [Fact] public void Partition_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Partition(1000); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } [Fact] public void Split_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Split(10); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } } }``` Add unit test for partition change
```c# using System.Linq; using Xunit; namespace PagedList.Tests { public class SplitAndPartitionFacts { [Fact] public void Partition_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Partition(1000); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } [Fact] public void Paritiion_Returns_Enumerable_With_One_Item_When_Count_Less_Than_Page_Size() { //arrange var list = Enumerable.Range(1,10); //act var partitionList = list.Partition(1000); //assert Assert.Equal(1, splitList.Count()); Assert.Equal(10, splitList.First().Count()); } [Fact] public void Split_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Split(10); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } } }```
8c0b9e70-444b-46c9-9dc4-273c3dac8334
{ "language": "C#" }
```c# using System; namespace School { public class REPL { public REPL() { } public void Run() { Evaluator evaluator = new Evaluator(); string line; Console.WriteLine("School REPL:"); do { Console.Write("> "); line = Console.ReadLine(); if (!String.IsNullOrEmpty(line)) { try { Value value = evaluator.Evaluate(line); Console.WriteLine(value); } catch (Exception e) { Console.WriteLine(e); } } } while (line != null); } } } ``` Use LineEditor instead of Console.ReadLine.
```c# using System; using Mono.Terminal; namespace School { public class REPL { public REPL() { } public void Run() { Evaluator evaluator = new Evaluator(); LineEditor editor = new LineEditor("School"); Console.WriteLine("School REPL:"); string line; while ((line = editor.Edit("> ", "")) != null) { try { Value value = evaluator.Evaluate(line); Console.WriteLine(value); } catch (Exception e) { Console.WriteLine(e); } } } } } ```
6a8956a5-1f56-4923-9cbb-06bbc4629810
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("elbsms_core")] [assembly: AssemblyDescription("")] [assembly: AssemblyProduct("elbsms_core")] // 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("59ef0f57-7a82-4cd8-80a6-0d0536ce1ed3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("elbsms_console")] ``` Update assembly description attribute in elbsms_core
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("elbsms_core")] [assembly: AssemblyDescription("elbsms core")] [assembly: AssemblyProduct("elbsms_core")] // 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("59ef0f57-7a82-4cd8-80a6-0d0536ce1ed3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("elbsms_console")] ```
3f6c348c-6be2-4968-abee-a4c4a5c628b0
{ "language": "C#" }
```c# using System; using System.Web; using Casper.Domain.Features.BlogPosts; using CroquetAustraliaWebsite.Library.Content; namespace CroquetAustraliaWebsite.Application.App.home { public class BlogPostViewModel { private readonly BlogPost _blogPost; private readonly Lazy<IHtmlString> _contentFactory; public BlogPostViewModel(BlogPost blogPost, IMarkdownTransformer markdownTransformer) { _blogPost = blogPost; _contentFactory = new Lazy<IHtmlString>(() => markdownTransformer.MarkdownToHtml(_blogPost.Content)); } public string Title { get { return _blogPost.Title; } } public IHtmlString Content { get { return _contentFactory.Value; } } public DateTimeOffset Published { get { return _blogPost.Published; } } } }``` Improve error message when BlogPost.Content markdown to html fails
```c# using System; using System.Web; using Anotar.NLog; using Casper.Domain.Features.BlogPosts; using CroquetAustraliaWebsite.Library.Content; namespace CroquetAustraliaWebsite.Application.App.home { public class BlogPostViewModel { private readonly BlogPost _blogPost; private readonly Lazy<IHtmlString> _contentFactory; public BlogPostViewModel(BlogPost blogPost, IMarkdownTransformer markdownTransformer) { _blogPost = blogPost; _contentFactory = new Lazy<IHtmlString>(() => MarkdownToHtml(markdownTransformer)); } public string Title => _blogPost.Title; public IHtmlString Content => _contentFactory.Value; public DateTimeOffset Published => _blogPost.Published; private IHtmlString MarkdownToHtml(IMarkdownTransformer markdownTransformer) { try { return markdownTransformer.MarkdownToHtml(_blogPost.Content); } catch (Exception innerException) { var exception = new Exception($"Could not convert content of blog post '{Title}' to HTML.", innerException); exception.Data.Add("BlogPost.Title", _blogPost.Title); exception.Data.Add("BlogPost.Content", _blogPost.Content); exception.Data.Add("BlogPost.Published", _blogPost.Published); exception.Data.Add("BlogPost.RelativeUri", _blogPost.RelativeUri); LogTo.ErrorException(exception.Message, exception); return new HtmlString("<p>Content currently not available.<p>"); } } } }```
48e98844-0755-4932-a510-048ba8524472
{ "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.ComponentModel; namespace osu.Game.Configuration { public enum ScoreMeterType { [Description("None")] None, [Description("Hit Error (left)")] HitErrorLeft, [Description("Hit Error (right)")] HitErrorRight, [Description("Hit Error (bottom)")] HitErrorBottom, [Description("Hit Error (left+right)")] HitErrorBoth, [Description("Colour (left)")] ColourLeft, [Description("Colour (right)")] ColourRight, [Description("Colour (left+right)")] ColourBoth, [Description("Colour (bottom)")] ColourBottom, } } ``` Fix misordered hit error in score meter types
```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.ComponentModel; namespace osu.Game.Configuration { public enum ScoreMeterType { [Description("None")] None, [Description("Hit Error (left)")] HitErrorLeft, [Description("Hit Error (right)")] HitErrorRight, [Description("Hit Error (left+right)")] HitErrorBoth, [Description("Hit Error (bottom)")] HitErrorBottom, [Description("Colour (left)")] ColourLeft, [Description("Colour (right)")] ColourRight, [Description("Colour (left+right)")] ColourBoth, [Description("Colour (bottom)")] ColourBottom, } } ```
4903b14a-2ba9-47e6-a89e-08376c71dab8
{ "language": "C#" }
```c# using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace AuthSamples.ClaimsTransformer.Controllers { public class AccountController : Controller { [HttpGet] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } private bool ValidateLogin(string userName, string password) { // For this sample, all logins are successful. return true; } [HttpPost] public async Task<IActionResult> Login(string userName, string password, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; // Normally Identity handles sign in, but you can do it directly if (ValidateLogin(userName, password)) { var claims = new List<Claim> { new Claim("user", userName), new Claim("role", "Member") }; await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies", "user", "role"))); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return Redirect("/"); } } return View(); } public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(); return Redirect("/"); } } } ``` Replace hardcoded string with constant
```c# using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; namespace AuthSamples.ClaimsTransformer.Controllers { public class AccountController : Controller { [HttpGet] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } private bool ValidateLogin(string userName, string password) { // For this sample, all logins are successful. return true; } [HttpPost] public async Task<IActionResult> Login(string userName, string password, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; // Normally Identity handles sign in, but you can do it directly if (ValidateLogin(userName, password)) { var claims = new List<Claim> { new Claim("user", userName), new Claim("role", "Member") }; await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme, "user", "role"))); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return Redirect("/"); } } return View(); } public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(); return Redirect("/"); } } } ```
2dcf9476-59b3-4525-bd16-390f2750ce0c
{ "language": "C#" }
```c# namespace Booma.Proxy { public sealed partial class CapturedPacketsTests { public class PacketCaptureTestEntry { public short OpCode { get; } public byte[] BinaryData { get; } public string FileName { get; } /// <inheritdoc /> public PacketCaptureTestEntry(short opCode, byte[] binaryData, string fileName) { OpCode = opCode; BinaryData = binaryData; FileName = fileName; } /// <inheritdoc /> public override string ToString() { //Special naming for 0x60 to make it easier to search if(OpCode == 0x60) return FileName.Replace("0x60_", $"0x60_0x{BinaryData[6]:X}_"); return $"{FileName}"; } /// <inheritdoc /> public override int GetHashCode() { return FileName.GetHashCode(); } } } } ``` Change subcommand60 packet test case name in VS
```c# namespace Booma.Proxy { public sealed partial class CapturedPacketsTests { public class PacketCaptureTestEntry { public short OpCode { get; } public byte[] BinaryData { get; } public string FileName { get; } /// <inheritdoc /> public PacketCaptureTestEntry(short opCode, byte[] binaryData, string fileName) { OpCode = opCode; BinaryData = binaryData; FileName = fileName; } /// <inheritdoc /> public override string ToString() { //Special naming for 0x60 to make it easier to search if(OpCode == 0x60) return FileName.Replace("0x60_", $"0x60_0x{(int)(BinaryData[6]):X2}_"); return $"{FileName}"; } /// <inheritdoc /> public override int GetHashCode() { return FileName.GetHashCode(); } } } } ```
a10cf9cf-d683-4ee6-9730-f67f1b0866b1
{ "language": "C#" }
```c# using System; using System.Windows.Forms; using CefSharp; using TweetDck.Core.Bridge; using TweetDck.Core.Controls; using TweetDck.Resources; namespace TweetDck.Core.Notification.Screenshot{ sealed class FormNotificationScreenshotable : FormNotification{ public FormNotificationScreenshotable(Action callback, FormBrowser owner, NotificationFlags flags) : base(owner, null, flags){ browser.RegisterAsyncJsObject("$TD_NotificationScreenshot", new CallbackBridge(this, callback)); browser.FrameLoadEnd += (sender, args) => { if (args.Frame.IsMain && browser.Address != "about:blank"){ ScriptLoader.ExecuteScript(args.Frame, "window.setTimeout(() => $TD_NotificationScreenshot.trigger(), 25)", "gen:screenshot"); } }; UpdateTitle(); } public void LoadNotificationForScreenshot(TweetNotification tweet, int width, int height){ browser.LoadHtml(tweet.GenerateHtml(enableCustomCSS: false), "http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks); Location = ControlExtensions.InvisibleLocation; FormBorderStyle = Program.UserConfig.ShowScreenshotBorder ? FormBorderStyle.FixedToolWindow : FormBorderStyle.None; SetNotificationSize(width, height, false); } public void TakeScreenshotAndHide(){ MoveToVisibleLocation(); Activate(); SendKeys.SendWait("%{PRTSC}"); Reset(); } public void Reset(){ Location = ControlExtensions.InvisibleLocation; browser.LoadHtml("", "about:blank"); } } } ``` Tweak screenshot notification script (minor edit)
```c# using System; using System.Windows.Forms; using CefSharp; using TweetDck.Core.Bridge; using TweetDck.Core.Controls; using TweetDck.Resources; namespace TweetDck.Core.Notification.Screenshot{ sealed class FormNotificationScreenshotable : FormNotification{ public FormNotificationScreenshotable(Action callback, FormBrowser owner, NotificationFlags flags) : base(owner, null, flags){ browser.RegisterAsyncJsObject("$TD_NotificationScreenshot", new CallbackBridge(this, callback)); browser.FrameLoadEnd += (sender, args) => { if (args.Frame.IsMain && browser.Address != "about:blank"){ ScriptLoader.ExecuteScript(args.Frame, "window.setTimeout($TD_NotificationScreenshot.trigger, 25)", "gen:screenshot"); } }; UpdateTitle(); } public void LoadNotificationForScreenshot(TweetNotification tweet, int width, int height){ browser.LoadHtml(tweet.GenerateHtml(enableCustomCSS: false), "http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks); Location = ControlExtensions.InvisibleLocation; FormBorderStyle = Program.UserConfig.ShowScreenshotBorder ? FormBorderStyle.FixedToolWindow : FormBorderStyle.None; SetNotificationSize(width, height, false); } public void TakeScreenshotAndHide(){ MoveToVisibleLocation(); Activate(); SendKeys.SendWait("%{PRTSC}"); Reset(); } public void Reset(){ Location = ControlExtensions.InvisibleLocation; browser.LoadHtml("", "about:blank"); } } } ```
ff44aad3-d911-4809-94bb-86fd149e89ac
{ "language": "C#" }
```c# @{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div> ``` Add temporary warning of upcoming lab closure.
```c# @{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <p class="lead">PLEASE NOTE: The Analytical Lab will be closed on July 4th and 5th.</p> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div> ```
7899b8d2-b0ff-4a30-8e65-27320abd2e8c
{ "language": "C#" }
```c# using Newtonsoft.Json; namespace AzureSpeed.WebUI.Models { public class Prefix { [JsonProperty("ip_prefix")] public string IpPrefix { get; set; } [JsonProperty("region")] public string Region { get; set; } [JsonProperty("region")] public string Service { get; set; } } }``` Fix IP look up page broken
```c# using Newtonsoft.Json; namespace AzureSpeed.WebUI.Models { public class Prefix { [JsonProperty("ip_prefix")] public string IpPrefix { get; set; } [JsonProperty("region")] public string Region { get; set; } [JsonProperty("service")] public string Service { get; set; } } }```
0e680c0f-e146-4303-9671-79d580ccfbb5
{ "language": "C#" }
```c# using System; using System.Diagnostics; using Microsoft.Web.Administration; using Microsoft.WindowsAzure.ServiceRuntime; using System.Linq; namespace SFA.DAS.ReferenceData.Api { public class WebRole : RoleEntryPoint { public override void Run() { using (var serverManager = new ServerManager()) { foreach (var application in serverManager.Sites.SelectMany(x => x.Applications)) { application["preloadEnabled"] = true; } foreach (var applicationPool in serverManager.ApplicationPools) { applicationPool["startMode"] = "AlwaysRunning"; } serverManager.CommitChanges(); } base.Run(); } } }``` Remove Idle timeout in IIS
```c# using System; using System.Diagnostics; using Microsoft.Web.Administration; using Microsoft.WindowsAzure.ServiceRuntime; using System.Linq; namespace SFA.DAS.ReferenceData.Api { public class WebRole : RoleEntryPoint { public override void Run() { using (var serverManager = new ServerManager()) { foreach (var application in serverManager.Sites.SelectMany(x => x.Applications)) { application["preloadEnabled"] = true; } foreach (var applicationPool in serverManager.ApplicationPools) { applicationPool["startMode"] = "AlwaysRunning"; applicationPool.ProcessModel.IdleTimeout = new System.TimeSpan(0); } serverManager.CommitChanges(); } base.Run(); } } }```
c4093d8d-db4f-47b6-8c6e-b923aa2e9233
{ "language": "C#" }
```c# static class LogLine { public static string Message(string logLine) { return logLine.Substring(logLine.IndexOf(":") + 1).Trim(); } public static string LogLevel(string logLine) { return logLine.Substring(1, (logLine.IndexOf("]") - 1).ToLower(); } public static string Reformat(string logLine) { return $"{Message(logLine)} ({LogLevel(logLine)})"; } } ``` Fix example of strings exercise
```c# static class LogLine { public static string Message(string logLine) { return logLine.Substring(logLine.IndexOf(":") + 1).Trim(); } public static string LogLevel(string logLine) { return logLine.Substring(1, logLine.IndexOf("]") - 1).ToLower(); } public static string Reformat(string logLine) { return $"{Message(logLine)} ({LogLevel(logLine)})"; } } ```
e6354c07-c5ee-434f-be96-c3853cc54849
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using CIV.Ccs; using CIV.Interfaces; using Moq; namespace CIV.Test { public static class Common { /// <summary> /// Setup a mock process that can only do the given action. /// </summary> /// <returns>The mock process.</returns> /// <param name="action">Action.</param> public static CcsProcess SetupMockProcess(String action = "action") { return Mock.Of<CcsProcess>(p => p.Transitions() == new List<Transition> { SetupTransition(action) } ); } static Transition SetupTransition(String label) { return new Transition { Label = label, Process = Mock.Of<CcsProcess>() }; } } } ``` Use new Process interface in tests
```c# using System; using System.Collections.Generic; using CIV.Ccs; using CIV.Interfaces; using Moq; namespace CIV.Test { public static class Common { /// <summary> /// Setup a mock process that can only do the given action. /// </summary> /// <returns>The mock process.</returns> /// <param name="action">Action.</param> public static CcsProcess SetupMockProcess(String action = "action") { return Mock.Of<CcsProcess>(p => p.GetTransitions() == new List<Transition> { SetupTransition(action) } ); } static Transition SetupTransition(String label) { return new Transition { Label = label, Process = Mock.Of<CcsProcess>() }; } } } ```
e1be3b7f-9c41-49a5-8de2-8358160faee9
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; namespace TirkxDownloader.Framework { public static class Extension { public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct) { using (ct.Register(() => request.Abort(), useSynchronizationContext: false)) { try { var response = await request.GetResponseAsync(); ct.ThrowIfCancellationRequested(); return (HttpWebResponse)response; } catch (WebException webEx) { if (ct.IsCancellationRequested) { throw new OperationCanceledException(webEx.Message, webEx, ct); } throw; } } } public static T[] Dequeue<T>(this Queue<T> queue, int count) { T[] list = new T[count]; for (int i = 0; i < count; i++) { list[i] = queue.Dequeue(); } return list; } } } ``` Add Link method to compare string with wildcards
```c# using System; using System.Collections.Generic; using System.Net; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace TirkxDownloader.Framework { public static class Extension { public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct) { using (ct.Register(() => request.Abort(), useSynchronizationContext: false)) { try { var response = await request.GetResponseAsync(); ct.ThrowIfCancellationRequested(); return (HttpWebResponse)response; } catch (WebException webEx) { if (ct.IsCancellationRequested) { throw new OperationCanceledException(webEx.Message, webEx, ct); } throw; } } } public static T[] Dequeue<T>(this Queue<T> queue, int count) { T[] list = new T[count]; for (int i = 0; i < count; i++) { list[i] = queue.Dequeue(); } return list; } /// <summary> /// Compares the string against a given pattern. /// </summary> /// <param name="str">The string.</param> /// <param name="pattern">The pattern to match, where "*" means any sequence of characters, and "?" means any single character.</param> /// <returns><c>true</c> if the string matches the given pattern; otherwise <c>false</c>.</returns> public static bool Like(this string str, string pattern) { return new Regex( "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$", RegexOptions.IgnoreCase | RegexOptions.Singleline ).IsMatch(str); } } } ```
e17d931f-86c8-407d-9ce1-ec144c4ec401
{ "language": "C#" }
```c# namespace Amazon.Lambda.APIGatewayEvents { /// <summary> /// For requests coming in to a custom API Gateway authorizer function. /// </summary> public class APIGatewayCustomAuthorizerRequest { /// <summary> /// Gets or sets the 'type' property. /// </summary> public string Type { get; set; } /// <summary> /// Gets or sets the 'authorizationToken' property. /// </summary> public string AuthorizationToken { get; set; } /// <summary> /// Gets or sets the 'methodArn' property. /// </summary> public string MethodArn { get; set; } } } ``` Add parameter for a REQUEST type API Gateway Custom Authorizer
```c# using System.Collections.Generic; namespace Amazon.Lambda.APIGatewayEvents { /// <summary> /// For requests coming in to a custom API Gateway authorizer function. /// </summary> public class APIGatewayCustomAuthorizerRequest { /// <summary> /// Gets or sets the 'type' property. /// </summary> public string Type { get; set; } /// <summary> /// Gets or sets the 'authorizationToken' property. /// </summary> public string AuthorizationToken { get; set; } /// <summary> /// Gets or sets the 'methodArn' property. /// </summary> public string MethodArn { get; set; } /// <summary> /// The url path for the caller. For Request type API Gateway Custom Authorizer only. /// </summary> public string Path { get; set; } /// <summary> /// The HTTP method used. For Request type API Gateway Custom Authorizer only. /// </summary> public string HttpMethod { get; set; } /// <summary> /// The headers sent with the request. For Request type API Gateway Custom Authorizer only. /// </summary> public IDictionary<string, string> Headers {get;set;} /// <summary> /// The query string parameters that were part of the request. For Request type API Gateway Custom Authorizer only. /// </summary> public IDictionary<string, string> QueryStringParameters { get; set; } /// <summary> /// The path parameters that were part of the request. For Request type API Gateway Custom Authorizer only. /// </summary> public IDictionary<string, string> PathParameters { get; set; } /// <summary> /// The stage variables defined for the stage in API Gateway. For Request type API Gateway Custom Authorizer only. /// </summary> public IDictionary<string, string> StageVariables { get; set; } /// <summary> /// The request context for the request. For Request type API Gateway Custom Authorizer only. /// </summary> public APIGatewayProxyRequest.ProxyRequestContext RequestContext { get; set; } } } ```
c52d3098-364b-4127-9fd1-1d8617f5bbd1
{ "language": "C#" }
```c# using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.4"; } } ``` Update file version to 2.2.1.5
```c# using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.5"; } } ```
2bb2af07-a6b2-43aa-9b46-d7cb799f9cf2
{ "language": "C#" }
```c# using System.Text.RegularExpressions; using Cassette; using Cassette.HtmlTemplates; using Cassette.Scripts; using Cassette.Stylesheets; namespace Example { public class CassetteConfiguration : ICassetteConfiguration { public void Configure(ModuleConfiguration modules) { modules.Add( new PerSubDirectorySource<ScriptModule>("Scripts") { FilePattern = "*.js", Exclude = new Regex("-vsdoc\\.js$") }, new ExternalScriptModule("twitter", "http://platform.twitter.com/widgets.js") { Location = "body" } ); modules.Add(new DirectorySource<StylesheetModule>("Styles") { FilePattern = "*.css;*.less" }); modules.Add(new PerSubDirectorySource<HtmlTemplateModule>("HtmlTemplates")); modules.Customize<StylesheetModule>(m => m.Processor = new StylesheetPipeline { CompileLess = true, ConvertImageUrlsToDataUris = true }); } } }``` Use HTML template compiler in example.
```c# using System.Text.RegularExpressions; using Cassette; using Cassette.HtmlTemplates; using Cassette.Scripts; using Cassette.Stylesheets; namespace Example { public class CassetteConfiguration : ICassetteConfiguration { public void Configure(ModuleConfiguration modules) { modules.Add( new PerSubDirectorySource<ScriptModule>("Scripts") { FilePattern = "*.js", Exclude = new Regex("-vsdoc\\.js$") }, new ExternalScriptModule("twitter", "http://platform.twitter.com/widgets.js") { Location = "body" } ); modules.Add(new DirectorySource<StylesheetModule>("Styles") { FilePattern = "*.css;*.less" }); modules.Add(new PerSubDirectorySource<HtmlTemplateModule>("HtmlTemplates")); modules.Customize<StylesheetModule>(m => m.Processor = new StylesheetPipeline { CompileLess = true, ConvertImageUrlsToDataUris = true }); modules.Customize<HtmlTemplateModule>(m => m.Processor = new JQueryTmplPipeline{KnockoutJS = true}); } } }```
91c6b97c-f8e7-441d-a383-36b5d2a8bee5
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Aggregates.NET")] [assembly: AssemblyDescription(".NET event sourced domain driven design model via NServiceBus and EventStore")] [assembly: AssemblyCopyright("Copyright © Charles Solar 2017")] [assembly: AssemblyVersion("0.12.0.0")] [assembly: AssemblyFileVersion("0.12.0.0")] [assembly: AssemblyInformationalVersion("0.12.0.0")] [assembly: InternalsVisibleTo("Aggregates.NET.UnitTests")] [assembly: InternalsVisibleTo("Aggregates.NET")] [assembly: InternalsVisibleTo("Aggregates.NET.EventStore")] [assembly: InternalsVisibleTo("Aggregates.NET.NServiceBus")] [assembly: InternalsVisibleTo("Aggregates.NET.NewtonsoftJson")] [assembly: InternalsVisibleTo("Aggregates.NET.StructureMap")] [assembly: InternalsVisibleTo("Aggregates.NET.SimpleInjector")] ``` Increment library version as version on pre-release line messed up versioning
```c# using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Aggregates.NET")] [assembly: AssemblyDescription(".NET event sourced domain driven design model via NServiceBus and EventStore")] [assembly: AssemblyCopyright("Copyright © Charles Solar 2017")] [assembly: AssemblyVersion("0.13.0.0")] [assembly: AssemblyFileVersion("0.13.0.0")] [assembly: AssemblyInformationalVersion("0.13.0.0")] [assembly: InternalsVisibleTo("Aggregates.NET.UnitTests")] [assembly: InternalsVisibleTo("Aggregates.NET")] [assembly: InternalsVisibleTo("Aggregates.NET.EventStore")] [assembly: InternalsVisibleTo("Aggregates.NET.NServiceBus")] [assembly: InternalsVisibleTo("Aggregates.NET.NewtonsoftJson")] [assembly: InternalsVisibleTo("Aggregates.NET.StructureMap")] [assembly: InternalsVisibleTo("Aggregates.NET.SimpleInjector")] ```
a87fe859-caf7-465f-895b-07d14bc5640b
{ "language": "C#" }
```c# namespace HeyRed.Mime { public enum MagicParams { MAGIC_PARAM_INDIR_MAX = 0, MAGIC_PARAM_NAME_MAX, MAGIC_PARAM_ELF_PHNUM_MAX, MAGIC_PARAM_ELF_SHNUM_MAX, MAGIC_PARAM_ELF_NOTES_MAX, MAGIC_PARAM_REGEX_MAX, MAGIC_PARAM_BYTES_MAX } } ``` Add description for magic params
```c# namespace HeyRed.Mime { public enum MagicParams { /// <summary> /// The parameter controls how many levels of recursion will be followed for indirect magic entries. /// </summary> MAGIC_PARAM_INDIR_MAX = 0, /// <summary> /// The parameter controls the maximum number of calls for name/use. /// </summary> MAGIC_PARAM_NAME_MAX, /// <summary> /// The parameter controls how many ELF program sections will be processed. /// </summary> MAGIC_PARAM_ELF_PHNUM_MAX, /// <summary> /// The parameter controls how many ELF sections will be processed. /// </summary> MAGIC_PARAM_ELF_SHNUM_MAX, /// <summary> /// The parameter controls how many ELF notes will be processed. /// </summary> MAGIC_PARAM_ELF_NOTES_MAX, MAGIC_PARAM_REGEX_MAX, MAGIC_PARAM_BYTES_MAX } } ```
72e322e2-efe9-4ae1-b0a5-498990db308f
{ "language": "C#" }
```c# using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Screens; namespace TemplateGame.Game { public class MainScreen : Screen { [BackgroundDependencyLoader] private void load() { AddInternal(new SpinningBox { Anchor = Anchor.Centre, }); } } } ``` Make main screen a bit more identifiable
```c# using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Screens; using osuTK.Graphics; namespace TemplateGame.Game { public class MainScreen : Screen { [BackgroundDependencyLoader] private void load() { InternalChildren = new Drawable[] { new Box { Colour = Color4.Violet, RelativeSizeAxes = Axes.Both, }, new SpriteText { Y = 20, Text = "Main Screen", Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Font = FontUsage.Default.With(size: 40) }, new SpinningBox { Anchor = Anchor.Centre, } }; } } } ```
657ad3b0-16bc-4afa-9cd8-9bae0b5e0ce0
{ "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 ExpireFundsJob { private readonly IMessageSession _messageSession; public ExpireFundsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 0 10 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ExpireFundsCommand()); } } }``` Change expiry job back to 28th
```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 ExpireFundsJob { private readonly IMessageSession _messageSession; public ExpireFundsJob(IMessageSession messageSession) { _messageSession = messageSession; } public Task Run([TimerTrigger("0 0 0 28 * *")] TimerInfo timer, ILogger logger) { return _messageSession.Send(new ExpireFundsCommand()); } } }```
f93d38cd-b91e-47aa-b44d-2ff4a6c650b7
{ "language": "C#" }
```c# using System; using System.Text.RegularExpressions; namespace Zenini.Patterns { public class KeyValuePattern { private static readonly Regex KeyValueRegex = new Regex(@"^\s*(.+?)\s*=\s*(.+?)\s*$", RegexOptions.Compiled); public virtual bool Matches(string line) { return KeyValueRegex.IsMatch(line); } public virtual Tuple<string, string> Extract(string line) { MatchCollection collection = KeyValueRegex.Matches(line); string key = collection[0].Groups[1].Value; string value = collection[0].Groups[2].Value; if (value.StartsWith("\"") && value.EndsWith("\"")) value = value.Substring(1, value.Length - 2); return new Tuple<string, string>(key, value); } } }``` Improve key/value pattern values enclosed in quotation marks
```c# using System; using System.Text.RegularExpressions; namespace Zenini.Patterns { public class KeyValuePattern { private static readonly Regex KeyValueRegex = new Regex(@"^\s*(.+?)\s*=\s*(?:"")?(.+?)(?:\"")?\s*$", RegexOptions.Compiled); public virtual bool Matches(string line) { return KeyValueRegex.IsMatch(line); } public virtual Tuple<string, string> Extract(string line) { MatchCollection collection = KeyValueRegex.Matches(line); string key = collection[0].Groups[1].Value; string value = collection[0].Groups[2].Value; return new Tuple<string, string>(key, value); } } }```
2e0e16c7-8e49-4e4c-861e-3f8fa34f9d00
{ "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. namespace Microsoft.Azure.EventHubs { using System; using System.Reflection; using System.Runtime.Versioning; using Microsoft.Azure.Amqp; static class ClientInfo { static readonly string product; static readonly string version; static readonly string framework; static readonly string platform; static ClientInfo() { try { Assembly assembly = typeof(ClientInfo).GetTypeInfo().Assembly; product = GetAssemblyAttributeValue<AssemblyProductAttribute>(assembly, p => p.Product); version = GetAssemblyAttributeValue<AssemblyVersionAttribute>(assembly, v => v.Version); framework = GetAssemblyAttributeValue<TargetFrameworkAttribute>(assembly, f => f.FrameworkName); #if NETSTANDARD platform = System.Runtime.InteropServices.RuntimeInformation.OSDescription; #else platform = Environment.OSVersion.VersionString; #endif } catch { } } public static void Add(AmqpConnectionSettings settings) { settings.AddProperty("product", product); settings.AddProperty("version", version); settings.AddProperty("framework", framework); settings.AddProperty("platform", platform); } static string GetAssemblyAttributeValue<T>(Assembly assembly, Func<T, string> getter) where T : Attribute { var attribute = assembly.GetCustomAttribute(typeof(T)) as T; return attribute == null ? null : getter(attribute); } } } ``` Use file version as client version
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.EventHubs { using System; using System.Reflection; using System.Runtime.Versioning; using Microsoft.Azure.Amqp; static class ClientInfo { static readonly string product; static readonly string version; static readonly string framework; static readonly string platform; static ClientInfo() { try { Assembly assembly = typeof(ClientInfo).GetTypeInfo().Assembly; product = GetAssemblyAttributeValue<AssemblyProductAttribute>(assembly, p => p.Product); version = GetAssemblyAttributeValue<AssemblyFileVersionAttribute>(assembly, v => v.Version); framework = GetAssemblyAttributeValue<TargetFrameworkAttribute>(assembly, f => f.FrameworkName); #if NETSTANDARD platform = System.Runtime.InteropServices.RuntimeInformation.OSDescription; #else platform = Environment.OSVersion.VersionString; #endif } catch { } } public static void Add(AmqpConnectionSettings settings) { settings.AddProperty("product", product); settings.AddProperty("version", version); settings.AddProperty("framework", framework); settings.AddProperty("platform", platform); } static string GetAssemblyAttributeValue<T>(Assembly assembly, Func<T, string> getter) where T : Attribute { var attribute = assembly.GetCustomAttribute(typeof(T)) as T; return attribute == null ? null : getter(attribute); } } } ```
76def8a6-e7d3-4372-b3cb-a98a5b61f506
{ "language": "C#" }
```c# using ICities; using MetroOverhaul.OptionsFramework.Extensions; namespace MetroOverhaul { public class Mod : IUserMod { public string Name => "Metro Overhaul"; public string Description => "Brings metro depots, ground and elevated metro tracks"; public void OnSettingsUI(UIHelperBase helper) { helper.AddOptionsGroup<Options>(); } } } ``` Make different mod name in patched version
```c# using ICities; using MetroOverhaul.OptionsFramework.Extensions; namespace MetroOverhaul { public class Mod : IUserMod { #if IS_PATCH public const bool isPatch = true; #else public const bool isPatch = false; #endif public string Name => "Metro Overhaul" + (isPatch ? " [Patched]" : ""); public string Description => "Brings metro depots, ground and elevated metro tracks"; public void OnSettingsUI(UIHelperBase helper) { helper.AddOptionsGroup<Options>(); } } } ```
ebe3f835-6fe9-45f9-84b1-659b98dd47b3
{ "language": "C#" }
```c# using NBi.Core.Structure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Structure.Relational.Builders { class SchemaDiscoveryCommandBuilder : RelationalDiscoveryCommandBuilder { protected override string BasicCommandText { get { return base.BasicCommandText + " and [schema_owner]='dbo'"; } } public SchemaDiscoveryCommandBuilder() { CaptionName = "schema"; TableName = "schemata"; } protected override IEnumerable<ICommandFilter> BuildCaptionFilters(IEnumerable<CaptionFilter> filters) { var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives); if (filter != null) yield return new CommandFilter(string.Format("[schema_name]='{0}'" , filter.Caption )); } } } ``` Remove requirement for [schema_owner] = 'dbo'
```c# using NBi.Core.Structure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Structure.Relational.Builders { class SchemaDiscoveryCommandBuilder : RelationalDiscoveryCommandBuilder { protected override string BasicCommandText { get { return base.BasicCommandText; } } public SchemaDiscoveryCommandBuilder() { CaptionName = "schema"; TableName = "schemata"; } protected override IEnumerable<ICommandFilter> BuildCaptionFilters(IEnumerable<CaptionFilter> filters) { var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives); if (filter != null) yield return new CommandFilter(string.Format("[schema_name]='{0}'" , filter.Caption )); } } } ```
5a2c091b-61b7-4597-abfe-2dfc2648fa7b
{ "language": "C#" }
```c# using System; using Microsoft.AspNetCore.Builder; using Criteo.Profiling.Tracing; namespace Criteo.Profiling.Tracing.Middleware { public static class TracingMiddleware { public static void UseTracing(this IApplicationBuilder app, string serviceName) { app.Use(async (context, next) => { var trace = Trace.Create(); Trace.Current = trace; trace.Record(Annotations.ServerRecv()); trace.Record(Annotations.ServiceName(serviceName)); trace.Record(Annotations.Rpc(context.Request.Method)); await next.Invoke(); trace.Record(Annotations.ServerSend()); }); } } }``` Enable middleware to extract trace from incoming request headers.
```c# using System; using Microsoft.AspNetCore.Builder; using Criteo.Profiling.Tracing; namespace Criteo.Profiling.Tracing.Middleware { public static class TracingMiddleware { public static void UseTracing(this IApplicationBuilder app, string serviceName) { var extractor = new ZipkinHttpTraceExtractor(); app.Use(async (context, next) => { Trace trace; if (!extractor.TryExtract(context.Request.Headers, out trace)) { trace = Trace.Create(); } Trace.Current = trace; trace.Record(Annotations.ServerRecv()); trace.Record(Annotations.ServiceName(serviceName)); trace.Record(Annotations.Rpc(context.Request.Method)); await next.Invoke(); trace.Record(Annotations.ServerSend()); }); } } }```
1de01b38-0a47-465c-b833-4a5bb08292d1
{ "language": "C#" }
```c# using System; namespace Plethora { public static class MathEx { /// <summary> /// Returns the greatest common divisor of two numbers. /// </summary> /// <param name="a">The first number.</param> /// <param name="b">The second number.</param> /// <returns>The greatest common divisor of <paramref name="a"/> and <paramref name="b"/>.</returns> /// <remarks> /// This implementation uses the Euclidean algorithm. /// <seealso cref="https://en.wikipedia.org/wiki/Euclidean_algorithm"/> /// </remarks> public static int GreatestCommonDivisor(int a, int b) { a = Math.Abs(a); b = Math.Abs(b); while (b != 0) { int rem = a % b; a = b; b = rem; } return a; } } } ``` Correct href in <see/> tag
```c# using System; namespace Plethora { public static class MathEx { /// <summary> /// Returns the greatest common divisor of two numbers. /// </summary> /// <param name="a">The first number.</param> /// <param name="b">The second number.</param> /// <returns>The greatest common divisor of <paramref name="a"/> and <paramref name="b"/>.</returns> /// <remarks> /// This implementation uses the Euclidean algorithm. /// <seealso href="https://en.wikipedia.org/wiki/Euclidean_algorithm"/> /// </remarks> public static int GreatestCommonDivisor(int a, int b) { a = Math.Abs(a); b = Math.Abs(b); while (b != 0) { int rem = a % b; a = b; b = rem; } return a; } } } ```
af632b27-22c1-48f0-9dbf-8245d0d81a86
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace ShopifyAPIAdapterLibrary.Models { public class ShopifyResourceModel : IResourceModel { public event PropertyChangedEventHandler PropertyChanged; private HashSet<string> Dirty; public void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "") { // thanks to http://danrigby.com/2012/03/01/inotifypropertychanged-the-net-4-5-way/ if (!EqualityComparer<T>.Default.Equals(field, value)) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } field = value; Dirty.Add(name); } } public void Reset() { Dirty.Clear(); } public bool IsFieldDirty(string field) { return Dirty.Contains(field); } public bool IsClean() { return Dirty.Count == 0; } private int? id; public int? Id { get { return id; } set { SetProperty(ref id, value); } } public ShopifyResourceModel() { Dirty = new HashSet<string>(); } } } ``` Throw an exception of [CallerMemberName] misbehaves.
```c# using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace ShopifyAPIAdapterLibrary.Models { public class ShopifyResourceModel : IResourceModel { public event PropertyChangedEventHandler PropertyChanged; private HashSet<string> Dirty; public void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = null) { if (name == null) { throw new ShopifyConfigurationException("Field name is coming up null in SetProperty. Something's wrong."); } Console.WriteLine("SETTING PROPERTY {0} to {1}", name, value); // thanks to http://danrigby.com/2012/03/01/inotifypropertychanged-the-net-4-5-way/ if (!EqualityComparer<T>.Default.Equals(field, value)) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } field = value; Dirty.Add(name); } } public void Reset() { Dirty.Clear(); } public bool IsFieldDirty(string field) { return Dirty.Contains(field); } public bool IsClean() { return Dirty.Count == 0; } private int? id; public int? Id { get { return id; } set { SetProperty(ref id, value); } } public ShopifyResourceModel() { Dirty = new HashSet<string>(); } } } ```
b1c9bd6e-2e39-4276-8e30-4d2ab295905d
{ "language": "C#" }
```c# using System; using System.Runtime.InteropServices; using LibGit2Sharp.Core; namespace LibGit2Sharp { public class IndexEntry { public IndexEntryState State { get; set; } public string Path { get; private set; } public ObjectId Id { get; private set; } internal static IndexEntry CreateFromPtr(IntPtr ptr) { var entry = (GitIndexEntry) Marshal.PtrToStructure(ptr, typeof (GitIndexEntry)); return new IndexEntry { Path = entry.Path, Id = new ObjectId(entry.oid), }; } } }``` Reduce exposure of public API
```c# using System; using System.Runtime.InteropServices; using LibGit2Sharp.Core; namespace LibGit2Sharp { public class IndexEntry { public IndexEntryState State { get; private set; } public string Path { get; private set; } public ObjectId Id { get; private set; } internal static IndexEntry CreateFromPtr(IntPtr ptr) { var entry = (GitIndexEntry) Marshal.PtrToStructure(ptr, typeof (GitIndexEntry)); return new IndexEntry { Path = entry.Path, Id = new ObjectId(entry.oid), }; } } }```
c5092294-84a5-4166-9b3f-3b6627d6a7e0
{ "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("TweetDick")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TweetDick")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7f09373d-8beb-416f-a48d-45d8aaeb8caf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ``` Change version to 0.9.0.0 for the premature build
```c# using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TweetDick")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TweetDick")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7f09373d-8beb-416f-a48d-45d8aaeb8caf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")] ```
420ad15b-2265-41b5-8b35-fa1b7badbfc1
{ "language": "C#" }
```c# using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class LeaderboardUI : MonoBehaviour { [SerializeField] private RectTransform _scoresList; [SerializeField] private Text _sceneTitle; [SerializeField] private string _defaultScene = "Tuto"; private const string _path = "./"; private string _filePath; private Leaderboard _leaderboard; private const string _leaderboardTitle = "Leaderboard - "; private void Start () { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; LoadScene(_defaultScene); } public void LoadScene(string scene) { _filePath = _path + scene + ".json"; _leaderboard = new Leaderboard(_filePath); _leaderboard.Show(_scoresList); UpdateLeaderboardTitle(scene); } public void BackToMainMenu() { SceneManager.LoadScene("MainMenu"); } private void UpdateLeaderboardTitle(string sceneTitle) { _sceneTitle.text = _leaderboardTitle + sceneTitle; } } ``` Remove list element when switching scene
```c# using UnityEditor; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class LeaderboardUI : MonoBehaviour { [SerializeField] private RectTransform _scoresList; [SerializeField] private Text _sceneTitle; [SerializeField] private string _defaultScene = "Tuto"; private const string _path = "./"; private string _filePath; private Leaderboard _leaderboard; private const string _leaderboardTitle = "Leaderboard - "; private void Start () { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; LoadScene(_defaultScene); } public void LoadScene(string scene) { ResetList(); _filePath = _path + scene + ".json"; _leaderboard = new Leaderboard(_filePath); _leaderboard.Show(_scoresList); UpdateLeaderboardTitle(scene); } private void ResetList() { for (var i = 0; i < _scoresList.childCount; ++i) { Destroy(_scoresList.GetChild(i).gameObject); } } public void BackToMainMenu() { SceneManager.LoadScene("MainMenu"); } private void UpdateLeaderboardTitle(string sceneTitle) { _sceneTitle.text = _leaderboardTitle + sceneTitle; } } ```
3c64ec95-eca5-4016-8f9f-0fdac6052634
{ "language": "C#" }
```c# using System.Net.Http; using MyCouch.Extensions; namespace MyCouch.Responses.Materializers { public class BasicResponseMaterializer { public virtual void Materialize(Response response, HttpResponseMessage httpResponse) { response.RequestUri = httpResponse.RequestMessage.RequestUri; response.StatusCode = httpResponse.StatusCode; response.RequestMethod = httpResponse.RequestMessage.Method; response.ContentLength = httpResponse.Content.Headers.ContentLength; response.ContentType = httpResponse.Content.Headers.ContentType.ToString(); response.ETag = httpResponse.Headers.GetETag(); } } }``` Fix for content type NULL in rare cercumstances
```c# using System.Net.Http; using MyCouch.Extensions; namespace MyCouch.Responses.Materializers { public class BasicResponseMaterializer { public virtual void Materialize(Response response, HttpResponseMessage httpResponse) { response.RequestUri = httpResponse.RequestMessage.RequestUri; response.StatusCode = httpResponse.StatusCode; response.RequestMethod = httpResponse.RequestMessage.Method; response.ContentLength = httpResponse.Content.Headers.ContentLength; response.ContentType = httpResponse.Content.Headers.ContentType != null ? httpResponse.Content.Headers.ContentType.ToString() : null; response.ETag = httpResponse.Headers.GetETag(); } } }```
560d5421-ffa9-45b0-839c-e021bb5b6b66
{ "language": "C#" }
```c# using Telerik.XamarinForms.DataControls.ListView; using TelerikListViewPoc.Components; using Xamarin.Forms; namespace TelerikListViewPoc.Controls { public class BookListCell : ListViewTemplateCell { public BookListCell() { var titleLabel = new Label { FontSize = Device.GetNamedSize(NamedSize.Default, typeof(Label)) }; titleLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Title), BindingMode.OneWay); var authorLabel = new Label { FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)) }; authorLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Author), BindingMode.OneWay); var yearLabel = new Label { FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)) }; yearLabel.SetBinding(Label.TextProperty, nameof(this.DataContext.Year), BindingMode.OneWay); var viewLayout = new StackLayout { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { titleLabel, authorLabel, yearLabel } }; this.View = viewLayout; } public Book DataContext { get { return this.BindingContext as Book; } } } } ``` Set fixed height and add debug messages for OnAppearing/OnDisappearing
```c# using System.Diagnostics; using Telerik.XamarinForms.DataControls.ListView; using TelerikListViewPoc.Components; using Xamarin.Forms; namespace TelerikListViewPoc.Controls { public class BookListCell : ListViewTemplateCell { public BookListCell() { var titleLabel = new Label { FontSize = Device.GetNamedSize(NamedSize.Default, typeof(Label)) }; titleLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Title), BindingMode.OneWay); var authorLabel = new Label { FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)) }; authorLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Author), BindingMode.OneWay); var yearLabel = new Label { FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)) }; yearLabel.SetBinding(Label.TextProperty, nameof(this.DataContext.Year), BindingMode.OneWay); var viewLayout = new StackLayout { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { titleLabel, authorLabel, yearLabel }, HeightRequest = 100 }; this.View = viewLayout; } public Book DataContext { get { return this.BindingContext as Book; } } protected override void OnAppearing() { Debug.WriteLine("OnAppearing"); base.OnAppearing(); } protected override void OnDisappearing() { Debug.WriteLine("OnDisappearing"); base.OnDisappearing(); } } } ```
666f71aa-3a71-4d0b-bb27-853cd5934bf0
{ "language": "C#" }
```c# using System; namespace DanTup.DartAnalysis { #region JSON deserialisation objects class ServerStatusEvent { public ServerAnalysisStatus analysis = null; } class ServerAnalysisStatus { public bool analyzing = false; } #endregion public class ServerStatusNotification { public bool IsAnalysing { get; internal set; } } internal static class ServerStatusEventImplementation { public static void RaiseServerStatusEvent(this DartAnalysisService service, ServerStatusEvent notification, EventHandler<ServerStatusNotification> handler) { if (handler != null) handler.Invoke(service, new ServerStatusNotification { IsAnalysing = notification.analysis.analyzing }); } } } ``` Use struct instead of class for event/notification data.
```c# using System; namespace DanTup.DartAnalysis { #region JSON deserialisation objects class ServerStatusEvent { public ServerAnalysisStatus analysis = null; } class ServerAnalysisStatus { public bool analyzing = false; } #endregion public struct ServerStatusNotification { public bool IsAnalysing { get; internal set; } } internal static class ServerStatusEventImplementation { public static void RaiseServerStatusEvent(this DartAnalysisService service, ServerStatusEvent notification, EventHandler<ServerStatusNotification> handler) { if (handler != null) handler.Invoke(service, new ServerStatusNotification { IsAnalysing = notification.analysis.analyzing }); } } } ```
fbf11f20-e556-45f6-92e7-da9532975660
{ "language": "C#" }
```c# namespace AdamS.StoreTemp.Models.Common { public static class StringExtensions { public static bool IsValidEmailAddress(this string emailAddress) { return !string.IsNullOrWhiteSpace(emailAddress); } } }``` Update StringExtension to validate email
```c# using System.Text.RegularExpressions; namespace AdamS.StoreTemp.Models.Common { public static class StringExtensions { public static bool IsValidEmailAddress(this string emailAddress) { Regex regex = new Regex(@"^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$"); Match match = regex.Match(emailAddress); return match.Success; } } }```
6c9399ee-47ff-4e1d-ae14-5624ec2a72b1
{ "language": "C#" }
```c# using System; using System.Linq; namespace BmpListener.Bgp { public abstract class BgpMessage { protected const int BgpHeaderLength = 19; protected BgpMessage(ref ArraySegment<byte> data) { Header = new BgpHeader(data); var offset = data.Offset + BgpHeaderLength; var count = Header.Length - BgpHeaderLength; data = new ArraySegment<byte>(data.Array, offset, count); } public enum Type { Open = 1, Update, Notification, Keepalive, RouteRefresh } public BgpHeader Header { get; } public abstract void DecodeFromBytes(ArraySegment<byte> data); public static BgpMessage GetBgpMessage(ArraySegment<byte> data) { var msgType = (Type) data.ElementAt(18); switch (msgType) { case Type.Open: return new BgpOpenMessage(data); case Type.Update: return new BgpUpdateMessage(data); case Type.Notification: return new BgpNotification(data); case Type.Keepalive: throw new NotImplementedException(); case Type.RouteRefresh: throw new NotImplementedException(); default: throw new NotImplementedException(); } } } }``` Replace ASN array with IList
```c# using System; namespace BmpListener.Bgp { public abstract class BgpMessage { protected const int BgpHeaderLength = 19; protected BgpMessage(ArraySegment<byte> data) { Header = new BgpHeader(data); var offset = data.Offset + BgpHeaderLength; var count = Header.Length - BgpHeaderLength; MessageData = new ArraySegment<byte>(data.Array, offset, count); } public enum Type { Open = 1, Update, Notification, Keepalive, RouteRefresh } protected ArraySegment<byte> MessageData { get; } public BgpHeader Header { get; } public abstract void DecodeFromBytes(ArraySegment<byte> data); public static BgpMessage GetBgpMessage(ArraySegment<byte> data) { var msgType = (Type)data.Array[data.Offset + 18]; switch (msgType) { case Type.Open: return new BgpOpenMessage(data); case Type.Update: return new BgpUpdateMessage(data); case Type.Notification: return new BgpNotification(data); case Type.Keepalive: throw new NotImplementedException(); case Type.RouteRefresh: throw new NotImplementedException(); default: throw new NotImplementedException(); } } } }```
df804cf6-a838-45da-bf5d-e23e34e74bca
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using MBEV = Microsoft.Build.Evaluation; using MBEX = Microsoft.Build.Execution; namespace MSBuildTracer { class ImportTracer { private MBEV.Project project; public ImportTracer(MBEV.Project project) { this.project = project; } public void Trace(MBEV.ResolvedImport import, int traceLevel = 0) { PrintImportInfo(import, traceLevel); foreach (var childImport in project.Imports.Where( i => string.Equals(i.ImportingElement.ContainingProject.FullPath, project.ResolveAllProperties(import.ImportingElement.Project), StringComparison.OrdinalIgnoreCase))) { Trace(childImport, traceLevel + 1); } } private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount) { var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : ""; Utils.WriteColor(indent, ConsoleColor.White); Utils.WriteColor($"{import.ImportingElement.Location.Line}: ", ConsoleColor.Cyan); Utils.WriteLineColor(project.ResolveAllProperties(import.ImportedProject.Location.File), ConsoleColor.Green); } } } ``` Fix import tracer to property trace all imports
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using MBEV = Microsoft.Build.Evaluation; using MBEX = Microsoft.Build.Execution; namespace MSBuildTracer { class ImportTracer { private MBEV.Project project; public ImportTracer(MBEV.Project project) { this.project = project; } public void Trace(MBEV.ResolvedImport import, int traceLevel = 0) { PrintImportInfo(import, traceLevel); foreach (var childImport in project.Imports.Where( i => string.Equals(i.ImportingElement.ContainingProject.FullPath, project.ResolveAllProperties(import.ImportedProject.Location.File), StringComparison.OrdinalIgnoreCase))) { Trace(childImport, traceLevel + 1); } } private void PrintImportInfo(MBEV.ResolvedImport import, int indentCount) { var indent = indentCount > 0 ? new StringBuilder().Insert(0, " ", indentCount).ToString() : ""; Utils.WriteColor(indent, ConsoleColor.White); Utils.WriteColor($"{import.ImportingElement.Location.Line}: ", ConsoleColor.Cyan); Utils.WriteLineColor(project.ResolveAllProperties(import.ImportedProject.Location.File), ConsoleColor.Green); } } } ```
ed50c722-2c77-4e87-a168-3c77577c5d50
{ "language": "C#" }
```c# using MediatR.Pipeline; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MediatR.Examples.ExceptionHandler.Overrides; public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResourceTimeout, Pong> { private readonly TextWriter _writer; public CommonExceptionHandler(TextWriter writer) => _writer = writer; protected override async Task Handle(PingResourceTimeout request, Exception exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class ServerExceptionHandler : ExceptionHandler.ServerExceptionHandler { private readonly TextWriter _writer; public ServerExceptionHandler(TextWriter writer) : base(writer) => _writer = writer; public override async Task Handle(PingNewResource request, ServerException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } }``` Fix MediatR examples exception handlers overrides
```c# using MediatR.Pipeline; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MediatR.Examples.ExceptionHandler.Overrides; public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResourceTimeout, Pong> { private readonly TextWriter _writer; public CommonExceptionHandler(TextWriter writer) => _writer = writer; protected override async Task Handle(PingResourceTimeout request, Exception exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { // Exception type name required because it is checked later in messages await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}"); // Exception handler type name required because it is checked later in messages await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } public class ServerExceptionHandler : ExceptionHandler.ServerExceptionHandler { private readonly TextWriter _writer; public ServerExceptionHandler(TextWriter writer) : base(writer) => _writer = writer; public override async Task Handle(PingNewResource request, ServerException exception, RequestExceptionHandlerState<Pong> state, CancellationToken cancellationToken) { // Exception type name required because it is checked later in messages await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}"); // Exception handler type name required because it is checked later in messages await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false); state.SetHandled(new Pong()); } } ```
9a5db766-0d1a-4758-84e4-8ab32a00e068
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using SharpResume.Model; using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace SharpResume.Tests { [TestClass] public class UnitTest { const string JsonName = "resume.json"; static readonly string _json = File.ReadAllText(Path.Combine( Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, JsonName)); readonly Resume _resume = Resume.Create(_json); readonly dynamic _expected = JObject.Parse(_json); [TestMethod] public void TestName() { string name = _expected.basics.name; Assert.AreEqual(name, _resume.Basics.Name); } [TestMethod] public void TestCoursesCount() { var educations = _expected.education.ToObject<List<Education>>(); Assert.AreEqual(educations.Count, _resume.Education.Length); } } } ``` Move from MSTest to NUnit
```c# using System.Collections.Generic; using System.IO; using Newtonsoft.Json.Linq; using NUnit.Framework; using SharpResume.Model; using Assert = NUnit.Framework.Assert; namespace SharpResume.Tests { [TestFixture] public class UnitTest { const string JsonName = "resume.json"; static readonly string _json = File.ReadAllText(Path.Combine( Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, JsonName)); readonly Resume _resume = Resume.Create(_json); readonly dynamic _expected = JObject.Parse(_json); [Test] public void TestName() { string name = _expected.basics.name; Assert.AreEqual(name, _resume.Basics.Name); } [Test] public void TestCoursesCount() { var educations = _expected.education.ToObject<List<Education>>(); Assert.AreEqual(educations.Count, _resume.Education.Length); } } } ```
30ea62c8-e240-43c4-a0eb-32f2cfc7f71f
{ "language": "C#" }
```c# // Copyright 2020, Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // TODO: Generate this file! // This file contains partial classes for all event and event data messages, to apply // the converter attributes to them. namespace Google.Events.Protobuf.Cloud.PubSub.V1 { [CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))] public partial class PubsubMessage { } } ``` Fix comment (which was in an unsaved file, unfortunately)
```c# // Copyright 2020, Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // TODO: Generate this file! // This file contains partial classes for all event data messages, to apply // the converter attributes to them. namespace Google.Events.Protobuf.Cloud.PubSub.V1 { [CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))] public partial class PubsubMessage { } } ```
05b25119-7e19-4527-be8f-4d9b52f4991f
{ "language": "C#" }
```c# // Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; namespace Yeena.Data { abstract class PersistentCache<T> where T : class { protected string Name { get; private set; } public T Value { get; protected set; } protected PersistentCache(string name) { Name = name; } public T Load(Func<T> factory) { OnLoad(); return Value ?? (Value = factory()); } public async Task<T> LoadAsync(Func<Task<T>> factory) { OnLoad(); return Value ?? (Value = await factory()); } public void Save() { OnSave(); } protected abstract void OnLoad(); protected abstract void OnSave(); } } ``` Allow manual changing of Value
```c# // Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; namespace Yeena.Data { abstract class PersistentCache<T> where T : class { protected string Name { get; private set; } public T Value { get; set; } protected PersistentCache(string name) { Name = name; } public T Load(Func<T> factory) { OnLoad(); return Value ?? (Value = factory()); } public async Task<T> LoadAsync(Func<Task<T>> factory) { OnLoad(); return Value ?? (Value = await factory()); } public void Save() { OnSave(); } protected abstract void OnLoad(); protected abstract void OnSave(); } } ```
73e9d640-3d07-4f62-89cd-0d9982594ff5
{ "language": "C#" }
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XiboClientWatchdog")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XiboClientWatchdog")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("ec4eaabc-ad30-4ac5-8e0a-0ddb06dad4b1")] // 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.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")] ``` Prepare for a release - this will go out with v2 R255
```c# using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XiboClientWatchdog")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XiboClientWatchdog")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("ec4eaabc-ad30-4ac5-8e0a-0ddb06dad4b1")] // 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.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")] ```
cac7d050-e0bf-4bf1-9f49-4a56d7699dfa
{ "language": "C#" }
```c# using System.Net.Http; using ShopifySharp.Filters; using System.Collections.Generic; using System.Threading.Tasks; using ShopifySharp.Infrastructure; using System; using System.Threading; using ShopifySharp.Lists; namespace ShopifySharp { /// <summary> /// A service for manipulating Shopify fulfillment orders. /// </summary> public class FulfillmentOrderService : ShopifyService { /// <summary> /// Creates a new instance of <see cref="FulfillmentOrderService" />. /// </summary> /// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param> /// <param name="shopAccessToken">An API access token for the shop.</param> public FulfillmentOrderService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { } /// <summary> /// Gets a list of up to 250 of the order's fulfillments. /// </summary> /// <param name="orderId">The order id to which the fulfillments belong.</param> /// <param name="cancellationToken">Cancellation Token</param> public virtual async Task<ListResult<FulfillmentOrder>> ListAsync(long orderId, CancellationToken cancellationToken = default) { return await ExecuteGetListAsync<FulfillmentOrder>($"orders/{orderId}/fulfillment_orders.json", "fulfillment_orders",null, cancellationToken); } } } ``` Return IEnumerable<FulfillmentOrder> instead of ListResult<FulfillmentOrder>
```c# using System.Net.Http; using ShopifySharp.Filters; using System.Collections.Generic; using System.Threading.Tasks; using ShopifySharp.Infrastructure; using System; using System.Threading; using ShopifySharp.Lists; namespace ShopifySharp { /// <summary> /// A service for manipulating Shopify fulfillment orders. /// </summary> public class FulfillmentOrderService : ShopifyService { /// <summary> /// Creates a new instance of <see cref="FulfillmentOrderService" />. /// </summary> /// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param> /// <param name="shopAccessToken">An API access token for the shop.</param> public FulfillmentOrderService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { } /// <summary> /// Gets a list of up to 250 of the order's fulfillments. /// </summary> /// <param name="orderId">The order id to which the fulfillments belong.</param> /// <param name="cancellationToken">Cancellation Token</param> public virtual async Task<IEnumerable<FulfillmentOrder>> ListAsync(long orderId, CancellationToken cancellationToken = default) { var req = PrepareRequest($"orders/{orderId}/fulfillment_orders.json"); var response = await ExecuteRequestAsync<IEnumerable<FulfillmentOrder>>(req, HttpMethod.Get, cancellationToken, rootElement: "fulfillment_orders"); return response.Result; } } } ```
f97a9add-d0c4-4870-9909-43b9a40186a7
{ "language": "C#" }
```c# using System.Windows.Forms; namespace XComponent.Common.UI.Pdf { public partial class WinFormPdfHost : UserControl { public WinFormPdfHost() { InitializeComponent(); if(!DesignMode) axAcroPDF1.setShowToolbar(true); } public void LoadFile(string path) { if (path != null) { axAcroPDF1.LoadFile(path); axAcroPDF1.src = path; axAcroPDF1.setViewScroll("FitH", 0); } } public void SetShowToolBar(bool on) { axAcroPDF1.setShowToolbar(on); } } } ``` Fix crash when acrobat is not correctly installed
```c# using System; using System.Windows.Forms; namespace XComponent.Common.UI.Pdf { public partial class WinFormPdfHost : UserControl { public WinFormPdfHost() { InitializeComponent(); if(!DesignMode) axAcroPDF1.setShowToolbar(true); } public void LoadFile(string path) { if (path != null) { try { axAcroPDF1.LoadFile(path); axAcroPDF1.src = path; axAcroPDF1.setViewScroll("FitH", 0); } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.ToString()); } } } public void SetShowToolBar(bool on) { axAcroPDF1.setShowToolbar(on); } } } ```
7659dedf-ecab-42fc-90c1-87c4cd6c0c6b
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; namespace SimpleApi { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentActions(); services.AddTransient<IUserService, UserService>(); services.AddTransient<INoteService, NoteService>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvc(); app.UseFluentActions(actions => { actions.RouteGet("/").To(() => "Hello World!"); actions.Add(UserActions.All); actions.Add(NoteActions.All); }); } } } ``` Move call to UseFluentActions before UseMvc in api test project
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; namespace SimpleApi { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentActions(); services.AddTransient<IUserService, UserService>(); services.AddTransient<INoteService, NoteService>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseFluentActions(actions => { actions.RouteGet("/").To(() => "Hello World!"); actions.Add(UserActions.All); actions.Add(NoteActions.All); }); app.UseMvc(); } } } ```
c84136c1-6625-471b-a99f-17d41d4fc082
{ "language": "C#" }
```c# namespace TraktApiSharp.Core { public static class TraktConstants { public static string OAuthBaseAuthorizeUrl => "https://trakt.tv"; public static string OAuthAuthorizeUri => "oauth/authorize"; public static string OAuthTokenUri => "oauth/token"; public static string OAuthRevokeUri => "oauth/revoke"; public static string OAuthDeviceCodeUri => "oauth/device/code"; public static string OAuthDeviceTokenUri => "oauth/device/token"; } } ``` Change access modifier for constants.
```c# namespace TraktApiSharp.Core { internal static class TraktConstants { internal static string OAuthBaseAuthorizeUrl => "https://trakt.tv"; internal static string OAuthAuthorizeUri => "oauth/authorize"; internal static string OAuthTokenUri => "oauth/token"; internal static string OAuthRevokeUri => "oauth/revoke"; internal static string OAuthDeviceCodeUri => "oauth/device/code"; internal static string OAuthDeviceTokenUri => "oauth/device/token"; } } ```
f390f382-c8a7-418b-a1a7-7c8066c82416
{ "language": "C#" }
```c# // Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Log4NetIntegration.Logging { using System.IO; using MassTransit.Logging; using log4net; using log4net.Config; public class Log4NetLogger : ILogger { public MassTransit.Logging.ILog Get(string name) { return new Log4NetLog(LogManager.GetLogger(name)); } public static void Use() { Logger.UseLogger(new Log4NetLogger()); } public static void Use(string file) { Logger.UseLogger(new Log4NetLogger()); var configFile = new FileInfo(file); XmlConfigurator.Configure(configFile); } } }``` Fix Log4Net path for loading config file
```c# // Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Log4NetIntegration.Logging { using System; using System.IO; using MassTransit.Logging; using log4net; using log4net.Config; public class Log4NetLogger : ILogger { public MassTransit.Logging.ILog Get(string name) { return new Log4NetLog(LogManager.GetLogger(name)); } public static void Use() { Logger.UseLogger(new Log4NetLogger()); } public static void Use(string file) { Logger.UseLogger(new Log4NetLogger()); file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file); var configFile = new FileInfo(file); XmlConfigurator.Configure(configFile); } } }```
b6e27fb4-2695-4636-b600-e443f5b40f42
{ "language": "C#" }
```c# namespace StraightSql { using System; using System.Data.Common; public interface IReader { Object Read(DbDataReader reader); Type Type { get; } } } ``` Sort properties vs. methods; whitespace.
```c# namespace StraightSql { using System; using System.Data.Common; public interface IReader { Type Type { get; } Object Read(DbDataReader reader); } } ```
8d6f0a47-1aaa-48f5-afdf-ac5fc5ec273f
{ "language": "C#" }
```c# public class ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Shane"; public string LastName => "O'Neill"; public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... "; public string StateOrRegion => "Ireland"; public string EmailAddress => string.Empty; public string TwitterHandle => "SOZDBA"; public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510"; public string GitHubHandle => "shaneis"; public GeoPosition Position => new GeoPosition(53.2707, 9.0568); public Uri WebSite => new Uri("https://nocolumnname.blog/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } ``` Add using lines and namespaces
```c# using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Shane"; public string LastName => "O'Neill"; public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... "; public string StateOrRegion => "Ireland"; public string EmailAddress => string.Empty; public string TwitterHandle => "SOZDBA"; public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510"; public string GitHubHandle => "shaneis"; public GeoPosition Position => new GeoPosition(53.2707, 9.0568); public Uri WebSite => new Uri("https://nocolumnname.blog/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } } ```
16a362dc-45d2-452b-b057-a98ec5092306
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; namespace Log4NetlyTesting { class Program { static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var logger = LogManager.GetLogger(typeof(Program)); ////logger.Info("I know he can get the job, but can he do the job?"); ////logger.Debug("I'm not arguing that with you."); ////logger.Warn("Be careful!"); logger.Error("Have you used a computer before?", new FieldAccessException("You can't access this field.", new AggregateException("You can't aggregate this!"))); try { var hi = 1/int.Parse("0"); } catch (Exception ex) { logger.Error("I'm afraid I can't do that.", ex); } ////logger.Fatal("That's it. It's over."); Console.ReadKey(); } } } ``` Add test for new properties feature.
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using log4net.Core; namespace Log4NetlyTesting { class Program { static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var logger = LogManager.GetLogger(typeof(Program)); ////logger.Info("I know he can get the job, but can he do the job?"); ////logger.Debug("I'm not arguing that with you."); ////logger.Warn("Be careful!"); logger.Error("Have you used a computer before?", new FieldAccessException("You can't access this field.", new AggregateException("You can't aggregate this!"))); try { var hi = 1/int.Parse("0"); } catch (Exception ex) { logger.Error("I'm afraid I can't do that.", ex); } var loggingEvent = new LoggingEvent(typeof(LogManager), logger.Logger.Repository, logger.Logger.Name, Level.Fatal, "Fatal properties, here.", new IndexOutOfRangeException()); loggingEvent.Properties["Foo"] = "Bar"; loggingEvent.Properties["Han"] = "Solo"; loggingEvent.Properties["Two Words"] = "Three words here"; logger.Logger.Log(loggingEvent); Console.ReadKey(); } } } ```
b56ef5a6-cad2-4969-935b-d9dc5cba0f20
{ "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.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; if (!string.IsNullOrEmpty(Password)) req.AddParameter("password", Password); return req; } protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}"; } } ``` Fix request failing due to parameters
```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.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; return req; } // Todo: Password needs to be specified here rather than via AddParameter() because this is a PUT request. May be a framework bug. protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}?password={Password}"; } } ```
445e34f9-c781-4c8e-8d9e-401ed4cc1d40
{ "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 System.IO; using System.Reflection; using System.Text; using System.Xml.Linq; using Vipr.Core; namespace Vipr { internal class Program { private static void Main(string[] args) { var bootstrapper = new Bootstrapper(); bootstrapper.Start(args); } } } ``` Enable automatic versioning and Nuget packaging of shippable Vipr binaries
```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 System.IO; namespace Vipr { internal class Program { private static void Main(string[] args) { var bootstrapper = new Bootstrapper(); bootstrapper.Start(args); } } } ```
cf8d844c-608d-4b53-82aa-71b196acb602
{ "language": "C#" }
```c# namespace Sitecore.FakeDb.Data.Engines.DataCommands { using System; using Sitecore.Data.Items; using Sitecore.Diagnostics; public class CreateItemCommand : Sitecore.Data.Engines.DataCommands.CreateItemCommand { private readonly DataStorage dataStorage; public CreateItemCommand(DataStorage dataStorage) { Assert.ArgumentNotNull(dataStorage, "dataStorage"); this.dataStorage = dataStorage; } public DataStorage DataStorage { get { return this.dataStorage; } } protected override Sitecore.Data.Engines.DataCommands.CreateItemCommand CreateInstance() { throw new NotSupportedException(); } protected override Item DoExecute() { var item = new DbItem(this.ItemName, this.ItemId, this.TemplateId) { ParentID = this.Destination.ID }; this.dataStorage.AddFakeItem(item); item.VersionsCount.Clear(); return this.dataStorage.GetSitecoreItem(this.ItemId); } } }``` Use the RemoveVersion method to clean up the unnecessary first version
```c# namespace Sitecore.FakeDb.Data.Engines.DataCommands { using System; using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Globalization; public class CreateItemCommand : Sitecore.Data.Engines.DataCommands.CreateItemCommand { private readonly DataStorage dataStorage; public CreateItemCommand(DataStorage dataStorage) { Assert.ArgumentNotNull(dataStorage, "dataStorage"); this.dataStorage = dataStorage; } public DataStorage DataStorage { get { return this.dataStorage; } } protected override Sitecore.Data.Engines.DataCommands.CreateItemCommand CreateInstance() { throw new NotSupportedException(); } protected override Item DoExecute() { var item = new DbItem(this.ItemName, this.ItemId, this.TemplateId) { ParentID = this.Destination.ID }; this.dataStorage.AddFakeItem(item); item.RemoveVersion(Language.Current.Name); return this.dataStorage.GetSitecoreItem(this.ItemId); } } }```
124ebe2b-2324-4e33-8260-29f9f5f3b32a
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine its playability. /// </summary> public enum ModUsage { /// <summary> /// In a solo gameplay session. /// </summary> User, /// <summary> /// In a multiplayer match, as a required mod. /// </summary> MultiplayerRequired, /// <summary> /// In a multiplayer match, as a "free" mod. /// </summary> MultiplayerFree, } } ``` Reword xmldoc to make more sense
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine whether it's playable in such context. /// </summary> public enum ModUsage { /// <summary> /// Used for a per-user gameplay session. Determines whether the mod is playable by an end user. /// </summary> User, /// <summary> /// Used as a "required mod" for a multiplayer match. /// </summary> MultiplayerRequired, /// <summary> /// Used as a "free mod" for a multiplayer match. /// </summary> MultiplayerFree, } } ```
176ae8d4-2e6c-4fbb-8dd5-744bcbe06ca7
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Net.Http; namespace Refit { public interface IRequestBuilder { IEnumerable<string> InterfaceHttpMethods { get; } Func<object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = ""); Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName); } interface IRequestBuilderFactory { IRequestBuilder Create(Type interfaceType, RefitSettings settings); } public static class RequestBuilder { static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory(); public static IRequestBuilder ForType(Type interfaceType, RefitSettings settings) { return platformRequestBuilderFactory.Create(interfaceType, settings); } public static IRequestBuilder ForType(Type interfaceType) { return platformRequestBuilderFactory.Create(interfaceType, null); } public static IRequestBuilder ForType<T>(RefitSettings settings) { return ForType(typeof(T), settings); } public static IRequestBuilder ForType<T>() { return ForType(typeof(T), null); } } #if PORTABLE class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null) { throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!"); } } #endif } ``` Remove method from interface because it's only useful for testing. Generates incorrect results if not used right
```c# using System; using System.Collections.Generic; using System.Net.Http; namespace Refit { public interface IRequestBuilder { IEnumerable<string> InterfaceHttpMethods { get; } Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName); } interface IRequestBuilderFactory { IRequestBuilder Create(Type interfaceType, RefitSettings settings); } public static class RequestBuilder { static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory(); public static IRequestBuilder ForType(Type interfaceType, RefitSettings settings) { return platformRequestBuilderFactory.Create(interfaceType, settings); } public static IRequestBuilder ForType(Type interfaceType) { return platformRequestBuilderFactory.Create(interfaceType, null); } public static IRequestBuilder ForType<T>(RefitSettings settings) { return ForType(typeof(T), settings); } public static IRequestBuilder ForType<T>() { return ForType(typeof(T), null); } } #if PORTABLE class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null) { throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!"); } } #endif } ```
48c57518-caa6-4962-89d2-4e3c4900aea9
{ "language": "C#" }
```c# using System; using Lucene.Net.Documents; using Orchard.Indexing; namespace Lucene.Models { public class LuceneSearchHit : ISearchHit { private readonly Document _doc; private readonly float _score; public float Score { get { return _score; } } public LuceneSearchHit(Document document, float score) { _doc = document; _score = score; } public int ContentItemId { get { return int.Parse(GetString("id")); } } public int GetInt(string name) { var field = _doc.GetField(name); return field == null ? 0 : Int32.Parse(field.StringValue); } public double GetDouble(string name) { var field = _doc.GetField(name); return field == null ? 0 : double.Parse(field.StringValue); } public bool GetBoolean(string name) { return GetInt(name) > 0; } public string GetString(string name) { var field = _doc.GetField(name); return field == null ? null : field.StringValue; } public DateTime GetDateTime(string name) { var field = _doc.GetField(name); return field == null ? DateTime.MinValue : DateTools.StringToDate(field.StringValue); } } } ``` Fix potential NRE in lucene index
```c# using System; using Lucene.Net.Documents; using Orchard.Indexing; namespace Lucene.Models { public class LuceneSearchHit : ISearchHit { private readonly Document _doc; private readonly float _score; public float Score { get { return _score; } } public LuceneSearchHit(Document document, float score) { _doc = document; _score = score; } public int ContentItemId { get { return GetInt("id"); } } public int GetInt(string name) { var field = _doc.GetField(name); return field == null ? 0 : Int32.Parse(field.StringValue); } public double GetDouble(string name) { var field = _doc.GetField(name); return field == null ? 0 : double.Parse(field.StringValue); } public bool GetBoolean(string name) { return GetInt(name) > 0; } public string GetString(string name) { var field = _doc.GetField(name); return field == null ? null : field.StringValue; } public DateTime GetDateTime(string name) { var field = _doc.GetField(name); return field == null ? DateTime.MinValue : DateTools.StringToDate(field.StringValue); } } } ```
7b56486f-3d0e-44c8-8abd-b4e1a0725ef4
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Taiko.Objects { public class BarLine : TaikoHitObject, IBarLine { public bool Major { get; set; } public override Judgement CreateJudgement() => new IgnoreJudgement(); } } ``` Add backing bindable for major field
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Taiko.Objects { public class BarLine : TaikoHitObject, IBarLine { public bool Major { get => MajorBindable.Value; set => MajorBindable.Value = value; } public readonly Bindable<bool> MajorBindable = new BindableBool(); public override Judgement CreateJudgement() => new IgnoreJudgement(); } } ```
1eca0d63-b7bf-4a6e-b671-89436f2daad6
{ "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.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osuTK; namespace osu.Game.Skinning { public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter { private readonly ISkin skin; public LegacyAccuracyCounter(ISkin skin) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; Scale = new Vector2(0.6f); Margin = new MarginPadding(10); this.skin = skin; } [Resolved(canBeNull: true)] private HUDOverlay hud { get; set; } protected sealed override OsuSpriteText CreateSpriteText() => (OsuSpriteText)skin?.GetDrawableComponent(new HUDSkinComponent(HUDSkinComponents.ScoreText)); protected override void Update() { base.Update(); if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score) { // for now align with the score counter. eventually this will be user customisable. Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y; } } } } ``` Apply same fix to legacy accuracy counter
```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.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osuTK; namespace osu.Game.Skinning { public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter { private readonly ISkin skin; public LegacyAccuracyCounter(ISkin skin) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; Scale = new Vector2(0.6f); Margin = new MarginPadding(10); this.skin = skin; } [Resolved(canBeNull: true)] private HUDOverlay hud { get; set; } protected sealed override OsuSpriteText CreateSpriteText() => (OsuSpriteText)skin?.GetDrawableComponent(new HUDSkinComponent(HUDSkinComponents.ScoreText)) ?.With(s => s.Anchor = s.Origin = Anchor.TopRight); protected override void Update() { base.Update(); if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score) { // for now align with the score counter. eventually this will be user customisable. Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y; } } } } ```
1ef215ee-0c15-4428-9cf2-f31154d2c997
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // Movement speed, can be set in the editor public float speed = 1.0f; // Player (camera) rotation private Vector3 playerRotation = new Vector3 (35, 0, 0); // Player (camera) height private float playerHeight = 5.0f; void Start () { // Setup the player camera Camera camera = gameObject.AddComponent<Camera> (); } void Update () { float horizontalMovement = Input.GetAxis ("Horizontal"); float verticalMovement = Input.GetAxis ("Vertical"); float rotationMovement = 0.0f; // Handle camera rotation if (Input.GetKey (KeyCode.Q)) { rotationMovement = -1.0f; } else if (Input.GetKey (KeyCode.E)) { rotationMovement = 1.0f; } playerRotation.y += rotationMovement * (speed / 2); // Handle movement on the terrain Vector3 movement = new Vector3 (horizontalMovement, 0.0f, verticalMovement); GetComponent<Rigidbody>().velocity = movement * speed; // Keep position with a variable height transform.position = new Vector3 (transform.position.x, playerHeight, transform.position.z); // Set player rotation transform.rotation = Quaternion.Euler (playerRotation); } } ``` Apply velocity based on rotational value
```c# using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // Movement speed, can be set in the editor public float speed = 1.0f; // Player (camera) rotation private Vector3 playerRotation = new Vector3 (35, 0, 0); // Player (camera) height private float playerHeight = 5.0f; void Start () { // Setup the player camera Camera camera = gameObject.AddComponent<Camera> (); // This is probably stupid to do gameObject.tag = "MainCamera"; } void Update () { float horizontalMovement = Input.GetAxis ("Horizontal"); float verticalMovement = Input.GetAxis ("Vertical"); float rotationMovement = 0.0f; // Handle camera rotation if (Input.GetKey (KeyCode.Q)) { rotationMovement = -1.0f; } else if (Input.GetKey (KeyCode.E)) { rotationMovement = 1.0f; } playerRotation.y += rotationMovement * (speed / 2); // Calculate movement velocity Vector3 velocityVertical = transform.forward * speed * verticalMovement; Vector3 velocityHorizontal = transform.right * speed * horizontalMovement; Vector3 calculatedVelocity = velocityHorizontal + velocityVertical; calculatedVelocity.y = 0.0f; // Apply calculated velocity GetComponent<Rigidbody>().velocity = calculatedVelocity; // Keep position with a variable height transform.position = new Vector3 (transform.position.x, playerHeight, transform.position.z); // Set player rotation transform.rotation = Quaternion.Euler (playerRotation); } } ```
9f60f39b-1297-4a2a-b2cf-36fa34afd88f
{ "language": "C#" }
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [Shared] [ExportLspMethod(Methods.InitializeName)] internal class InitializeHandler : IRequestHandler<InitializeParams, InitializeResult> { private static readonly InitializeResult s_initializeResult = new InitializeResult { Capabilities = new ServerCapabilities { DefinitionProvider = true, ImplementationProvider = true, CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new[] { "." } }, SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { "(", "," } }, DocumentSymbolProvider = true, WorkspaceSymbolProvider = true, DocumentFormattingProvider = true, DocumentRangeFormattingProvider = true, DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = "}", MoreTriggerCharacter = new[] { ";", "\n" } }, DocumentHighlightProvider = true, } }; public Task<InitializeResult> HandleRequestAsync(Solution solution, InitializeParams request, ClientCapabilities clientCapabilities, CancellationToken cancellationToken) => Task.FromResult(s_initializeResult); } } ``` Update completion triggers in LSP to better match local completion.
```c# // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [Shared] [ExportLspMethod(Methods.InitializeName)] internal class InitializeHandler : IRequestHandler<InitializeParams, InitializeResult> { private static readonly InitializeResult s_initializeResult = new InitializeResult { Capabilities = new ServerCapabilities { DefinitionProvider = true, ImplementationProvider = true, CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new[] { ".", " ", "#", "<", ">", "\"", ":", "[", "(", "~" } }, SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { "(", "," } }, DocumentSymbolProvider = true, WorkspaceSymbolProvider = true, DocumentFormattingProvider = true, DocumentRangeFormattingProvider = true, DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = "}", MoreTriggerCharacter = new[] { ";", "\n" } }, DocumentHighlightProvider = true, } }; public Task<InitializeResult> HandleRequestAsync(Solution solution, InitializeParams request, ClientCapabilities clientCapabilities, CancellationToken cancellationToken) => Task.FromResult(s_initializeResult); } } ```
f8e458aa-c329-456b-99db-0e0ead106de7
{ "language": "C#" }
```c# using System.Linq; using Xunit; namespace Bugsnag.Tests { public class BreadcrumbsTests { [Fact] public void RestrictsMaxNumberOfBreadcrumbs() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 30; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(25, breadcrumbs.Retrieve().Count()); } [Fact] public void WhenRetrievingBreadcrumbsCorrectNumberIsReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(10, breadcrumbs.Retrieve().Count()); } [Fact] public void CorrectBreadcrumbsAreReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 5 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } var breadcrumbNames = breadcrumbs.Retrieve().Select(b => b.Name); Assert.Equal(new string[] { "5", "6", "7", "8", "9" }, breadcrumbNames); } } } ``` Update test to check that breadcrumbs are returned in correct order when MaximumBreadcrumbs is exceeded
```c# using System.Linq; using Xunit; namespace Bugsnag.Tests { public class BreadcrumbsTests { [Fact] public void RestrictsMaxNumberOfBreadcrumbs() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 30; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(25, breadcrumbs.Retrieve().Count()); } [Fact] public void WhenRetrievingBreadcrumbsCorrectNumberIsReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(10, breadcrumbs.Retrieve().Count()); } [Fact] public void CorrectBreadcrumbsAreReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 5 }); for (int i = 0; i < 6; i++) { breadcrumbs.Leave($"{i}"); } var breadcrumbNames = breadcrumbs.Retrieve().Select(b => b.Name); Assert.Equal(new string[] { "1", "2", "3", "4", "5" }, breadcrumbNames); } } } ```
5a7b847e-4560-40dc-845f-bfc6c9494452
{ "language": "C#" }
```c# using ManagedBass; using System; using System.Diagnostics; using System.Resources; namespace BrewLib.Audio { public class AudioSample { private const int MaxSimultaneousPlayBacks = 8; private string path; public string Path => path; private int sample; public readonly AudioManager Manager; internal AudioSample(AudioManager audioManager, string path, ResourceManager resourceManager) { Manager = audioManager; this.path = path; sample = Bass.SampleLoad(path, 0, 0, MaxSimultaneousPlayBacks, BassFlags.Default); if (sample == 0) { Trace.WriteLine($"Failed to load audio sample ({path}): {Bass.LastError}"); return; } } public void Play(float volume = 1) { if (sample == 0) return; var channel = new AudioChannel(Manager, Bass.SampleGetChannel(sample), true) { Volume = volume, }; Manager.RegisterChannel(channel); channel.Playing = true; } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { } if (sample != 0) { Bass.SampleFree(sample); sample = 0; } disposedValue = true; } } ~AudioSample() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } } ``` Use SampleOverrideLongestPlaying for audio samples.
```c# using ManagedBass; using System; using System.Diagnostics; using System.Resources; namespace BrewLib.Audio { public class AudioSample { private const int MaxSimultaneousPlayBacks = 8; private string path; public string Path => path; private int sample; public readonly AudioManager Manager; internal AudioSample(AudioManager audioManager, string path, ResourceManager resourceManager) { Manager = audioManager; this.path = path; sample = Bass.SampleLoad(path, 0, 0, MaxSimultaneousPlayBacks, BassFlags.SampleOverrideLongestPlaying); if (sample == 0) { Trace.WriteLine($"Failed to load audio sample ({path}): {Bass.LastError}"); return; } } public void Play(float volume = 1) { if (sample == 0) return; var channel = new AudioChannel(Manager, Bass.SampleGetChannel(sample), true) { Volume = volume, }; Manager.RegisterChannel(channel); channel.Playing = true; } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { } if (sample != 0) { Bass.SampleFree(sample); sample = 0; } disposedValue = true; } } ~AudioSample() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } } ```
cf566b0d-319b-4862-bde2-1d54e85f6710
{ "language": "C#" }
```c# using System.Text; namespace SnippetsToMarkdown.Commands { class WriteHeaderHtmlCommand : ICommand { private string directory; public WriteHeaderHtmlCommand(string directory) { this.directory = directory; } public void WriteToOutput(StringBuilder output) { output.AppendLine("<h3>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h3>"); output.AppendLine("<br />"); output.AppendLine("<table>"); output.AppendLine("<thead>"); output.AppendLine("<tr>"); output.AppendLine("<td>Shortcut</td>"); output.AppendLine("<td>Name</td>"); output.AppendLine("</tr>"); output.AppendLine("</thead>"); output.AppendLine("<tbody>"); } } } ``` Change header size in HTML generation.
```c# using System.Text; namespace SnippetsToMarkdown.Commands { class WriteHeaderHtmlCommand : ICommand { private string directory; public WriteHeaderHtmlCommand(string directory) { this.directory = directory; } public void WriteToOutput(StringBuilder output) { output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>"); output.AppendLine("<br />"); output.AppendLine("<table>"); output.AppendLine("<thead>"); output.AppendLine("<tr>"); output.AppendLine("<td>Shortcut</td>"); output.AppendLine("<td>Name</td>"); output.AppendLine("</tr>"); output.AppendLine("</thead>"); output.AppendLine("<tbody>"); } } } ```
053f9ca5-dc22-467b-81fe-af6ca08e5526
{ "language": "C#" }
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using JSNLog.Infrastructure; namespace JSNLog { internal class JSNlogLogger : IJSNLogLogger { private ILoggerFactory _loggerFactory; public JSNlogLogger(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public void Log(FinalLogData finalLogData) { ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger); Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage); switch (finalLogData.FinalLevel) { case Level.TRACE: logger.LogDebug("{logMessage}", message); break; case Level.DEBUG: logger.LogVerbose("{logMessage}", message); break; case Level.INFO: logger.LogInformation("{logMessage}", message); break; case Level.WARN: logger.LogWarning("{logMessage}", message); break; case Level.ERROR: logger.LogError("{logMessage}", message); break; case Level.FATAL: logger.LogCritical("{logMessage}", message); break; } } } } ``` Make JSNLogLogger available to the outside world, so it can actually be used in ASP.NET 5 apps
```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using JSNLog.Infrastructure; namespace JSNLog { public class JSNlogLogger : IJSNLogLogger { private ILoggerFactory _loggerFactory; public JSNlogLogger(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public void Log(FinalLogData finalLogData) { ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger); Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage); switch (finalLogData.FinalLevel) { case Level.TRACE: logger.LogDebug("{logMessage}", message); break; case Level.DEBUG: logger.LogVerbose("{logMessage}", message); break; case Level.INFO: logger.LogInformation("{logMessage}", message); break; case Level.WARN: logger.LogWarning("{logMessage}", message); break; case Level.ERROR: logger.LogError("{logMessage}", message); break; case Level.FATAL: logger.LogCritical("{logMessage}", message); break; } } } } ```
7209c04d-0816-4f14-8e51-562c771465dc
{ "language": "C#" }
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Modes.Objects.Types { /// <summary> /// A HitObject that has a distance. /// </summary> public interface IHasDistance : IHasEndTime { /// <summary> /// The distance of the HitObject. /// </summary> double Distance { get; } } } ``` Fix up distance -> positional length comments.
```c# // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Modes.Objects.Types { /// <summary> /// A HitObject that has a positional length. /// </summary> public interface IHasDistance : IHasEndTime { /// <summary> /// The positional length of the HitObject. /// </summary> double Distance { get; } } } ```
fff1374e-3543-452b-9a60-55294a68881c
{ "language": "C#" }
```c#  namespace Nvelope { public enum Month { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12 } } ``` Document and suppress an FxCop warning
```c# //----------------------------------------------------------------------- // <copyright file="Month.cs" company="TWU"> // MIT Licenced // </copyright> //----------------------------------------------------------------------- namespace Nvelope { using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents a month of the year /// </summary> [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "There's no such thing as a 'default' or 'none' month.")] public enum Month { /* These doc comments are stupid, but it keeps FxCop from getting made * and it by looking at Microsoft's docs it seems to be in line with * their practices */ /// <summary> /// Indicates January /// </summary> January = 1, /// <summary> /// Indicates February /// </summary> February = 2, /// <summary> /// Indicates January /// </summary> March = 3, /// <summary> /// Indicates April /// </summary> April = 4, /// <summary> /// Indicates January /// </summary> May = 5, /// <summary> /// Indicates June /// </summary> June = 6, /// <summary> /// Indicates July /// </summary> July = 7, /// <summary> /// Indicates August /// </summary> August = 8, /// <summary> /// Indicates September /// </summary> September = 9, /// <summary> /// Indicates October /// </summary> October = 10, /// <summary> /// Indicates November /// </summary> November = 11, /// <summary> /// Indicates December /// </summary> December = 12 } } ```
7e0dba35-1f27-4fdb-a267-6f2e72e36d78
{ "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. namespace Microsoft.Azure.Devices.Client { public enum AuthenticationScheme { // Shared Access Signature SAS = 0, // X509 Certificate X509 = 1 } } ``` Add XML description for Authentication Scheme
```c# // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Client { /// <summary> /// Specifies the Authentication Scheme used by Device Client /// </summary> public enum S { // Shared Access Signature SAS = 0, // X509 Certificate X509 = 1 } } ```
fa6f9252-e18a-4d3f-98bb-79b76f819719
{ "language": "C#" }
```c# using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public float baseFireCooldown; public float baseRotationSpeed; public God god; // public Weapon weapon; public Vector2 direction; // Maybe this should be private? public Vector2 targetDirection; // This too. // Temporary public GameObject tempProjectile; private float cooldownTimeStamp; // Use this for initialization void Start () { } public void Move(float horizontal, float vertical) { targetDirection = new Vector2 (horizontal, vertical); } public void Fire () { // Don't fire when the cooldown is still active. if (this.cooldownTimeStamp >= Time.time) { return; } // Fire the weapon. // TODO Moveable arrowMoveable = Instantiate(tempProjectile).GetComponent<Moveable> (); arrowMoveable.direction = this.direction; // Set the cooldown. this.cooldownTimeStamp = Time.time + this.baseFireCooldown; } // Update is called once per frame void Update () { float angle = Vector2.Angle (direction, targetDirection); this.transform.Rotate (targetDirection.x, angle * baseRotationSpeed * Time.deltaTime); this.direction = new Vector2 (this.transform.TransformDirection.x, this.transform.TransformDirection.y); } } ``` Add playerID and revisit the moving.
```c# using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public int playerID; public float baseFireCooldown; public float baseRotationSpeed; public God god; // public Weapon weapon; public Vector2 direction; // Maybe this should be private? public Vector2 targetDirection; // This too. // Temporary public GameObject tempProjectile; private float cooldownTimeStamp; // Use this for initialization void Start () { } public void Move(float horizontal, float vertical) { targetDirection = new Vector2 (horizontal, vertical); } public void Fire () { // Don't fire when the cooldown is still active. if (this.cooldownTimeStamp >= Time.time) { return; } // Fire the weapon. // TODO Moveable arrowMoveable = Instantiate(tempProjectile).GetComponent<Moveable> (); arrowMoveable.direction = this.direction; // Set the cooldown. this.cooldownTimeStamp = Time.time + this.baseFireCooldown; } // Update is called once per frame void Update () { float angle = Vector2.Angle (direction, targetDirection); // this.transform.Rotate (targetDirection.x, angle * baseRotationSpeed * Time.deltaTime); this.direction = new Vector2 (this.transform.TransformDirection.x , this.transform.TransformDirection.y); } } ```
a2eff0e1-f08f-44c7-bdbe-22a3033e90ba
{ "language": "C#" }
```c# using System.Diagnostics; using System.Windows.Controls; using System.Windows.Input; using Junctionizer.Model; namespace Junctionizer.UI.Styles { public partial class DataGridStyles { private void DataGridRow_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton != MouseButton.Left) return; var dataGridRow = sender as DataGridRow; if (dataGridRow?.Item is GameFolder folder) { OpenInFileExplorer(folder); } else if (dataGridRow?.Item is GameFolderPair pair) { if (pair.SourceEntry?.IsJunction == false) OpenInFileExplorer(pair.SourceEntry); if (pair.DestinationEntry?.IsJunction == false) OpenInFileExplorer(pair.DestinationEntry); } } private static void OpenInFileExplorer(GameFolder folder) { var path = folder.DirectoryInfo.FullName; ErrorHandling.ThrowIfDirectoryNotFound(path); Process.Start(path); } } } ``` Allow double click to open on junctions when lacking a destination
```c# using System.Diagnostics; using System.Windows.Controls; using System.Windows.Input; using Junctionizer.Model; namespace Junctionizer.UI.Styles { public partial class DataGridStyles { private void DataGridRow_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton != MouseButton.Left) return; var dataGridRow = sender as DataGridRow; if (dataGridRow?.Item is GameFolder folder) { OpenInFileExplorer(folder); } else if (dataGridRow?.Item is GameFolderPair pair) { if (pair.DestinationEntry == null || pair.SourceEntry?.IsJunction == false) OpenInFileExplorer(pair.SourceEntry); if (pair.DestinationEntry != null) OpenInFileExplorer(pair.DestinationEntry); } } private static void OpenInFileExplorer(GameFolder folder) { var path = folder.DirectoryInfo.FullName; ErrorHandling.ThrowIfDirectoryNotFound(path); Process.Start(path); } } } ```
fe15f172-5f31-4d3c-96e5-0b8e170dcf88
{ "language": "C#" }
```c# //------------------------------------------------------------------------------ // <copyright file="StackAnalysisToolWindow.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace StackUsageAnalyzer { using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; /// <summary> /// This class implements the tool window exposed by this package and hosts a user control. /// </summary> /// <remarks> /// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane, /// usually implemented by the package implementer. /// <para> /// This class derives from the ToolWindowPane class provided from the MPF in order to use its /// implementation of the IVsUIElementPane interface. /// </para> /// </remarks> [Guid("ffbd67c0-1100-4fa5-8c20-cc10264c540b")] public class StackAnalysisToolWindow : ToolWindowPane { /// <summary> /// Initializes a new instance of the <see cref="StackAnalysisToolWindow"/> class. /// </summary> public StackAnalysisToolWindow() : base(null) { this.Caption = "StackAnalysisToolWindow"; // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. this.Content = new StackAnalysisToolWindowControl(); } } } ``` Change caption of Tool Window
```c# //------------------------------------------------------------------------------ // <copyright file="StackAnalysisToolWindow.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace StackUsageAnalyzer { using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; /// <summary> /// This class implements the tool window exposed by this package and hosts a user control. /// </summary> /// <remarks> /// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane, /// usually implemented by the package implementer. /// <para> /// This class derives from the ToolWindowPane class provided from the MPF in order to use its /// implementation of the IVsUIElementPane interface. /// </para> /// </remarks> [Guid("ffbd67c0-1100-4fa5-8c20-cc10264c540b")] public class StackAnalysisToolWindow : ToolWindowPane { /// <summary> /// Initializes a new instance of the <see cref="StackAnalysisToolWindow"/> class. /// </summary> public StackAnalysisToolWindow() : base(null) { this.Caption = "Function Stack Analysis"; // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. this.Content = new StackAnalysisToolWindowControl(); } } } ```
9474ee50-5505-44b8-97db-db146b7dbd85
{ "language": "C#" }
```c# using NLog; namespace Wox.Infrastructure.Logger { public class Log { private static NLog.Logger logger = LogManager.GetCurrentClassLogger(); public static void Error(System.Exception e) { #if DEBUG throw e; #else while (e.InnerException != null) { logger.Error(e.Message); logger.Error(e.StackTrace); e = e.InnerException; } #endif } public static void Debug(string msg) { System.Diagnostics.Debug.WriteLine($"DEBUG: {msg}"); logger.Debug(msg); } public static void Info(string msg) { System.Diagnostics.Debug.WriteLine($"INFO: {msg}"); logger.Info(msg); } public static void Warn(string msg) { System.Diagnostics.Debug.WriteLine($"WARN: {msg}"); logger.Warn(msg); } public static void Fatal(System.Exception e) { #if DEBUG throw e; #else logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); #endif } } } ``` Fix using for Release build
```c# using NLog; using Wox.Infrastructure.Exception; namespace Wox.Infrastructure.Logger { public class Log { private static NLog.Logger logger = LogManager.GetCurrentClassLogger(); public static void Error(System.Exception e) { #if DEBUG throw e; #else while (e.InnerException != null) { logger.Error(e.Message); logger.Error(e.StackTrace); e = e.InnerException; } #endif } public static void Debug(string msg) { System.Diagnostics.Debug.WriteLine($"DEBUG: {msg}"); logger.Debug(msg); } public static void Info(string msg) { System.Diagnostics.Debug.WriteLine($"INFO: {msg}"); logger.Info(msg); } public static void Warn(string msg) { System.Diagnostics.Debug.WriteLine($"WARN: {msg}"); logger.Warn(msg); } public static void Fatal(System.Exception e) { #if DEBUG throw e; #else logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); #endif } } } ```
8e164b06-cb7a-4dbb-8fa9-07c4d9d3ce0d
{ "language": "C#" }
```c# // Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; namespace SmugMugCodeGen { public class Options { public string OutputDir { get; private set; } public string OutputDirEnums { get; private set; } public string[] InputFiles { get; private set; } public Options(string[] args) { OutputDir = args[0]; OutputDirEnums = Path.Combine(OutputDir, "Enums"); // Copy the input files from the args array. InputFiles = new string[args.Length - 1]; Array.Copy(args, 1, InputFiles, 0, args.Length - 1); } } } ``` Change the location of where the Enums are generated to be at the same level as the types.
```c# // Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; namespace SmugMugCodeGen { public class Options { public string OutputDir { get; private set; } public string OutputDirEnums { get; private set; } public string[] InputFiles { get; private set; } public Options(string[] args) { OutputDir = args[0]; OutputDirEnums = Path.Combine(OutputDir, @"\..\Enums"); // Copy the input files from the args array. InputFiles = new string[args.Length - 1]; Array.Copy(args, 1, InputFiles, 0, args.Length - 1); } } } ```
2dee8fd7-8fc3-47e3-b004-b78a0b612525
{ "language": "C#" }
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Samples.AspNetCore { public class Startup { public Startup(IConfiguration configuration, IHostingEnvironment env) { Configuration = configuration; HostingEnvironment = env; } public IConfiguration Configuration { get; } public IHostingEnvironment HostingEnvironment { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Make IOptions<ExceptionalSettings> available for injection everywhere services.AddExceptional(Configuration.GetSection("Exceptional"), settings => { //settings.ApplicationName = "Samples.AspNetCore"; settings.UseExceptionalPageOnThrow = HostingEnvironment.IsDevelopment(); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { // Boilerplate we're no longer using with Exceptional //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); // app.UseBrowserLink(); //} //else //{ // app.UseExceptionHandler("/Home/Error"); //} app.UseExceptional(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }``` Update ASP.NET Core sample code to match actual
```c# using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Samples.AspNetCore { public class Startup { public Startup(IConfiguration configuration, IHostingEnvironment env) { Configuration = configuration; HostingEnvironment = env; } public IConfiguration Configuration { get; } public IHostingEnvironment HostingEnvironment { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Make IOptions<ExceptionalSettings> available for injection everywhere services.AddExceptional(Configuration.GetSection("Exceptional"), settings => { //settings.DefaultStore.ApplicationName = "Samples.AspNetCore"; settings.UseExceptionalPageOnThrow = HostingEnvironment.IsDevelopment(); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { // Boilerplate we're no longer using with Exceptional //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); // app.UseBrowserLink(); //} //else //{ // app.UseExceptionHandler("/Home/Error"); //} app.UseExceptional(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } } ```
b2ec0d0a-bd92-4eea-9170-9bdfc373ba50
{ "language": "C#" }
```c# using System; using System.Collections; using UnityEngine; using System.Threading; using UnityEngine.Networking; namespace GLTF { class GLTFComponent : MonoBehaviour { public string Url; public Shader Shader; public bool Multithreaded = true; IEnumerator Start() { var loader = new GLTFLoader(Url, Shader, gameObject.transform); loader.Multithreaded = Multithreaded; yield return loader.Load(); IntegrationTest.Pass(); } } } ``` Remove stray integration test call.
```c# using System; using System.Collections; using UnityEngine; using System.Threading; using UnityEngine.Networking; namespace GLTF { class GLTFComponent : MonoBehaviour { public string Url; public Shader Shader; public bool Multithreaded = true; IEnumerator Start() { var loader = new GLTFLoader(Url, Shader, gameObject.transform); loader.Multithreaded = Multithreaded; yield return loader.Load(); } } } ```
637f712e-43ee-4460-8f4e-096d0ecb3959
{ "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 Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Session; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding session services to the DI container. /// </summary> public static class SessionServiceCollectionExtensions { /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> public static void AddSession(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddTransient<ISessionStore, DistributedSessionStore>(); } /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <param name="configure">The session options to configure the middleware with.</param> public static void AddSession(this IServiceCollection services, Action<SessionOptions> configure) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } services.Configure(configure); services.AddSession(); } } }``` Return IServiceCollection from AddSession extension methods
```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 Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Session; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding session services to the DI container. /// </summary> public static class SessionServiceCollectionExtensions { /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddTransient<ISessionStore, DistributedSessionStore>(); return services; } /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <param name="configure">The session options to configure the middleware with.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services, Action<SessionOptions> configure) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } services.Configure(configure); services.AddSession(); return services; } } }```
ba98a2f8-3e55-4f1c-b633-912b1abf7366
{ "language": "C#" }
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.Chat { public enum ChannelType { Public, Private, Multiplayer, Spectator, Temporary, PM, Group, System, } } ``` Add missing "announce" channel type
```c# // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.Chat { public enum ChannelType { Public, Private, Multiplayer, Spectator, Temporary, PM, Group, System, Announce, } } ```
5bb18297-7b8e-4446-b23a-2d4fa1f43487
{ "language": "C#" }
```c# using System; using Microsoft.Extensions.Logging; namespace Gibraltar.Agent { /// <summary> /// This enumerates the severity levels used by Loupe log messages. /// </summary> /// <remarks>The values for these levels are chosen to directly map to the TraceEventType enum /// for the five levels we support. These also can be mapped from Log4Net event levels, /// with slight name changes for Fatal->Critical and for Debug->Verbose.</remarks> [Flags] public enum LogMessageSeverity { /// <summary> /// The severity level is uninitialized and thus unknown. /// </summary> None = 0, // FxCop demands we have a defined 0. /// <summary> /// Fatal error or application crash. /// </summary> Critical = LogLevel.Critical, /// <summary> /// Recoverable error. /// </summary> Error = LogLevel.Error, /// <summary> /// Noncritical problem. /// </summary> Warning = LogLevel.Warning, /// <summary> /// Informational message. /// </summary> Information = LogLevel.Information, /// <summary> /// Debugging trace. /// </summary> Verbose = LogLevel.Debug, } } ``` Correct second copy of severity mappings to be compatible with Loupe.
```c# using System; using Microsoft.Extensions.Logging; namespace Gibraltar.Agent { /// <summary> /// This enumerates the severity levels used by Loupe log messages. /// </summary> /// <remarks>The values for these levels are chosen to directly map to the TraceEventType enum /// for the five levels we support. These also can be mapped from Log4Net event levels, /// with slight name changes for Fatal->Critical and for Debug->Verbose.</remarks> [Flags] public enum LogMessageSeverity { /// <summary> /// The severity level is uninitialized and thus unknown. /// </summary> None = 0, // FxCop demands we have a defined 0. /// <summary> /// Fatal error or application crash. /// </summary> Critical = Loupe.Extensibility.Data.LogMessageSeverity.Critical, /// <summary> /// Recoverable error. /// </summary> Error = Loupe.Extensibility.Data.LogMessageSeverity.Error, /// <summary> /// Noncritical problem. /// </summary> Warning = Loupe.Extensibility.Data.LogMessageSeverity.Warning, /// <summary> /// Informational message. /// </summary> Information = Loupe.Extensibility.Data.LogMessageSeverity.Information, /// <summary> /// Debugging trace. /// </summary> Verbose = Loupe.Extensibility.Data.LogMessageSeverity.Verbose, } } ```
4efec803-f985-4ba8-a191-4419c8faa399
{ "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.Threading; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osuTK; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneSynchronizationContext : FrameworkTestScene { private AsyncPerformingBox box; [Test] public void TestAsyncPerformingBox() { AddStep("add box", () => Child = box = new AsyncPerformingBox()); AddAssert("not spun", () => box.Rotation == 0); AddStep("trigger", () => box.Trigger()); AddUntilStep("has spun", () => box.Rotation == 180); } public class AsyncPerformingBox : Box { private readonly SemaphoreSlim waiter = new SemaphoreSlim(0); public AsyncPerformingBox() { Size = new Vector2(100); Anchor = Anchor.Centre; Origin = Anchor.Centre; } protected override async void LoadComplete() { base.LoadComplete(); await waiter.WaitAsync().ConfigureAwait(true); this.RotateTo(180, 500); } public void Trigger() { waiter.Release(); } } } } ``` Add test of scheduler usage
```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.Threading; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osuTK; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneSynchronizationContext : FrameworkTestScene { private AsyncPerformingBox box; [Test] public void TestAsyncPerformingBox() { AddStep("add box", () => Child = box = new AsyncPerformingBox()); AddAssert("not spun", () => box.Rotation == 0); AddStep("trigger", () => box.Trigger()); AddUntilStep("has spun", () => box.Rotation == 180); } [Test] public void TestUsingLocalScheduler() { AddStep("add box", () => Child = box = new AsyncPerformingBox()); AddAssert("scheduler null", () => box.Scheduler == null); AddStep("trigger", () => box.Trigger()); AddUntilStep("scheduler non-null", () => box.Scheduler != null); } public class AsyncPerformingBox : Box { private readonly SemaphoreSlim waiter = new SemaphoreSlim(0); public AsyncPerformingBox() { Size = new Vector2(100); Anchor = Anchor.Centre; Origin = Anchor.Centre; } protected override async void LoadComplete() { base.LoadComplete(); await waiter.WaitAsync().ConfigureAwait(true); this.RotateTo(180, 500); } public void Trigger() { waiter.Release(); } } } } ```
1b96c544-76cb-4328-a41d-5830312792b3
{ "language": "C#" }
```c# using System; namespace Eluant { public static class LuaValueExtensions { public static bool IsNil(this LuaValue self) { return self == null || self == LuaNil.Instance; } } } ``` Add EnumerateArray() extension for tables
```c# using System; using System.Collections.Generic; namespace Eluant { public static class LuaValueExtensions { public static bool IsNil(this LuaValue self) { return self == null || self == LuaNil.Instance; } public static IEnumerable<LuaValue> EnumerateArray(this LuaTable self) { if (self == null) { throw new ArgumentNullException("self"); } return CreateEnumerateArrayEnumerable(self); } private static IEnumerable<LuaValue> CreateEnumerateArrayEnumerable(LuaTable self) { // By convention, the 'n' field refers to the array length, if present. using (var n = self["n"]) { var num = n as LuaNumber; if (num != null) { var length = (int)num.Value; for (int i = 1; i <= length; ++i) { yield return self[i]; } yield break; } } // If no 'n' then stop at the first nil element. for (int i = 1; ; ++i) { var value = self[i]; if (value.IsNil()) { yield break; } yield return value; } } } } ```
78885f12-dc99-4993-9546-bf00dded8cde
{ "language": "C#" }
```c# using Mapsui.Fetcher; using Mapsui.Geometries; using Mapsui.Providers; using System.Collections.Generic; using System.Threading.Tasks; using Mapsui.Styles; namespace Mapsui.Layers { public class MemoryLayer : BaseLayer { public IProvider DataSource { get; set; } public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution) { var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution); return DataSource.GetFeaturesInView(biggerBox, resolution); } public override BoundingBox Envelope => DataSource?.GetExtents(); public override void AbortFetch() { // do nothing. This is not an async layer } public override void ViewChanged(bool majorChange, BoundingBox extent, double resolution) { //The MemoryLayer always has it's data ready so can fire a DataChanged event immediately so that listeners can act on it. Task.Run(() => OnDataChanged(new DataChangedEventArgs())); } public override void ClearCache() { // do nothing. This is not an async layer } } } ``` Fix NullException ocurring in GetFeaturesInView() when BoundingBox is null
```c# using Mapsui.Fetcher; using Mapsui.Geometries; using Mapsui.Providers; using System.Collections.Generic; using System.Threading.Tasks; using Mapsui.Styles; namespace Mapsui.Layers { public class MemoryLayer : BaseLayer { public IProvider DataSource { get; set; } public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution) { // Safeguard in case BoundingBox is null, most likely due to no features in layer if (box == null) { return new List<IFeature>(); } var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution); return DataSource.GetFeaturesInView(biggerBox, resolution); } public override BoundingBox Envelope => DataSource?.GetExtents(); public override void AbortFetch() { // do nothing. This is not an async layer } public override void ViewChanged(bool majorChange, BoundingBox extent, double resolution) { //The MemoryLayer always has it's data ready so can fire a DataChanged event immediately so that listeners can act on it. Task.Run(() => OnDataChanged(new DataChangedEventArgs())); } public override void ClearCache() { // do nothing. This is not an async layer } } } ```
7b1f296d-6b7a-4a2c-a337-6cd0102abc0e
{ "language": "C#" }
```c# using Advanced_Combat_Tracker; using CefSharp; using CefSharp.Wpf; using System; using System.Windows.Forms; namespace Cactbot { public class ACTPlugin : IActPluginV1 { SettingsTab settingsTab = new SettingsTab(); BrowserWindow browserWindow; #region IActPluginV1 Members public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText) { settingsTab.Initialize(pluginStatusText); browserWindow = new BrowserWindow(); browserWindow.ShowInTaskbar = false; browserWindow.BrowserControl.CreationHandlers += OnBrowserCreated; browserWindow.Show(); pluginScreenSpace.Controls.Add(settingsTab); } public void DeInitPlugin() { browserWindow.Hide(); settingsTab.Shutdown(); // FIXME: This needs to be called from the right thread, so it can't happen automatically. // However, calling it here means the plugin can never be reinitialized, oops. Cef.Shutdown(); } #endregion private void OnBrowserCreated(object sender, IWpfWebBrowser browser) { browser.RegisterJsObject("act", new BrowserBindings()); // FIXME: Make it possible to create more than one window. // Tie loading html to the browser window creation and bindings to the // browser creation. browser.Load(settingsTab.HTMLFile()); browser.ShowDevTools(); } } } ``` Allow cactbot to be restarted
```c# using Advanced_Combat_Tracker; using CefSharp; using CefSharp.Wpf; using System; using System.Windows.Forms; namespace Cactbot { public class ACTPlugin : IActPluginV1 { SettingsTab settingsTab = new SettingsTab(); BrowserWindow browserWindow; #region IActPluginV1 Members public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText) { settingsTab.Initialize(pluginStatusText); browserWindow = new BrowserWindow(); browserWindow.ShowInTaskbar = false; browserWindow.BrowserControl.CreationHandlers += OnBrowserCreated; browserWindow.Show(); pluginScreenSpace.Controls.Add(settingsTab); Application.ApplicationExit += OnACTShutdown; } public void DeInitPlugin() { browserWindow.Hide(); settingsTab.Shutdown(); } #endregion private void OnBrowserCreated(object sender, IWpfWebBrowser browser) { browser.RegisterJsObject("act", new BrowserBindings()); // FIXME: Make it possible to create more than one window. // Tie loading html to the browser window creation and bindings to the // browser creation. browser.Load(settingsTab.HTMLFile()); browser.ShowDevTools(); } private void OnACTShutdown(object sender, EventArgs args) { // Cef has to be manually shutdown on this thread, but can only be // shutdown once. Cef.Shutdown(); } } } ```
3529e80f-eeee-4b65-ba0e-6402fca05bed
{ "language": "C#" }
```c# using System; using System.Threading.Tasks; using Carrot.Configuration; using Carrot.Extensions; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Carrot.Messages { public abstract class ConsumedMessageBase { protected readonly BasicDeliverEventArgs Args; protected ConsumedMessageBase(BasicDeliverEventArgs args) { Args = args; } internal abstract Object Content { get; } internal abstract Task<AggregateConsumingResult> ConsumeAsync(SubscriptionConfiguration configuration); internal ConsumedMessage<TMessage> As<TMessage>() where TMessage : class { var content = Content as TMessage; if (content == null) throw new InvalidCastException(String.Format("cannot cast '{0}' to '{1}'", Content.GetType(), typeof(TMessage))); return new ConsumedMessage<TMessage>(content, HeaderCollection.Parse(Args)); } internal abstract Boolean Match(Type type); internal void Acknowledge(IModel model) { model.BasicAck(Args.DeliveryTag, false); } internal void Requeue(IModel model) { model.BasicNack(Args.DeliveryTag, false, true); } internal void ForwardTo(IModel model, Func<String, String> exchangeNameBuilder) { var exchange = Exchange.DurableDirect(exchangeNameBuilder(Args.Exchange)); exchange.Declare(model); var properties = Args.BasicProperties.Copy(); properties.Persistent = true; model.BasicPublish(exchange.Name, String.Empty, properties, Args.Body); } } }``` Use new API to build durable Exchange
```c# using System; using System.Threading.Tasks; using Carrot.Configuration; using Carrot.Extensions; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Carrot.Messages { public abstract class ConsumedMessageBase { protected readonly BasicDeliverEventArgs Args; protected ConsumedMessageBase(BasicDeliverEventArgs args) { Args = args; } internal abstract Object Content { get; } internal abstract Task<AggregateConsumingResult> ConsumeAsync(SubscriptionConfiguration configuration); internal ConsumedMessage<TMessage> As<TMessage>() where TMessage : class { var content = Content as TMessage; if (content == null) throw new InvalidCastException(String.Format("cannot cast '{0}' to '{1}'", Content.GetType(), typeof(TMessage))); return new ConsumedMessage<TMessage>(content, HeaderCollection.Parse(Args)); } internal abstract Boolean Match(Type type); internal void Acknowledge(IModel model) { model.BasicAck(Args.DeliveryTag, false); } internal void Requeue(IModel model) { model.BasicNack(Args.DeliveryTag, false, true); } internal void ForwardTo(IModel model, Func<String, String> exchangeNameBuilder) { var exchange = Exchange.Direct(exchangeNameBuilder(Args.Exchange)).Durable(); exchange.Declare(model); var properties = Args.BasicProperties.Copy(); properties.Persistent = true; model.BasicPublish(exchange.Name, String.Empty, properties, Args.Body); } } }```
25f9b615-6377-49c6-bc76-6a33340eb43b
{ "language": "C#" }
```c# using UnityEngine; using UnityEditor; using System; using System.Collections; namespace mLogger { public class LoggerWindow : EditorWindow { private Logger loggerInstance; public Logger LoggerInstance { get { if (loggerInstance == null) { loggerInstance = FindObjectOfType<Logger>(); if (loggerInstance == null) { GameObject loggerGO = new GameObject(); loggerGO.AddComponent<Logger>(); loggerInstance = loggerGO.GetComponent<Logger>(); } } return loggerInstance; } } [MenuItem("Debug/Logger")] public static void Init() { LoggerWindow window = (LoggerWindow)EditorWindow.GetWindow(typeof(LoggerWindow)); window.title = "Logger"; window.minSize = new Vector2(100f, 60f); } private void OnGUI() { EditorGUILayout.BeginHorizontal(); // Draw Start/Stop button. LoggerInstance.LoggingEnabled = InspectorControls.DrawStartStopButton( LoggerInstance.LoggingEnabled, LoggerInstance.EnableOnPlay, null, () => LoggerInstance.LogWriter.Add("[PAUSE]", true), () => LoggerInstance.LogWriter.WriteAll( LoggerInstance.FilePath, false)); // Draw -> button. if (GUILayout.Button("->", GUILayout.Width(30))) { EditorGUIUtility.PingObject(LoggerInstance); Selection.activeGameObject = LoggerInstance.gameObject; } EditorGUILayout.EndHorizontal(); Repaint(); } } } ``` Add mLogger to Unity Window menu
```c# using UnityEngine; using UnityEditor; using System; using System.Collections; namespace mLogger { public class LoggerWindow : EditorWindow { private Logger loggerInstance; public Logger LoggerInstance { get { if (loggerInstance == null) { loggerInstance = FindObjectOfType<Logger>(); if (loggerInstance == null) { GameObject loggerGO = new GameObject(); loggerGO.AddComponent<Logger>(); loggerInstance = loggerGO.GetComponent<Logger>(); } } return loggerInstance; } } [MenuItem("Window/mLogger")] public static void Init() { LoggerWindow window = (LoggerWindow)EditorWindow.GetWindow(typeof(LoggerWindow)); window.title = "Logger"; window.minSize = new Vector2(100f, 60f); } private void OnGUI() { EditorGUILayout.BeginHorizontal(); // Draw Start/Stop button. LoggerInstance.LoggingEnabled = InspectorControls.DrawStartStopButton( LoggerInstance.LoggingEnabled, LoggerInstance.EnableOnPlay, null, () => LoggerInstance.LogWriter.Add("[PAUSE]", true), () => LoggerInstance.LogWriter.WriteAll( LoggerInstance.FilePath, false)); // Draw -> button. if (GUILayout.Button("->", GUILayout.Width(30))) { EditorGUIUtility.PingObject(LoggerInstance); Selection.activeGameObject = LoggerInstance.gameObject; } EditorGUILayout.EndHorizontal(); Repaint(); } } } ```
7a8e9653-ccb0-4d93-922b-850642aac0ca
{ "language": "C#" }
```c# using System; namespace Yeamul.Test { class Program { static void Main(string[] args) { Node nn = Node.Null; Console.WriteLine(nn); Node nbt = true; Console.WriteLine(nbt); Node nbf = false; Console.WriteLine(nbf); Node n16 = short.MinValue; Console.WriteLine(n16); Node n32 = int.MinValue; Console.WriteLine(n32); Node n64 = long.MinValue; Console.WriteLine(n64); Node nu16 = ushort.MaxValue; Console.WriteLine(nu16); Node nu32 = uint.MaxValue; Console.WriteLine(nu32); Node nu64 = ulong.MaxValue; Console.WriteLine(nu64); Node nf = 1.2f; Console.WriteLine(nf); Node nd = Math.PI; Console.WriteLine(nd); Node nm = 1.2345678901234567890m; Console.WriteLine(nm); Node ng = Guid.NewGuid(); Console.WriteLine(ng); Node ns = "derp"; Console.WriteLine(ns); Console.ReadKey(); } } }``` Remove Main()'s unused args parameter
```c# using System; namespace Yeamul.Test { class Program { static void Main() { Node nn = Node.Null; Console.WriteLine(nn); Node nbt = true; Console.WriteLine(nbt); Node nbf = false; Console.WriteLine(nbf); Node n16 = short.MinValue; Console.WriteLine(n16); Node n32 = int.MinValue; Console.WriteLine(n32); Node n64 = long.MinValue; Console.WriteLine(n64); Node nu16 = ushort.MaxValue; Console.WriteLine(nu16); Node nu32 = uint.MaxValue; Console.WriteLine(nu32); Node nu64 = ulong.MaxValue; Console.WriteLine(nu64); Node nf = 1.2f; Console.WriteLine(nf); Node nd = Math.PI; Console.WriteLine(nd); Node nm = 1.2345678901234567890m; Console.WriteLine(nm); Node ng = Guid.NewGuid(); Console.WriteLine(ng); Node ns = "derp"; Console.WriteLine(ns); Console.ReadKey(); } } }```
81ca4480-1920-428f-86c4-01a645ff19de
{ "language": "C#" }
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LivrariaTest { [TestClass] public class AutorTest { [TestMethod] public void TestMethod1() { Assert.AreEqual(true, true); } } } ``` Add test for autor properties
```c# using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Livraria; namespace LivrariaTest { [TestClass] public class AutorTest { [TestMethod] public void TestProperties() { Autor autor = new Autor(); autor.CodAutor = 999; autor.Nome = "George R. R. Martin"; autor.Cpf = "012.345.678.90"; autor.DtNascimento = new DateTime(1948, 9, 20); Assert.AreEqual(autor.CodAutor, 999); Assert.AreEqual(autor.Nome, "George R. R. Martin"); Assert.AreEqual(autor.Cpf, "012.345.678.90"); Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20)); } } } ```
42192f74-6b05-41ab-b3d4-01883d13eff8
{ "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.Configuration; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; namespace osu.Game.Screens.Multi.Components { public abstract class DisableableTabControl<T> : TabControl<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected override void AddTabItem(TabItem<T> tab, bool addToDropdown = true) { if (tab is DisableableTabItem<T> disableable) disableable.ReadOnly.BindTo(ReadOnly); base.AddTabItem(tab, addToDropdown); } protected abstract class DisableableTabItem<T> : TabItem<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected DisableableTabItem(T value) : base(value) { ReadOnly.BindValueChanged(updateReadOnly); } private void updateReadOnly(bool readOnly) { Alpha = readOnly ? 0.2f : 1; } protected override bool OnClick(ClickEvent e) { if (ReadOnly) return true; return base.OnClick(e); } } } } ``` Use graying rather than alpha
```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.Configuration; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osuTK.Graphics; namespace osu.Game.Screens.Multi.Components { public abstract class DisableableTabControl<T> : TabControl<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected override void AddTabItem(TabItem<T> tab, bool addToDropdown = true) { if (tab is DisableableTabItem<T> disableable) disableable.ReadOnly.BindTo(ReadOnly); base.AddTabItem(tab, addToDropdown); } protected abstract class DisableableTabItem<T> : TabItem<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected DisableableTabItem(T value) : base(value) { ReadOnly.BindValueChanged(updateReadOnly); } private void updateReadOnly(bool readOnly) { Colour = readOnly ? Color4.Gray : Color4.White; } protected override bool OnClick(ClickEvent e) { if (ReadOnly) return true; return base.OnClick(e); } } } } ```
e5eee4a2-4601-4996-8781-ceded1a5266e
{ "language": "C#" }
```c# using System; namespace OpenTkApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } ``` Use OpenTK triangle sample in OpenTkApp project
```c# using System; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; namespace OpenTkApp { class Game : GameWindow { public Game() : base(800, 600, GraphicsMode.Default, "OpenTK Quick Start Sample") { VSync = VSyncMode.On; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f); GL.Enable(EnableCap.DepthTest); } protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref projection); } protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (Keyboard[Key.Escape]) Exit(); } protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, Vector3.UnitY); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref modelview); GL.Begin(BeginMode.Triangles); GL.Color3(1.0f, 1.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, 4.0f); GL.Color3(1.0f, 0.0f, 0.0f); GL.Vertex3(1.0f, -1.0f, 4.0f); GL.Color3(0.2f, 0.9f, 1.0f); GL.Vertex3(0.0f, 1.0f, 4.0f); GL.End(); SwapBuffers(); } } class Program { [STAThread] static void Main(string[] args) { using (Game game = new Game()) { game.Run(30.0); } } } } ```
556dcd5b-0ab3-404f-b9c2-f8de7b19f1d7
{ "language": "C#" }
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="WinAPI.NET"> // Copyright (c) Marek Dzikiewicz, All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; 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("WinApiNet")] [assembly: AssemblyDescription("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")] // Assembly is CLS-compliant [assembly: CLSCompliant(true)]``` Mark WinApiNet assembly as not CLS-compliant
```c# // -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="WinAPI.NET"> // Copyright (c) Marek Dzikiewicz, All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; 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("WinApiNet")] [assembly: AssemblyDescription("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")] // Assembly is not CLS-compliant [assembly: CLSCompliant(false)]```
0db618b0-4355-45cb-bfd3-f6c31d4ca073
{ "language": "C#" }
```c# // <copyright file="DotNetFileSystem.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.IO; using System.Threading; using System.Threading.Tasks; using FubarDev.WebDavServer.Props.Store; using Microsoft.VisualStudio.Threading; namespace FubarDev.WebDavServer.FileSystem.DotNet { public class DotNetFileSystem : ILocalFileSystem { private readonly PathTraversalEngine _pathTraversalEngine; public DotNetFileSystem(DotNetFileSystemOptions options, string rootFolder, PathTraversalEngine pathTraversalEngine, IPropertyStoreFactory propertyStoreFactory = null) { RootDirectoryPath = rootFolder; _pathTraversalEngine = pathTraversalEngine; var rootDir = new DotNetDirectory(this, null, new DirectoryInfo(rootFolder), new Uri(string.Empty, UriKind.Relative)); Root = new AsyncLazy<ICollection>(() => Task.FromResult<ICollection>(rootDir)); Options = options; PropertyStore = propertyStoreFactory?.Create(this); } public string RootDirectoryPath { get; } public AsyncLazy<ICollection> Root { get; } public DotNetFileSystemOptions Options { get; } public IPropertyStore PropertyStore { get; } public Task<SelectionResult> SelectAsync(string path, CancellationToken ct) { return _pathTraversalEngine.TraverseAsync(this, path, ct); } } } ``` Set property store before creating the root collection to make the property store available for some internal file hiding logic
```c# // <copyright file="DotNetFileSystem.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.IO; using System.Threading; using System.Threading.Tasks; using FubarDev.WebDavServer.Props.Store; using Microsoft.VisualStudio.Threading; namespace FubarDev.WebDavServer.FileSystem.DotNet { public class DotNetFileSystem : ILocalFileSystem { private readonly PathTraversalEngine _pathTraversalEngine; public DotNetFileSystem(DotNetFileSystemOptions options, string rootFolder, PathTraversalEngine pathTraversalEngine, IPropertyStoreFactory propertyStoreFactory = null) { RootDirectoryPath = rootFolder; _pathTraversalEngine = pathTraversalEngine; Options = options; PropertyStore = propertyStoreFactory?.Create(this); var rootDir = new DotNetDirectory(this, null, new DirectoryInfo(rootFolder), new Uri(string.Empty, UriKind.Relative)); Root = new AsyncLazy<ICollection>(() => Task.FromResult<ICollection>(rootDir)); } public string RootDirectoryPath { get; } public AsyncLazy<ICollection> Root { get; } public DotNetFileSystemOptions Options { get; } public IPropertyStore PropertyStore { get; } public Task<SelectionResult> SelectAsync(string path, CancellationToken ct) { return _pathTraversalEngine.TraverseAsync(this, path, ct); } } } ```
ff4160db-3383-484e-a209-49ed55166085
{ "language": "C#" }
```c# namespace PrimusFlex.Web.Areas.Admin.ViewModels.Employees { using System.ComponentModel.DataAnnotations; using Infrastructure.Mapping; using Data.Models.Types; using Data.Models; public class CreateEmployeeViewModel : IMapFrom<Employee>, IMapTo<Employee> { [Required] [StringLength(60, MinimumLength = 3)] public string Name { get; set; } [Required] public string Email { get; set; } [Required] public string Password { get; set; } [Required] public string ConfirmPassword { get; set; } public string PhoneNumber { get; set; } // Bank details [Required] public BankName BankName { get; set; } [Required] public string SortCode { get; set; } [Required] public string Account { get; set; } } } ``` Add attribute for checking if password and conformation password match
```c# namespace PrimusFlex.Web.Areas.Admin.ViewModels.Employees { using System.ComponentModel.DataAnnotations; using Infrastructure.Mapping; using Data.Models.Types; using Data.Models; public class CreateEmployeeViewModel : IMapFrom<Employee>, IMapTo<Employee> { [Required] [StringLength(60, MinimumLength = 3)] public string Name { get; set; } [Required] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string PhoneNumber { get; set; } // Bank details [Required] public BankName BankName { get; set; } [Required] public string SortCode { get; set; } [Required] public string Account { get; set; } } } ```
495de349-bbb7-4786-ba8e-6c638a258ab1
{ "language": "C#" }
```c# using System; namespace Sharper.C.Data { using static UnitModule; public static class FunctionModule { public static Func<A, B> Fun<A, B>(Func<A, B> f) => f; public static Func<A, Unit> Fun<A>(Action<A> f) => ToFunc(f); public static Action<A> Act<A>(Action<A> f) => f; public static A Id<A>(A a) => a; public static Func<B, A> Const<A, B>(A a) => b => a; public static Func<B, A, C> Flip<A, B, C>(Func<A, B, C> f) => (b, a) => f(a, b); public static Func<A, C> Compose<A, B, C>(this Func<B, C> f, Func<A, B> g) => a => f(g(a)); public static Func<A, C> Then<A, B, C>(this Func<A, B> f, Func<B, C> g) => a => g(f(a)); public static Func<A, Func<B, C>> Curry<A, B, C>(Func<A, B, C> f) => a => b => f(a, b); public static Func<A, B, C> Uncurry<A, B, C>(Func<A, Func<B, C>> f) => (a, b) => f(a)(b); } } ``` Make Compose a non-extension method
```c# using System; namespace Sharper.C.Data { using static UnitModule; public static class FunctionModule { public static Func<A, B> Fun<A, B>(Func<A, B> f) => f; public static Func<A, Unit> Fun<A>(Action<A> f) => ToFunc(f); public static Action<A> Act<A>(Action<A> f) => f; public static A Id<A>(A a) => a; public static Func<B, A> Const<A, B>(A a) => b => a; public static Func<B, A, C> Flip<A, B, C>(Func<A, B, C> f) => (b, a) => f(a, b); public static Func<A, C> Compose<A, B, C>(Func<B, C> f, Func<A, B> g) => a => f(g(a)); public static Func<A, C> Then<A, B, C>(this Func<A, B> f, Func<B, C> g) => a => g(f(a)); public static Func<A, Func<B, C>> Curry<A, B, C>(Func<A, B, C> f) => a => b => f(a, b); public static Func<A, B, C> Uncurry<A, B, C>(Func<A, Func<B, C>> f) => (a, b) => f(a)(b); } } ```
214465c0-ff0f-43fa-b6a5-3e12131f1530
{ "language": "C#" }
```c# namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); DoAllOfTheThings(); } } } ``` Fix build issues for TeamCity.
```c# namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); } } } ```
2a75b643-740a-4a3e-8618-5922b91a648c
{ "language": "C#" }
```c# using Autofac; using SceneJect.Autofac; using SceneJect.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Autofac { public class AutofacServiceAdapter : ContainerServiceProvider, IResolver, IServiceRegister { private readonly AutofacRegisterationStrat registerationStrat = new AutofacRegisterationStrat(new ContainerBuilder()); public override IServiceRegister Registry { get { return registerationStrat; } } private IResolver resolver = null; public override IResolver Resolver { get { return GenerateResolver(); } } private readonly object syncObj = new object(); private IResolver GenerateResolver() { if(resolver == null) { //double check locking lock(syncObj) if (resolver == null) resolver = new AutofacResolverStrat(registerationStrat.Build()); } return resolver; } } } ``` Fix travis/mono by remove SUO
```c# using Autofac; using SceneJect.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Autofac { public class AutofacServiceAdapter : ContainerServiceProvider, IResolver, IServiceRegister { private readonly AutofacRegisterationStrat registerationStrat = new AutofacRegisterationStrat(new ContainerBuilder()); public override IServiceRegister Registry { get { return registerationStrat; } } private IResolver resolver = null; public override IResolver Resolver { get { return GenerateResolver(); } } private readonly object syncObj = new object(); private IResolver GenerateResolver() { if(resolver == null) { //double check locking lock(syncObj) if (resolver == null) resolver = new AutofacResolverStrat(registerationStrat.Build()); } return resolver; } } } ```
7f0b571c-5fe0-4580-9269-fafe9bbf5159
{ "language": "C#" }
```c# using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace UserInputMacro { static class ScriptExecuter { public static async Task ExecuteAsync( string scriptPath ) { using( var hook = new UserInputHook() ) { HookSetting( hook ); var script = CSharpScript.Create( File.ReadAllText( scriptPath ), ScriptOptions.Default, typeof( MacroScript ) ); await script.RunAsync( new MacroScript() ); } } private static void LoggingMouseMacro( MouseHookStruct mouseHookStr, int mouseEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteMouseEvent( mouseHookStr, ( MouseHookEvent ) mouseEvent ); } } private static void LoggingKeyMacro( KeyHookStruct keyHookStr, int keyEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteKeyEventAsync( keyHookStr, ( KeyHookEvent ) keyEvent ).Wait(); } } private static void HookSetting( UserInputHook hook ) { hook.MouseHook = LoggingMouseMacro; hook.KeyHook = LoggingKeyMacro; hook.HookErrorProc = CommonUtil.HandleException; hook.RegisterKeyHook(); hook.RegisterMouseHook(); } } } ``` Correct in order not to use "Wait" method for synchronized method
```c# using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace UserInputMacro { static class ScriptExecuter { public static async Task ExecuteAsync( string scriptPath ) { using( var hook = new UserInputHook() ) { HookSetting( hook ); var script = CSharpScript.Create( File.ReadAllText( scriptPath ), ScriptOptions.Default, typeof( MacroScript ) ); await script.RunAsync( new MacroScript() ); } } private static void LoggingMouseMacro( MouseHookStruct mouseHookStr, int mouseEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteMouseEvent( mouseHookStr, ( MouseHookEvent ) mouseEvent ); } } private static void LoggingKeyMacro( KeyHookStruct keyHookStr, int keyEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteKeyEvent( keyHookStr, ( KeyHookEvent ) keyEvent ); } } private static void HookSetting( UserInputHook hook ) { hook.MouseHook = LoggingMouseMacro; hook.KeyHook = LoggingKeyMacro; hook.HookErrorProc = CommonUtil.HandleException; hook.RegisterKeyHook(); hook.RegisterMouseHook(); } } } ```
6adfcb4d-1ccc-4153-923b-4c6afacaeddb
{ "language": "C#" }
```c# namespace ElectronicCash { public struct ActorName { private readonly string _firstName; private readonly string _middleName; private readonly string _lastName; private readonly string _title; private readonly string _entityName; public ActorName(string firstName, string middleName, string lastName, string title) { _firstName = firstName; _middleName = middleName; _lastName = lastName; _title = title; _entityName = null; } public ActorName(string entityName) { _firstName = null; _middleName = null; _lastName = null; _title = null; _entityName = entityName; } public string FirstName => _firstName; public string MiddleName => _middleName; public string LastName => _lastName; public string Title => _title; public string EntityName => _entityName; } } ``` Validate data in the ctors
```c# using System; namespace ElectronicCash { public struct ActorName { private readonly string _firstName; private readonly string _middleName; private readonly string _lastName; private readonly string _title; private readonly string _entityName; public ActorName(string firstName, string middleName, string lastName, string title) { if (string.IsNullOrEmpty(firstName)) { throw new ArgumentException("First name must not be empty"); } if (string.IsNullOrEmpty(middleName)) { throw new ArgumentException("Middle name must not be empty"); } if (string.IsNullOrEmpty(lastName)) { throw new ArgumentException("Last name must not be empty"); } _firstName = firstName; _middleName = middleName; _lastName = lastName; _title = title; _entityName = null; } public ActorName(string entityName) { if (string.IsNullOrEmpty(entityName)) { throw new ArgumentException("Entity name must be provided"); } _firstName = null; _middleName = null; _lastName = null; _title = null; _entityName = entityName; } public string FirstName => _firstName; public string MiddleName => _middleName; public string LastName => _lastName; public string Title => _title; public string EntityName => _entityName; } } ```
141604be-aa54-431f-a3a5-fe6f326b7a97
{ "language": "C#" }
```c# // Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; namespace AppBrix.Time { /// <summary> /// Service which operates with <see cref="DateTime"/>. /// </summary> public interface ITimeService { /// <summary> /// Gets the current time. /// This should be used instead of DateTime.Now or DateTime.UtcNow. /// </summary> /// <returns></returns> DateTime GetTime(); /// <summary> /// Converts the specified time to the configured application time kind. /// </summary> /// <param name="time">The specified time.</param> /// <returns>The converted time.</returns> DateTime ToAppTime(DateTime time); /// <summary> /// Converts a given <see cref="DateTime"/> to a predefined <see cref="string"/> representation. /// </summary> /// <param name="time">The time.</param> /// <returns>The string representation of the time.</returns> string ToString(DateTime time); /// <summary> /// Converts a given <see cref="string"/> to a <see cref="DateTime"/> in a system time kind. /// </summary> /// <param name="time"></param> /// <returns></returns> DateTime ToDateTime(string time); } } ``` Improve time service interface documentation
```c# // Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; namespace AppBrix.Time { /// <summary> /// Service which operates with <see cref="DateTime"/>. /// </summary> public interface ITimeService { /// <summary> /// Gets the current time. /// This should be used instead of <see cref="DateTime.Now"/> or <see cref="DateTime.UtcNow"/>. /// </summary> /// <returns>The current date and time.</returns> DateTime GetTime(); /// <summary> /// Converts the specified time to the configured application <see cref="DateTimeKind"/>. /// </summary> /// <param name="time">The specified time.</param> /// <returns>The converted time.</returns> DateTime ToAppTime(DateTime time); /// <summary> /// Converts a given <see cref="DateTime"/> to a predefined <see cref="string"/> representation. /// </summary> /// <param name="time">The time.</param> /// <returns>The string representation of the time.</returns> string ToString(DateTime time); /// <summary> /// Converts a given <see cref="string"/> to a <see cref="DateTime"/> in the configured <see cref="DateTimeKind"/>. /// </summary> /// <param name="time">The date and time in string representation.</param> /// <returns>The date and time.</returns> DateTime ToDateTime(string time); } } ```
6b8c9e58-9f2c-4e40-bd6b-d16910fe849b
{ "language": "C#" }
```c# using System; using System.IO; namespace Kyru.Core { internal sealed class Config { internal string storeDirectory; internal Config() { storeDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Kyru", "objects"); } } }``` Fix to make path independant to the version
```c# using System; using System.IO; namespace Kyru.Core { internal sealed class Config { internal string storeDirectory; internal Config() { storeDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Kyru", "objects"); } } }```
0108b691-4428-4eb6-9408-db9786ba0e5e
{ "language": "C#" }
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.CommonServiceLocator")] [assembly: AssemblyDescription("")] ``` Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
```c# using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.CommonServiceLocator")] ```
14d07188-d611-48b1-b4cc-b4e09c6e6ec5
{ "language": "C#" }
```c# using ToSic.Razor.Blade; // todo: change to use Get public class Links : Custom.Hybrid.Code12 { // Returns a safe url to a post details page public dynamic LinkToDetailsPage(dynamic post) { var detailsPageTabId = Text.Has(Settings.DetailsPage) ? int.Parse((AsEntity(App.Settings).GetBestValue("DetailsPage")).Split(':')[1]) : CmsContext.Page.Id; return Link.To(pageId: detailsPageTabId, parameters: "details=" + post.UrlKey); } } ``` Improve how the link is made and page is cached
```c# using ToSic.Razor.Blade; public class Links : Custom.Hybrid.Code12 { /// <Summary> /// Returns a safe url to a post details page /// </Summary> public dynamic LinkToDetailsPage(dynamic post) { return Link.To(pageId: DetailsPageId, parameters: "details=" + post.UrlKey); } /// <Summary> /// Get / cache the page which will show the details of a post /// </Summary> private int DetailsPageId { get { if (_detailsPageId != 0) return _detailsPageId; if (Text.Has(Settings.DetailsPage)) _detailsPageId = int.Parse((App.Settings.Get("DetailsPage", convertLinks: false)).Split(':')[1]); else _detailsPageId = CmsContext.Page.Id; return _detailsPageId; } } private int _detailsPageId; } ```